Advertisement
marksweb

ParseXML

Apr 26th, 2012
594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 20.47 KB | None | 0 0
  1. from lxml import etree as ET
  2. from decimal import *
  3. import importArgs as Args
  4. import os, re, sys
  5.  
  6. class Parser():
  7.     """
  8.     File usage: xml2.py <path to script & output dir> <input XML> <output file>
  9.  
  10.     Shortfalls of this script;
  11.     If an XML comment spans multiple lines without a <!-- on each line, only the first will be commented in the Python
  12.  
  13.     Comments inside a list of arguments for execute method will likely need to be removed from the output, these aren't
  14.     ignored incase something in the args is required but not defined
  15.  
  16.     if an <if> has it's <condition> somewhere other than the first or 2nd tag within and doesn't appear after <then>
  17.     or <else> you'll probably see `if None` in the output because of the comment appearing where parse_if expects <condition>
  18.  
  19.     The following processes need to be created manually, although corresponding data from XMl should be printed in
  20.     the generated Python;
  21.         Import
  22.         Delete
  23.         Dialog
  24.         SetNextStage
  25.  
  26.     ParserUtils.py isn't currently implemented compeltely, but intended for output use, so the following also require attention;
  27.         Errors
  28.         RegularExp
  29.         Requried
  30.     """
  31.  
  32.     def __init__(self):
  33.         self.output_list = []  # collected output lines
  34.         self.requried = ''
  35.         self.decimalDict = {}
  36.         self.varDict = {}
  37.         self.allDecimalDict = {}
  38.         self.importArgs = []
  39.         self.il = 0            # indentation level
  40.  
  41.     def __iter__(self):
  42.         return iter(self.output_list)
  43.  
  44.     def out(self, s):
  45.         """Output the indented string to the output list."""
  46.         self.output_list.append('    ' * self.il + s)
  47.  
  48.     def indent(self, incr=1):
  49.         """Increase the indentation level."""
  50.         self.il += incr
  51.  
  52.     def dedent(self, incr=1):
  53.         """Decrease the indentation level."""
  54.         self.il -= incr
  55.  
  56.     def parse(self, elem):
  57.         """Call the parser of the elem.tag name.
  58.  
  59.         The tag name appended to "parse_" and then the name of that
  60.         function is called.  If the function is not defined, then
  61.         self.parse_undefined() is called.
  62.         """
  63.         fn_name = 'parse_{0}'.format(elem.tag)
  64.         try:fn = getattr(self, fn_name)
  65.         except AttributeError:fn = self.parse_undefined
  66.         return fn(elem)
  67.  
  68.     def loop(self, elem):
  69.         """Helper method to loop through the child elements."""
  70.         for e in elem:
  71.             if e.sourceline == 339:
  72.                 print e.tag + ' ' + e.attrib['id']
  73.                 self.parse(e)
  74.             else:
  75.                 self.parse(e)
  76.  
  77.     def parseXMLfile(self, script):
  78.         """Reads the XML file and starts parsing from the root element."""
  79.  
  80.         events = ("start", "end", "comment", "pi")
  81.         try:
  82.             context = ET.iterparse(script, events=events)
  83.             context = iter(context)
  84.             event, root = context.next()
  85.             for event, elem in context:
  86.                 if event == "end" and elem.tag == "stage":
  87.                     self.parse(elem)
  88.                     root.clear()
  89.         except IOError:
  90.             self.out("## Error : Cannot parse script" + script)
  91.  
  92.     ###################### ELEMENT PARSERS #######################
  93.  
  94.     def parse_undefined(self, elem):
  95.         """Called for the element that has no parser defined."""
  96.         self.out('## {0} '.format(elem.text))
  97.  
  98.     def parse_script(self, elem):
  99.         self.loop(elem)
  100.  
  101.     def parse_stage(self, elem):
  102.         self.out('')
  103.         self.out('class {0}():'.format(elem.attrib['id']))
  104.         self.indent()
  105.         self.loop(elem)
  106.         self.dedent()
  107.  
  108.     def parse_initialise(self, elem):
  109.         self.out(','.join(self.importArgs))
  110.         vars = self.passed_vars(elem)
  111.         if not vars: self.out('def {initialise}(self):'.format(initialise = elem.tag))
  112.         else: self.out('def {initialise}(self, {vars}):'.format(initialise = elem.tag, vars = ", ".join(vars)))
  113.         self.indent()
  114.         for e in elem:
  115.             if e.tag == 'decimal': d = self.init_decimals(e)
  116.             elif e.tag == 'variable': v = self.init_vars(e)
  117.         self.loop(elem)
  118.         self.dedent()
  119.  
  120.     def parse_execute(self, elem):
  121.         # possible limitation here with detecting the type of execute tag
  122.         if elem[0].tag == 'required':self.loop(elem)
  123.         else:
  124.             self.out('')
  125.             vars = self.passed_vars(elem)
  126.             if not vars:self.out('def {execute}(self):'.format(execute = elem.tag))
  127.             else:self.out('def {execute}(self, {vars}):'.format(execute = elem.tag, vars = ", ".join(vars)))
  128.             self.indent()
  129.             self.loop(elem)
  130.             self.dedent()
  131.  
  132.     def passed_vars(self, elem):
  133.         passed_vars = []
  134.  
  135.         for e in elem:
  136.             if e.tag == 'variable' or e.tag == 'decimal':
  137.                 passed_vars.append(e.attrib['id'])
  138.  
  139.         passed_vars = list(set(passed_vars))
  140.         return passed_vars
  141.  
  142.     def collect_attrs(self, elem, tag, attr):
  143.         elemVars = [var for var in self.get_attrs(elem, tag, attr)]
  144.         # Remove duplicate variables from list
  145.         elemVars = list(set(elemVars))
  146.         return elemVars
  147.  
  148.  
  149.     def get_attrs(self, elem, tag, attr):
  150.         """Return attribute `attr` of `tag` child elements of `elem`."""
  151.  
  152.         # If an element has any children loop them
  153.         if len(elem):
  154.             for e in elem:
  155.                 # Recursively call this func, yield each result:
  156.                 for attribute in self.get_attrs(e, tag, attr):
  157.                     yield attribute
  158.  
  159.         # Otherwise, check if elem is of type `tag` with attribute of `attr`,
  160.         # if so yield the value of the attribute.
  161.         if elem.tag == 'variable':
  162.             if attr in elem.attrib:
  163.                 yield elem.attrib[attr]
  164.         elif elem.tag == 'required':
  165.             if attr in elem.attrib:
  166.                 yield elem.attrib[attr]
  167.  
  168.     def parse_decimal(self, elem):
  169.         '''
  170.         when we get a line of xml for a decimal value it is now ignored as init_decimals
  171.         handles these all at the beginning of the init/execute methods
  172.         '''
  173.         self.create_dec_dict(self.allDecimalDict, elem)
  174.  
  175.     def init_decimals(self, elem):
  176.         id_ = elem.attrib['id']
  177.         value = elem.attrib['value']
  178.         decDict = {}
  179.         self.decimalDict = self.create_dec_dict(decDict, elem)
  180.         ##
  181.         # Old parse_decimal code
  182.         if self.is_number(value) is True:
  183.             try:
  184.                 self.out("{id} = decimal.Decimal('{value}').quantize(decimal.Decimal('{dp}'), rounding=decimal.{rounding})".format(id= id_, value= value, dp= self.decimalDict[id_]['dp'], rounding= self.decimalDict[id_]['rounding']))
  185.             except:
  186.                 print 'Check setVariableValue for {0}'.format(id_)
  187.         else:
  188.             try:
  189.                 self.out("{id} = decimal.Decimal({value}).quantize(decimal.Decimal('{dp}'), rounding=decimal.{rounding})".format(id= id_, value= value, dp= self.decimalDict[id_]['dp'], rounding= self.decimalDict[id_]['rounding']))
  190.             except:
  191.                 print 'Check setVariableValue for {0}'.format(id_)
  192.         return self.decimalDict
  193.  
  194.     def create_dec_dict(self, d, elem):
  195.         ROUNDZERO =     "1"
  196.         ROUNDONE =      "0.1"
  197.         ROUNDTWO =      "0.01"
  198.         ROUNDTHREE =    "0.001"
  199.         ROUNDFOUR =     "0.0001"
  200.         ROUNDFIVE =     "0.00001"
  201.         ROUNDSIX =      "0.000001"
  202.  
  203.         ROUND_DOWN = 'ROUND_DOWN'
  204.         ROUND_HALF_UP = 'ROUND_HALF_UP'
  205.         ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  206.         ROUND_CEILING = 'ROUND_CEILING'
  207.         ROUND_FLOOR = 'ROUND_FLOOR'
  208.         ROUND_UP = 'ROUND_UP'
  209.         ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  210.         ROUND_05UP = 'ROUND_05UP'
  211.         ROUND_FIVE_DOWN = 'ROUND_FIVE_DOWN'
  212.  
  213.         decimalPlacesDict = {"0":ROUNDZERO, "1":ROUNDONE, "2":ROUNDTWO, "3":ROUNDTHREE, "4":ROUNDFOUR, "5":ROUNDFIVE, "6":ROUNDSIX}
  214.         roundingTypeDict = {"ROUND_CEILING":ROUND_CEILING, "ROUND_DOWN":ROUND_DOWN, "ROUND_FLOOR":ROUND_FLOOR, "ROUND_HALF_DOWN":ROUND_HALF_DOWN, "ROUND_HALF_EVEN":ROUND_HALF_EVEN, "ROUND_HALF_UP":ROUND_HALF_UP, "ROUND_UP":ROUND_UP, "ROUND_FIVE_DOWN":ROUND_FIVE_DOWN}
  215.         id_ = elem.attrib['id']
  216.  
  217.         if elem.attrib['value'] == '':
  218.             value = None
  219.         else:
  220.             value = elem.attrib['value']
  221.             value = re.sub(r'\$','',value)
  222.  
  223.         if ('decimalPlaces' in elem.attrib and 'roundingType' in elem.attrib):
  224.             decimalPlaces = decimalPlacesDict[elem.attrib["decimalPlaces"]]
  225.             roundingType = roundingTypeDict[elem.attrib["roundingType"]]
  226.             #decimalDict[elem.attrib['id']] = 'Decimal({0}).quantize(Decimal({1}), rounding={2}'.format(value, decimalPlaces, roundingType)
  227.             d[elem.attrib['id']] = {'value' : value, 'dp' : Decimal(str(decimalPlaces)), 'rounding' : roundingType}
  228.  
  229.         elif 'roundingType' in elem.attrib:
  230.             roundingType = roundingTypeDict[elem.attrib["roundingType"]]
  231.             #decimalDict[elem.attrib['id']] = 'value : {0}, dp : Decimal(0.01), rounding : {1}'.format(value, roundingType)
  232.             d[elem.attrib['id']] = {'value' : value, 'dp' : Decimal(str(0.01)), 'rounding' : roundingType}
  233.  
  234.         elif 'decimalPlaces' in elem.attrib:
  235.             decimalPlaces = decimalPlacesDict[elem.attrib["decimalPlaces"]]
  236.             d[elem.attrib['id']] = {'value' : value, 'dp' : Decimal(str(decimalPlaces)), 'rounding' : ROUND_HALF_UP}
  237.  
  238.         else:
  239.             #decimalDict[elem.attrib['id']] = 'Decimal({0}).quantize(Decimal(0.01), rounding=ROUND_HALF_UP'.format(value)
  240.             d[elem.attrib['id']] = {'value': value, 'dp': Decimal(str(0.01)), 'rounding' : ROUND_HALF_UP}
  241.         return d
  242.  
  243.     def init_vars(self, elem):
  244.         varDict = {}
  245.         id_ = elem.attrib['id']
  246.         value = elem.attrib['value']
  247.         newValue = re.sub(r'\$','', value)
  248.         self.varDict = self.create_var_dict(varDict, elem)
  249.         ##
  250.         # Old parse_variable code
  251.         if not 'index' in elem.attrib:
  252.             errorID = self.collect_attrs(elem, 'required', 'errorID')
  253.             execute = elem.find('execute')
  254.  
  255.             try: errorID = execute.attrib['errorID']
  256.             except: pass
  257.  
  258.             # Conversion of the value to the type because of the later repr().
  259.             value = elem.attrib['value']
  260.             etype = elem.attrib['type']
  261.  
  262.             newValue = re.sub(r'\$', '', value)
  263.  
  264.             id_ = elem.attrib['id']
  265.  
  266.             if execute is not None:
  267.                 required = execute[0]
  268.                 if required.tag == "required":
  269.                     self.var_required(required, value, etype, errorID)
  270.  
  271.             if 'startString' in elem.attrib:
  272.                 if id_ in self.varDict.keys():
  273.                     self.out('if {id} is None:'.format(id= id_))
  274.                     self.indent()
  275.                 else:
  276.                     pass
  277.                 self.out('{id} = {value}[{start}:{end}]'.format(id= id_, value= newValue, start= elem.attrib['startString'], end= elem.attrib['endString']))
  278.             else:
  279.                 if id_ in self.varDict.keys():
  280.                     self.out('if {id} is None:'.format(id= id_))
  281.                     self.indent()
  282.                 else:
  283.                     pass
  284.                 if elem.attrib['type'] == 'String':
  285.                     self.out("{id} = {value}".format(id= id_, value= repr(newValue)))
  286.                 elif elem.attrib['type'] == 'Integer' and elem.attrib['value'] is '':
  287.                     # incase an Int isn't defined, stops var = <blank> being written
  288.                     self.out("{id} = 0".format(id= id_))
  289.                 elif elem.attrib['type'] == 'HTML' and elem.attrib['value'] is '':
  290.                     self.out("{id} = ''".format(id= id_))
  291.                 elif elem.attrib['type'] == 'Date' and elem.attrib['value'] is not '':
  292.                     self.out("{id} = '{value}'".format(id= id_, value= elem.attrib['value']))
  293.                 elif elem.attrib['type'] == 'Date' and elem.attrib['value'] is '':
  294.                     self.out("{id} = ''".format(id = id_))
  295.                 else:
  296.                     self.out('{id} = {value}'.format(id= id_, value= value))
  297.                 if id_ in self.varDict.keys():
  298.                     self.dedent()
  299.                 else:
  300.                     pass
  301.         return self.varDict
  302.  
  303.     def create_var_dict(self, d, elem):
  304.         id_ = elem.attrib['id']
  305.         value = elem.attrib['value']
  306.         newValue = re.sub(r'\$','', value)
  307.         try:
  308.             d[elem.attrib['id']] = {'value' : newValue, 'type' : elem.attrib['type']}
  309.  
  310.         except KeyError:
  311.             print '{0} on {1}'.format(elem.tag, unicode(elem.sourceline))
  312.         return d
  313.  
  314.     def parse_variable(self, elem):
  315.         '''
  316.         when we get a line of xml for a variable value it is now ignored as init_vars
  317.         handles these all at the beginning of the init/execute methods
  318.         '''
  319.         pass
  320.  
  321.     def parse_variableArray(self, elem):
  322.         array = elem.attrib['id']
  323.         value = re.sub(r'\$','',elem.attrib['value'])
  324.  
  325.         self.out("{0}.append('''{1}''')".format(array, value))
  326.  
  327.  
  328.     def parse_setVariableValue(self, elem):
  329.         if elem.text:
  330.             text = re.sub(r'\$','',elem.text)
  331.             id_ = elem.attrib['id']
  332.  
  333.             if id_ in self.allDecimalDict.keys():
  334.                 if self.is_number(text) is True:
  335.                     try:
  336.                         self.out("{id} = decimal.Decimal('{text}').quantize(decimal.Decimal('{dp}'), rounding=decimal.{rounding})".format(id= id_, text= text, dp= self.allDecimalDict[id_]['dp'], rounding= self.allDecimalDict[id_]['rounding']))
  337.                     except:
  338.                         print 'Check setVariableValue for {0}'.format(id_)
  339.                 else:
  340.                     try:
  341.                         self.out("{id} = decimal.Decimal({text}).quantize(decimal.Decimal('{dp}'), rounding=decimal.{rounding})".format(id= id_, text= text, dp= self.allDecimalDict[id_]['dp'], rounding= self.allDecimalDict[id_]['rounding']))
  342.                     except:
  343.                         print 'Check setVariableValue for {0}'.format(id_)
  344.             elif text in self.varDict.keys():
  345.                 # value to be assigned is a variable
  346.                 try:
  347.                     self.out('{id} = {text}'.format(id= id_,text= text))
  348.                 except:
  349.                     print 'Check setVariableValue for {0}, {1}'.format(id_, text)
  350.             elif id_ in self.varDict.keys():
  351.                 try:
  352.                     if self.varDict[id_]['type'] == 'String':
  353.                         self.out('{id} = {text}'.format(id= id_, text= repr(text)))
  354.                     elif self.varDict[id_]['type'] == 'Boolean':
  355.                         self.out('{id} = {text}'.format(id= id_, text= text))
  356.                     elif self.varDict[id_]['type'] == 'Integer':
  357.                         self.out('{id} = {text}'.format(id= id_, text= text))
  358.                 except:
  359.                     print 'Check setVariableValue for {0}'.format(id_)
  360.             else:
  361.                 self.out("## this isn't in a dict so no type check done. Line {0}".format(unicode(elem.sourceline)))
  362.                 self.out('{id} = {text}'.format(id= id_,text= text))
  363.         else:
  364.             self.out("{id} = ''".format(id= elem.attrib['id']))
  365.             print '{tag} has no CDATA. Sourceline: {line}'.format(tag= elem.tag, line= unicode(elem.sourceline))
  366.  
  367.  
  368.     def parse_executeMethod(self, elem):
  369.         a = elem.attrib
  370.         argumentsTag = elem.find('arguments')
  371.         returnTag = elem.find('return')
  372.         argVars, returnVars = [], []
  373.  
  374.         self.out('import ' + a['class'])
  375.  
  376.         for arg in argumentsTag:
  377.             # variables & values
  378.             try:
  379.                 if arg.tag == "value": argVars.append(arg.text)
  380.                 elif arg.tag == "variable": argVars.append(arg.attrib['id'])
  381.             #else: print 'Problem or Comment in Args, {0}, on line {1}'.format(arg.text, unicode(elem.sourceline))
  382.             except KeyError:
  383.                 self.out('KeyError on line {line} with: {tag}'.format(line= arg.sourceline, tag= arg.tag))
  384.  
  385.         for r in returnTag:
  386.             # inside executeMethod return tag
  387.             try: returnVars.append(r.attrib['id'])
  388.             except KeyError:
  389.                 self.out('KeyError on line {line} with: {tag}'.format(line= r.sourceline, tag= r.tag))
  390.  
  391.         # Wait for list of vars
  392.         if len(argVars) > 0:
  393.             self.out('{0}.{1}(*{2})'.format(a['class'], a['method'], argVars))
  394.         else: self.out('{0}.{1}()'.format(a['class'], a['method']))
  395.  
  396.         for r in returnTag:
  397.             self.out('{0} = {1}.{2}()'.format(r.attrib['id'], a['class'], a['method']))
  398.  
  399.  
  400.     def parse_if(self, elem):
  401.         if elem[0].tag == 'condition':
  402.             condition = self.parse(elem[0])
  403.             #self.out('if {0}, {1}:'.format(unicode(elem.sourceline), condition))   # to debug sourceline when if None
  404.             self.out('if {0}:'.format(condition))
  405.         #if elem[0].tag == "if": self.parse_if(elem)
  406.         elif elem[1].tag == 'condition':
  407.             condition = self.parse(elem[1])
  408.             self.out('if {0}:'.format(condition))
  409.         else:
  410.             self.out("print 'problem on line {0}'".format(unicode(elem.sourceline)))
  411.         self.loop(elem)
  412.  
  413.  
  414.     def parse_condition(self, elem):
  415.         condition = re.sub(r'\$','',elem.text)
  416.         return condition
  417.  
  418.     def parse_then(self, elem):
  419.         ifblock = elem.find('if')
  420.         if ifblock is not None:
  421.             for t in ifblock:
  422.                 if t.tag == 'condition':
  423.                     condition = self.parse(t)
  424.                     self.indent()
  425.                     self.out('')
  426.                     self.out('if {condition}:'.format(condition= condition))
  427.             self.loop(ifblock)
  428.             self.dedent()
  429.         else:
  430.             self.indent()
  431.             #print '{0}. Sourceline: {1}'.format(elem.tag, unicode(elem.sourceline))
  432.             self.loop(elem)
  433.             self.dedent()
  434.  
  435.     def parse_validate(self, elem):
  436.         self.loop(elem)
  437.  
  438.     def parse_else(self, elem):
  439.         ifblock = elem.find('if')
  440.         if ifblock is not None:
  441.             for t in ifblock:
  442.                 if t.tag == 'condition': condition = self.parse(t); self.out(''); self.out('elif {condition}:'.format(condition= condition))
  443.             self.loop(ifblock)
  444.         else:
  445.             self.out('else:')
  446.             self.indent()
  447.             self.loop(elem)
  448.             self.dedent()
  449.  
  450.  
  451.     def parse_regularExpression(self, elem):
  452.         try:
  453.             if elem.attrib['fieldID'] == '': fieldID = None
  454.             else: fieldID = elem.attrib['fieldID']
  455.             if elem.attrib['errorID'] == '': errorID = None
  456.             else: errorID = elem.attrib['errorID']
  457.             pattern = elem.attrib.get('pattern')
  458.             text = elem.text
  459.             self.out('')
  460.             if not pattern: self.out("""utils.regularExp('''{text}''', {field}, {error})""".format(text= text, field= fieldID, error= errorID))
  461.             else: self.out("""utils.regularExp('''{text}''', {field}, {error}, '{pattern}')""".format(text= text, field= fieldID, error= errorID, pattern= pattern))
  462.         except KeyError:
  463.             print '{tag}. Sourceline: {line}'.format(tag= elem.tag, line= unicode(elem.sourceline))
  464.             self.out('## TODO: failed regex on script line {0}'.format(unicode(elem.sourceline)))
  465.  
  466.  
  467.     def parse_updateGUIFieldState(self, elem):
  468.         field = elem.attrib['id']
  469.         text = re.sub(r'\$','',elem.text)
  470.  
  471.         self.out('fieldState = {}')
  472.         self.out('fieldState[{0}] = [{1}]'.format(field, text))
  473.  
  474.  
  475.     def parse_error(self, elem):
  476.         self.out('print "TODO: Error. script line {0}"'.format(unicode(elem.sourceline)))
  477.         self.out('utils.error({text}, {field}, {error})'.format(text= elem.text, field= elem.attrib.get("fieldID"), error= elem.attrib.get("errorID")))
  478.  
  479.  
  480.     def parse_import(self, elem):
  481.         a = elem.attrib
  482.         argumentsTag = elem.find('arguments')
  483.         returnTag = elem.find('return')
  484.         argVars, returnVars = [], []
  485.  
  486.         path = a['path'].split('/')
  487.         path = '{0}{1}'.format('etk.scripts.', '.'.join(path))
  488.         year = re.findall(r"\.(\d{4})\.", path) # find a 4 digit folder name in the path directly following the '.'
  489.         year = ''.join(year)    # convert list to string
  490.         path = re.sub(year, '{0}{1}'.format('yr_',year), path)
  491.  
  492.         self.out('import {0}'.format(path))
  493.         self.out('calc = {path}.{method}()'.format(path= path, method= elem.attrib['stageID']))
  494.  
  495.         for arg in argumentsTag:
  496.             # variables & values
  497.             try:
  498.                 if arg.tag == "value": argVars.append(arg.text)
  499.                 elif arg.tag == "variable": argVars.append(arg.attrib['id'])
  500.             #else: print 'Problem or Comment in Args, {0}, on line {1}'.format(arg.text, unicode(elem.sourceline))
  501.             except KeyError:
  502.                 self.out('## KeyError on line {0} with: {1}'.format(arg.sourceline, arg.tag))
  503.  
  504.         for r in returnTag:
  505.             # inside executeMethod return tag
  506.             try: returnVars.append(r.attrib['id'])
  507.             except KeyError:
  508.                 self.out('## KeyError on line {0} with: {1}'.format(r.sourceline, r.tag))
  509.  
  510.         # Wait for list of vars
  511.         if len(argVars) > 0:
  512.             self.out('{returnvars} = {calc}.initialise({vars})'.format(returnvars = ', '.join(returnVars), calc= 'calc', vars= ', '.join(argVars)))
  513.         else: self.out('TODO: Problem. Check this import: {0}()'.format('calc'))
  514.         self.out('')
  515.  
  516.  
  517.     def parse_dialog(self, elem):
  518.         text = self.parse_escapeString(elem.attrib['text'])
  519.         text.encode('ascii', 'ignore')
  520.         try:
  521.             self.out('')
  522.             self.out('print "TODO: Dialog. {0}"'.format(unicode(elem.sourceline)))
  523.             self.out("## item_dialog(id='{id}', text='''{text}''', type='{type}')".format(id= elem.attrib['id'], text= text, type= elem.attrib['type']))
  524.         except:
  525.             self.out('print "Problem with the Dialog on line {0}" '.format(unicode(elem.sourceline)))
  526.  
  527.     def parse_escapeString(self, s):
  528.         text = re.sub(r'\$','',s)
  529.         escapeString = re.sub(r'\s',' ', text)
  530.         return escapeString
  531.  
  532.     def parse_delete(self, elem):
  533.         self.out('## TODO: Delete. {0}'.format(elem.attrib['id']))
  534.  
  535.     def var_required(self, elem, value, etype, errorID):
  536.         ## value perhaps needs to be the field.getvalue()
  537.         if value == '':
  538.             value = None
  539.         if value is not None:
  540.             value = re.sub(r'\$','', value)
  541.         ## Store this to output with parse_requried
  542.         self.required = "utils.required({value}, {type}, {error})".format(value= value, type= repr(etype), error= "".join(errorID))
  543.  
  544.     def parse_required(self, elem):
  545.         self.out(self.required)
  546.  
  547.     def parse_setNextStage(self, elem):
  548.         self.out('print "TODO: set next stage : {text} line {line}"'.format(text= re.sub(r'\$','',elem.text), line= unicode(elem.sourceline)))
  549.  
  550.     def is_number(self, value):
  551.         """
  552.         Check if a given value is a number or not.
  553.         """
  554.         try:
  555.             float(value) # for int, long and float
  556.         except ValueError:
  557.             try:
  558.                 complex(value) # for complex
  559.             except ValueError:
  560.                 return False
  561.         return True
  562.  
  563. def main():
  564.     if len(sys.argv) is not 3:
  565.         print 'usage: xml2.py <path to script & output dir> <path to import script>'
  566.         sys.exit(1)
  567.  
  568.     try:
  569.         importArgs = Args.importArgs()
  570.         importArgs.parseImportXML(sys.argv[2], sys.argv[1])
  571.     finally:
  572.         parser = Parser()
  573.         folder = sys.argv[1]
  574.         for a in importArgs:
  575.             parser.importArgs.append(a)
  576.         parser.parseXMLfile((os.path.join(folder, 'script.xml')))
  577.         fname = 'newOutput.py'
  578.         outputpath = os.path.join(folder, fname)
  579.         with open(outputpath, 'w') as f:
  580.             f.write('# coding: UTF-8\nfrom etk import decimal\n')
  581.             for s in parser:
  582.                 f.write(s + '\n')
  583.             f.close()
  584.  
  585. if __name__ == '__main__':
  586.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement