Debian Codegraph @

gavo/utils/plainxml.py

raw
1 """
2 Some XML hacks.
3
4 StartEndHandler simplifies the creation of SAX parsers, intended for
5 client code or non-DC XML parsing.
6
7 iterparse is an elementtree-inspired thin expat layer; both VOTable
8 and base.structure parsing builds on it.
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import collections
18 import weakref
19 import xml.sax
20 from xml.parsers import expat
21 from xml.sax.handler import ContentHandler
22
23 from gavo.utils import excs
24 from gavo.utils import misctricks
25 from gavo.utils import texttricks
26
27 from gavo.utils.dachstypes import (
28 Any, Dict,
29 IO, Iterator,
30 Optional, PlainXMLEvent,
31 StrOrBytes, Tuple, Type)
32
33 class ErrorPosition(object):
34 """A wrapper for an error position.
35
36 Construct it with file name, line number, and column. Use None
37 for missing or unknown values.
38 """
39 fName = None
40 def __init__(self, fName: str, line: int, column: int) -> None:
41 self.line = line or '?'
42 self.col = column
43 if self.col is None:
44 self.col = '?'
45 self.fName = fName
46
47 def __str__(self) -> str:
48 if self.fName:
49 return "%s, (%s, %s)"%(self.fName, self.line, self.col)
50 else:
51 return "(%s, %s)"%(self.line, self.col)
52
53
54 class iterparse:
55 """iterates over start, data, and end events in source.
56
57 To keep things simple downstream, we swallow all namespace prefixes,
58 if present.
59
60 The events this yields are one of:
61
62 * ("start", element-name, attributes)
63 * ("end", element-name, None)
64 * ("data", None, payload)
65
66 utils.dachstypes.PlainXMLEvent is a type for these.
67
68 iterparse is constructed with a source (anything that can read(source))
69 and optionally a custom error class. This error class needs to
70 have the message as the first argument. Since expat error messages
71 usually contain line number and column in them, no extra pos attribute
72 is supported.
73
74 Since the parser typically is far ahead of the events seen, we
75 do our own bookkeeping by storing the parser position with each
76 event. The *end* of the construct that caused an event can
77 be retrieved using pos.
78 """
79 chunkSize: int = 2**20
80 "The number of bytes handed to expat from iterparse at one go."
81
82 def __init__(self,
83 source: IO,
84 parseErrorClass: Type[excs.Error] = excs.StructureError) -> None:
85 self.source = source
86 self.parseErrorClass = parseErrorClass
87
88 if hasattr(source, "name"):
89 self.inputName = source.name
90 elif hasattr(source, "getvalue"):
91 self.inputName = texttricks.makeEllipsis("IO:'"
92 +texttricks.safe_str(source.getvalue()))+"'"
93 else:
94 self.inputName = texttricks.makeSourceEllipsis(source)
95
96 self.parser = expat.ParserCreate()
97 self.parser.buffer_text = True
98 self.lastLine, self.lastColumn = 1, 0
99 self.evBuf: collections.deque[Tuple[
100 PlainXMLEvent, Optional[Tuple[int, int]]]
101 ] = collections.deque()
102 self.parser.StartElementHandler = self._startElement
103 self.parser.EndElementHandler = self._endElement
104 self.parser.CharacterDataHandler = self._characters
105
106 def __iter__(self) -> Iterator[PlainXMLEvent]:
107 return self
108
109 def _startElement(self, name: str, attrs: Dict[str, str]) -> None:
110 self.evBuf.append(
111 (("start", name.split(":")[-1], attrs),
112 (self.parser.CurrentLineNumber, self.parser.CurrentColumnNumber)))
113
114 def _endElement(self, name: str) -> None:
115 self.evBuf.append((("end", name.split(":")[-1], None),
116 (self.parser.CurrentLineNumber, self.parser.CurrentColumnNumber)))
117
118 def _characters(self, data: str) -> None:
119 self.evBuf.append((("data", None, data), None))
120
121 def pushBack(self, type: str, name: str, payload: str) -> None:
122 self.evBuf.appendleft(((type, name, payload), None))
123
124 def __next__(self) -> PlainXMLEvent:
125 while not self.evBuf:
126 try:
127 nextChunk = self.source.read(self.chunkSize)
128 if nextChunk:
129 self.parser.Parse(nextChunk)
130 else:
131 self.close()
132 break
133 except expat.ExpatError as ex:
134 srcDesc = getattr(self.source, "name", "(internal source)")
135 newEx = self.parseErrorClass(srcDesc+" "+str(ex))
136 # see base.xmlstruct for the following ignore.
137 newEx.posInMsg = True # type: ignore
138 newEx.inFile = srcDesc # type: ignore
139 raise misctricks.logOldExc(newEx)
140
141 if not self.evBuf:
142 raise StopIteration("End of Input")
143 event, pos = self.evBuf.popleft()
144 if pos is not None:
145 self.lastLine, self.lastColumn = pos
146 return event
147
148 def close(self) -> None:
149 self.parser.Parse("", True)
150 self.parser.StartElementHandler =\
151 self.parser.EndElementHandler = \
152 self.parser.CharacterDataHandler = None
153
154 @property
155 def pos(self) -> ErrorPosition:
156 return ErrorPosition(self.inputName, self.lastLine, self.lastColumn)
157
158 def getParseError(self, msg: str) -> Exception:
159 """returns an instance of what you passed in in parseErrorClass
160 with location information.
161 """
162 res = self.parseErrorClass("At %s: %s"%(self.pos, msg))
163 # see base.xmlstruct for the following ignore
164 res.posInMsg = True # type: ignore
165 return res
166
167
168 # Not type annotating the SAX interface methods. See xml.sax.handler
169 # declarations for these.
170 class StartEndHandler(ContentHandler):
171 """This class provides startElement, endElement and characters
172 methods that translate events into method calls.
173
174 When an opening tag is seen, we look of a _start_<element name>
175 method and, if present, call it with the name and the attributes.
176 When a closing tag is seen, we try to call _end_<element name> with
177 name, attributes and contents. If the _end_xxx method returns a
178 string (or similar), this value will be added to the content of the
179 enclosing element.
180
181 Rather than overriding __init__, you probably want to override
182 the _initialize() method to create the data structures you want
183 to fill from XML.
184
185 StartEndHandlers clean element names from namespace prefixes, and
186 they ignore them in every other way. If you need namespaces, use
187 a different interface.
188 """
189 def __init__(self):
190 ContentHandler.__init__(self)
191 self.realHandler = weakref.proxy(self)
192 self.elementStack = []
193 self.contentsStack = [[]]
194 self._initialize()
195
196 def _initialize(self) -> None:
197 pass
198
199 def processingInstruction(self, target: str, data:str) -> None:
200 self.contentsStack[-1].append(data)
201
202 def cleanupName(self, name: str) -> str:
203 """returning an element name replacing _ for -.
204
205 That's so people can define methods for such names, and if that
206 leads to clashes, the schema designers were sadists.
207 """
208 return name.split(":")[-1].replace("-", "_")
209
210 def startElementNS(self, namePair, qName, attrs):
211 newAttrs = {}
212 for ns, name in list(attrs.keys()):
213 if ns is None:
214 newAttrs[name] = attrs[(ns, name)]
215 else:
216 newAttrs["{%s}%s"%(ns, name)] = attrs[(ns, name)]
217 self.startElement(namePair[1], newAttrs)
218
219 def startElement(self, name: str, attrs) -> None:
220 self.contentsStack.append([])
221 name = self.cleanupName(name)
222 self.elementStack.append((name, attrs))
223 if hasattr(self.realHandler, "_start_%s"%name):
224 getattr(self.realHandler, "_start_%s"%name)(name, attrs)
225 elif hasattr(self, "_defaultStart"):
226 self._defaultStart(name, attrs)
227
228 def endElementNS(self, namePair, qName):
229 self.endElement(namePair[1])
230
231 def endElement(self, name: str, suppress: Optional[bool]=False) -> None:
232 contents = "".join(self.contentsStack.pop())
233 name = self.cleanupName(name)
234 _, attrs = self.elementStack.pop()
235 res = None
236 if hasattr(self.realHandler, "_end_%s"%name):
237 res = getattr(self.realHandler,
238 "_end_%s"%name)(name, attrs, contents)
239 elif hasattr(self, "_defaultEnd"):
240 res = self._defaultEnd(name, attrs, contents)
241 if isinstance(res, str) and not suppress:
242 self.contentsStack[-1].append(res)
243
244 def characters(self, chars):
245 self.contentsStack[-1].append(chars)
246
247 def getResult(self) -> Any:
248 return self.contentsStack[0][0]
249
250 def getParentTag(self, depth:int=1) -> Optional[str]:
251 """Returns the name of the parent element.
252
253 This only works as written here in end handlers. In start handlers,
254 you have to path depth=2 (since their tag already is on the stack).
255 """
256 if self.elementStack:
257 return self.elementStack[-depth][0]
258 return None
259
260 def parse(self, stream: IO) -> ContentHandler:
261 xml.sax.parse(stream, self)
262 return self
263
264 def parseString(self, string: StrOrBytes) -> "StartEndHandler":
265 xml.sax.parseString(string, self)
266 return self
267
268 # xml.sax is smart enough to do the right thing when it gets passed bytes.
269 # TODO: to away with parseBytes.
270 def parseBytes(self, data: StrOrBytes) -> "StartEndHandler":
271 return self.parseString(data)
272
273 def getAttrsAsDict(self, attrs):
274 """returns attrs as received from SAX as a dictionary.
275
276 The main selling point is that any namespace prefixes are removed from
277 the attribute names. Any prefixes on attrs remain, though.
278 """
279 return dict((k.split(":")[-1], v) for k, v in list(attrs.items()))
280
281 def setDocumentLocator(self, locator):
282 self.locator = locator
283
284
285 def traverseETree(eTree):
286 """iterates the elements of an elementTree in postorder.
287 """
288 for child in eTree:
289 for gc in traverseETree(child):
290 yield gc
291 yield eTree