/demo/kekule.py

https://github.com/pombredanne/amara · Python · 89 lines · 67 code · 12 blank · 10 comment · 19 complexity · 2a86323048f6dc0be39feef5bc4d9e88 MD5 · raw file

  1. import sys
  2. import amara
  3. from amara import tree
  4. from amara.writers.struct import *
  5. #from amara.namespaces import *
  6. INDENT_STR = ' '
  7. def srewrite(source, **kwargs):
  8. doc = amara.parse(source)
  9. def handle_node(node, indent=0):
  10. empty = True
  11. if isinstance(node, tree.text):
  12. yield repr(node.xml_value)
  13. elif isinstance(node, tree.entity):
  14. yield INDENT_STR*indent + 'ROOT('
  15. for child in node.xml_children:
  16. empty = False
  17. yield '\n'
  18. for chunk in handle_node(child, indent+1):
  19. yield chunk
  20. yield (not empty)*INDENT_STR*indent + ')\n'
  21. elif isinstance(node, tree.element):
  22. yield INDENT_STR*indent + 'E('
  23. yield repr((node.xml_namespace, node.xml_local)) if node.xml_namespace else repr(node.xml_local)
  24. if node.xml_attributes:
  25. yield repr(dict(node.xml_attributes))
  26. for child in node.xml_children:
  27. empty = False
  28. yield '\n'
  29. for chunk in handle_node(child, indent+1):
  30. yield chunk
  31. yield (not empty)*INDENT_STR*indent + ')\n'
  32. for chunk in handle_node(doc): yield chunk
  33. return
  34. def launch(source, **kwargs):
  35. print kwargs['srewrite']
  36. if kwargs.get('srewrite', True):
  37. print ''.join(srewrite(source, **kwargs))
  38. return
  39. #Ideas borrowed from
  40. # http://www.artima.com/forums/flat.jsp?forum=106&thread=4829
  41. def command_line_prep():
  42. from optparse import OptionParser
  43. usage = "Amara 2.x. Tool to generate code to generate XML.\n"
  44. usage += "python -m 'amara.tools.kekule' [options] source"
  45. parser = OptionParser(usage=usage)
  46. parser.add_option("--struct-rewrite",
  47. action="store_true", dest="srewrite", default=True,
  48. help="Output a skeleton of structwriter code corresponding to the given XML")
  49. parser.add_option("-S", "--struct",
  50. action="store_true", dest="structw", default=True,
  51. help="Output code for Amara structwriter")
  52. return parser
  53. def main(argv=None):
  54. #But with better integration of entry points
  55. if argv is None:
  56. argv = sys.argv
  57. # By default, optparse usage errors are terminated by SystemExit
  58. try:
  59. optparser = command_line_prep()
  60. options, args = optparser.parse_args(argv[1:])
  61. # Process mandatory arguments with IndexError try...except blocks
  62. try:
  63. source = args[0]
  64. except IndexError:
  65. optparser.error("Missing source kekule")
  66. except SystemExit, status:
  67. return status
  68. # Perform additional setup work here before dispatching to run()
  69. # Detectable errors encountered here should be handled and a status
  70. # code of 1 should be returned. Note, this would be the default code
  71. # for a SystemExit exception with a string message.
  72. if source == '-':
  73. source = sys.stdin
  74. launch(source, structw=options.structw, srewrite=options.srewrite)
  75. return
  76. if __name__ == "__main__":
  77. sys.exit(main(sys.argv))