_xsyn_includes.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. def get_include_callback():
  2. """
  3. .. function: get_include_callback returns function that processes each DOM element to get xsyn include from it, and it's aware of directory with all the xsyns.
  4. :param xsyn_dir directory with xsyns.
  5. """
  6. def get_include(element):
  7. """
  8. .. function: get_include returns list of includes from this DOM element.
  9. :param element DOM element.
  10. """
  11. res = []
  12. if element.nodeType == element.ELEMENT_NODE and element.nodeName == "parse:include":
  13. attrs = element.attributes
  14. for i in xrange(attrs.length):
  15. attr = attrs.item(i)
  16. if attr.nodeName == "path":
  17. include_filename = attr.nodeValue
  18. res.append(include_filename)
  19. return res
  20. return get_include
  21. def traverse_xsyn(element, on_element):
  22. """
  23. .. function: traverse_xsyn traverses element and returns concatenated lists of calling on_element of each element.
  24. :param element element in DOM.
  25. :param on_element callback on element that returns list of values.
  26. """
  27. res = on_element(element)
  28. for child in element.childNodes:
  29. child_results = traverse_xsyn(child, on_element)
  30. res += child_results
  31. return res
  32. def process_xsyn(filepath, on_element):
  33. """
  34. .. function: process_xsyn processes xsyn file and return concatenated list of calling on_element on each DOM element.
  35. :param filepath path to xsyn file
  36. :param on_element callback called on each element in xsyn that returns list of values.
  37. """
  38. # keep a stack of filepathes if on_element calls process_xsyn recursively
  39. with open(filepath) as xsyn_file:
  40. from xml.dom.minidom import parse
  41. tree = parse(xsyn_file)
  42. tree.normalize()
  43. res = traverse_xsyn(tree, on_element)
  44. return res
  45. def get_all_includes(filepath):
  46. callback = get_include_callback()
  47. return process_xsyn(filepath, callback)