-
Notifications
You must be signed in to change notification settings - Fork 39
/
generateDS.py
executable file
·5703 lines (5417 loc) · 245 KB
/
generateDS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Synopsis:
Generate Python classes from XML Schema definition.
Input is read from in_xsd_file or, if "-" (dash) arg, from stdin.
Output is written to files named in "-o" and "-s" options.
Usage:
python generateDS.py [ options ] <xsd_file>
python generateDS.py [ options ] -
Options:
-h, --help Display this help information.
-o <outfilename> Output file name for data representation classes
-s <subclassfilename> Output file name for subclasses
-p <prefix> Prefix string to be pre-pended to the class names
-f Force creation of output files. Do not ask.
-a <namespaceabbrev> Namespace abbreviation, e.g. "xsd:".
Default = 'xs:'.
-b <behaviorfilename> Input file name for behaviors added to subclasses
-m Generate properties for member variables
--subclass-suffix="XXX" Append XXX to the generated subclass names.
Default="Sub".
--root-element="XXX" Assume XXX is root element of instance docs.
Default is first element defined in schema.
Also see section "Recognizing the top level
element" in the documentation.
--super="XXX" Super module name in subclass module. Default="???"
--validator-bodies=path Path to a directory containing files that provide
bodies (implementations) of validator methods.
--use-old-getter-setter Name getters and setters getVar() and setVar(),
instead of get_var() and set_var().
--user-methods= <module>,
-u <module> Optional module containing user methods. See
section "User Methods" in the documentation.
--no-dates Do not include the current date in the generated
files. This is useful if you want to minimize
the amount of (no-operation) changes to the
generated python code.
--no-versions Do not include the current version in the generated
files. This is useful if you want to minimize
the amount of (no-operation) changes to the
generated python code.
--no-process-includes Do not process included XML Schema files. By
default, generateDS.py will insert content
from files referenced by <include ... />
elements into the XML Schema to be processed.
--silence Normally, the code generated with generateDS
echoes the information being parsed. To prevent
the echo from occurring, use the --silence switch.
--namespacedef='xmlns:abc="http://www.abc.com"'
Namespace definition to be passed in as the
value for the namespacedef_ parameter of
the export_xml() method by the generated
parse() and parseString() functions.
Default=''.
--external-encoding=<encoding>
Encode output written by the generated export
methods using this encoding. Default, if omitted,
is the value returned by sys.getdefaultencoding().
Example: --external-encoding='utf-8'.
--member-specs=list|dict
Generate member (type) specifications in each
class: a dictionary of instances of class
MemberSpec_ containing member name, type,
and array or not. Allowed values are
"list" or "dict". Default: do not generate.
-q, --no-questions Do not ask questios, for example,
force overwrite.
--session=mysession.session
Load and use options from session file. You can
create session file in generateds_gui.py. Or,
copy and edit sample.session from the
distribution.
--version Print version and exit.
"""
## LICENSE
## Copyright (c) 2003 Dave Kuhlman
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell copies of the Software, and to
## permit persons to whom the Software is furnished to do so, subject to
## the following conditions:
## The above copyright notice and this permission notice shall be
## included in all copies or substantial portions of the Software.
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
## IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
## CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
## TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
## SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#from __future__ import generators # only needed for Python 2.2
import sys
import os.path
import time
import getopt
import urllib2
import imp
from xml.sax import handler, make_parser
import xml.sax.xmlreader
import logging
import keyword
import StringIO
import textwrap
from cctype import TypeGenerator
from ccmap import IFMapGenerator
from ccsvc import ServiceGenerator
# Default logger configuration
## logging.basicConfig(level=logging.DEBUG,
## format='%(asctime)s %(levelname)s %(message)s')
## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\\nHit Ctrl-D to exit')
#
# Global variables etc.
#
#
# Do not modify the following VERSION comments.
# Used by updateversion.py.
##VERSION##
VERSION = '2.7c'
##VERSION##
class XsdParserGenerator(object):
def __init__(self):
self.Version = VERSION
self.GenerateProperties = 0
self.UseOldGetterSetter = 0
self.MemberSpecs = None
self.DelayedElements = []
self.DelayedElements_subclass = []
self.AlreadyGenerated = []
self.AlreadyGenerated_subclass = []
self.PostponedExtensions = []
self.ElementsForSubclasses = []
self.ElementDict = {}
self.Force = False
self.NoQuestions = False
self.Dirpath = []
self.ExternalEncoding = sys.getdefaultencoding()
self.genCategory = None
self.genLang = None
self.LangGenr = None
self.NamespacesDict = {}
self.Targetnamespace = ""
self.NameTable = {
'type': 'type_',
'float': 'float_',
'build': 'build_',
}
extras = ['self']
for kw in keyword.kwlist + extras:
self.NameTable[kw] = '%sxx' % kw
self.SubclassSuffix = 'Sub'
self.RootElement = None
self.AttributeGroups = {}
self.ElementGroups = {}
self.SubstitutionGroups = {}
#
# SubstitutionGroups can also include simple types that are
# not (defined) elements. Keep a list of these simple types.
# These are simple types defined at top level.
self.SimpleElementDict = {}
self.SimpleTypeDict = {}
self.ValidatorBodiesBasePath = None
self.UserMethodsPath = None
self.UserMethodsModule = None
self.XsdNameSpace = ''
self.CurrentNamespacePrefix = 'xs:'
self.AnyTypeIdentifier = '__ANY__'
self.TEMPLATE_HEADER = """\
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated %s by generateDS.py%s.
#
import sys
import getopt
import re as re_
etree_ = None
Verbose_import_ = False
( XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_import_library = None
try:
# lxml
from lxml import etree as etree_
XMLParser_import_library = XMLParser_import_lxml
if Verbose_import_:
print("running with lxml.etree")
except ImportError:
try:
# cElementTree from Python 2.5+
import xml.etree.cElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# ElementTree from Python 2.5+
import xml.etree.ElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with ElementTree")
except ImportError:
raise ImportError("Failed to import ElementTree from any known place")
def parsexml_(*args, **kwargs):
if (XMLParser_import_library == XMLParser_import_lxml and
'parser' not in kwargs):
# Use the lxml ElementTree compatible parser so that, e.g.,
# we ignore comments.
kwargs['parser'] = etree_.ETCompatXMLParser()
doc = etree_.parse(*args, **kwargs)
return doc
#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
# in a module named generatedssuper.py.
try:
from generatedssuper import GeneratedsSuper
except ImportError, exp:
class GeneratedsSuper(object):
def gds_format_string(self, input_data, input_name=''):
return input_data
def gds_validate_string(self, input_data, node, input_name=''):
return input_data
def gds_format_integer(self, input_data, input_name=''):
return '%%d' %% input_data
def gds_validate_integer(self, input_data, node, input_name=''):
return input_data
def gds_format_integer_list(self, input_data, input_name=''):
return '%%s' %% input_data
def gds_validate_integer_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, ValueError), exp:
raise_parse_error(node, 'Requires sequence of integers')
return input_data
def gds_format_float(self, input_data, input_name=''):
return '%%f' %% input_data
def gds_validate_float(self, input_data, node, input_name=''):
return input_data
def gds_format_float_list(self, input_data, input_name=''):
return '%%s' %% input_data
def gds_validate_float_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, ValueError), exp:
raise_parse_error(node, 'Requires sequence of floats')
return input_data
def gds_format_double(self, input_data, input_name=''):
return '%%e' %% input_data
def gds_validate_double(self, input_data, node, input_name=''):
return input_data
def gds_format_double_list(self, input_data, input_name=''):
return '%%s' %% input_data
def gds_validate_double_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, ValueError), exp:
raise_parse_error(node, 'Requires sequence of doubles')
return input_data
def gds_format_boolean(self, input_data, input_name=''):
return '%%s' %% input_data
def gds_validate_boolean(self, input_data, node, input_name=''):
return input_data
def gds_format_boolean_list(self, input_data, input_name=''):
return '%%s' %% input_data
def gds_validate_boolean_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
if value not in ('true', '1', 'false', '0', ):
raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")')
return input_data
def gds_str_lower(self, instring):
return instring.lower()
def get_path_(self, node):
path_list = []
self.get_path_list_(node, path_list)
path_list.reverse()
path = '/'.join(path_list)
return path
Tag_strip_pattern_ = re_.compile(r'\{.*\}')
def get_path_list_(self, node, path_list):
if node is None:
return
tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
if tag:
path_list.append(tag)
self.get_path_list_(node.getparent(), path_list)
def get_class_obj_(self, node, default_class=None):
class_obj1 = default_class
if 'xsi' in node.nsmap:
classname = node.get('{%%s}type' %% node.nsmap['xsi'])
if classname is not None:
names = classname.split(':')
if len(names) == 2:
classname = names[1]
class_obj2 = globals().get(classname)
if class_obj2 is not None:
class_obj1 = class_obj2
return class_obj1
def gds_build_any(self, node, type_name=None):
return None
#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\\nHit Ctrl-D to exit')
#
# Globals
#
ExternalEncoding = '%s'
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
String_cleanup_pat_ = re_.compile(r"[\\n\\r\\s]+")
Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
#
# Support/utility functions.
#
def showIndent(outfile, level, pretty_print=True):
if pretty_print:
for idx in range(level):
outfile.write(' ')
def quote_xml(inStr):
if not inStr:
return ''
s1 = (isinstance(inStr, basestring) and inStr or
'%%s' %% inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
return s1
def quote_attrib(inStr):
s1 = (isinstance(inStr, basestring) and inStr or
'%%s' %% inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
if '"' in s1:
if "'" in s1:
s1 = '"%%s"' %% s1.replace('"', """)
else:
s1 = "'%%s'" %% s1
else:
s1 = '"%%s"' %% s1
return s1
def quote_python(inStr):
s1 = inStr
if s1.find("'") == -1:
if s1.find('\\n') == -1:
return "'%%s'" %% s1
else:
return "'''%%s'''" %% s1
else:
if s1.find('"') != -1:
s1 = s1.replace('"', '\\\\"')
if s1.find('\\n') == -1:
return '"%%s"' %% s1
else:
return '\"\"\"%%s\"\"\"' %% s1
def get_all_text_(node):
if node.text is not None:
text = node.text
else:
text = ''
for child in node:
if child.tail is not None:
text += child.tail
return text
def find_attr_value_(attr_name, node):
attrs = node.attrib
attr_parts = attr_name.split(':')
value = None
if len(attr_parts) == 1:
value = attrs.get(attr_name)
elif len(attr_parts) == 2:
prefix, name = attr_parts
namespace = node.nsmap.get(prefix)
if namespace is not None:
value = attrs.get('{%%s}%%s' %% (namespace, name, ))
return value
class GDSParseError(Exception):
pass
def raise_parse_error(node, msg):
if XMLParser_import_library == XMLParser_import_lxml:
msg = '%%s (element %%s/line %%d)' %% (msg, node.tag, node.sourceline, )
else:
msg = '%%s (element %%s)' %% (msg, node.tag, )
raise GDSParseError(msg)
class MixedContainer:
# Constants for category:
CategoryNone = 0
CategoryText = 1
CategorySimple = 2
CategoryComplex = 3
# Constants for content_type:
TypeNone = 0
TypeText = 1
TypeString = 2
TypeInteger = 3
TypeFloat = 4
TypeDecimal = 5
TypeDouble = 6
TypeBoolean = 7
def __init__(self, category, content_type, name, value):
self.category = category
self.content_type = content_type
self.name = name
self.value = value
def getCategory(self):
return self.category
def getContenttype(self, content_type):
return self.content_type
def getValue(self):
return self.value
def getName(self):
return self.name
def export_xml(self, outfile, level, name, namespace, pretty_print=True):
if self.category == MixedContainer.CategoryText:
# Prevent exporting empty content as empty lines.
if self.value.strip():
outfile.write(self.value)
elif self.category == MixedContainer.CategorySimple:
self.exportSimple(outfile, level, name)
else: # category == MixedContainer.CategoryComplex
self.value.export_xml(outfile, level, namespace, name, pretty_print)
def exportSimple(self, outfile, level, name):
if self.content_type == MixedContainer.TypeString:
outfile.write('<%%s>%%s</%%s>' %% (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeInteger or \\
self.content_type == MixedContainer.TypeBoolean:
outfile.write('<%%s>%%d</%%s>' %% (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeFloat or \\
self.content_type == MixedContainer.TypeDecimal:
outfile.write('<%%s>%%f</%%s>' %% (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeDouble:
outfile.write('<%%s>%%g</%%s>' %% (self.name, self.value, self.name))
def exportLiteral(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%%d, %%d, "%%s", "%%s"),\\n' %% \\
(self.category, self.content_type, self.name, self.value))
elif self.category == MixedContainer.CategorySimple:
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%%d, %%d, "%%s", "%%s"),\\n' %% \\
(self.category, self.content_type, self.name, self.value))
else: # category == MixedContainer.CategoryComplex
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%%d, %%d, "%%s",\\n' %% \\
(self.category, self.content_type, self.name,))
self.value.exportLiteral(outfile, level + 1)
showIndent(outfile, level)
outfile.write(')\\n')
class MemberSpec_(object):
def __init__(self, name='', data_type='', container=0):
self.name = name
self.data_type = data_type
self.container = container
def set_name(self, name): self.name = name
def get_name(self): return self.name
def set_data_type(self, data_type): self.data_type = data_type
def get_data_type_chain(self): return self.data_type
def get_data_type(self):
if isinstance(self.data_type, list):
if len(self.data_type) > 0:
return self.data_type[-1]
else:
return 'xs:string'
else:
return self.data_type
def set_container(self, container): self.container = container
def get_container(self): return self.container
def cast_(typ, value):
if typ is None or value is None:
return value
return typ(value)
#
# Data representation classes.
#
"""
self.TEMPLATE_MAIN = """\
USAGE_TEXT = \"\"\"
Usage: python <%(prefix)sParser>.py [ -s ] <in_xml_file>
\"\"\"
def usage():
print USAGE_TEXT
sys.exit(1)
def get_root_tag(node):
tag = Tag_pattern_.match(node.tag).groups()[-1]
rootClass = globals().get(tag)
return tag, rootClass
def parse(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = '%(name)s'
rootClass = %(prefix)s%(root)s
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
#silence# sys.stdout.write('<?xml version="1.0" ?>\\n')
#silence# rootObj.export_xml(sys.stdout, 0, name_=rootTag,
#silence# namespacedef_='%(namespacedef)s',
#silence# pretty_print=True)
return rootObj
def parseString(inString):
from StringIO import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = '%(name)s'
rootClass = %(prefix)s%(root)s
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
#silence# sys.stdout.write('<?xml version="1.0" ?>\\n')
#silence# rootObj.export_xml(sys.stdout, 0, name_="%(name)s",
#silence# namespacedef_='%(namespacedef)s')
return rootObj
def parseLiteral(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = '%(name)s'
rootClass = %(prefix)s%(root)s
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
#silence# sys.stdout.write('#from %(module_name)s import *\\n\\n')
#silence# sys.stdout.write('import %(module_name)s as model_\\n\\n')
#silence# sys.stdout.write('rootObj = model_.rootTag(\\n')
#silence# rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
#silence# sys.stdout.write(')\\n')
return rootObj
def main():
args = sys.argv[1:]
if len(args) == 1:
parse(args[0])
else:
usage()
if __name__ == '__main__':
main()
"""
self.SchemaToPythonTypeMap = {}
self.SchemaToCppTypeMap = {}
def args_parse(self):
#LG global Force, GenerateProperties, SubclassSuffix, RootElement, \
#LG ValidatorBodiesBasePath, UseOldGetterSetter, \
#LG UserMethodsPath, XsdNameSpace, \
#LG Namespacedef, NoDates, NoVersion, \
#LG TEMPLATE_MAIN, TEMPLATE_SUBCLASS_FOOTER, Dirpath, \
#LG ExternalEncoding, MemberSpecs, NoQuestions, LangGenr
self.outputText = True
self.args = sys.argv[1:]
try:
options, self.args = getopt.getopt(self.args, 'l:g:hfyo:s:p:a:b:mu:q',
['help', 'subclass-suffix=',
'root-element=', 'super=',
'validator-bodies=', 'use-old-getter-setter',
'user-methods=', 'no-process-includes', 'silence',
'namespacedef=', 'external-encoding=',
'member-specs=', 'no-dates', 'no-versions',
'no-questions', 'session=', 'generator-category=',
'generated-language=', 'version',
])
except getopt.GetoptError, exp:
usage()
self.prefix = ''
self.outFilename = None
self.subclassFilename = None
self.behaviorFilename = None
self.nameSpace = 'xs:'
superModule = '???'
self.processIncludes = 1
self.namespacedef = ''
self.ExternalEncoding = sys.getdefaultencoding()
self.NoDates = False
self.NoVersion = False
self.NoQuestions = False
showVersion = False
self.xschemaFileName = None
for option in options:
if option[0] == '--session':
sessionFilename = option[1]
from libgenerateDS.gui import generateds_gui_session
from xml.etree import ElementTree as etree
doc = etree.parse(sessionFilename)
rootNode = doc.getroot()
sessionObj = generateds_gui_session.sessionType()
sessionObj.build(rootNode)
if sessionObj.get_input_schema():
self.xschemaFileName = sessionObj.get_input_schema()
if sessionObj.get_output_superclass():
self.outFilename = sessionObj.get_output_superclass()
if sessionObj.get_output_subclass():
self.subclassFilename = sessionObj.get_output_subclass()
if sessionObj.get_force():
self.Force = True
if sessionObj.get_prefix():
self.prefix = sessionObj.get_prefix()
if sessionObj.get_empty_namespace_prefix():
self.nameSpace = ''
elif sessionObj.get_namespace_prefix():
self.nameSpace = sessionObj.get_namespace_prefix()
if sessionObj.get_behavior_filename():
self.behaviorFilename = sessionObj.get_behavior_filename()
if sessionObj.get_properties():
self.GenerateProperties = True
if sessionObj.get_subclass_suffix():
SubclassSuffix = sessionObj.get_subclass_suffix()
if sessionObj.get_root_element():
self.RootElement = sessionObj.get_root_element()
if sessionObj.get_superclass_module():
superModule = sessionObj.get_superclass_module()
if sessionObj.get_old_getters_setters():
self.UseOldGetterSetter = 1
if sessionObj.get_validator_bodies():
ValidatorBodiesBasePath = sessionObj.get_validator_bodies()
if not os.path.isdir(ValidatorBodiesBasePath):
err_msg('*** Option validator-bodies must specify an existing path.\n')
sys.exit(1)
if sessionObj.get_user_methods():
UserMethodsPath = sessionObj.get_user_methods()
if sessionObj.get_no_dates():
self.NoDates = True
if sessionObj.get_no_versions():
self.NoVersion = True
if sessionObj.get_no_process_includes():
self.processIncludes = 0
if sessionObj.get_silence():
self.outputText = False
if sessionObj.get_namespace_defs():
self.namespacedef = sessionObj.get_naspace_defs()
if sessionObj.get_external_encoding():
self.ExternalEncoding = sessionObj.get_external_encoding()
if sessionObj.get_member_specs() in ('list', 'dict'):
MemberSpecs = sessionObj.get_member_specs()
break
for option in options:
if option[0] == '-h' or option[0] == '--help':
usage()
elif option[0] == '-p':
self.prefix = option[1]
elif option[0] == '-o':
self.outFilename = option[1]
elif option[0] == '-s':
self.subclassFilename = option[1]
elif option[0] == '-f':
self.Force = 1
elif option[0] == '-a':
self.nameSpace = option[1]
elif option[0] == '-b':
self.behaviorFilename = option[1]
elif option[0] == '-m':
self.GenerateProperties = 1
elif option[0] == '--no-dates':
self.NoDates = True
elif option[0] == '--no-versions':
self.NoVersion = True
elif option[0] == '--subclass-suffix':
SubclassSuffix = option[1]
elif option[0] == '--root-element':
self.RootElement = option[1]
elif option[0] == '--super':
superModule = option[1]
elif option[0] == '--validator-bodies':
ValidatorBodiesBasePath = option[1]
if not os.path.isdir(ValidatorBodiesBasePath):
err_msg('*** Option validator-bodies must specify an existing path.\n')
sys.exit(1)
elif option[0] == '--use-old-getter-setter':
self.UseOldGetterSetter = 1
elif option[0] in ('-u', '--user-methods'):
UserMethodsPath = option[1]
elif option[0] == '--no-process-includes':
self.processIncludes = 0
elif option[0] == "--silence":
self.outputText = False
elif option[0] == "--namespacedef":
self.namespacedef = option[1]
elif option[0] == '--external-encoding':
self.ExternalEncoding = option[1]
elif option[0] in ('-q', '--no-questions'):
self.NoQuestions = True
elif option[0] == '--version':
showVersion = True
elif option[0] == '--member-specs':
MemberSpecs = option[1]
if MemberSpecs not in ('list', 'dict', ):
raise RuntimeError('Option --member-specs must be "list" or "dict".')
elif option[0] in ('-l', '--generated-language'):
self.genLang = option[1]
if self.genLang not in ('py', 'c++'):
raise RuntimeError('Option --generated-language must be "py" or "c++".')
elif option[0] in ('-g', '--generator-category'):
self.genCategory = option[1]
if self.genCategory not in ('type',
'service',
'ifmap-frontend',
'ifmap-backend',
'device-api',
'java-api',
'golang-api',
'contrail-json-schema',
'json-schema'):
raise RuntimeError('Option --generator-category must be "type", service", "ifmap-frontend", "ifmap-backend", "device-api", "java-api", "golang-api", "contrail-json-schema" or "json-schema".')
if showVersion:
print 'generateDS.py version %s' % VERSION
sys.exit(0)
def countChildren(self, element, count):
count += len(element.getChildren())
base = element.getBase()
if base and base in self.ElementDict:
parent = self.ElementDict[base]
count = self.countChildren(parent, count)
return count
def getParentName(self, element):
base = element.getBase()
rBase = element.getRestrictionBaseObj()
parentName = None
parentObj = None
if base and base in self.ElementDict:
parentObj = self.ElementDict[base]
parentName = self.cleanupName(parentObj.getName())
elif rBase:
base = element.getRestrictionBase()
parentObj = self.ElementDict[base]
parentName = self.cleanupName(parentObj.getName())
return parentName, parentObj
def makeFile(self, outFileName, outAppend = False):
outFile = None
if ((not self.Force) and os.path.exists(outFileName)
and not outAppend):
if self.NoQuestions:
sys.stderr.write('File %s exists. Change output file or use -f (force).\n' % outFileName)
sys.exit(1)
else:
reply = raw_input('File %s exists. Overwrite? (y/n): ' % outFileName)
if reply == 'y':
outFile = file(outFileName, 'w')
else:
if (outAppend):
outFile = file(outFileName, 'a')
else:
outFile = file(outFileName, 'w')
return outFile
def mapName(self, oldName):
newName = oldName
if self.NameTable:
if oldName in self.NameTable:
newName = self.NameTable[oldName]
return newName
def cleanupName(self, oldName):
newName = oldName.replace(':', '_')
newName = newName.replace('-', '_')
newName = newName.replace('.', '_')
return newName
def make_gs_name(self, oldName):
if self.UseOldGetterSetter:
newName = oldName.capitalize()
else:
newName = '_%s' % oldName
return newName
def is_builtin_simple_type(self, type_val):
if type_val in self.StringType or \
type_val == self.TokenType or \
type_val == self.DateTimeType or \
type_val == self.TimeType or \
type_val == self.DateType or \
type_val in self.IntegerType or \
type_val == self.DecimalType or \
type_val == self.PositiveIntegerType or \
type_val == self.NonPositiveIntegerType or \
type_val == self.NegativeIntegerType or \
type_val == self.NonNegativeIntegerType or \
type_val == self.BooleanType or \
type_val == self.FloatType or \
type_val == self.DoubleType or \
type_val in self.OtherSimpleTypes:
return True
else:
return False
def set_type_constants(self, nameSpace):
#LG global CurrentNamespacePrefix, \
#LG StringType, TokenType, \
#LG IntegerType, DecimalType, \
#LG PositiveIntegerType, NegativeIntegerType, \
#LG NonPositiveIntegerType, NonNegativeIntegerType, \
#LG BooleanType, FloatType, DoubleType, \
#LG ElementType, ComplexTypeType, GroupType, SequenceType, ChoiceType, \
#LG AttributeGroupType, AttributeType, SchemaType, \
#LG DateTimeType, DateType, TimeType, \
#LG SimpleContentType, ComplexContentType, ExtensionType, \
#LG IDType, IDREFType, IDREFSType, IDTypes, \
#LG NameType, NCNameType, QNameType, NameTypes, \
#LG AnyAttributeType, SimpleTypeType, RestrictionType, \
#LG WhiteSpaceType, ListType, EnumerationType, UnionType, \
#LG AnyType, \
#LG AnnotationType, DocumentationType, \
#LG OtherSimpleTypes
self.CurrentNamespacePrefix = nameSpace
self.AttributeGroupType = nameSpace + 'attributeGroup'
self.AttributeType = nameSpace + 'attribute'
self.BooleanType = nameSpace + 'boolean'
self.ChoiceType = nameSpace + 'choice'
self.SimpleContentType = nameSpace + 'simpleContent'
self.ComplexContentType = nameSpace + 'complexContent'
self.ComplexTypeType = nameSpace + 'complexType'
self.GroupType = nameSpace + 'group'
self.SimpleTypeType = nameSpace + 'simpleType'
self.RestrictionType = nameSpace + 'restriction'
self.WhiteSpaceType = nameSpace + 'whiteSpace'
self.AnyAttributeType = nameSpace + 'anyAttribute'
self.DateTimeType = nameSpace + 'dateTime'
self.TimeType = nameSpace + 'time'
self.DateType = nameSpace + 'date'
self.IntegerType = (nameSpace + 'integer',
nameSpace + 'unsignedShort',
nameSpace + 'unsignedLong',
nameSpace + 'unsignedInt',
nameSpace + 'unsignedByte',
nameSpace + 'byte',
nameSpace + 'short',
nameSpace + 'long',
nameSpace + 'int',
)
self.DecimalType = nameSpace + 'decimal'
self.PositiveIntegerType = nameSpace + 'positiveInteger'
self.NegativeIntegerType = nameSpace + 'negativeInteger'
self.NonPositiveIntegerType = nameSpace + 'nonPositiveInteger'
self.NonNegativeIntegerType = nameSpace + 'nonNegativeInteger'
self.DoubleType = nameSpace + 'double'
self.ElementType = nameSpace + 'element'
self.ExtensionType = nameSpace + 'extension'
self.FloatType = nameSpace + 'float'
self.IDREFSType = nameSpace + 'IDREFS'
self.IDREFType = nameSpace + 'IDREF'
self.IDType = nameSpace + 'ID'
self.IDTypes = (self.IDREFSType, self.IDREFType, self.IDType, )
self.SchemaType = nameSpace + 'schema'
self.SequenceType = nameSpace + 'sequence'
self.StringType = (nameSpace + 'string',
nameSpace + 'duration',
nameSpace + 'anyURI',
nameSpace + 'base64Binary',
nameSpace + 'hexBinary',
nameSpace + 'normalizedString',
nameSpace + 'NMTOKEN',
nameSpace + 'ID',
nameSpace + 'Name',
nameSpace + 'language',
)
self.TokenType = nameSpace + 'token'
self.NameType = nameSpace + 'Name'
self.NCNameType = nameSpace + 'NCName'
self.QNameType = nameSpace + 'QName'
self.NameTypes = (self.NameType, self.NCNameType, self.QNameType, )
self.ListType = nameSpace + 'list'
self.EnumerationType = nameSpace + 'enumeration'
self.MinInclusiveType = nameSpace + 'minInclusive'
self.MaxInclusiveType = nameSpace + 'maxInclusive'
self.UnionType = nameSpace + 'union'
self.AnnotationType = nameSpace + 'annotation'
self.DocumentationType = nameSpace + 'documentation'
self.AnyType = nameSpace + 'any'
self.OtherSimpleTypes = (
nameSpace + 'ENTITIES',
nameSpace + 'ENTITY',
nameSpace + 'ID',
nameSpace + 'IDREF',
nameSpace + 'IDREFS',
nameSpace + 'NCName',
nameSpace + 'NMTOKEN',
nameSpace + 'NMTOKENS',
nameSpace + 'NOTATION',
nameSpace + 'Name',
nameSpace + 'QName',
nameSpace + 'anyURI',
nameSpace + 'base64Binary',
nameSpace + 'hexBinary',
nameSpace + 'boolean',
nameSpace + 'byte',
nameSpace + 'date',