diff --git a/build_dist b/build_dist new file mode 100755 index 0000000000000000000000000000000000000000..a78242ee1708fadec35b2e85792fbd4b7f1a47ba --- /dev/null +++ b/build_dist @@ -0,0 +1,15 @@ +#!/bin/sh -v +#cp ../Xslt/xsltvsgenerateds/xsltvsgenerateds.css . +#cp ../Xslt/xsltvsgenerateds/xsltvsgenerateds.html . +#rst2html.py --source-url=generateDS.txt --generator \ +# --stylesheet-path=/home/dkuhlman/bin/dave_docutils.css \ +# generateDS.txt generateDS.html +generate generateDS.txt +generate librarytemplate_howto.txt +generate generateds_gui_notes.txt +cd tutorial +generate generateds_tutorial.txt +zip -f generateds_tutorial.zip +cd .. +#python setup.py sdist --formats=gztar,zip +python setup.py sdist --formats=gztar diff --git a/generateDS.html b/generateDS.html index 0632a41bc8a30300c210a0c75206f16c605173e2..dde039ca9c0576a968e4817344f52c3c3d09d953 100644 --- a/generateDS.html +++ b/generateDS.html @@ -220,7 +220,7 @@ They are used by updateversion.py. --> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.22b</td> +<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.23a</td> </tr> </tbody> </table> @@ -229,7 +229,7 @@ They are used by updateversion.py. --> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">date:</th><td class="field-body">June 01, 2016</td> +<tr class="field"><th class="field-name">date:</th><td class="field-body">September 14, 2016</td> </tr> </tbody> </table> @@ -3180,7 +3180,7 @@ following among others:</p> <div class="footer"> <hr class="footer" /> <a class="reference external" href="generateDS.txt">View document source</a>. -Generated on: 2016-06-01 20:25 UTC. +Generated on: 2016-09-14 18:26 UTC. Generated by <a class="reference external" href="http://docutils.sourceforge.net/">Docutils</a> from <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> source. </div> diff --git a/generateDS.py b/generateDS.py index 26fa8284adffb85d930371f524bfa506bb2dbc42..d4091bbfc482c2ca23e3b4a54499c25b3eeee9db 100755 --- a/generateDS.py +++ b/generateDS.py @@ -204,7 +204,7 @@ logging.disable(logging.INFO) # Do not modify the following VERSION comments. # Used by updateversion.py. ##VERSION## -VERSION = '2.22b' +VERSION = '2.23a' ##VERSION## if sys.version_info.major == 2: diff --git a/generateDS.txt b/generateDS.txt index b43951775858dd1a6f799ee931e239baafff2a24..3230e02b1f1dcd02b39aedbd7f2a958200b36c30 100644 --- a/generateDS.txt +++ b/generateDS.txt @@ -12,7 +12,7 @@ generateDS -- Generate Data Structures from XML Schema .. version -:revision: 2.22b +:revision: 2.23a .. version diff --git a/generateds_gui_notes.html b/generateds_gui_notes.html index 2b700894173d4c34807ef6a73b506b9decf5763c..8196a0d5c7fde99d33a3d04b627a7215bcf21536 100644 --- a/generateds_gui_notes.html +++ b/generateds_gui_notes.html @@ -220,7 +220,7 @@ They are used by updateversion.py. --> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.22b</td> +<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.23a</td> </tr> </tbody> </table> @@ -229,7 +229,7 @@ They are used by updateversion.py. --> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">date:</th><td class="field-body">April 20, 2016</td> +<tr class="field"><th class="field-name">date:</th><td class="field-body">September 14, 2016</td> </tr> </tbody> </table> @@ -401,7 +401,7 @@ $ mv generateds_gui.mo locale/ru/LC_MESSAGES/ <div class="footer"> <hr class="footer" /> <a class="reference external" href="generateds_gui_notes.txt">View document source</a>. -Generated on: 2016-04-21 00:07 UTC. +Generated on: 2016-09-14 18:26 UTC. Generated by <a class="reference external" href="http://docutils.sourceforge.net/">Docutils</a> from <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> source. </div> diff --git a/generateds_gui_notes.txt b/generateds_gui_notes.txt index 656a1dbd0100b0701be034ce242551b177f65bda..bfcd9449b9532c819ea739fb0992fc5e196d919f 100644 --- a/generateds_gui_notes.txt +++ b/generateds_gui_notes.txt @@ -12,7 +12,7 @@ GenerateDS GUI Notes .. version -:revision: 2.22b +:revision: 2.23a .. version diff --git a/gui/generateds_gui.py b/gui/generateds_gui.py index da981e97a6e22e73fba3a493e8ef6b45b0cecf31..21f2b10ed897dbd269cfd5be86dce6829c3efef5 100755 --- a/gui/generateds_gui.py +++ b/gui/generateds_gui.py @@ -41,7 +41,7 @@ from libgenerateDS.gui import generateds_gui_session # Do not modify the following VERSION comments. # Used by updateversion.py. ##VERSION## -VERSION = '2.22b' +VERSION = '2.23a' ##VERSION## diff --git a/librarytemplate_howto.html b/librarytemplate_howto.html index 303c08389161fab034283a94eda68e652f26164f..8d2313ff96aabe92e050e32d48ff139787b9472e 100644 --- a/librarytemplate_howto.html +++ b/librarytemplate_howto.html @@ -217,7 +217,7 @@ dkuhlman (at) davekuhlman (dot) org <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.22b</td> +<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.23a</td> </tr> </tbody> </table> @@ -226,7 +226,7 @@ dkuhlman (at) davekuhlman (dot) org <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">date:</th><td class="field-body">April 20, 2016</td> +<tr class="field"><th class="field-name">date:</th><td class="field-body">September 14, 2016</td> </tr> </tbody> </table> @@ -380,7 +380,7 @@ this command for your needs. For example, you may need to use <div class="footer"> <hr class="footer" /> <a class="reference external" href="librarytemplate_howto.txt">View document source</a>. -Generated on: 2016-04-21 00:07 UTC. +Generated on: 2016-09-14 18:26 UTC. Generated by <a class="reference external" href="http://docutils.sourceforge.net/">Docutils</a> from <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> source. </div> diff --git a/librarytemplate_howto.txt b/librarytemplate_howto.txt index f508d04fc3aa98992bb5195ac155f014199ee4c3..7c62ef2aa1c023d3c8be6e6989cc34c519208642 100644 --- a/librarytemplate_howto.txt +++ b/librarytemplate_howto.txt @@ -8,7 +8,7 @@ How to package a generateDS.py generated library .. version -:revision: 2.22b +:revision: 2.23a .. version diff --git a/process_includes.py b/process_includes.py index e9516b642046c9f543ad95a18f27ebf403a33234..1745adca768e9694fcebc3b4c67a4fe2bd0b338e 100755 --- a/process_includes.py +++ b/process_includes.py @@ -40,7 +40,7 @@ except ImportError: # Do not modify the following VERSION comments. # Used by updateversion.py. ##VERSION## -VERSION = '2.22b' +VERSION = '2.23a' ##VERSION## CatalogDict = {} diff --git a/setup.py b/setup.py index 4468b677422382ef8cac69f5b5ed521f3ebab239..9ade05226f25a5f2be2d59562544cb3bf5620561 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup(name="generateDS", # Do not modify the following VERSION comments. # Used by updateversion.py. ##VERSION## - version="2.22b", + version="2.23a", ##VERSION## author="Dave Kuhlman", author_email="dkuhlman@davekuhlman.org", diff --git a/tests/catalogtest2_sub.py b/tests/catalogtest2_sub.py deleted file mode 100644 index eae693ca029cbb2d512241379630c6cdd2f37992..0000000000000000000000000000000000000000 --- a/tests/catalogtest2_sub.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python - -# -# Generated by generateDS.py. -# -# Command line options: -# ('--no-dates', '') -# ('--no-versions', '') -# ('--silence', '') -# ('--member-specs', 'list') -# ('-f', '') -# ('-o', 'tests/catalogtest2_sup.py') -# ('-s', 'tests/catalogtest2_sub.py') -# ('--super', 'catalogtest2_sup') -# ('-c', 'tests/catalog.xml') -# -# Command line arguments: -# tests/catalogtest.xsd -# -# Command line: -# generateDS.py --no-dates --no-versions --silence --member-specs="list" -f -o "tests/catalogtest2_sup.py" -s "tests/catalogtest2_sub.py" --super="catalogtest2_sup" -c "tests/catalog.xml" tests/catalogtest.xsd -# -# Current working directory (os.getcwd()): -# generateds -# - -import sys -from lxml import etree as etree_ - -import catalogtest2_sup as supermod - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - parser = etree_.ETCompatXMLParser() - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -# -# Globals -# - -ExternalEncoding = 'ascii' - -# -# Data representation classes -# - - -def get_root_tag(node): - tag = supermod.Tag_pattern_.match(node.tag).groups()[-1] - rootClass = None - rootClass = supermod.GDSClassesMapping.get(tag) - if rootClass is None and hasattr(supermod, tag): - rootClass = getattr(supermod, tag) - return tag, rootClass - - -def parse(inFilename, silence=False): - parser = None - doc = parsexml_(inFilename, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = supermod. - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## if not silence: -## sys.stdout.write('<?xml version="1.0" ?>\n') -## rootObj.export( -## sys.stdout, 0, name_=rootTag, -## namespacedef_='', -## pretty_print=True) - return rootObj - - -def parseEtree(inFilename, silence=False): - parser = None - doc = parsexml_(inFilename, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = supermod. - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - mapping = {} - rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) - reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) -## if not silence: -## content = etree_.tostring( -## rootElement, pretty_print=True, -## xml_declaration=True, encoding="utf-8") -## sys.stdout.write(content) -## sys.stdout.write('\n') - return rootObj, rootElement, mapping, reverse_mapping - - -def parseString(inString, silence=False): - from StringIO import StringIO - parser = None - doc = parsexml_(StringIO(inString), parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = supermod. - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## if not silence: -## sys.stdout.write('<?xml version="1.0" ?>\n') -## rootObj.export( -## sys.stdout, 0, name_=rootTag, -## namespacedef_='') - return rootObj - - -def parseLiteral(inFilename, silence=False): - parser = None - doc = parsexml_(inFilename, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = supermod. - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## if not silence: -## sys.stdout.write('#from catalogtest2_sup import *\n\n') -## sys.stdout.write('import catalogtest2_sup as model_\n\n') -## sys.stdout.write('rootObj = model_.rootClass(\n') -## rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) -## sys.stdout.write(')\n') - return rootObj - - -USAGE_TEXT = """ -Usage: python ???.py <infilename> -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def main(): - args = sys.argv[1:] - if len(args) != 1: - usage() - infilename = args[0] - parse(infilename) - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() diff --git a/tests/catalogtest2_sup.py b/tests/catalogtest2_sup.py deleted file mode 100644 index 370be9424dbb138c5c75d497158057f49a87a4f1..0000000000000000000000000000000000000000 --- a/tests/catalogtest2_sup.py +++ /dev/null @@ -1,778 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated by generateDS.py. -# -# Command line options: -# ('--no-dates', '') -# ('--no-versions', '') -# ('--silence', '') -# ('--member-specs', 'list') -# ('-f', '') -# ('-o', 'tests/catalogtest2_sup.py') -# ('-s', 'tests/catalogtest2_sub.py') -# ('--super', 'catalogtest2_sup') -# ('-c', 'tests/catalog.xml') -# -# Command line arguments: -# tests/catalogtest.xsd -# -# Command line: -# generateDS.py --no-dates --no-versions --silence --member-specs="list" -f -o "tests/catalogtest2_sup.py" -s "tests/catalogtest2_sub.py" --super="catalogtest2_sup" -c "tests/catalog.xml" tests/catalogtest.xsd -# -# Current working directory (os.getcwd()): -# generateds -# - -import sys -import re as re_ -import base64 -import datetime as datetime_ -import warnings as warnings_ -try: - from lxml import etree as etree_ -except ImportError: - from xml.etree import ElementTree as etree_ - - -Validate_simpletypes_ = True -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - doc = etree_.parse(infile, parser=parser, **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 as exp: - - class GeneratedsSuper(object): - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data) - def gds_validate_base64(self, input_data, node=None, 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=None, input_name=''): - return input_data - def gds_format_integer_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integers') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % input_data).rstrip('0') - def gds_validate_float(self, input_data, node=None, input_name=''): - return input_data - def gds_format_float_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of floats') - return values - def gds_format_double(self, input_data, input_name=''): - return '%e' % input_data - def gds_validate_double(self, input_data, node=None, input_name=''): - return input_data - def gds_format_double_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of doubles') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_validate_boolean(self, input_data, node=None, input_name=''): - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, 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 values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % (time_parts[0], micro_seconds, ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. We should: - # - AND the outer elements - # - OR the inner elements - found1 = True - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - if re_.search(patterns2, target) is not None: - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - 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 - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.iteritems())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - return instring.encode(ExternalEncoding) - else: - return instring - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - 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 = 'ascii' -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) 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): - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - 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 - TypeBase64 = 8 - 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(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(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)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s</%s>' % ( - self.name, base64.b64encode(self.value), self.name)) - def to_etree(self, element): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement(element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - 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. -# - - -GDSClassesMapping = { -} - - -USAGE_TEXT = """ -Usage: python <Parser>.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 = GDSClassesMapping.get(tag) - if rootClass is None: - rootClass = globals().get(tag) - return tag, rootClass - - -def parse(inFileName, silence=False): - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## if not silence: -## sys.stdout.write('<?xml version="1.0" ?>\n') -## rootObj.export( -## sys.stdout, 0, name_=rootTag, -## namespacedef_='', -## pretty_print=True) - return rootObj - - -def parseEtree(inFileName, silence=False): - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - mapping = {} - rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) - reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) -## if not silence: -## content = etree_.tostring( -## rootElement, pretty_print=True, -## xml_declaration=True, encoding="utf-8") -## sys.stdout.write(content) -## sys.stdout.write('\n') - return rootObj, rootElement, mapping, reverse_mapping - - -def parseString(inString, silence=False): - from StringIO import StringIO - parser = None - doc = parsexml_(StringIO(inString), parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## if not silence: -## sys.stdout.write('<?xml version="1.0" ?>\n') -## rootObj.export( -## sys.stdout, 0, name_=rootTag, -## namespacedef_='') - return rootObj - - -def parseLiteral(inFileName, silence=False): - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = '' - rootClass = - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## if not silence: -## sys.stdout.write('#from catalogtest2_sup import *\n\n') -## sys.stdout.write('import catalogtest2_sup as model_\n\n') -## sys.stdout.write('rootObj = model_.rootClass(\n') -## rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) -## sys.stdout.write(')\n') - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - - -__all__ = [ - -] diff --git a/tests/ipo2_out.xml b/tests/ipo2_out.xml deleted file mode 100644 index c6da399281a0ff8d96ad0c4617acfaf78c72922b..0000000000000000000000000000000000000000 --- a/tests/ipo2_out.xml +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" ?> -<ipo:purchaseOrder xmlns:ipo="http://www.example.com/IPO" orderDate="1999-12-01"> - <ipo:shipTo xmlns:ipo="http://www.example.com/IPO" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ipo:UKAddress" category="1-a" exportCode="1"> - <ipo:name>Helen Zoe</ipo:name> - <ipo:street>47 Eden Street</ipo:street> - <ipo:city>Cambridge</ipo:city> - <ipo:postcode>CB1 1JR</ipo:postcode> - <ipo:category>oneA</ipo:category> - </ipo:shipTo> - <ipo:billTo xmlns:ipo="http://www.example.com/IPO" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ipo:USAddress"> - <ipo:name>Robert Smith</ipo:name> - <ipo:street>8 Oak Avenue</ipo:street> - <ipo:city>Old Town</ipo:city> - <ipo:state>PA</ipo:state> - <ipo:zip>95819</ipo:zip> - </ipo:billTo> - <ipo:items xmlns:ipo="http://www.example.com/IPO"> - <ipo:item xmlns:ipo="http://www.example.com/IPO" partNum="833-AA"> - <ipo:productName>Lapis necklace</ipo:productName> - <ipo:quantity>1</ipo:quantity> - <ipo:USPrice>99.950000000000003</ipo:USPrice> - <ipo:comment>Want this for the holidays</ipo:comment> - <ipo:shipDate>1999-12-05</ipo:shipDate> - </ipo:item> - </ipo:items> -</ipo:purchaseOrder> diff --git a/tests/nested_def2_out.xml b/tests/nested_def2_out.xml deleted file mode 100644 index 692c598588827c7a3c7f7bdbbc4d6f24771086a4..0000000000000000000000000000000000000000 --- a/tests/nested_def2_out.xml +++ /dev/null @@ -1,9 +0,0 @@ -<?xml version="1.0" ?> -<container> - <item1> - <inner attrA1="attrA1value" attrA2="attrA2value"/> - </item1> - <item2> - <inner attrB1="attrB1value" attrB2="attrB2value"/> - </item2> -</container> diff --git a/tests/nested_def2_sub.py b/tests/nested_def2_sub.py deleted file mode 100644 index 2abcd144f29c7d5f805978ced900011e6eab0fdd..0000000000000000000000000000000000000000 --- a/tests/nested_def2_sub.py +++ /dev/null @@ -1,200 +0,0 @@ -#!/usr/bin/env python - -# -# Generated by generateDS.py. -# -# Command line options: -# ('--no-dates', '') -# ('--no-versions', '') -# ('--member-specs', 'list') -# ('-f', '') -# ('-o', 'tests/nested_def2_sup.py') -# ('-s', 'tests/nested_def2_sub.py') -# ('--super', 'nested_def2_sup') -# -# Command line arguments: -# tests/nested_def.xsd -# -# Command line: -# generateDS.py --no-dates --no-versions --member-specs="list" -f -o "tests/nested_def2_sup.py" -s "tests/nested_def2_sub.py" --super="nested_def2_sup" tests/nested_def.xsd -# -# Current working directory (os.getcwd()): -# generateds -# - -import sys -from lxml import etree as etree_ - -import nested_def2_sup as supermod - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - parser = etree_.ETCompatXMLParser() - doc = etree_.parse(infile, parser=parser, **kwargs) - return doc - -# -# Globals -# - -ExternalEncoding = 'ascii' - -# -# Data representation classes -# - - -class containerTypeSub(supermod.containerType): - def __init__(self, item1=None, item2=None): - super(containerTypeSub, self).__init__(item1, item2, ) -supermod.containerType.subclass = containerTypeSub -# end class containerTypeSub - - -class classATypeSub(supermod.classAType): - def __init__(self, inner=None): - super(classATypeSub, self).__init__(inner, ) -supermod.classAType.subclass = classATypeSub -# end class classATypeSub - - -class classBTypeSub(supermod.classBType): - def __init__(self, inner=None): - super(classBTypeSub, self).__init__(inner, ) -supermod.classBType.subclass = classBTypeSub -# end class classBTypeSub - - -class innerTypeSub(supermod.innerType): - def __init__(self, attrA1=None, attrA2=None): - super(innerTypeSub, self).__init__(attrA1, attrA2, ) -supermod.innerType.subclass = innerTypeSub -# end class innerTypeSub - - -class innerType1Sub(supermod.innerType1): - def __init__(self, attrB1=None, attrB2=None): - super(innerType1Sub, self).__init__(attrB1, attrB2, ) -supermod.innerType1.subclass = innerType1Sub -# end class innerType1Sub - - -def get_root_tag(node): - tag = supermod.Tag_pattern_.match(node.tag).groups()[-1] - rootClass = None - rootClass = supermod.GDSClassesMapping.get(tag) - if rootClass is None and hasattr(supermod, tag): - rootClass = getattr(supermod, tag) - return tag, rootClass - - -def parse(inFilename, silence=False): - parser = None - doc = parsexml_(inFilename, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = supermod.containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - if not silence: - sys.stdout.write('<?xml version="1.0" ?>\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='', - pretty_print=True) - return rootObj - - -def parseEtree(inFilename, silence=False): - parser = None - doc = parsexml_(inFilename, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = supermod.containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - mapping = {} - rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) - reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(content) - sys.stdout.write('\n') - return rootObj, rootElement, mapping, reverse_mapping - - -def parseString(inString, silence=False): - from StringIO import StringIO - parser = None - doc = parsexml_(StringIO(inString), parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = supermod.containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - if not silence: - sys.stdout.write('<?xml version="1.0" ?>\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - return rootObj - - -def parseLiteral(inFilename, silence=False): - parser = None - doc = parsexml_(inFilename, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = supermod.containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - if not silence: - sys.stdout.write('#from nested_def2_sup import *\n\n') - sys.stdout.write('import nested_def2_sup as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - return rootObj - - -USAGE_TEXT = """ -Usage: python ???.py <infilename> -""" - - -def usage(): - print(USAGE_TEXT) - sys.exit(1) - - -def main(): - args = sys.argv[1:] - if len(args) != 1: - usage() - infilename = args[0] - parse(infilename) - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() diff --git a/tests/nested_def2_sup.py b/tests/nested_def2_sup.py deleted file mode 100644 index 0240702bf6c0452fd6edfc9ef4e7ffd52ba06045..0000000000000000000000000000000000000000 --- a/tests/nested_def2_sup.py +++ /dev/null @@ -1,1180 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated by generateDS.py. -# -# Command line options: -# ('--no-dates', '') -# ('--no-versions', '') -# ('--member-specs', 'list') -# ('-f', '') -# ('-o', 'tests/nested_def2_sup.py') -# ('-s', 'tests/nested_def2_sub.py') -# ('--super', 'nested_def2_sup') -# -# Command line arguments: -# tests/nested_def.xsd -# -# Command line: -# generateDS.py --no-dates --no-versions --member-specs="list" -f -o "tests/nested_def2_sup.py" -s "tests/nested_def2_sub.py" --super="nested_def2_sup" tests/nested_def.xsd -# -# Current working directory (os.getcwd()): -# generateds -# - -import sys -import re as re_ -import base64 -import datetime as datetime_ -import warnings as warnings_ -try: - from lxml import etree as etree_ -except ImportError: - from xml.etree import ElementTree as etree_ - - -Validate_simpletypes_ = True -if sys.version_info.major == 2: - BaseStrType_ = basestring -else: - BaseStrType_ = str - - -def parsexml_(infile, parser=None, **kwargs): - if parser is None: - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - try: - parser = etree_.ETCompatXMLParser() - except AttributeError: - # fallback to xml.etree - parser = etree_.XMLParser() - doc = etree_.parse(infile, parser=parser, **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 as exp: - - class GeneratedsSuper(object): - tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$') - class _FixedOffsetTZ(datetime_.tzinfo): - def __init__(self, offset, name): - self.__offset = datetime_.timedelta(minutes=offset) - self.__name = name - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return None - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_validate_string(self, input_data, node=None, input_name=''): - if not input_data: - return '' - else: - return input_data - def gds_format_base64(self, input_data, input_name=''): - return base64.b64encode(input_data) - def gds_validate_base64(self, input_data, node=None, 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=None, input_name=''): - return input_data - def gds_format_integer_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_integer_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - int(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of integers') - return values - def gds_format_float(self, input_data, input_name=''): - return ('%.15f' % input_data).rstrip('0') - def gds_validate_float(self, input_data, node=None, input_name=''): - return input_data - def gds_format_float_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_float_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of floats') - return values - def gds_format_double(self, input_data, input_name=''): - return '%e' % input_data - def gds_validate_double(self, input_data, node=None, input_name=''): - return input_data - def gds_format_double_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_double_list( - self, input_data, node=None, input_name=''): - values = input_data.split() - for value in values: - try: - float(value) - except (TypeError, ValueError): - raise_parse_error(node, 'Requires sequence of doubles') - return values - def gds_format_boolean(self, input_data, input_name=''): - return ('%s' % input_data).lower() - def gds_validate_boolean(self, input_data, node=None, input_name=''): - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - return '%s' % ' '.join(input_data) - def gds_validate_boolean_list( - self, input_data, node=None, 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 values - def gds_validate_datetime(self, input_data, node=None, input_name=''): - return input_data - def gds_format_datetime(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % ( - input_data.year, - input_data.month, - input_data.day, - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - @classmethod - def gds_parse_datetime(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - time_parts = input_data.split('.') - if len(time_parts) > 1: - micro_seconds = int(float('0.' + time_parts[1]) * 1000000) - input_data = '%s.%s' % (time_parts[0], micro_seconds, ) - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime( - input_data, '%Y-%m-%dT%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt - def gds_validate_date(self, input_data, node=None, input_name=''): - return input_data - def gds_format_date(self, input_data, input_name=''): - _svalue = '%04d-%02d-%02d' % ( - input_data.year, - input_data.month, - input_data.day, - ) - try: - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format( - hours, minutes) - except AttributeError: - pass - return _svalue - @classmethod - def gds_parse_date(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') - dt = dt.replace(tzinfo=tz) - return dt.date() - def gds_validate_time(self, input_data, node=None, input_name=''): - return input_data - def gds_format_time(self, input_data, input_name=''): - if input_data.microsecond == 0: - _svalue = '%02d:%02d:%02d' % ( - input_data.hour, - input_data.minute, - input_data.second, - ) - else: - _svalue = '%02d:%02d:%02d.%s' % ( - input_data.hour, - input_data.minute, - input_data.second, - ('%f' % (float(input_data.microsecond) / 1000000))[2:], - ) - if input_data.tzinfo is not None: - tzoff = input_data.tzinfo.utcoffset(input_data) - if tzoff is not None: - total_seconds = tzoff.seconds + (86400 * tzoff.days) - if total_seconds == 0: - _svalue += 'Z' - else: - if total_seconds < 0: - _svalue += '-' - total_seconds *= -1 - else: - _svalue += '+' - hours = total_seconds // 3600 - minutes = (total_seconds - (hours * 3600)) // 60 - _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) - return _svalue - def gds_validate_simple_patterns(self, patterns, target): - # pat is a list of lists of strings/patterns. We should: - # - AND the outer elements - # - OR the inner elements - found1 = True - for patterns1 in patterns: - found2 = False - for patterns2 in patterns1: - if re_.search(patterns2, target) is not None: - found2 = True - break - if not found2: - found1 = False - break - return found1 - @classmethod - def gds_parse_time(cls, input_data): - tz = None - if input_data[-1] == 'Z': - tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') - input_data = input_data[:-1] - else: - results = GeneratedsSuper.tzoff_pattern.search(input_data) - if results is not None: - tzoff_parts = results.group(2).split(':') - tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) - if results.group(1) == '-': - tzoff *= -1 - tz = GeneratedsSuper._FixedOffsetTZ( - tzoff, results.group(0)) - input_data = input_data[:-6] - if len(input_data.split('.')) > 1: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') - else: - dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') - dt = dt.replace(tzinfo=tz) - return dt.time() - 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 - @classmethod - def gds_reverse_node_mapping(cls, mapping): - return dict(((v, k) for k, v in mapping.iteritems())) - @staticmethod - def gds_encode(instring): - if sys.version_info.major == 2: - return instring.encode(ExternalEncoding) - else: - return instring - - def getSubclassFromModule_(module, class_): - '''Get the subclass of a class from a specific module.''' - name = class_.__name__ + 'Sub' - if hasattr(module, name): - return getattr(module, name) - else: - 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 = 'ascii' -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") -Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') -CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL) - -# Change this to redirect the generated superclass module to use a -# specific subclass module. -CurrentSubclassModule_ = None - -# -# Support/utility functions. -# - - -def showIndent(outfile, level, pretty_print=True): - if pretty_print: - for idx in range(level): - outfile.write(' ') - - -def quote_xml(inStr): - "Escape markup chars, but do not modify CDATA sections." - if not inStr: - return '' - s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) - s2 = '' - pos = 0 - matchobjects = CDATA_pattern_.finditer(s1) - for mo in matchobjects: - s3 = s1[pos:mo.start()] - s2 += quote_xml_aux(s3) - s2 += s1[mo.start():mo.end()] - pos = mo.end() - s3 = s1[pos:] - s2 += quote_xml_aux(s3) - return s2 - - -def quote_xml_aux(inStr): - s1 = inStr.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - - -def quote_attrib(inStr): - s1 = (isinstance(inStr, BaseStrType_) 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): - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - 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 - TypeBase64 = 8 - 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(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(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)) - elif self.content_type == MixedContainer.TypeBase64: - outfile.write('<%s>%s</%s>' % ( - self.name, base64.b64encode(self.value), self.name)) - def to_etree(self, element): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - if len(element) > 0: - if element[-1].tail is None: - element[-1].tail = self.value - else: - element[-1].tail += self.value - else: - if element.text is None: - element.text = self.value - else: - element.text += self.value - elif self.category == MixedContainer.CategorySimple: - subelement = etree_.SubElement(element, '%s' % self.name) - subelement.text = self.to_etree_simple() - else: # category == MixedContainer.CategoryComplex - self.value.to_etree(element) - def to_etree_simple(self): - if self.content_type == MixedContainer.TypeString: - text = self.value - elif (self.content_type == MixedContainer.TypeInteger or - self.content_type == MixedContainer.TypeBoolean): - text = '%d' % self.value - elif (self.content_type == MixedContainer.TypeFloat or - self.content_type == MixedContainer.TypeDecimal): - text = '%f' % self.value - elif self.content_type == MixedContainer.TypeDouble: - text = '%g' % self.value - elif self.content_type == MixedContainer.TypeBase64: - text = '%s' % base64.b64encode(self.value) - return text - 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. -# - - -class containerType(GeneratedsSuper): - member_data_items_ = [ - MemberSpec_('item1', 'classAType', 0), - MemberSpec_('item2', 'classBType', 0), - ] - subclass = None - superclass = None - def __init__(self, item1=None, item2=None): - self.original_tagname_ = None - self.item1 = item1 - self.item2 = item2 - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, containerType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if containerType.subclass: - return containerType.subclass(*args_, **kwargs_) - else: - return containerType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_item1(self): return self.item1 - def set_item1(self, item1): self.item1 = item1 - def get_item2(self): return self.item2 - def set_item2(self, item2): self.item2 = item2 - def hasContent_(self): - if ( - self.item1 is not None or - self.item2 is not None - ): - return True - else: - return False - def export(self, outfile, level, namespace_='', name_='containerType', namespacedef_='', pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None: - name_ = self.original_tagname_ - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self.exportAttributes(outfile, level, already_processed, namespace_, name_='containerType') - if self.hasContent_(): - outfile.write('>%s' % (eol_, )) - self.exportChildren(outfile, level + 1, namespace_='', name_='containerType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='containerType'): - pass - def exportChildren(self, outfile, level, namespace_='', name_='containerType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.item1 is not None: - self.item1.export(outfile, level, namespace_, name_='item1', pretty_print=pretty_print) - if self.item2 is not None: - self.item2.export(outfile, level, namespace_, name_='item2', pretty_print=pretty_print) - def build(self, node): - already_processed = set() - self.buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - return self - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'item1': - obj_ = classAType.factory() - obj_.build(child_) - self.item1 = obj_ - obj_.original_tagname_ = 'item1' - elif nodeName_ == 'item2': - obj_ = classBType.factory() - obj_.build(child_) - self.item2 = obj_ - obj_.original_tagname_ = 'item2' -# end class containerType - - -class classAType(GeneratedsSuper): - member_data_items_ = [ - MemberSpec_('inner', 'innerType', 0), - ] - subclass = None - superclass = None - def __init__(self, inner=None): - self.original_tagname_ = None - self.inner = inner - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, classAType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if classAType.subclass: - return classAType.subclass(*args_, **kwargs_) - else: - return classAType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_inner(self): return self.inner - def set_inner(self, inner): self.inner = inner - def hasContent_(self): - if ( - self.inner is not None - ): - return True - else: - return False - def export(self, outfile, level, namespace_='', name_='classAType', namespacedef_='', pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None: - name_ = self.original_tagname_ - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self.exportAttributes(outfile, level, already_processed, namespace_, name_='classAType') - if self.hasContent_(): - outfile.write('>%s' % (eol_, )) - self.exportChildren(outfile, level + 1, namespace_='', name_='classAType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='classAType'): - pass - def exportChildren(self, outfile, level, namespace_='', name_='classAType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.inner is not None: - self.inner.export(outfile, level, namespace_, name_='inner', pretty_print=pretty_print) - def build(self, node): - already_processed = set() - self.buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - return self - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'inner': - obj_ = innerType.factory() - obj_.build(child_) - self.inner = obj_ - obj_.original_tagname_ = 'inner' -# end class classAType - - -class classBType(GeneratedsSuper): - member_data_items_ = [ - MemberSpec_('inner', 'innerType1', 0), - ] - subclass = None - superclass = None - def __init__(self, inner=None): - self.original_tagname_ = None - self.inner = inner - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, classBType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if classBType.subclass: - return classBType.subclass(*args_, **kwargs_) - else: - return classBType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_inner(self): return self.inner - def set_inner(self, inner): self.inner = inner - def hasContent_(self): - if ( - self.inner is not None - ): - return True - else: - return False - def export(self, outfile, level, namespace_='', name_='classBType', namespacedef_='', pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None: - name_ = self.original_tagname_ - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self.exportAttributes(outfile, level, already_processed, namespace_, name_='classBType') - if self.hasContent_(): - outfile.write('>%s' % (eol_, )) - self.exportChildren(outfile, level + 1, namespace_='', name_='classBType', pretty_print=pretty_print) - showIndent(outfile, level, pretty_print) - outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='classBType'): - pass - def exportChildren(self, outfile, level, namespace_='', name_='classBType', fromsubclass_=False, pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.inner is not None: - self.inner.export(outfile, level, namespace_, name_='inner', pretty_print=pretty_print) - def build(self, node): - already_processed = set() - self.buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - return self - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'inner': - obj_ = innerType1.factory() - obj_.build(child_) - self.inner = obj_ - obj_.original_tagname_ = 'inner' -# end class classBType - - -class innerType(GeneratedsSuper): - member_data_items_ = [ - MemberSpec_('attrA1', 'xs:string', 0), - MemberSpec_('attrA2', 'xs:string', 0), - ] - subclass = None - superclass = None - def __init__(self, attrA1=None, attrA2=None): - self.original_tagname_ = None - self.attrA1 = _cast(None, attrA1) - self.attrA2 = _cast(None, attrA2) - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, innerType) - if subclass is not None: - return subclass(*args_, **kwargs_) - if innerType.subclass: - return innerType.subclass(*args_, **kwargs_) - else: - return innerType(*args_, **kwargs_) - factory = staticmethod(factory) - def get_attrA1(self): return self.attrA1 - def set_attrA1(self, attrA1): self.attrA1 = attrA1 - def get_attrA2(self): return self.attrA2 - def set_attrA2(self, attrA2): self.attrA2 = attrA2 - def hasContent_(self): - if ( - - ): - return True - else: - return False - def export(self, outfile, level, namespace_='', name_='innerType', namespacedef_='', pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None: - name_ = self.original_tagname_ - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self.exportAttributes(outfile, level, already_processed, namespace_, name_='innerType') - if self.hasContent_(): - outfile.write('>%s' % (eol_, )) - self.exportChildren(outfile, level + 1, namespace_='', name_='innerType', pretty_print=pretty_print) - outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='innerType'): - if self.attrA1 is not None and 'attrA1' not in already_processed: - already_processed.add('attrA1') - outfile.write(' attrA1=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.attrA1), input_name='attrA1')), )) - if self.attrA2 is not None and 'attrA2' not in already_processed: - already_processed.add('attrA2') - outfile.write(' attrA2=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.attrA2), input_name='attrA2')), )) - def exportChildren(self, outfile, level, namespace_='', name_='innerType', fromsubclass_=False, pretty_print=True): - pass - def build(self, node): - already_processed = set() - self.buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - return self - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('attrA1', node) - if value is not None and 'attrA1' not in already_processed: - already_processed.add('attrA1') - self.attrA1 = value - value = find_attr_value_('attrA2', node) - if value is not None and 'attrA2' not in already_processed: - already_processed.add('attrA2') - self.attrA2 = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class innerType - - -class innerType1(GeneratedsSuper): - member_data_items_ = [ - MemberSpec_('attrB1', 'xs:string', 0), - MemberSpec_('attrB2', 'xs:string', 0), - ] - subclass = None - superclass = None - def __init__(self, attrB1=None, attrB2=None): - self.original_tagname_ = None - self.attrB1 = _cast(None, attrB1) - self.attrB2 = _cast(None, attrB2) - def factory(*args_, **kwargs_): - if CurrentSubclassModule_ is not None: - subclass = getSubclassFromModule_( - CurrentSubclassModule_, innerType1) - if subclass is not None: - return subclass(*args_, **kwargs_) - if innerType1.subclass: - return innerType1.subclass(*args_, **kwargs_) - else: - return innerType1(*args_, **kwargs_) - factory = staticmethod(factory) - def get_attrB1(self): return self.attrB1 - def set_attrB1(self, attrB1): self.attrB1 = attrB1 - def get_attrB2(self): return self.attrB2 - def set_attrB2(self, attrB2): self.attrB2 = attrB2 - def hasContent_(self): - if ( - - ): - return True - else: - return False - def export(self, outfile, level, namespace_='', name_='innerType1', namespacedef_='', pretty_print=True): - if pretty_print: - eol_ = '\n' - else: - eol_ = '' - if self.original_tagname_ is not None: - name_ = self.original_tagname_ - showIndent(outfile, level, pretty_print) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = set() - self.exportAttributes(outfile, level, already_processed, namespace_, name_='innerType1') - if self.hasContent_(): - outfile.write('>%s' % (eol_, )) - self.exportChildren(outfile, level + 1, namespace_='', name_='innerType1', pretty_print=pretty_print) - outfile.write('</%s%s>%s' % (namespace_, name_, eol_)) - else: - outfile.write('/>%s' % (eol_, )) - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='innerType1'): - if self.attrB1 is not None and 'attrB1' not in already_processed: - already_processed.add('attrB1') - outfile.write(' attrB1=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.attrB1), input_name='attrB1')), )) - if self.attrB2 is not None and 'attrB2' not in already_processed: - already_processed.add('attrB2') - outfile.write(' attrB2=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.attrB2), input_name='attrB2')), )) - def exportChildren(self, outfile, level, namespace_='', name_='innerType1', fromsubclass_=False, pretty_print=True): - pass - def build(self, node): - already_processed = set() - self.buildAttributes(node, node.attrib, already_processed) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - return self - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('attrB1', node) - if value is not None and 'attrB1' not in already_processed: - already_processed.add('attrB1') - self.attrB1 = value - value = find_attr_value_('attrB2', node) - if value is not None and 'attrB2' not in already_processed: - already_processed.add('attrB2') - self.attrB2 = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class innerType1 - - -GDSClassesMapping = { - 'classA': classAType, - 'classB': classBType, - 'container': containerType, - 'inner': innerType1, - 'item1': classAType, - 'item2': classBType, -} - - -USAGE_TEXT = """ -Usage: python <Parser>.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 = GDSClassesMapping.get(tag) - if rootClass is None: - rootClass = globals().get(tag) - return tag, rootClass - - -def parse(inFileName, silence=False): - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - if not silence: - sys.stdout.write('<?xml version="1.0" ?>\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='', - pretty_print=True) - return rootObj - - -def parseEtree(inFileName, silence=False): - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - mapping = {} - rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping) - reverse_mapping = rootObj.gds_reverse_node_mapping(mapping) - if not silence: - content = etree_.tostring( - rootElement, pretty_print=True, - xml_declaration=True, encoding="utf-8") - sys.stdout.write(content) - sys.stdout.write('\n') - return rootObj, rootElement, mapping, reverse_mapping - - -def parseString(inString, silence=False): - from StringIO import StringIO - parser = None - doc = parsexml_(StringIO(inString), parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - if not silence: - sys.stdout.write('<?xml version="1.0" ?>\n') - rootObj.export( - sys.stdout, 0, name_=rootTag, - namespacedef_='') - return rootObj - - -def parseLiteral(inFileName, silence=False): - parser = None - doc = parsexml_(inFileName, parser) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'containerType' - rootClass = containerType - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None - if not silence: - sys.stdout.write('#from nested_def2_sup import *\n\n') - sys.stdout.write('import nested_def2_sup as model_\n\n') - sys.stdout.write('rootObj = model_.rootClass(\n') - rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) - sys.stdout.write(')\n') - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - - -__all__ = [ - "classAType", - "classBType", - "containerType", - "innerType", - "innerType1" -] diff --git a/tutorial/generateds_tutorial.html b/tutorial/generateds_tutorial.html index f0388da4973b316ee4bc8f5ec3e20e5b26426d76..95260f7aa6435b93f2ef89aea15bdf6f1eb72464 100644 --- a/tutorial/generateds_tutorial.html +++ b/tutorial/generateds_tutorial.html @@ -219,7 +219,7 @@ They are used by updateversion.py. --> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.22b</td> +<tr class="field"><th class="field-name">revision:</th><td class="field-body">2.23a</td> </tr> </tbody> </table> @@ -228,7 +228,7 @@ They are used by updateversion.py. --> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">date:</th><td class="field-body">April 20, 2016</td> +<tr class="field"><th class="field-name">date:</th><td class="field-body">September 14, 2016</td> </tr> </tbody> </table> @@ -1210,7 +1210,7 @@ named <tt class="docutils literal">garden_api.py</tt>, you can create an instanc <div class="footer"> <hr class="footer" /> <a class="reference external" href="generateds_tutorial.txt">View document source</a>. -Generated on: 2016-04-21 00:07 UTC. +Generated on: 2016-09-14 18:26 UTC. Generated by <a class="reference external" href="http://docutils.sourceforge.net/">Docutils</a> from <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> source. </div> diff --git a/tutorial/generateds_tutorial.txt b/tutorial/generateds_tutorial.txt index 284cd931754e522ba9ff00242368a3ea086a081d..b8c51a102bfcbcb6a5de12444e9e015dfa446ce8 100644 --- a/tutorial/generateds_tutorial.txt +++ b/tutorial/generateds_tutorial.txt @@ -11,7 +11,7 @@ generateDS -- Introduction and Tutorial .. version -:revision: 2.22b +:revision: 2.23a .. version diff --git a/tutorial/generateds_tutorial.zip b/tutorial/generateds_tutorial.zip index c4d2106650554582769f23f527c2ac60244d8ce8..f04f23a34a619a12fb46d87854fc0a8f89142bff 100644 Binary files a/tutorial/generateds_tutorial.zip and b/tutorial/generateds_tutorial.zip differ