You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

333 lines
11 KiB

  1. ################################################################################
  2. # ObjectPath
  3. ctypedef struct _ObjectPath:
  4. const_xmlChar* href
  5. const_xmlChar* name
  6. Py_ssize_t index
  7. cdef object _NO_DEFAULT = object()
  8. cdef class ObjectPath:
  9. """ObjectPath(path)
  10. Immutable object that represents a compiled object path.
  11. Example for a path: 'root.child[1].{other}child[25]'
  12. """
  13. cdef readonly object find
  14. cdef list _path
  15. cdef object _path_str
  16. cdef _ObjectPath* _c_path
  17. cdef Py_ssize_t _path_len
  18. def __init__(self, path):
  19. if python._isString(path):
  20. self._path = _parse_object_path_string(path)
  21. self._path_str = path
  22. else:
  23. self._path = _parse_object_path_list(path)
  24. self._path_str = '.'.join(path)
  25. self._path_len = len(self._path)
  26. self._c_path = _build_object_path_segments(self._path)
  27. self.find = self.__call__
  28. def __dealloc__(self):
  29. if self._c_path is not NULL:
  30. python.lxml_free(self._c_path)
  31. def __str__(self):
  32. return self._path_str
  33. def __call__(self, _Element root not None, *_default):
  34. """Follow the attribute path in the object structure and return the
  35. target attribute value.
  36. If it it not found, either returns a default value (if one was passed
  37. as second argument) or raises AttributeError.
  38. """
  39. if _default:
  40. if len(_default) > 1:
  41. raise TypeError, "invalid number of arguments: needs one or two"
  42. default = _default[0]
  43. else:
  44. default = _NO_DEFAULT
  45. return _find_object_path(root, self._c_path, self._path_len, default)
  46. def hasattr(self, _Element root not None):
  47. "hasattr(self, root)"
  48. try:
  49. _find_object_path(root, self._c_path, self._path_len, _NO_DEFAULT)
  50. except AttributeError:
  51. return False
  52. return True
  53. def setattr(self, _Element root not None, value):
  54. """setattr(self, root, value)
  55. Set the value of the target element in a subtree.
  56. If any of the children on the path does not exist, it is created.
  57. """
  58. _create_object_path(root, self._c_path, self._path_len, 1, value)
  59. def addattr(self, _Element root not None, value):
  60. """addattr(self, root, value)
  61. Append a value to the target element in a subtree.
  62. If any of the children on the path does not exist, it is created.
  63. """
  64. _create_object_path(root, self._c_path, self._path_len, 0, value)
  65. cdef object __MATCH_PATH_SEGMENT = re.compile(
  66. r"(\.?)\s*(?:\{([^}]*)\})?\s*([^.{}\[\]\s]+)\s*(?:\[\s*([-0-9]+)\s*\])?",
  67. re.U).match
  68. cdef tuple _RELATIVE_PATH_SEGMENT = (None, None, 0)
  69. cdef list _parse_object_path_string(_path):
  70. """Parse object path string into a (ns, name, index) list.
  71. """
  72. cdef bint has_dot
  73. cdef unicode path
  74. new_path = []
  75. if isinstance(_path, bytes):
  76. path = (<bytes>_path).decode('ascii')
  77. elif type(_path) is not unicode:
  78. path = unicode(_path)
  79. else:
  80. path = _path
  81. path = path.strip()
  82. if path == '.':
  83. return [_RELATIVE_PATH_SEGMENT]
  84. path_pos = 0
  85. while path:
  86. match = __MATCH_PATH_SEGMENT(path, path_pos)
  87. if match is None:
  88. break
  89. dot, ns, name, index = match.groups()
  90. index = int(index) if index else 0
  91. has_dot = dot == '.'
  92. if not new_path:
  93. if has_dot:
  94. # path '.child' => ignore root
  95. new_path.append(_RELATIVE_PATH_SEGMENT)
  96. elif index:
  97. raise ValueError, "index not allowed on root node"
  98. elif not has_dot:
  99. raise ValueError, "invalid path"
  100. if ns is not None:
  101. ns = python.PyUnicode_AsUTF8String(ns)
  102. name = python.PyUnicode_AsUTF8String(name)
  103. new_path.append( (ns, name, index) )
  104. path_pos = match.end()
  105. if not new_path or len(path) > path_pos:
  106. raise ValueError, "invalid path"
  107. return new_path
  108. cdef list _parse_object_path_list(path):
  109. """Parse object path sequence into a (ns, name, index) list.
  110. """
  111. new_path = []
  112. for item in path:
  113. item = item.strip()
  114. if not new_path and item == '':
  115. # path '.child' => ignore root
  116. ns = name = None
  117. index = 0
  118. else:
  119. ns, name = cetree.getNsTag(item)
  120. c_name = _xcstr(name)
  121. index_pos = tree.xmlStrchr(c_name, c'[')
  122. if index_pos is NULL:
  123. index = 0
  124. else:
  125. index_end = tree.xmlStrchr(index_pos + 1, c']')
  126. if index_end is NULL:
  127. raise ValueError, "index must be enclosed in []"
  128. index = int(index_pos[1:index_end - index_pos])
  129. if not new_path and index != 0:
  130. raise ValueError, "index not allowed on root node"
  131. name = <bytes>c_name[:index_pos - c_name]
  132. new_path.append( (ns, name, index) )
  133. if not new_path:
  134. raise ValueError, "invalid path"
  135. return new_path
  136. cdef _ObjectPath* _build_object_path_segments(list path_list) except NULL:
  137. cdef _ObjectPath* c_path
  138. cdef _ObjectPath* c_path_segments
  139. c_path_segments = <_ObjectPath*>python.lxml_malloc(len(path_list), sizeof(_ObjectPath))
  140. if c_path_segments is NULL:
  141. raise MemoryError()
  142. c_path = c_path_segments
  143. for href, name, index in path_list:
  144. c_path[0].href = _xcstr(href) if href is not None else NULL
  145. c_path[0].name = _xcstr(name) if name is not None else NULL
  146. c_path[0].index = index
  147. c_path += 1
  148. return c_path_segments
  149. cdef _find_object_path(_Element root, _ObjectPath* c_path, Py_ssize_t c_path_len, default_value):
  150. """Follow the path to find the target element.
  151. """
  152. cdef tree.xmlNode* c_node
  153. cdef Py_ssize_t c_index
  154. c_node = root._c_node
  155. c_name = c_path[0].name
  156. c_href = c_path[0].href
  157. if c_href is NULL or c_href[0] == c'\0':
  158. c_href = tree._getNs(c_node)
  159. if not cetree.tagMatches(c_node, c_href, c_name):
  160. if default_value is not _NO_DEFAULT:
  161. return default_value
  162. else:
  163. raise ValueError(
  164. f"root element does not match: need {cetree.namespacedNameFromNsName(c_href, c_name)}, got {root.tag}")
  165. while c_node is not NULL:
  166. c_path_len -= 1
  167. if c_path_len <= 0:
  168. break
  169. c_path += 1
  170. if c_path[0].href is not NULL:
  171. c_href = c_path[0].href # otherwise: keep parent namespace
  172. c_name = tree.xmlDictExists(c_node.doc.dict, c_path[0].name, -1)
  173. if c_name is NULL:
  174. c_name = c_path[0].name
  175. c_node = NULL
  176. break
  177. c_index = c_path[0].index
  178. c_node = c_node.last if c_index < 0 else c_node.children
  179. c_node = _findFollowingSibling(c_node, c_href, c_name, c_index)
  180. if c_node is not NULL:
  181. return cetree.elementFactory(root._doc, c_node)
  182. elif default_value is not _NO_DEFAULT:
  183. return default_value
  184. else:
  185. tag = cetree.namespacedNameFromNsName(c_href, c_name)
  186. raise AttributeError, f"no such child: {tag}"
  187. cdef _create_object_path(_Element root, _ObjectPath* c_path,
  188. Py_ssize_t c_path_len, int replace, value):
  189. """Follow the path to find the target element, build the missing children
  190. as needed and set the target element to 'value'. If replace is true, an
  191. existing value is replaced, otherwise the new value is added.
  192. """
  193. cdef _Element child
  194. cdef tree.xmlNode* c_node
  195. cdef tree.xmlNode* c_child
  196. cdef Py_ssize_t c_index
  197. if c_path_len == 1:
  198. raise TypeError, "cannot update root node"
  199. c_node = root._c_node
  200. c_name = c_path[0].name
  201. c_href = c_path[0].href
  202. if c_href is NULL or c_href[0] == c'\0':
  203. c_href = tree._getNs(c_node)
  204. if not cetree.tagMatches(c_node, c_href, c_name):
  205. raise ValueError(
  206. f"root element does not match: need {cetree.namespacedNameFromNsName(c_href, c_name)}, got {root.tag}")
  207. while c_path_len > 1:
  208. c_path_len -= 1
  209. c_path += 1
  210. if c_path[0].href is not NULL:
  211. c_href = c_path[0].href # otherwise: keep parent namespace
  212. c_index = c_path[0].index
  213. c_name = tree.xmlDictExists(c_node.doc.dict, c_path[0].name, -1)
  214. if c_name is NULL:
  215. c_name = c_path[0].name
  216. c_child = NULL
  217. else:
  218. c_child = c_node.last if c_index < 0 else c_node.children
  219. c_child = _findFollowingSibling(c_child, c_href, c_name, c_index)
  220. if c_child is not NULL:
  221. c_node = c_child
  222. elif c_index != 0:
  223. raise TypeError, "creating indexed path attributes is not supported"
  224. elif c_path_len == 1:
  225. _appendValue(cetree.elementFactory(root._doc, c_node),
  226. cetree.namespacedNameFromNsName(c_href, c_name),
  227. value)
  228. return
  229. else:
  230. child = cetree.makeSubElement(
  231. cetree.elementFactory(root._doc, c_node),
  232. cetree.namespacedNameFromNsName(c_href, c_name),
  233. None, None, None, None)
  234. c_node = child._c_node
  235. # if we get here, the entire path was already there
  236. if replace:
  237. element = cetree.elementFactory(root._doc, c_node)
  238. _replaceElement(element, value)
  239. else:
  240. _appendValue(cetree.elementFactory(root._doc, c_node.parent),
  241. cetree.namespacedName(c_node), value)
  242. cdef list _build_descendant_paths(tree.xmlNode* c_node, prefix_string):
  243. """Returns a list of all descendant paths.
  244. """
  245. cdef list path, path_list
  246. tag = cetree.namespacedName(c_node)
  247. if prefix_string:
  248. if prefix_string[-1] != '.':
  249. prefix_string += '.'
  250. prefix_string = prefix_string + tag
  251. else:
  252. prefix_string = tag
  253. path = [prefix_string]
  254. path_list = []
  255. _recursive_build_descendant_paths(c_node, path, path_list)
  256. return path_list
  257. cdef int _recursive_build_descendant_paths(tree.xmlNode* c_node,
  258. list path, list path_list) except -1:
  259. """Fills the list 'path_list' with all descendant paths, initial prefix
  260. being in the list 'path'.
  261. """
  262. cdef tree.xmlNode* c_child
  263. tags = {}
  264. path_list.append('.'.join(path))
  265. c_href = tree._getNs(c_node)
  266. c_child = c_node.children
  267. while c_child is not NULL:
  268. while c_child.type != tree.XML_ELEMENT_NODE:
  269. c_child = c_child.next
  270. if c_child is NULL:
  271. return 0
  272. if c_href is tree._getNs(c_child):
  273. tag = pyunicode(c_child.name)
  274. elif c_href is not NULL and tree._getNs(c_child) is NULL:
  275. # special case: parent has namespace, child does not
  276. tag = '{}' + pyunicode(c_child.name)
  277. else:
  278. tag = cetree.namespacedName(c_child)
  279. count = tags.get(tag)
  280. if count is None:
  281. tags[tag] = 1
  282. else:
  283. tags[tag] = count + 1
  284. tag += f'[{count}]'
  285. path.append(tag)
  286. _recursive_build_descendant_paths(c_child, path, path_list)
  287. del path[-1]
  288. c_child = c_child.next
  289. return 0