| 1 |
""" |
| 2 |
A stan-like model for building namespaced XML trees. |
| 3 |
|
| 4 |
The main reason for this module is that much of the VO's XML mess is based |
| 5 |
on XML schema and thus has namespaced attributes. This single design |
| 6 |
decision ruins the entire XML design. To retain some rests of |
| 7 |
sanity, I treat the prefixes themselves as namespaces and maintain |
| 8 |
a single central registry from prefixes to namespaces in this module. |
| 9 |
|
| 10 |
Then, the elements only use these prefixes, and this module makes sure |
| 11 |
that during serialization the instance document's root element contains |
| 12 |
the namespace mapping (and the schema locations) required. |
| 13 |
""" |
| 14 |
|
| 15 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 16 |
#c |
| 17 |
#c This program is free software, covered by the GNU GPL. See the |
| 18 |
#c COPYING file in the source distribution. |
| 19 |
|
| 20 |
|
| 21 |
import io |
| 22 |
import types |
| 23 |
# This is utils.ElementTree, which is what DaCHS-internal code |
| 24 |
# should use to avoid multiple etrees having to interact: |
| 25 |
# This should by and large work with the built-in etree: |
| 26 |
from xml.etree import ElementTree #noflake: re-export |
| 27 |
# But then we now hard-depend on lxml anyway, and that's cool for tests because |
| 28 |
# it has a predictable element order. So, let's use that one day (will |
| 29 |
# need code updates, though, because lxml doesn't understand our ColRef yet) |
| 30 |
#from lxml import etree as ElementTree #noflake: re-export |
| 31 |
|
| 32 |
from gavo.utils import autonode |
| 33 |
from gavo.utils import excs |
| 34 |
from gavo.utils import misctricks |
| 35 |
from gavo.utils import texttricks |
| 36 |
|
| 37 |
from gavo.utils.dachstypes import (Any, BytesWritable, Callable, Dict, |
| 38 |
FrozenSet, IO, Iterator, List, Optional, Self, Set, Sequence, |
| 39 |
StanElement, Tuple, Type, TypeVar, Union) |
| 40 |
|
| 41 |
# note on type annotation: mypy 1.0.1 doesn't cope with attributes |
| 42 |
# introduced by metaclasses. Most of the type ignore pragmas in here |
| 43 |
# work around that deficiency and can perhaps be dropped with a |
| 44 |
# metaclass-aware mypy. |
| 45 |
|
| 46 |
|
| 47 |
class Error(Exception): |
| 48 |
pass |
| 49 |
|
| 50 |
class ChildNotAllowed(Error): |
| 51 |
pass |
| 52 |
|
| 53 |
|
| 54 |
XML_HEADER = b'<?xml version="1.0" encoding="utf-8"?>' |
| 55 |
|
| 56 |
|
| 57 |
class _Autoconstructor(autonode.AutoNodeType): |
| 58 |
"""A metaclass used for Elements. |
| 59 |
|
| 60 |
On the one hand, it does autonode's constructor magic with _a_<attrname> |
| 61 |
attributes, on the other, it will instantiate itself when indexed |
| 62 |
-- that we want for convenient stan-like notation. |
| 63 |
""" |
| 64 |
def __init__(cls, name: str, bases: Tuple[type, ...], dict: Dict): |
| 65 |
autonode.AutoNodeType.__init__(cls, name, bases, dict) |
| 66 |
if hasattr(cls, "_childSequence") and cls._childSequence is not None: |
| 67 |
cls._allowedChildren = set(cls._childSequence) |
| 68 |
else: |
| 69 |
cls._childSequence: Optional[List[str]] = None |
| 70 |
|
| 71 |
# TODO: this is so you can say Foo[child1, child2], which has |
| 72 |
# type Foo. I can't explain that to mypy, though, because |
| 73 |
# it won't let me annotate cls. |
| 74 |
def __getitem__(cls, |
| 75 |
items: StanElement | Sequence[StanElement]) -> "Element": |
| 76 |
return cls()[items] |
| 77 |
|
| 78 |
|
| 79 |
class Stub: |
| 80 |
"""A sentinel class for embedding objects not yet existing into |
| 81 |
stanxml trees. |
| 82 |
|
| 83 |
These have a single opaque object and need to be dealt with by the |
| 84 |
user. One example of how these can be used is the ColRefs in stc to |
| 85 |
utype conversion. |
| 86 |
|
| 87 |
Stubs are equal to each othter if their handles are identical. |
| 88 |
""" |
| 89 |
name_ = "stub" |
| 90 |
text_ = None |
| 91 |
|
| 92 |
def __init__(self, dest: str) -> None: |
| 93 |
self.dest = dest |
| 94 |
|
| 95 |
def __repr__(self) -> str: |
| 96 |
return "%s(%s)"%(self.__class__.__name__, repr(self.dest)) |
| 97 |
|
| 98 |
def __eq__(self, other: Any) -> bool: |
| 99 |
return self.dest==getattr(other, "dest", Stub) |
| 100 |
|
| 101 |
def __ne__(self, other: Any) -> bool: |
| 102 |
return not self==other |
| 103 |
|
| 104 |
def __hash__(self) -> int: |
| 105 |
return hash(self.dest) |
| 106 |
|
| 107 |
def isEmpty(self) -> bool: |
| 108 |
return False |
| 109 |
|
| 110 |
def shouldBeSkipped(self) -> bool: |
| 111 |
return False |
| 112 |
|
| 113 |
def getChildDict(self) -> Dict: |
| 114 |
return {} |
| 115 |
|
| 116 |
def iterAttNames(self): |
| 117 |
if False: |
| 118 |
yield |
| 119 |
|
| 120 |
def apply(self, func: Callable) -> None: |
| 121 |
"""does nothing. |
| 122 |
|
| 123 |
Stubs don't have what Element.apply needs, so we don't even pretend. |
| 124 |
""" |
| 125 |
return |
| 126 |
|
| 127 |
|
| 128 |
class Element(metaclass=_Autoconstructor): |
| 129 |
"""An element for serialization into XML. |
| 130 |
|
| 131 |
This is loosely modelled after t.w.template stan. |
| 132 |
|
| 133 |
Don't add to the children attribute directly, use addChild or (more |
| 134 |
usually) __getitem__. |
| 135 |
|
| 136 |
Elements have attributes and children. The attributes are defined, |
| 137 |
complete with defaults, in _a_<name> attributes as in AutoNodes. |
| 138 |
Attributes are checked. |
| 139 |
|
| 140 |
Children are not usually checked, but you can set a _childSequence |
| 141 |
attribute containing a list of (unqualified) element names. These |
| 142 |
children will be emitted in the sequence given. |
| 143 |
|
| 144 |
When deriving from Elements, you may need attribute names that are not |
| 145 |
python identifiers (e.g., with dashes in them). In that case, define |
| 146 |
an attribute _name_a_<att> and point it to any string you want as the |
| 147 |
attribute. |
| 148 |
|
| 149 |
When serializing these, empty elements (i.e. those having an empty text and |
| 150 |
having no non-empty children) are usually discarded. If you need such an |
| 151 |
element (e.g., for attributes), set mayBeEmpty to True. |
| 152 |
|
| 153 |
Since insane XSD mandates that local elements must not be qualified when |
| 154 |
elementFormDefault is unqualified, you need to set _local=True on |
| 155 |
such local elements to suppress the namespace prefix. Attribute names |
| 156 |
are never qualified here. If you need qualified attributes, you'll |
| 157 |
have to use attribute name translation. |
| 158 |
|
| 159 |
The content of the DOM may be anything recognized by addChild. |
| 160 |
In particular, you can give objects a serializeToXMLStan method returning |
| 161 |
strings or an Element to make them good DOM citizens. |
| 162 |
|
| 163 |
Elements cannot harbor mixed content (or rather, there is only |
| 164 |
one piece of text). |
| 165 |
""" |
| 166 |
name_ = None |
| 167 |
_a_id = None |
| 168 |
_prefix = "" |
| 169 |
_additionalPrefixes: FrozenSet[str] = frozenset() |
| 170 |
_mayBeEmpty = False |
| 171 |
_local = False |
| 172 |
_stringifyContent = False |
| 173 |
|
| 174 |
_localAttrs: Union[Tuple, List[Tuple[str, str]]] = () |
| 175 |
|
| 176 |
# should probably do this in the elements needing it (quite a lot of them |
| 177 |
# do, however...) |
| 178 |
_name_a_xsi_type = "xsi:type" |
| 179 |
|
| 180 |
# see _setupNode below for __init__ |
| 181 |
|
| 182 |
def __getitem__(self, children: Any) -> Self: |
| 183 |
self.addChild(children) |
| 184 |
return self |
| 185 |
|
| 186 |
def __call__(self, **kw: Any) -> Self: |
| 187 |
if not kw: |
| 188 |
return self |
| 189 |
|
| 190 |
for k, v in kw.items(): |
| 191 |
# Only allow setting attributes already present |
| 192 |
getattr(self, k) |
| 193 |
setattr(self, k, v) |
| 194 |
return self |
| 195 |
|
| 196 |
def __iter__(self): |
| 197 |
raise NotImplementedError("Element instances are not iterable.") |
| 198 |
|
| 199 |
def __bool__(self) -> bool: |
| 200 |
return not self.isEmpty() |
| 201 |
|
| 202 |
def _setupNodeNext(self, cls) -> None: |
| 203 |
try: |
| 204 |
pc = super(cls, self)._setupNode #type: ignore |
| 205 |
except AttributeError: |
| 206 |
pass |
| 207 |
else: |
| 208 |
pc() |
| 209 |
|
| 210 |
def _setupNode(self) -> None: |
| 211 |
self._isEmptyCache: Optional[bool] = None |
| 212 |
self._children: List[Any] = [] |
| 213 |
self.text_ = "" |
| 214 |
if self.name_ is None: |
| 215 |
self.name_ = self.__class__.__name__.split(".")[-1] |
| 216 |
self._setupNodeNext(Element) |
| 217 |
|
| 218 |
def _makeAttrDict(self) -> Dict[str, str]: |
| 219 |
res = {} |
| 220 |
for name, attName in self.iterAttNames(): |
| 221 |
if getattr(self, name, None) is not None: |
| 222 |
res[attName] = str(getattr(self, name)) |
| 223 |
|
| 224 |
for name, value in self._localAttrs: |
| 225 |
res[name] = value |
| 226 |
|
| 227 |
return res |
| 228 |
|
| 229 |
def _iterChildrenInSequence(self) -> Iterator["Element"]: |
| 230 |
cDict = self.getChildDict() |
| 231 |
for cName in self._childSequence: #type: ignore |
| 232 |
if cName in cDict: |
| 233 |
for c in cDict[cName]: |
| 234 |
yield c |
| 235 |
|
| 236 |
def bailIfBadChild(self, child: Any) -> None: |
| 237 |
if (self._childSequence is not None # type: ignore |
| 238 |
and getattr(child, "name_", None) not in self._allowedChildren # type: ignore |
| 239 |
and type(child) not in self._allowedChildren): # type: ignore |
| 240 |
raise ChildNotAllowed("No %s children in %s"%( |
| 241 |
getattr(child, "name_", "text"), self.name_)) |
| 242 |
|
| 243 |
def deepcopy(self): |
| 244 |
"""returns a deep copy of self. |
| 245 |
""" |
| 246 |
copy = self.__class__(**self._makeAttrDict()) |
| 247 |
for child in self.iterChildren(): |
| 248 |
if isinstance(child, Element): |
| 249 |
copy.addChild(child.deepcopy()) |
| 250 |
else: |
| 251 |
copy.addChild(child) |
| 252 |
return copy |
| 253 |
|
| 254 |
# t.w.template compatibility |
| 255 |
clone = deepcopy |
| 256 |
|
| 257 |
def addChild(self, child: Any) -> None: |
| 258 |
"""adds child to the list of children. |
| 259 |
|
| 260 |
Child may be an Element, a string, or a list or tuple of Elements and |
| 261 |
strings. Finally, child may be None, in which case nothing will be |
| 262 |
added. |
| 263 |
""" |
| 264 |
self._isEmptyCache = None |
| 265 |
if child is None: |
| 266 |
pass |
| 267 |
|
| 268 |
elif hasattr(child, "serializeToXMLStan"): |
| 269 |
self.addChild(child.serializeToXMLStan()) |
| 270 |
|
| 271 |
elif isinstance(child, str): |
| 272 |
self.bailIfBadChild(child) |
| 273 |
self.text_ = child |
| 274 |
|
| 275 |
elif isinstance(child, (Element, Stub)): |
| 276 |
self.bailIfBadChild(child) |
| 277 |
self._children.append(child) |
| 278 |
|
| 279 |
elif isinstance(child, (list, tuple, types.GeneratorType)): |
| 280 |
for c in child: |
| 281 |
self.addChild(c) |
| 282 |
|
| 283 |
elif isinstance(child, _Autoconstructor): |
| 284 |
self.addChild(child()) |
| 285 |
|
| 286 |
elif self._stringifyContent: |
| 287 |
self.addChild(str(child)) |
| 288 |
|
| 289 |
elif isinstance(child, Exception): |
| 290 |
self.addChild("EXCEPTION:\n%s: %s"%( |
| 291 |
child.__class__.__name__, |
| 292 |
str(child))) |
| 293 |
|
| 294 |
elif isinstance(child, bytes): |
| 295 |
# we assume our standard encoding of utf-8 and an actual string; |
| 296 |
# not much else would make sense within a stan tree |
| 297 |
self.addChild(child.decode("utf-8")) |
| 298 |
|
| 299 |
else: |
| 300 |
raise Error("%s element %s cannot be added to %s node"%( |
| 301 |
type(child), repr(child), self.name_)) |
| 302 |
|
| 303 |
def isEmpty(self) -> bool: |
| 304 |
"""returns true if the current node has no non-empty children and no |
| 305 |
non-whitespace text content. |
| 306 |
""" |
| 307 |
if self._isEmptyCache is None: |
| 308 |
self._isEmptyCache = True |
| 309 |
|
| 310 |
if self.text_.strip(): |
| 311 |
self._isEmptyCache = False |
| 312 |
if self._isEmptyCache: |
| 313 |
for c in self._children: |
| 314 |
if not c.shouldBeSkipped(): |
| 315 |
self._isEmptyCache = False |
| 316 |
break |
| 317 |
|
| 318 |
return self._isEmptyCache |
| 319 |
|
| 320 |
def shouldBeSkipped(self) -> bool: |
| 321 |
"""returns true if the current node should be part of an output. |
| 322 |
|
| 323 |
That is true if it is either non-empty or _mayBeEmpty is true. |
| 324 |
An empty element is one that has only empty children and no |
| 325 |
non-whitespace text content. |
| 326 |
""" |
| 327 |
if self._mayBeEmpty: |
| 328 |
return False |
| 329 |
return self.isEmpty() |
| 330 |
|
| 331 |
def iterAttNames(self) -> Iterator[Tuple[str, str]]: |
| 332 |
"""iterates over the defined attribute names of this node. |
| 333 |
|
| 334 |
Each element returned is a pair of the node attribute name and the |
| 335 |
xml name (which may be translated via _a_name_<att> |
| 336 |
""" |
| 337 |
for name, default in self._nodeAttrs: # type: ignore |
| 338 |
publicName = getattr(self, "_name_a_"+name, name) |
| 339 |
yield name, publicName |
| 340 |
|
| 341 |
def addAttribute(self, attName: str, attValue: str) -> None: |
| 342 |
"""adds attName, attValue as a local attribute/value pair. |
| 343 |
|
| 344 |
This is for when you have, if you will, "non-namespace" attributes |
| 345 |
(most of the time, xml namespace declarations). |
| 346 |
|
| 347 |
If you set the same name multiple times, the last value set will win. |
| 348 |
""" |
| 349 |
if self._localAttrs==(): |
| 350 |
self._localAttrs = [(attName, attValue)] |
| 351 |
else: |
| 352 |
self._localAttrs.append((attName, attValue)) # type: ignore |
| 353 |
|
| 354 |
def iterChildrenOfType(self, type: Type["SomeElement"] |
| 355 |
) -> Iterator["SomeElement"]: |
| 356 |
"""iterates over all children having type. |
| 357 |
""" |
| 358 |
for c in self._children: |
| 359 |
if isinstance(c, type): |
| 360 |
yield c |
| 361 |
|
| 362 |
def iterChildren(self) -> Iterator[Any]: |
| 363 |
return iter(self._children) |
| 364 |
|
| 365 |
def getChildDict(self) -> Dict[str, Any]: |
| 366 |
cDict: Dict[str, List] = {} |
| 367 |
for c in self._children: |
| 368 |
cDict.setdefault(c.name_, []).append(c) |
| 369 |
return cDict |
| 370 |
|
| 371 |
def iterChildrenWithName(self, elName: str |
| 372 |
) -> Iterator[Any]: |
| 373 |
"""iterates over children whose element name is elName. |
| 374 |
|
| 375 |
This always does a linear search through the children and hence |
| 376 |
may be slow. |
| 377 |
""" |
| 378 |
for c in self._children: |
| 379 |
if c.name_==elName: |
| 380 |
yield c |
| 381 |
|
| 382 |
def _getChildIter(self) -> Iterator[Any]: |
| 383 |
if self._childSequence is None: # type: ignore |
| 384 |
return iter(self._children) |
| 385 |
else: |
| 386 |
return self._iterChildrenInSequence() |
| 387 |
|
| 388 |
def apply(self, func: Callable) -> Optional[Any]: |
| 389 |
"""calls func(node, text, attrs, childIter). |
| 390 |
|
| 391 |
This is a building block for tree traversals. |
| 392 |
""" |
| 393 |
try: |
| 394 |
if self.shouldBeSkipped(): |
| 395 |
return None |
| 396 |
attrs = self._makeAttrDict() |
| 397 |
return func( |
| 398 |
self, self.text_, attrs, self._getChildIter()) |
| 399 |
except Error: |
| 400 |
raise |
| 401 |
except Exception: |
| 402 |
misctricks.sendUIEvent("Info", |
| 403 |
"Internal failure while building XML; context is" |
| 404 |
" %s node with children %s"%( |
| 405 |
self.name_, |
| 406 |
texttricks.makeEllipsis(repr(self._children), 60))) |
| 407 |
raise |
| 408 |
|
| 409 |
def render(self, |
| 410 |
prefixForEmpty: Optional[str] = None, |
| 411 |
includeSchemaLocation: bool = True, |
| 412 |
xmlDecl: bool = False, |
| 413 |
prolog: str = "") -> bytes: |
| 414 |
"""returns this and its children as a string. |
| 415 |
""" |
| 416 |
f = io.BytesIO() |
| 417 |
xmlwrite(self, |
| 418 |
f, |
| 419 |
prefixForEmpty=prefixForEmpty, |
| 420 |
xmlDecl=xmlDecl, |
| 421 |
includeSchemaLocation=includeSchemaLocation, |
| 422 |
prolog=prolog) |
| 423 |
return f.getvalue() |
| 424 |
|
| 425 |
|
| 426 |
SomeElement = TypeVar("SomeElement", bound=Element) |
| 427 |
|
| 428 |
|
| 429 |
class NSRegistry: |
| 430 |
"""A container for a registry of namespace prefixes to namespaces. |
| 431 |
|
| 432 |
This is used to have fixed namespace prefixes (IMHO the only way |
| 433 |
to have namespaced attribute values and retain sanity). The |
| 434 |
class is never instantiated. It is used through the module-level |
| 435 |
method registerPrefix. |
| 436 |
""" |
| 437 |
_registry: Dict[str, str] = {} |
| 438 |
_reverseRegistry: Dict[str, str] = {} |
| 439 |
_schemaLocations: Dict[str, Optional[str]] = {} |
| 440 |
|
| 441 |
@classmethod |
| 442 |
def registerPrefix(cls, |
| 443 |
prefix: str, |
| 444 |
ns: str, |
| 445 |
schemaLocation: Optional[str]) -> None: |
| 446 |
if prefix in cls._registry: |
| 447 |
if ns!=cls._registry[prefix]: |
| 448 |
raise ValueError("Prefix %s is already allocated for namespace %s"% |
| 449 |
(prefix, ns)) |
| 450 |
cls._registry[prefix] = ns |
| 451 |
cls._reverseRegistry[ns] = prefix |
| 452 |
cls._schemaLocations[prefix] = schemaLocation |
| 453 |
|
| 454 |
@classmethod |
| 455 |
def getPrefixForNS(cls, ns:str) -> str: |
| 456 |
try: |
| 457 |
return cls._reverseRegistry[ns] |
| 458 |
except KeyError: |
| 459 |
raise excs.NotFoundError(ns, "XML namespace", |
| 460 |
"registry of XML namespaces.", hint="The registry is filled" |
| 461 |
" by modules as they are imported -- maybe you need to import" |
| 462 |
" the right module?") |
| 463 |
|
| 464 |
@classmethod |
| 465 |
def getNSForPrefix(cls, prefix:str) -> str: |
| 466 |
try: |
| 467 |
return cls._registry[prefix] |
| 468 |
except KeyError: |
| 469 |
raise excs.NotFoundError(prefix, "XML namespace prefix", |
| 470 |
"registry of prefixes.", hint="The registry is filled" |
| 471 |
" by modules as they are imported -- maybe you need to import" |
| 472 |
" the right module?") |
| 473 |
|
| 474 |
@classmethod |
| 475 |
def _iterNSAttrs(cls, |
| 476 |
prefixes: set[str], |
| 477 |
prefixForEmpty: Optional[str], |
| 478 |
includeSchemaLocation: bool |
| 479 |
) -> Iterator[Tuple[str, str]]: |
| 480 |
"""iterates over pairs of (attrName, attrVal) for declaring |
| 481 |
prefixes. |
| 482 |
""" |
| 483 |
# null prefixes are ignored here; prefixForEmpty, if non-null, gives |
| 484 |
# the prefix the namespace would normally be bound to. |
| 485 |
prefixes.discard("") |
| 486 |
|
| 487 |
schemaLocations = [] |
| 488 |
for pref in sorted(prefixes): |
| 489 |
yield "xmlns:%s"%pref, cls._registry[pref] |
| 490 |
if includeSchemaLocation and cls._schemaLocations[pref]: |
| 491 |
schemaLocations.append("%s %s"%( |
| 492 |
cls._registry[pref], |
| 493 |
cls._schemaLocations[pref])) |
| 494 |
|
| 495 |
if prefixForEmpty: |
| 496 |
yield "xmlns", cls._registry[prefixForEmpty] |
| 497 |
|
| 498 |
if schemaLocations: |
| 499 |
if not "xsi" in prefixes: |
| 500 |
yield "xmlns:xsi", cls._registry["xsi"] |
| 501 |
yield "xsi:schemaLocation", " ".join(schemaLocations) |
| 502 |
|
| 503 |
@classmethod |
| 504 |
def addNamespaceDeclarations(cls, |
| 505 |
root: Element, |
| 506 |
prefixes: Set[str], |
| 507 |
prefixForEmpty: Optional[str] = None, |
| 508 |
includeSchemaLocation: bool = True) -> None: |
| 509 |
"""adds xmlns declarations for prefixes to the stanxml node root. |
| 510 |
|
| 511 |
With stanxml and the global-prefix scheme, xmlns declarations |
| 512 |
only come at the root element; thus, root should indeed be root |
| 513 |
rather than some random element. |
| 514 |
""" |
| 515 |
for attName, attVal in cls._iterNSAttrs( |
| 516 |
prefixes, prefixForEmpty, includeSchemaLocation): |
| 517 |
root.addAttribute(attName, attVal) |
| 518 |
|
| 519 |
@classmethod |
| 520 |
def getPrefixInfo(cls, prefix: str) -> Tuple[str, Optional[str]]: |
| 521 |
return (cls._registry[prefix], cls._schemaLocations[prefix]) |
| 522 |
|
| 523 |
@classmethod |
| 524 |
def getSchemaForNS(self, ns: str) -> Optional[str]: |
| 525 |
try: |
| 526 |
return self._schemaLocations[self._reverseRegistry[ns]] |
| 527 |
except KeyError: |
| 528 |
raise excs.NotFoundError(ns, "XML namespace", |
| 529 |
"registry of XML namespaces.", hint="The registry is filled" |
| 530 |
" by modules as they are imported -- maybe you need to import" |
| 531 |
" the right module?") |
| 532 |
|
| 533 |
|
| 534 |
registerPrefix = NSRegistry.registerPrefix |
| 535 |
getPrefixInfo = NSRegistry.getPrefixInfo |
| 536 |
|
| 537 |
def schemaURL(xsdName: str) -> str: |
| 538 |
"""returns the URL to the local mirror of the schema xsdName. |
| 539 |
|
| 540 |
This is used by the various xmlstan clients to make schemaLocations. |
| 541 |
""" |
| 542 |
return "http://vo.ari.uni-heidelberg.de/docs/schemata/"+xsdName |
| 543 |
|
| 544 |
|
| 545 |
registerPrefix("xsi","http://www.w3.org/2001/XMLSchema-instance", None) |
| 546 |
# convenience for _additionalPrefixes of elements needing the xsi prefix |
| 547 |
# (and no others) in their attributes. |
| 548 |
xsiPrefix = frozenset(["xsi"]) |
| 549 |
|
| 550 |
|
| 551 |
class NillableMixin: |
| 552 |
"""An Element mixin making the element XSD nillable. |
| 553 |
|
| 554 |
This element will automatically have an xsi:nil="true" attribute |
| 555 |
on empty elements (rather than leave them out entirely). |
| 556 |
|
| 557 |
This overrides apply, so the mixin must be before the base class in |
| 558 |
the inheritance list. |
| 559 |
""" |
| 560 |
# typing TODO: Mixins are nasty; we would need to define a Protocol, |
| 561 |
# which seems over the top here. Let's see if they come up with something |
| 562 |
# smarter and meanwhile sprinkle ignore-s. |
| 563 |
_mayBeEmpty = True |
| 564 |
|
| 565 |
def apply(self, func: Callable) -> Any: |
| 566 |
if self.text_: # type: ignore |
| 567 |
return Element.apply(self, func) # type: ignore |
| 568 |
else: |
| 569 |
attrs = self._makeAttrDict() # type: ignore |
| 570 |
attrs["xsi:nil"] = "true" |
| 571 |
self._additionalPrefixes |= {"xsi"} # type: ignore |
| 572 |
return func(self, "", attrs, ()) |
| 573 |
|
| 574 |
def isEmpty(self) -> bool: |
| 575 |
return False |
| 576 |
|
| 577 |
|
| 578 |
def escapePCDATA(val: str | bytes) -> str: |
| 579 |
if isinstance(val, bytes): |
| 580 |
val = val.decode("utf-8") |
| 581 |
|
| 582 |
return (val |
| 583 |
).replace("&", "&" |
| 584 |
).replace('<', '<' |
| 585 |
).replace('>', '>' |
| 586 |
).replace("\0", "&x00;") |
| 587 |
|
| 588 |
|
| 589 |
def escapeAttrVal(val: str) -> str: |
| 590 |
return '"%s"'%(escapePCDATA(val).replace('"', '"')) |
| 591 |
|
| 592 |
|
| 593 |
class WriteBuffer: |
| 594 |
"""a very simple write buffer, collecting strings and handing them |
| 595 |
through to an actual files in suitably large chunks. |
| 596 |
|
| 597 |
This ought to help make our XML writing to twisted requests a bit |
| 598 |
more wire-efficient. |
| 599 |
|
| 600 |
The raw argument of course can't be Any, it needs to be a |
| 601 |
binary-writable thing. I'm not giving a proper type because |
| 602 |
what's here most of the time is a twisted web Request. The |
| 603 |
incomplete implementation of an io writer is also why this |
| 604 |
class exists in the first place. |
| 605 |
""" |
| 606 |
def __init__(self, raw: Any, bufSize: int=8192): |
| 607 |
self.raw, self.bufSize = raw, 8192 |
| 608 |
self.curSize = 0 |
| 609 |
self.buffer: List[bytes] = [] |
| 610 |
|
| 611 |
def write(self, data): |
| 612 |
self.curSize += len(data) |
| 613 |
self.buffer.append(data) |
| 614 |
if self.curSize>=self.bufSize: |
| 615 |
self.flush() |
| 616 |
|
| 617 |
def flush(self): |
| 618 |
self.raw.write(b"".join(self.buffer)) |
| 619 |
self.curSize, self.buffer = 0, [] |
| 620 |
|
| 621 |
|
| 622 |
def _makeVisitor( |
| 623 |
outputFile: Union[IO, WriteBuffer], |
| 624 |
prefixForEmpty: Optional[str]) -> Callable: |
| 625 |
"""returns a function writing nodes to outputFile. |
| 626 |
""" |
| 627 |
|
| 628 |
def visit( |
| 629 |
node: Any, |
| 630 |
text: str, |
| 631 |
attrs: Dict[str, str], |
| 632 |
childIter: Iterator) -> None: |
| 633 |
attrRepr = " ".join(sorted("%s=%s"%(k, escapeAttrVal(attrs[k])) |
| 634 |
for k in attrs)) |
| 635 |
if attrRepr: |
| 636 |
attrRepr = " "+attrRepr |
| 637 |
|
| 638 |
if getattr(node, "_fixedTagMaterial", None): |
| 639 |
attrRepr = attrRepr+" "+node._fixedTagMaterial |
| 640 |
|
| 641 |
if not node._prefix or node._local or node._prefix==prefixForEmpty: |
| 642 |
name = node.name_ |
| 643 |
else: |
| 644 |
name = "%s:%s"%(node._prefix, node.name_) |
| 645 |
|
| 646 |
if node.isEmpty(): |
| 647 |
if node._mayBeEmpty: |
| 648 |
outputFile.write(texttricks.bytify("<%s%s/>"%(name, attrRepr))) |
| 649 |
else: |
| 650 |
outputFile.write(texttricks.bytify("<%s%s>"%(name, attrRepr))) |
| 651 |
try: |
| 652 |
try: |
| 653 |
if text: |
| 654 |
outputFile.write(texttricks.bytify(escapePCDATA(text))) |
| 655 |
|
| 656 |
for c in childIter: |
| 657 |
if hasattr(c, "write"): |
| 658 |
c.write(outputFile) |
| 659 |
else: |
| 660 |
c.apply(visit) |
| 661 |
except Exception as ex: |
| 662 |
if hasattr(node, "writeErrorElement"): |
| 663 |
node.writeErrorElement(outputFile, ex) |
| 664 |
raise |
| 665 |
finally: |
| 666 |
outputFile.write(texttricks.bytify("</%s>"%name)) |
| 667 |
|
| 668 |
return visit |
| 669 |
|
| 670 |
|
| 671 |
def xmlwrite( |
| 672 |
root: Element, |
| 673 |
outputFile: BytesWritable, |
| 674 |
prefixForEmpty: Optional[str] = None, |
| 675 |
nsRegistry: Type[NSRegistry] = NSRegistry, |
| 676 |
xmlDecl: bool = True, |
| 677 |
includeSchemaLocation: bool = True, |
| 678 |
prolog: Optional[str] = None) -> None: |
| 679 |
"""writes an xmlstan tree starting at root to outputFile. |
| 680 |
|
| 681 |
prefixForEmpty is a namespace URI that should have no prefix at all. |
| 682 |
|
| 683 |
outputFile must be opened in binary mode. |
| 684 |
""" |
| 685 |
# since namespaces only enter here through prefixes, I just need to |
| 686 |
# figure out which ones are used. |
| 687 |
prefixesUsed: Set[str] = set() |
| 688 |
|
| 689 |
def collectPrefixes( |
| 690 |
node: Element, |
| 691 |
text: str, |
| 692 |
attrs: Dict[str, str], |
| 693 |
childIter: Iterator[Any], |
| 694 |
prefixesUsed: Set[str] = prefixesUsed) -> None: |
| 695 |
prefixesUsed |= node._additionalPrefixes |
| 696 |
prefixesUsed.add(node._prefix) |
| 697 |
for child in childIter: |
| 698 |
child.apply(collectPrefixes) |
| 699 |
|
| 700 |
# put a buffer between us and the output; if we don't twisted |
| 701 |
# will produce one little chunk per tag in http chunked encoding. |
| 702 |
buffered = WriteBuffer(outputFile) |
| 703 |
|
| 704 |
root.apply(collectPrefixes) |
| 705 |
# An incredibly nasty hack for VOTable generation; we need a better |
| 706 |
# way to handle with the 1.1/1.2 namespaces: Root may declare it |
| 707 |
# handles all NS declarations itself. Die, die, die. |
| 708 |
if getattr(root, "_fixedTagMaterial", None) is None: |
| 709 |
nsRegistry.addNamespaceDeclarations(root, prefixesUsed, prefixForEmpty, |
| 710 |
includeSchemaLocation) |
| 711 |
|
| 712 |
if xmlDecl: |
| 713 |
buffered.write(b"<?xml version='1.0' encoding='utf-8'?>\n") |
| 714 |
|
| 715 |
if prolog: |
| 716 |
buffered.write(texttricks.bytify(prolog)+b"\n") |
| 717 |
|
| 718 |
try: |
| 719 |
root.apply(_makeVisitor(buffered, prefixForEmpty)) |
| 720 |
finally: |
| 721 |
buffered.flush() |
| 722 |
|
| 723 |
|
| 724 |
def xmlrender( |
| 725 |
tree: Element, |
| 726 |
prolog: str = "", |
| 727 |
prefixForEmpty: Optional[Any] = None) -> bytes: |
| 728 |
"""returns a unicode object containing tree in serialized forms. |
| 729 |
|
| 730 |
tree should be a stanxml.Element. Anything else will be phased out. |
| 731 |
|
| 732 |
If prolog is given, it must be a string that will be prepended to the |
| 733 |
serialization of tree. The way ElementTree currently is implemented, |
| 734 |
you can use this for xml declarations or stylesheet processing |
| 735 |
instructions. |
| 736 |
""" |
| 737 |
# Historically, we have accepted all kind of mess in here. In the |
| 738 |
# end, we only want to retain option 1 of the following selection. |
| 739 |
# TODO: nuke the rest |
| 740 |
if hasattr(tree, "render"): |
| 741 |
res = tree.render(prefixForEmpty=prefixForEmpty) |
| 742 |
elif isinstance(tree, bytes): |
| 743 |
res = tree |
| 744 |
elif isinstance(tree, str): |
| 745 |
res = tree.encode("utf-8") |
| 746 |
else: |
| 747 |
raise ValueError("Cannot render %s"%repr(tree)) |
| 748 |
|
| 749 |
if prolog: |
| 750 |
res = texttricks.bytify(prolog)+res |
| 751 |
return res |