Coverage for src/somesy/pom_xml/xmlproxy.py: 94%
210 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
1"""Wrapper to provide dict-like access to XML via ElementTree."""
3from __future__ import annotations
5import xml.etree.ElementTree as ET
6from io import BytesIO
7from pathlib import Path
8from typing import Any, Literal, cast, overload
10import defusedxml.ElementTree as DET
12from somesy.core.core import atomic_write
14# shallow type hint mostly for documentation purpose
15JSONLike = Any
18def load_xml(path: Path) -> ET.ElementTree:
19 """Parse an XML file into an ElementTree, preserving comments."""
20 path = path if isinstance(path, Path) else Path(path)
21 parser = DET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
22 return DET.parse(path, parser=parser)
25def indent(elem, level=0):
26 """Indent the elements of this XML node (i.e. pretty print)."""
27 i = "\n" + level * " "
28 if len(elem):
29 if not elem.text or not elem.text.strip():
30 elem.text = i + " "
31 if not elem.tail or not elem.tail.strip():
32 elem.tail = i
33 children = list(elem)
34 for child in children:
35 indent(child, level + 1)
36 if not children[-1].tail or not children[-1].tail.strip():
37 children[-1].tail = i
38 else:
39 if level and (not elem.tail or not elem.tail.strip()):
40 elem.tail = i
43class XMLProxy:
44 """Class providing dict-like access to edit XML via ElementTree.
46 Note that this wrapper facade is limited to a restricted (but useful) subset of XML:
47 * XML attributes are not supported
48 * DTDs are ignored (arbitrary keys can be queried and added)
49 * each tag is assumed to EITHER contain text OR more nested tags
50 * lists are treated atomically (no way to add/remove element from a collection)
52 The semantics is implemented as follows:
54 * If there are multiple tags with the same name, a list of XMLProxy nodes is returned
55 * If a unique tag does have no nested tags, its `text` string value is returned
56 * Otherwise, the node is returned
57 """
59 def _wrap(self, el: ET.Element) -> XMLProxy:
60 """Wrap a different element, inheriting the same namespace."""
61 return XMLProxy(el, default_namespace=self._def_ns)
63 def _dump(self):
64 """Dump XML to stdout (for debugging)."""
65 ET.dump(self._node)
67 def _qualified_key(self, key: str):
68 """If passed key is not qualified, prepends the default namespace (if set)."""
69 if key[0] == "{" or not self._def_ns:
70 return key
71 return "{" + self._def_ns + "}" + key
73 def _shortened_key(self, key: str):
74 """Inverse of `_qualified_key` (strips default namespace from element name)."""
75 if key[0] != "{" or not self._def_ns or key.find(self._def_ns) < 0:
76 return key
77 return key[key.find("}") + 1 :]
79 # ----
81 def __init__(self, el: ET.Element, *, default_namespace: str | None = None):
82 """Wrap an existing XML ElementTree Element."""
83 self._node: ET.Element = el
84 self._def_ns = default_namespace
86 @classmethod
87 def parse(cls, path: str | Path, **kwargs) -> XMLProxy:
88 """Parse an XML file into a wrapped ElementTree, preserving comments."""
89 path = path if isinstance(path, Path) else Path(path)
90 root = load_xml(path).getroot()
91 if root is None:
92 raise ValueError(f"XML file has no root element: {path}")
93 return cls(root, **kwargs)
95 def write(self, path: str | Path, *, header: bool = True, **kwargs):
96 """Write the XML DOM to an UTF-8 encoded file."""
97 path = path if isinstance(path, Path) else Path(path)
98 et = ET.ElementTree(self._node)
99 if self._def_ns and "default_namespace" not in kwargs:
100 kwargs["default_namespace"] = self._def_ns
101 indent(et.getroot())
102 buffer = BytesIO()
103 et.write(buffer, encoding="UTF-8", xml_declaration=header, **kwargs)
104 atomic_write(path, buffer.getvalue())
106 def __repr__(self):
107 """See `object.__repr__`."""
108 return str(self._node)
110 def __len__(self):
111 """Return number of inner tags inside current XML element.
113 Note that bool(node) thus checks whether an XML node is a leaf in the element tree.
114 """
115 return len(self._node)
117 def __iter__(self):
118 """Iterate the nested elements in-order."""
119 return map(self._wrap, iter(self._node))
121 @property
122 def namespace(self) -> str | None:
123 """Default namespace of this node."""
124 return self._def_ns
126 @property
127 def is_comment(self):
128 """Return whether the current element node is an XML comment."""
129 return not isinstance(self._node.tag, str)
131 @property
132 def tag(self) -> str | None:
133 """Return tag name of this element (unless it is a comment)."""
134 if self.is_comment:
135 return None
136 return self._shortened_key(self._node.tag)
138 @tag.setter
139 def tag(self, val: str):
140 """Set the tag of this element."""
141 if self.is_comment:
142 raise ValueError("Cannot set tag name for comment element!")
143 self._node.tag = self._qualified_key(val)
145 # ---- helpers ----
147 def to_jsonlike(
148 self,
149 *,
150 strip_default_ns: bool = True,
151 keep_root: bool = False,
152 ) -> JSONLike:
153 """Convert XML node to a JSON-like primitive, array or dict (ignoring attributes).
155 Note that all leaf values are strings (i.e. not parsed to bool/int/float etc.).
157 Args:
158 strip_default_ns: Do not qualify keys from the default namespace
159 keep_root: If true, the root tag name will be preserved (`{"root_tag": {...}}`)
161 """
162 # leaf -> assume it's a primitive value (comments do not make a node)
163 if all(child.is_comment for child in self):
164 return self._node.text or ""
166 dct = {}
167 ccnt = 0
168 for elem in iter(self):
169 raw = elem._node
170 if not isinstance(raw.tag, str):
171 ccnt += 1
172 key = f"__comment_{ccnt}__"
173 else:
174 key = raw.tag if not strip_default_ns else self._shortened_key(raw.tag)
176 curr_val = elem.to_jsonlike(strip_default_ns=strip_default_ns)
177 if key not in dct:
178 dct[key] = curr_val
179 continue
180 val = dct[key]
181 if not isinstance(val, list):
182 dct[key] = [dct[key]]
183 dct[key].append(curr_val)
185 return dct if not keep_root else {self._shortened_key(self._node.tag): dct}
187 @staticmethod
188 def _new_element(tag: str, *, default_namespace: str | None = None) -> ET.Element:
189 """Create a new element, qualifying the tag with the default namespace."""
190 if default_namespace and tag[0] != "{":
191 tag = "{" + default_namespace + "}" + tag
192 return ET.Element(tag)
194 @classmethod
195 def _from_jsonlike_primitive(
196 cls, val, *, elem_name: str | None = None, **kwargs
197 ) -> str | XMLProxy:
198 """Convert a leaf node into a string value (i.e. return inner text).
200 Returns a string (or an XML element, if elem_name is passed).
201 """
202 if val is None:
203 ret = "" # turn None into empty string
204 elif isinstance(val, str):
205 ret = val
206 elif isinstance(val, bool):
207 ret = str(val).lower() # True -> true / False -> false
208 elif isinstance(val, (int, float)):
209 ret = str(val)
210 else:
211 raise TypeError(
212 f"Value of type {type(val)} is not JSON-like primitive: {val}"
213 )
215 if not elem_name:
216 return ret
217 else: # return the value wrapped as an element (needed in from_jsonlike)
218 elem = cls._new_element(elem_name, **kwargs)
219 elem.text = ret
220 return cls(elem, **kwargs)
222 @classmethod
223 def from_jsonlike(
224 cls, val: JSONLike, *, root_name: str | None = None, **kwargs: Any
225 ) -> Any:
226 """Convert a JSON-like primitive, array or dict into an XML element.
228 Note that booleans are serialized as `true`/`false` and None as `null`.
230 Args:
231 val: Value to convert into an XML element.
232 root_name: If `val` is a dict, defines the tag name for the root element.
233 kwargs: Additional arguments for XML element instantiation.
235 """
236 if isinstance(val, list):
237 return [cls.from_jsonlike(x, root_name=root_name, **kwargs) for x in val]
238 if not isinstance(val, dict): # primitive val
239 return cls._from_jsonlike_primitive(val, elem_name=root_name, **kwargs)
241 # now the dict case remains
242 elem = cls._new_element(root_name or "root", **kwargs)
243 for k, v in val.items():
244 if k.startswith(
245 "__comment_"
246 ): # special key names are mapped to XML comments
247 elem.append(ET.Comment(v if isinstance(v, str) else str(v)))
249 elif isinstance(v, list):
250 for vv in cast(
251 list[XMLProxy], XMLProxy.from_jsonlike(v, root_name=k, **kwargs)
252 ):
253 elem.append(vv._node)
254 elif not isinstance(v, dict): # primitive val
255 # FIXME: use better case-splitting for type of function to avoid cast
256 tmp = cast(
257 XMLProxy,
258 XMLProxy._from_jsonlike_primitive(v, elem_name=k, **kwargs),
259 )
260 elem.append(tmp._node)
261 else: # dict
262 elem.append(
263 cast(
264 XMLProxy, XMLProxy.from_jsonlike(v, root_name=k, **kwargs)
265 )._node
266 )
268 return cls(elem, **kwargs)
270 # ---- dict-like access ----
272 @overload
273 def get(
274 self, key: str, *, as_nodes: Literal[True], deep: Literal[False] = False
275 ) -> list[XMLProxy]: ...
277 @overload
278 def get(
279 self, key: str, *, as_nodes: Literal[False] = False, deep: bool = False
280 ) -> Any: ...
282 def get(self, key: str, *, as_nodes: bool = False, deep: bool = False) -> Any:
283 """Get sub-structure(s) of value(s) matching desired XML tag name.
285 * If there are multiple matching elements, will return them all as a list.
286 * If there is a single matching element, will return that element without a list.
288 Args:
289 key: tag name to retrieve
290 as_nodes: If true, will *always* return a list of (zero or more) XML nodes
291 deep: Expand nested XML elements instead of returning them as XML nodes
293 """
294 # NOTE: could allow to retrieve comments when using empty string/none as key?
296 if as_nodes and deep:
297 raise ValueError("as_nodes and deep are mutually exclusive!")
298 if not key:
299 raise ValueError("Key must not be an empty string!")
300 key = self._qualified_key(key)
302 # if not fully qualified + default NS is given, use it for query
303 lst = self._node.findall(key)
304 ns: list[XMLProxy] = list(map(self._wrap, lst))
305 if as_nodes: # return it as a list of xml nodes
306 return ns
307 if not ns: # no element
308 return None
310 ret = ns if not deep else [x.to_jsonlike() for x in ns]
311 if len(ret) == 1:
312 return ret[0] # single element
313 else:
314 return ret
316 def __getitem__(self, key: str):
317 """Acts like `dict.__getitem__`, implemented with `get`."""
318 val = self.get(key)
319 if val is not None:
320 return val
321 else:
322 raise KeyError(key)
324 def __contains__(self, key: str) -> bool:
325 """Acts like `dict.__contains__`, implemented with `get`."""
326 return self.get(key) is not None
328 def __delitem__(self, key: str | XMLProxy):
329 """Delete a nested XML element with matching key name.
331 Note that **all** XML elements with the given tag name are removed!
333 To prevent this behavior, instead of a string tag name you can provide the
334 exact element to be removed, i.e. if a node `node_a` represents the following XML:
336 ```
337 <a>
338 <b>1</b>
339 <c>2</c>
340 <b>3</b>
341 </a>
342 ```
344 Then we have that:
346 * `del node_a["b"]` removes **both** tags, leaving just the `c` tag.
347 * `del node_a[node_a["a"][1]]` removes just the second tag with the `3`.
348 """
349 if isinstance(key, str):
350 nodes = self.get(key, as_nodes=True)
351 else:
352 nodes = [key] if key._node in self._node else []
354 if not nodes:
355 raise KeyError(key)
357 if self._node.text is not None:
358 self._node.text = ""
359 for child in nodes:
360 self._node.remove(child._node)
362 def _clear(self):
363 """Remove contents of this XML element (e.g. for overwriting in-place)."""
364 self._node.text = ""
365 children = list(iter(self._node)) # need to store, removal invalidates iterator
366 for child in children:
367 self._node.remove(child)
369 def __setitem__(self, key: str | XMLProxy, val: JSONLike | XMLProxy):
370 """Add or overwrite an inner XML tag.
372 If there is exactly one matching tag, the value is substituted in-place.
373 If the passed value is a list, all list entries are added in their own element.
375 If there are multiple existing matches or target values, then
376 **all** existing elements are removed and the new value(s) are added in
377 new element(s) (i.e. coming after other unrelated existing elements)!
379 To prevent this behavior, instead of a string tag name you can provide the
380 exact element to be overwritten, i.e. if a node `node_a` represents the following XML:
382 ```
383 <a>
384 <b>1</b>
385 <c>2</c>
386 <b>3</b>
387 </a>
388 ```
390 Then we have that:
392 * `node_a["b"] = 5` removes both existing tags and creates a new tag with the passed value(s).
393 * `node_a[node_a["b"][1]] = 5` replaces the `3` in the second tag with the `5`.
395 Note that the passed value must be either an XML element already, or be a pure JSON-like object.
396 """
397 # validate and convert everything first, so errors leave the tree untouched
398 if isinstance(key, str):
399 key_name: str = self._qualified_key(key)
400 else: # an XMLProxy object was passed as key -> try to use that
401 if isinstance(val, list):
402 raise TypeError(
403 "Cannot overwrite a single element with a list of values!"
404 )
405 if key.tag is None:
406 raise ValueError("Cannot overwrite an XML element without a tag")
407 key_name = self._qualified_key(key.tag)
409 # normalize passed value(s) to be list (general case)
410 vals = val if isinstance(val, list) else [val]
412 # normalize values no XML element nodes
413 nvals: list[XMLProxy] = []
414 for item in vals:
415 # ensure value is represented as an XML node
416 if isinstance(item, XMLProxy):
417 obj = self._wrap(ET.Element("dummy"))
418 obj._node.append(item._node)
419 else:
420 obj = cast(
421 XMLProxy,
422 self.from_jsonlike(
423 item, root_name=key_name, default_namespace=self._def_ns
424 ),
425 )
427 nvals.append(obj)
429 # now mutate the tree
430 if isinstance(key, str):
431 nodes = self.get(key, as_nodes=True)
432 # delete all existing elements if multiple exist or are passed
433 if len(nodes) > 1 or (len(nodes) and isinstance(val, list)):
434 del self[key]
435 nodes = []
436 # now we can assume there's zero or one suitable target elements
437 if nodes: # if it is one, clear it out
438 nodes[0]._clear()
439 else:
440 # ensure the target node is cleared out and use it as target
441 key._clear()
442 nodes = [key]
444 # ensure there is the required number of target element nodes
445 for _ in range(len(vals) - len(nodes)):
446 nodes.append(self._wrap(ET.SubElement(self._node, key_name)))
448 for node, item in zip(nodes, nvals, strict=False):
449 # transplant node contents into existing element (so it is inserted in-place)
450 node._node.text = item._node.text
451 for child in iter(item):
452 node._node.append(child._node)