Debian Codegraph @

gavo/base/meta.py

raw
1 """
2 Code dealing with meta information.
3
4 In DaCHS, tree-structured metadata can be attached to tables, services,
5 resources as a whole, and some other structures. This module provides
6 a python mixin to keep and manipulate such metadata.
7
8 We deal with VO-style RMI metadata but also allow custom metadata. Custom
9 metadata keys should usually start with _.
10
11 See develNotes for some discussion of why this is so messy and an explanation
12 of why in particular addMeta and helpers are a minefield of selections.
13
14 The rough plan to do this looks like this:
15
16 Metadata is kept in containers that mix in MetaMixin. Meta information is
17 accessed through keys of the form <atom>{.<atom>} The first atom is the
18 primary key. An atom consists exclusively of ascii letters and the
19 underscore.
20
21 There's a meta mixin having the methods addMeta and getMeta that care
22 about finding metadata including handover. For compound metadata, they
23 will split the key and hand over to the parent if the don't have a meta
24 item for the main key.
25
26 To make this complete for DaCHS, this needs to be completemented with magic,
27 "typed" meta classes overriding certain types of behaviour (see the
28 forKeys class decorator for how this works); base.__init__ arranges
29 for base.typedmeta to be imported. To access these magic types,
30 use META_CLASSES_FOR_KEYS (but don't change that directory except
31 through @meta.forKeys).
32 """
33
34 #c Copyright 2008-2025, the GAVO project <[email protected]>
35 #c
36 #c This program is free software, covered by the GNU GPL. See the
37 #c COPYING file in the source distribution.
38
39
40 import functools
41 import re
42 import textwrap
43
44 from gavo import utils
45 from gavo.base import attrdef
46 from gavo.base import common
47 from gavo.base import config
48 from gavo.utils import stanxml
49
50 from gavo.utils.dachstypes import (
51 cast,
52 Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence,
53 StanElement, StructParseContext, StructParserValue,
54 Structure, Tuple, TYPE_CHECKING, Type, Union)
55
56
57 if TYPE_CHECKING:
58 # what you can pass as value to most methods
59 _MetaSeed = Union[None, str, "MetaMixin"]
60 from gavo.base.macros import MacroPackage
61 else:
62 _MetaSeed, MacroPackage = None, None
63
64
65 # This dictionary maps meta atoms that were found to be somehow
66 # misleading or confusing to the ones that are now used. This
67 # is so RDs won't get broken.
68 DEPRECATED_ATOMS = {
69 "_associatedDatalinkSvc": "_associatedDatalinkService",
70 }
71
72
73 class MetaError(utils.Error):
74 """A base class for metadata-related errors.
75
76 MetaErrors have a carrier attribute that should point to the MetaMixin
77 item queried. Metadata propagation makes this a bit tricky, but we
78 should at least try; for setMeta and addMeta, the top-level entry
79 functions manipulate the carrier attributes for this purpose.
80
81 To yield useful error messages, leave carrier at its default None
82 only when you really have no idea what the meta will end up on.
83 """
84 def __init__(self,
85 msg: str,
86 carrier: Optional["MetaMixin"] = None,
87 hint: Optional[str] = None,
88 key: Optional[str] = None) -> None:
89 self.carrier = carrier
90 self.key = key
91 utils.Error.__init__(self, msg, hint=hint)
92
93 def __str__(self) -> str:
94 prefix = ""
95 if self.carrier:
96 prefix = "On %s: "%repr(self.carrier)
97 return prefix+utils.Error.__str__(self)
98
99 class MetaSyntaxError(MetaError):
100 """is raised when a meta key is invalid.
101 """
102
103
104 class NoMetaKey(MetaError):
105 """is raised when a meta key does not exist (and raiseOnFail is True).
106 """
107
108
109 class MetaCardError(MetaError):
110 """is raised when a meta value somehow has the wrong cardinality (e.g.,
111 on attempting to stringify a sequence meta).
112 """
113 def __init__(self,
114 msg: str,
115 carrier: Optional["MetaMixin"] = None,
116 hint: Optional[str] = None,
117 key: Optional[str] = None) -> None:
118 self.origMsg = msg
119 if key is None:
120 MetaError.__init__(self, msg, hint=hint)
121 else:
122 MetaError.__init__(self, "%s (key %s)"%(msg, key), hint=hint)
123
124
125 class MetaValueError(MetaError):
126 """is raised when a meta value is inapproriate for the key given.
127 """
128
129 #############################################
130 # Magic meta handling start
131
132 META_CLASSES_FOR_KEYS: Dict[str, Type["MetaValue"]] = {}
133
134 def forKeys(*keys: str) -> Callable[[Type["MetaValue"]], Type["MetaValue"]]:
135 """decorates typed MetaValues and declares them to handle one or more
136 meta keys.
137 """
138 def _(cls: Type["MetaValue"]) -> Type["MetaValue"]:
139 for k in keys:
140 assert k not in META_CLASSES_FOR_KEYS, "Redefining "+k
141 META_CLASSES_FOR_KEYS[k] = cls
142 return cls
143 return _
144
145
146 @functools.lru_cache(maxsize=16)
147 def getKeysForClass(metaCls: Type["MetaValue"]) -> Sequence[str]:
148 """yields all the keys that will lead to a metaCls-typed meta value.
149
150 subclasses count as well.
151 """
152 return [key
153 for key, val in META_CLASSES_FOR_KEYS.items()
154 if issubclass(val, metaCls)]
155
156
157 def doMetaOverride(
158 container: "MetaMixin",
159 metaKey: str,
160 metaValue: _MetaSeed,
161 extraArgs: Dict[str, Any] = {}) -> bool:
162 """creates the representation of metaKey/metaValue in container.
163
164 This is there for magic meta types, mostly from typedmeta. It
165 inspects META_CLASSES_FOR_KEYS, which in turn is fed by
166 the forKeys class decorator. There's some hard-coded junk
167 in here that doesn't quite fit anywhere else yet (but that should
168 be rationalised if more hackery of this kind becomes necessary).
169
170 If metaKey does not need any special action, this returns None.
171
172 This gets called from one central point in MetaMixin.addMeta, and
173 essentially all magic involved should be concentrated here.
174 """
175 if metaKey in META_CLASSES_FOR_KEYS and not isinstance(metaValue, MetaValue):
176 try:
177 container.addMeta(metaKey,
178 META_CLASSES_FOR_KEYS[metaKey](metaValue, **extraArgs))
179 return True
180 except TypeError:
181 raise utils.logOldExc(MetaError(
182 "Invalid arguments for %s meta items: %s"%(metaKey,
183 utils.safe_str(extraArgs)), None))
184
185 # let's see if there's some way to rationalise this kind of thing
186 # later.
187 if metaKey=="creator":
188 return _doCreatorMetaOverride(container, metaValue)
189
190 elif metaKey=="copyright" or metaKey=="_copyright":
191 # Backwards compatibility 2019; it's cheap enough so I don't
192 # bother deprecating the two keys for now.
193 container.addMeta("rights", metaValue, **extraArgs)
194
195 # fallthrough: let addMeta do its standard thing.
196 return False
197
198
199 def _doCreatorMetaOverride(
200 container: "MetaMixin",
201 value: _MetaSeed) -> bool:
202 """handles the adding of the creator meta.
203
204 value is empty or a parsed meta value, this does nothing (which will cause
205 addMeta to do its default operation).
206
207 If value is a non-empty string, it will be split along semicolons
208 to produce individual creator metas with names .
209 """
210 if not value or isinstance(value, MetaValue):
211 return False
212
213 value = cast(str, value)
214 for authName in (s.strip() for s in value.split(";")):
215 container.addMeta("creator",
216 MetaValue().addMeta("name", authName))
217
218 return True
219
220
221 class IncludesChildren(str):
222 """a formatted result that already includes all meta children.
223
224 This is returned from some of the special meta types' HTML formatters
225 to keep the HTMLMetaBuilder from adding meta items that are already
226 included in their HTML.
227 """
228
229 # Magic meta handling end
230 #############################################
231
232
233 _metaPat = re.compile(r"([a-zA-Z_][\w-]*)(?:\.([a-zA-Z_][\w-]*))*$")
234 _primaryPat = re.compile(r"([a-zA-Z_][\w-]*)(\.|$)")
235
236
237 def parseKey(metaKey: str) -> Sequence[str]:
238 """returns a list of the meta atoms in a meta key.
239
240 Deprecated atoms are replaced by their successors.
241 """
242 if not _metaPat.match(metaKey):
243 raise MetaSyntaxError("Invalid meta key: %s"%metaKey, None)
244
245 parsed = metaKey.split(".")
246 for atom in parsed:
247 if atom in DEPRECATED_ATOMS:
248 utils.sendUIEvent("Warning", "Deprecated meta atom %s used in %s;"
249 " please change the atom to %s."%(
250 atom, metaKey, DEPRECATED_ATOMS[atom]))
251 return [DEPRECATED_ATOMS.get(a, a) for a in parsed]
252
253 return parsed
254
255
256 def parseMetaStream(
257 metaContainer: "MetaMixin",
258 metaStream: str,
259 clearItems: bool = False) -> None:
260 """parses meta key/value pairs from metaStream and adds them to
261 metaContainer.
262
263 If clearItems is true, for each key found in the metaStream there's
264 first a delMeta for that key executed. This is for re-parsing
265 meta streams.
266
267 The stream format is:
268
269 - continuation lines with backslashes, where any sequence of
270 backslash, (cr?) lf (blank or tab)* is replaced by nothing.
271 - comments are lines like (ws*)# anything
272 - empty lines are no-ops
273 - all other lines are (ws*)<key>(ws*):(ws*)value(ws*)
274 - if a key starts with !, any meta info for the key is cleared before
275 setting
276 - a value may be prefixed with rst:, literal:, or raw: to set the format
277 of the meta literal (default is plain).
278 """
279 if metaStream is None:
280 return
281
282 # handle continuation lines
283 metaStream = re.sub("\\\\\r?\n[\t ]*", "", metaStream)
284
285 keysSeen = set()
286
287 for line in metaStream.split("\n"):
288 line = line.strip()
289 if line.startswith("#") or not line:
290 continue
291 try:
292 key, value = line.split(":", 1)
293 except ValueError:
294 raise MetaSyntaxError("%s is no valid line for a meta stream"%
295 repr(line), None,
296 hint="In general, meta streams contain lines like 'meta.key:"
297 " meta value; see also the documentation.")
298
299 key = key.strip()
300 if key.startswith("!"):
301 key = key[1:]
302 metaContainer.delMeta(key)
303
304 if key not in keysSeen and clearItems:
305 metaContainer.delMeta(key)
306 keysSeen.add(key)
307
308 value, format = value.strip(), "plain"
309 mat = re.match("(rst|literal|raw):", value)
310 if mat:
311 value = value[mat.end():].strip()
312 format = mat.group(1)
313
314 metaContainer.addMeta(key, value, format=format)
315
316
317 class MetaParser(common.Parser):
318 """A structure parser that kicks in when meta information is
319 parsed from XML.
320
321 This parser can also handle the notation with an attribute-less
322 meta tag and lf-separated colon-pairs as content.
323 """
324 # These are constructed a lot, so let's keep __init__ as clean as possible.
325 def __init__(self, container: "MetaMixin", nextParser: common.Parser):
326 self.container, self.nextParser = container, nextParser
327 self.attrs: Dict[str, StructParserValue] = {}
328 self.children: List[Tuple[str, _MetaSeed, Dict]] = []
329 self.next: Optional[str] = None
330
331 def addMeta(self, key: str, content: _MetaSeed = "", **kwargs: Any
332 ) -> None:
333 # this parse can be a temporary meta parent for children; we
334 # record them here and play them back when we have created
335 # the meta value itself
336 self.children.append((key, content, kwargs))
337
338 def setMeta(self, key:str, content: _MetaSeed = "", **kwargs: Any
339 ) -> None:
340 # see addMeta comment on why we need to do magic here.
341 self.children.append(("!"+key, content, kwargs))
342
343 def start_(self, ctx: StructParseContext, name: str, value: StructParserValue
344 ) -> Optional[common.Parser]:
345 if name=="meta":
346 return MetaParser(cast("MetaMixin", self), self)
347 else:
348 self.next = name
349 return self
350
351 def value_(self, ctx: StructParseContext, name: str, value: StructParserValue
352 ) -> common.Parser:
353 if self.next is None:
354 self.attrs[str(name)] = value
355 else:
356 self.attrs[str(self.next)] = value
357 return self
358
359 def _doAddMeta(self) -> None:
360 content = cast(str, self.attrs.pop("content_", ""))
361 if not self.attrs: # content only, parse this as a meta stream
362 parseMetaStream(cast("MetaMixin", self.container), content)
363
364 else:
365 try:
366 content = utils.fixIndentation(content, "", 1).rstrip()
367 except common.Error as ex:
368 raise utils.logOldExc(common.StructureError("Bad text in meta value"
369 " (%s)"%ex))
370 if not "name" in self.attrs:
371 raise common.StructureError("meta elements must have a"
372 " name attribute")
373
374 metaKey = cast(str, self.attrs.pop("name"))
375 if metaKey.startswith("!"):
376 self.container.setMeta(metaKey[1:], content, **self.attrs)
377 else:
378 self.container.addMeta(metaKey, content, **self.attrs)
379
380 # meta elements can have children; add these, properly fudging
381 # their keys. The ignored type is because mypy doesn't see
382 # that content is a string here.
383 for key, content, kwargs in self.children: # type: ignore
384 if key.startswith("!"):
385 fullKey = "%s.%s"%(metaKey, key[1:])
386 self.container.setMeta(fullKey, content, **kwargs)
387 else:
388 fullKey = "%s.%s"%(metaKey, key)
389 self.container.addMeta(fullKey, content, **kwargs)
390
391 def end_(self, ctx: StructParseContext, name: str, value: StructParserValue
392 ) -> Optional[common.Parser]:
393 if name=="meta":
394 try:
395 self._doAddMeta()
396 except TypeError as msg:
397 raise utils.StructureError("While constructing meta: %s"%msg)
398 return self.nextParser
399
400 else:
401 self.next = None
402 return self
403
404
405 class MetaAttribute(attrdef.AttributeDef):
406 """An attribute magically inserting meta values to Structures mixing
407 in MetaMixin.
408
409 We don't want to keep metadata itself in structures for performance
410 reasons, so we define a parser of our own in here.
411 """
412 typedesc = "Metadata"
413
414 def __init__(self, description: str = "Metadata") -> None:
415 attrdef.AttributeDef.__init__(self, "meta_",
416 attrdef.Computed, description)
417 self.aliases = ["meta"]
418
419 @property
420 def default_(self) -> Dict[str, "MetaItem"]:
421 return {}
422
423 def feedObject(self, instance: Structure, value: "MetaItem") -> None:
424 self.meta_ = value
425
426 def getCopy(self,
427 parent: Union["MetaMixin", Structure],
428 newParent: Union["MetaMixin", Structure],
429 ctx: StructParseContext) -> Dict[str, "MetaItem"]:
430 """creates a deep copy of the current meta dictionary and returns it.
431
432 This is used when a MetaMixin's attribute is set to copyable and a
433 meta carrier is copied. As there's currently no way to make the
434 _metaAttr copyable, this isn't called by itself. If you
435 must, you can manually call this (_metaAttr.getCopy), but that'd
436 really be an indication the interface needs changes.
437
438 Note that the copying semantics is a bit funky: Copied values
439 remain, but on write, sequences are replaced rather than added to.
440 """
441 parent, newParent = cast(MetaMixin, parent), cast(MetaMixin, newParent)
442 oldDict = parent.meta_
443 newMeta = {}
444 for key, mi in oldDict.items():
445 newMeta[key] = mi.copy()
446 return newMeta
447
448 def create(self, parent: "MetaMixin", ctx: StructParseContext, name: str
449 ) -> common.Parser:
450 return MetaParser(parent, cast(common.Parser, parent))
451
452 def makeUserDoc(self) -> Optional[str]:
453 return ("**meta** -- a piece of meta information, giving at least a name"
454 " and some content. See Metadata_ on what is permitted here.")
455
456 def iterEvents(self, instance: Structure) -> Iterator[common.ParserEvent]:
457 def doIter(metaDict: Dict[str, "MetaItem"]
458 ) -> Iterator[common.ParserEvent]:
459 for key, item in metaDict.items():
460 for value in item:
461 yield common.ParserEvent("start", "meta", None)
462 yield common.ParserEvent("value", "name", key)
463 if value.getContent():
464 yield common.ParserEvent("value", "content_", value.getContent())
465
466 if value.meta_:
467 yield from doIter(value.meta_)
468 yield common.ParserEvent("end", "meta", None)
469
470 yield from doIter(cast("MetaMixin", instance).meta_)
471
472
473 class MetaMixin(common.StructCallbacks):
474 """A mixin for entities carrying meta information.
475
476 The meta mixin provides the following methods:
477
478 - setMetaParent(m) -- sets the name of the meta container enclosing the
479 current one. m has to have the Meta mixin as well.
480 - getMeta(key, propagate=True, raiseOnFail=False, default=None) -- returns
481 meta information for key or default.
482 - addMeta(key, metaItem, moreAttrs) -- adds a piece of meta information
483 here. Key may be a compound, metaItem may be a text, in which
484 case it will be turned into a proper MetaValue taking key and
485 moreAttrs into account.
486 - setMeta(key, metaItem) -- like addMeta, only previous value(s) are
487 overwritten
488 - delMeta(key) -- removes a meta value(s) for key.
489
490 When querying meta information, by default all parents are queried as
491 well (propagate=True).
492
493 Metadata is not copied when the embedding object is copied.
494 That, frankly, has not been a good design decision, and there should
495 probably be a way to pass copypable=True to the mixin's attribute
496 definition.
497 """
498 _metaAttr = MetaAttribute()
499
500 def __init__(self) -> None:
501 """is a constructor for standalone use. You do *not* want to
502 call this when mixing into a Structure.
503 """
504 self.meta_: Dict[str, "MetaItem"] = {}
505
506 def __hasMetaParent(self) -> bool:
507 try:
508 self.__metaParent # assert existence
509 return True
510 except AttributeError:
511 return False
512
513 def isEmpty(self) -> bool:
514 return len(self.meta_)==0 and getattr(self, "content", "")==""
515
516 def setMetaParent(self, parent: "MetaMixin") -> None:
517 if parent is not None:
518 self.__metaParent = parent
519
520 def setParent(self, parent: "MetaMixin") -> None:
521 if hasattr(parent, "_getMeta"):
522 self.setMetaParent(parent)
523 super().setParent(parent)
524
525 def getMetaParent(self) -> Optional["MetaMixin"]:
526 if self.__hasMetaParent():
527 return self.__metaParent
528 else:
529 return None
530
531 def _getMeta(self,
532 atoms: Sequence[str],
533 propagate: bool,
534 acceptSequence: bool = False) -> "MetaItem":
535 try:
536 return self._getFromAtom(atoms[0])._getMeta(atoms[1:],
537 acceptSequence=acceptSequence)
538 except NoMetaKey:
539 pass # See if parent has the key
540
541 if propagate:
542 if self.__hasMetaParent():
543 return self.__metaParent._getMeta(atoms, propagate,
544 acceptSequence=acceptSequence)
545 else:
546 return CONFIG_META._getMeta(atoms, propagate=False,
547 acceptSequence=acceptSequence)
548
549 raise NoMetaKey("No meta item %s"%".".join(atoms), carrier=self)
550
551 def getMeta(self,
552 key: str,
553 propagate: bool = True,
554 raiseOnFail:bool = False,
555 default: Optional[str] = None,
556 acceptSequence: bool = False) -> Union["MetaItem", Optional[str]]:
557 try:
558 try:
559 return self._getMeta(
560 parseKey(key), propagate, acceptSequence=acceptSequence)
561 except NoMetaKey as ex:
562 if raiseOnFail:
563 ex.key = key
564 raise
565 except MetaCardError as ex:
566 raise utils.logOldExc(
567 MetaCardError(ex.origMsg, hint=ex.hint, key=key))
568 except MetaError as ex:
569 ex.carrier = self
570 raise
571 return default
572
573 def hasMeta(self, atom: str, propagate: bool = False) -> bool:
574 """returns true if this meta carrier has an atom metadatum.
575
576 This will *not* parse atom, so you cannot (yet) pass in hierarchical
577 meta names.
578
579 With propagate, it will also ask the meta parents.
580
581 In user code, it is generally preferable to just call getMeta
582 with raiseOnFail. This is mainly a shortcut for internal code.
583 """
584 if atom in self.meta_:
585 return True
586 if propagate:
587 parent = self.getMetaParent()
588 if parent:
589 return parent.hasMeta(atom, True)
590 return False
591
592 def _iterMeta(self, atoms: Sequence[str]) -> Iterable["MetaValue"]:
593 mine, others = atoms[0], atoms[1:]
594 for mv in self.meta_.get(mine, []):
595 if others:
596 for child in mv._iterMeta(others):
597 yield child
598 else:
599 yield mv
600
601 def iterMeta(self, key: str, propagate: bool = False
602 ) -> Iterable["MetaValue"]:
603 """yields all MetaValues for key.
604
605 This will traverse down all branches necessary to yield, in sequence,
606 all MetaValues reachable by key.
607
608 If propagation is enabled, the first meta carrier that has at least
609 one item exhausts the iteration.
610
611 (this currently doesn't return an iterator but a sequence; that's an
612 implementation detail, though. You should only assume whatever comes
613 back is iterable)
614 """
615 val: Iterable[MetaValue] = list(self._iterMeta(parseKey(key)))
616 if not val and propagate:
617 if self.__hasMetaParent():
618 val = self.__metaParent.iterMeta(key, propagate=True)
619 else:
620 val = CONFIG_META.iterMeta(key, propagate=False)
621 return val
622
623 def getAllMetaPairs(self) -> Iterator[Tuple[str, "MetaItem"]]:
624 """iterates over all meta items this container has.
625
626 Each item consists of key, MetaValue. Multiple MetaValues per
627 key may be given.
628
629 This will not iterate up, i.e., in general, getMeta will succeed
630 for more keys than what's given here.
631 """
632 class Accum(MetaBuilder):
633 def __init__(self):
634 self.items = []
635 self.keys = []
636 def startKey(self, key: str) -> None:
637 self.keys.append(key)
638 def enterValue(self, value: MetaValue) -> None:
639 self.items.append((".".join(self.keys), value))
640 def endKey(self, key: str) -> None:
641 self.keys.pop()
642
643 accum = Accum()
644 self.traverse(accum)
645 return accum.items
646
647 def buildRepr(self,
648 key: str,
649 builder: "MetaBuilder",
650 propagate: bool = True,
651 raiseOnFail: bool = True) -> str:
652 value = self.getMeta(key, raiseOnFail=raiseOnFail, propagate=propagate)
653 if value:
654 builder.startKey(key)
655 cast(MetaItem, value).traverse(builder)
656 builder.endKey(key)
657 return builder.getResult()
658
659 def _hasAtom(self, atom: str) -> bool:
660 return atom in self.meta_
661
662 def _getFromAtom(self, atom: str) -> "MetaItem":
663 if atom in self.meta_:
664 return self.meta_[atom]
665 raise NoMetaKey("No meta child %s"%atom, carrier=self)
666
667 def getMetaKeys(self) -> List[str]:
668 return list(self.meta_.keys())
669
670 # If you are looking for a keys method here: use getMetaKeys;
671 # keys has existed up to 2.11, but it was too common a name to keep.
672
673 def _setForAtom(self, atom: str, metaItem: "MetaItem") -> None:
674 self.meta_[atom] = metaItem
675
676 def _addMeta(self, atoms: Sequence[str], metaValue: _MetaSeed) -> None:
677 primary = atoms[0]
678 if primary in self.meta_:
679 self.meta_[primary]._addMeta(atoms[1:], metaValue)
680 else:
681 self.meta_[primary] = MetaItem.fromAtoms(atoms[1:], metaValue)
682
683 def addMeta(self, key: str, metaValue: _MetaSeed, **moreAttrs: Any
684 ) -> "MetaMixin":
685 """adds metaItem to self under key.
686
687 moreAttrs can be additional keyword arguments; these are used by
688 the XML constructor to define formats or to pass extra items
689 to special meta types.
690
691 For convenience, this returns the meta container.
692 """
693 try:
694 if not doMetaOverride(self, key, metaValue, moreAttrs):
695 self._addMeta(parseKey(key), ensureMetaValue(metaValue, moreAttrs))
696 except MetaError as ex:
697 ex.carrier = self
698 raise
699
700 return self
701
702 def _delMeta(self, atoms: Sequence[str]) -> None:
703 if atoms[0] not in self.meta_:
704 return
705 if len(atoms)==1:
706 del self.meta_[atoms[0]]
707 else:
708 child = self.meta_[atoms[0]]
709 child._delMeta(atoms[1:])
710 if child.isEmpty():
711 del self.meta_[atoms[0]]
712
713 def delMeta(self, key: str) -> None:
714 """removes a meta item from this meta container.
715
716 This will not propagate, i.e., getMeta(key) might still
717 return something unless you give propagate=False.
718
719 It is not an error do delete an non-existing meta key.
720 """
721 self._delMeta(parseKey(key))
722
723 def setMeta(self, key: str, value: _MetaSeed, **moreAttrs: Any):
724 """replaces any previous meta content of key (on this container)
725 with value.
726 """
727 self.delMeta(key)
728 self.addMeta(key, value, **moreAttrs)
729
730 def traverse(self, builder: "MetaBuilder") -> None:
731 for key, item in self.meta_.items():
732 builder.startKey(key)
733 item.traverse(builder)
734 builder.endKey(key)
735
736 def copyMetaFrom(self, other: "MetaMixin") -> None:
737 """sets a copy of other's meta items on self.
738 """
739 for key in other.getMetaKeys():
740 orig = cast(MetaItem, other.getMeta(key))
741 if orig is not None:
742 # (orig None can happen for computed metadata)
743 self.meta_[key] = orig.copy()
744
745 def makeOriginal(self, key: str) -> None:
746 """marks the meta item key, if existing, as original.
747
748 This is for when a meta container has copied metadata. DaCHS'
749 default behaviour is that a subsequent addMeta will clear the
750 copied content. Call this method for the key in question to
751 enable adding to copied metadata.
752 """
753 item = self.getMeta(key)
754 if item is not None and hasattr(item, "copied"):
755 del item.copied
756
757
758 class ComputedMetaMixin(MetaMixin):
759 """A MetaMixin for classes that want to implement defaults for
760 unresolvable meta items.
761
762 If getMeta would return a NoMetaKey, this mixin's getMeta will check
763 the presence of a _meta_<key> method (replacing dots with two underscores)
764 and, if it exists, returns whatever it returns. Otherwise, the
765 exception will be propagated.
766
767 The _meta_<key> methods should return MetaItems; if something else
768 is returned, it is wrapped in a MetaValue.
769
770 On copying such metadata, the copy will retain the value on the original
771 if it has one. This does not work for computed metadata that would be
772 inherited.
773 """
774 def _getFromAtom(self, atom: str) -> "MetaItem":
775 try:
776 return MetaMixin._getFromAtom(self, atom)
777 except NoMetaKey:
778 methName = "_meta_"+atom
779 if hasattr(self, methName):
780 res = getattr(self, methName)()
781 if res is None:
782 raise
783 return ensureMetaItem(res)
784
785 raise
786
787 def getMetaKeys(self) -> List[str]:
788 computedKeys = []
789 for name in dir(self):
790 if name.startswith("_meta_"):
791 computedKeys.append(name[6:])
792 return MetaMixin.getMetaKeys(self)+computedKeys
793
794 def _iterMeta(self, atoms: Sequence[str]) -> Iterable["MetaValue"]:
795 if len(atoms)>1:
796 yield from MetaMixin._iterMeta(self, atoms)
797 else:
798 res: Union[List, MetaItem] = list(MetaMixin._iterMeta(self, atoms))
799 if not res:
800 try:
801 res = self._getFromAtom(atoms[0])
802 except NoMetaKey:
803 res = []
804 for val in res:
805 yield val
806
807
808 class MetaItem:
809 """A collection of homogeneous MetaValues.
810
811 All MetaValues within a MetaItem have the same key.
812
813 A MetaItem contains a list of children MetaValues; it is usually
814 constructed with just one MetaValue, though. Use the alternative
815 constructor formSequence if you already have a sequence of
816 MetaValues. Or, better, use the ensureMetaItem utility function.
817
818 The last added MetaValue is the "active" one that will be changed
819 on _addMeta calls.
820 """
821 def __init__(self, val: _MetaSeed):
822 self.children: List["MetaValue"] = []
823 self.addChild(val)
824
825 @classmethod
826 def fromSequence(cls, seq: Sequence[_MetaSeed]) -> "MetaItem":
827 res = cls(seq[0])
828 for item in seq[1:]:
829 res.addChild(item)
830 return res
831
832 @classmethod
833 def fromAtoms(cls, atoms: Sequence[str], metaValue: _MetaSeed) -> "MetaItem":
834 if len(atoms)==0: # This will become my child.
835 return cls(metaValue)
836
837 elif len(atoms)==1: # Create a MetaValue with the target as child
838 mv = MetaValue()
839 mv._setForAtom(atoms[0], cls(ensureMetaValue(metaValue)))
840 return cls(mv)
841
842 else: # Create a MetaValue with an ancestor of the target as child
843 mv = MetaValue()
844 mv._setForAtom(atoms[0], cls.fromAtoms(atoms[1:],
845 ensureMetaValue(metaValue)))
846 return cls(mv)
847
848 def __str__(self) -> str:
849 try:
850 res = self.getContent(targetFormat="text")
851 return res
852 except MetaError:
853 return ", ".join(m.getContent(targetFormat="text")
854 for m in self.children)
855
856 def __iter__(self) -> Iterator["MetaValue"]:
857 return iter(self.children)
858
859 def __len__(self) -> int:
860 return len(self.children)
861
862 def __getitem__(self, index: int) -> "MetaValue":
863 return self.children[index]
864
865 def isEmpty(self) -> bool:
866 return len(self)==0
867
868 def addContent(self, item: _MetaSeed) -> None:
869 cast(MetaItem, self.children[-1]).addContent(item)
870
871 def addChild(self,
872 metaValue: _MetaSeed = None,
873 key: Optional[str] = None) -> None:
874 # XXX should we force metaValue to be "compatible" with what's
875 # already in children?
876 if hasattr(self, "copied"):
877 self.children = []
878 delattr(self, "copied")
879 if metaValue is None:
880 metaValue = MetaValue(None)
881 if isinstance(metaValue, str):
882 metaValue = MetaValue(metaValue)
883
884 assert isinstance(metaValue, MetaValue)
885 self.children.append(metaValue)
886
887 def _getMeta(self, atoms: Sequence[str], acceptSequence: bool = False
888 ) -> "MetaItem":
889 if atoms:
890 if len(self.children)!=1 and not acceptSequence:
891 raise MetaCardError("Meta sequence in branch for getMeta")
892 else:
893 return self.children[0]._getMeta(
894 atoms, acceptSequence=acceptSequence)
895 return self
896
897 def _addMeta(self, atoms: Sequence[str], metaValue: _MetaSeed):
898 # See above for this mess -- I'm afraid it has to be that complex
899 # if we want to be able to build compound sequences using text labels.
900
901 # Case 1: Direct child of MetaMixin, sequence addition
902 if not atoms:
903 self.addChild(metaValue)
904 else:
905 self.children[-1]._addMeta(atoms, metaValue)
906 # the other cases are in MetaValue._addMeta
907
908 def getMeta(self, key: str, *args: Any, **kwargs: Any):
909 if len(self.children)==1:
910 return self.children[0].getMeta(key, *args, **kwargs)
911 else:
912 raise MetaCardError("No getMeta for meta value sequences",
913 carrier=cast(MetaMixin, self), key=key)
914
915 def getContent(self,
916 targetFormat: str = "text",
917 macroPackage: Optional[MacroPackage] = None,
918 acceptSequence: bool = False) -> str:
919 if len(self.children)==1 or acceptSequence:
920 return self.children[0].getContent(targetFormat, macroPackage)
921 raise MetaCardError("getContent not allowed for sequence meta items"
922 " ({}).".format(self.children),
923 carrier=cast(MetaMixin, self))
924
925 def _delMeta(self, atoms: Sequence[str]) -> None:
926 newChildren = []
927 for c in self.children:
928 c._delMeta(atoms)
929 if not c.isEmpty():
930 newChildren.append(c)
931 self.children = newChildren
932
933 def traverse(self, builder: "MetaBuilder") -> None:
934 """traverses the meta tree, calling methods on builder for each meta
935 item found.
936
937 See MetaBuilder for the methods called.
938 """
939 for mv in self.children:
940 if mv.content:
941 builder.enterValue(mv)
942 mv.traverse(builder)
943
944 def copy(self) -> "MetaItem":
945 """returns a deep copy of self.
946 """
947 newOb = self.__class__("")
948 newOb.children = [mv.copy() for mv in self.children]
949 # copied attribute evaluated in makeOriginal
950 newOb.copied = True # type: ignore # (dynamic sentinel)
951 return newOb
952
953 def serializeToXMLStan(self) -> str:
954 return str(self)
955
956
957 class _NoHyphenWrapper(textwrap.TextWrapper):
958 # we don't want whitespace after hyphens in plain meta strings (looks
959 # funny in HTML), so fix wordsep_re
960 wordsep_re = re.compile(
961 r'(\s+|' # any whitespace
962 r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
963
964
965 class MetaValue(MetaMixin):
966 """is a piece of meta information about a resource.
967
968 The content is always a string.
969
970 The text content may be in different formats, notably
971
972 - literal
973
974 - rst (restructured text)
975
976 - plain (the default)
977
978 - raw (for embedded HTML, mainly -- only use this if you know
979 the item will only be embedded into HTML templates).
980 """
981 knownFormats = set(["literal", "rst", "plain", "raw"])
982 paragraphPat = re.compile("\n\\s*\n")
983 consecutiveWSPat = re.compile(r"\s\s+")
984 plainWrapper = _NoHyphenWrapper(break_long_words=False,
985 replace_whitespace=True)
986
987 def __init__(self, content="", format="plain"):
988 self.initArgs = content, format
989 MetaMixin.__init__(self)
990 if format not in self.knownFormats:
991 raise common.StructureError(
992 "Unknown meta format '%s'; allowed are %s."%(
993 format, ", ".join(self.knownFormats)))
994 self.content = content
995 self.format = format
996 self._preprocessContent()
997
998 def __str__(self) -> str:
999 return self.getContent()
1000
1001 def __repr__(self) -> str:
1002 return "<meta {}>".format(utils.makeEllipsis(self.getContent(), 30))
1003
1004 def _preprocessContent(self) -> None:
1005 if self.format=="plain" and self.content is not None:
1006 self.content = "\n\n".join(self.plainWrapper.fill(
1007 self.consecutiveWSPat.sub(" ", para))
1008 for para in self.paragraphPat.split(self.content))
1009
1010 def _getContentAsText(self, content: str) -> str:
1011 return content
1012
1013 def _getContentAsHTML(self, content: str, block: bool = False) -> StanElement:
1014 if block:
1015 encTag = "p"
1016 else:
1017 encTag = "span"
1018 if self.format=="literal":
1019 return '<%s class="literalmeta">%s</%s>'%(encTag,
1020 stanxml.escapePCDATA(content), encTag)
1021 elif self.format=="plain":
1022 return "\n".join('<%s class="plainmeta">%s</%s>'%(
1023 encTag, stanxml.escapePCDATA(p), encTag)
1024 for p in content.split("\n\n"))
1025 elif self.format=="rst":
1026 # XXX TODO: figure out a way to have them block=False
1027 return utils.rstxToHTML(content)
1028 elif self.format=="raw":
1029 return content
1030
1031 return None # type: ignore # notreached
1032
1033 def getExpandedContent(self, macroPackage: Optional[MacroPackage]) -> str:
1034 if hasattr(macroPackage, "expand") and "\\" in self.content:
1035 return cast(MacroPackage, macroPackage).expand(self.content)
1036 return self.content
1037
1038 def getContent(self,
1039 targetFormat: str="text",
1040 macroPackage: Optional["MacroPackage"] = None) -> Union[StanElement, str]:
1041 content = self.getExpandedContent(macroPackage)
1042 if targetFormat=="text":
1043 return self._getContentAsText(content)
1044 elif targetFormat=="html":
1045 return self._getContentAsHTML(content)
1046 elif targetFormat=="blockhtml":
1047 return self._getContentAsHTML(content, block=True)
1048 else:
1049 raise MetaError("Invalid meta target format: %s"%targetFormat)
1050
1051 def _getMeta(self,
1052 atoms: Sequence[str],
1053 propagate: bool = False,
1054 acceptSequence: bool = False):
1055 return self._getFromAtom(atoms[0])._getMeta(atoms[1:],
1056 acceptSequence=acceptSequence)
1057
1058 def _addMeta(self, atoms: Sequence[str], metaValue: _MetaSeed):
1059 # Cases continued from MetaItem._addMeta
1060 # Case 2: Part of a compound, metaValue is to become direct child
1061 if len(atoms)==1:
1062 primary = atoms[0]
1063
1064 # Case 2.1: Requested child exists
1065 if self._hasAtom(primary):
1066 self._getFromAtom(primary).addChild(metaValue, primary)
1067
1068 # Case 2.2: Requested child does not exist
1069 else:
1070 self._setForAtom(primary, MetaItem(metaValue))
1071
1072 # Case 3: metaItem will become an indirect child
1073 else:
1074 primary = atoms[0]
1075
1076 # Case 3.1: metaValue will become a child of an existing child of ours
1077 if self._hasAtom(primary):
1078 self._getFromAtom(primary)._addMeta(atoms[1:], metaValue)
1079
1080 # Case 3.2: metaItem is on a branch that needs yet to be created.
1081 else:
1082 self._setForAtom(
1083 primary,
1084 MetaItem.fromAtoms(atoms[1:], metaValue))
1085
1086 def copy(self) -> "MetaValue":
1087 """returns a deep copy of self.
1088 """
1089 newOb = self.__class__(*self.initArgs)
1090 newOb.format, newOb.content = self.format, self.content
1091 newOb.copyMetaFrom(self)
1092 return newOb
1093
1094
1095 def printMetaTree(metaContainer: MetaMixin, curKey: str = "") -> None:
1096 #for debugging
1097 md = metaContainer.meta_
1098 for childName in md:
1099 childKey = curKey+"."+childName
1100 for child in md[childName]:
1101 print(childKey, child.getContent("text"))
1102 printMetaTree(child, childKey)
1103
1104
1105 def ensureMetaValue(val: _MetaSeed, moreAttrs: Any={}) -> MetaValue:
1106 """makes a MetaValue out of val and a dict moreAttrs unless val already
1107 is a MetaValue.
1108 """
1109 if isinstance(val, MetaValue):
1110 return val
1111 return MetaValue(val, **moreAttrs)
1112
1113
1114 def ensureMetaItem(
1115 thing: Union[_MetaSeed, List[_MetaSeed]],
1116 moreAttrs: Any={}) -> MetaItem:
1117 """ensures that thing is a MetaItem.
1118
1119 If it is not, thing is turned into a sequence of MetaValues, which is
1120 then packed into a MetaItem.
1121
1122 Essentially, if thing is not a MetaValue, it is made into one with
1123 moreAttrs. If thing is a list, this recipe is used for all its items.
1124 """
1125 if isinstance(thing, MetaItem):
1126 return thing
1127
1128 if isinstance(thing, list):
1129 return MetaItem.fromSequence(
1130 [ensureMetaValue(item, moreAttrs) for item in thing])
1131
1132 return MetaItem(ensureMetaValue(thing, moreAttrs))
1133
1134
1135 def getMetaText(
1136 ob: MetaMixin,
1137 key: str,
1138 default: Optional[str] = None,
1139 **kwargs: Any):
1140 """returns the meta item key from ob in text form if present, default
1141 otherwise.
1142
1143 You can pass getMeta keyword arguments (except default).
1144
1145 Additionally, there's acceptSequence; if set to true, this will
1146 return the first item of a sequence-valued meta item rather than
1147 raising an error.
1148
1149 ob will be used as a macro package if it has an expand method; to
1150 use something else as the macro package, pass a macroPackage keyword
1151 argument.
1152 """
1153 macroPackage = cast(MacroPackage, ob)
1154 if "macroPackage" in kwargs:
1155 macroPackage = kwargs.pop("macroPackage")
1156 acceptSequence = kwargs.get("acceptSequence", False)
1157
1158 m = ob.getMeta(key, default=None, **kwargs)
1159 if m is None:
1160 return default
1161 try:
1162 return cast(MetaItem, m).getContent(
1163 macroPackage=macroPackage, acceptSequence=acceptSequence)
1164 except MetaCardError as ex:
1165 raise MetaCardError(ex.origMsg,
1166 carrier=ex.carrier, hint=ex.hint, key=key)
1167
1168
1169 class MetaBuilder:
1170 """A base class for meta builders.
1171
1172 Builders are passed to a MetaItem's traverse method or to MetaMixin's
1173 buildRepr method to build representations of the meta information.
1174
1175 You can override startKey, endKey, and enterValue. If you are
1176 not doing anything fancy, you can get by by just overriding enterValue
1177 and inspecting curAtoms[-1] (which contains the last meta key).
1178
1179 You will want to override getResult.
1180 """
1181 def __init__(self) -> None:
1182 self.curAtoms: List[str] = []
1183
1184 def startKey(self, key: str) -> None:
1185 self.curAtoms.append(key)
1186
1187 def endKey(self, key: str) -> None:
1188 self.curAtoms.pop()
1189
1190 def enterValue(self, value: MetaValue) -> None:
1191 pass
1192
1193 def getResult(self) -> Any:
1194 pass
1195
1196
1197 class TextBuilder(MetaBuilder):
1198 """A MetaBuilder that recovers a tuple sequence of the meta items
1199 in text representation.
1200 """
1201 def __init__(self) -> None:
1202 self.metaItems: List[Tuple[str, str]] = []
1203 super(TextBuilder, self).__init__()
1204
1205 def enterValue(self, value: MetaValue) -> None:
1206 self.metaItems.append((".".join(self.curAtoms), value.getContent()))
1207
1208 def getResult(self) -> List[Tuple[str, str]]:
1209 return self.metaItems
1210
1211
1212 def stanFactory(tag: StanElement, **kwargs: Any
1213 ) -> Callable[[List[Any], Optional[Dict[str, Any]]], StanElement]:
1214 """returns a factory for ModelBasedBuilder built from a stan-like "tag".
1215 """
1216 def factory(args: List[Any], localattrs: Optional[Dict[str, Any]] = None
1217 ) -> StanElement:
1218 if localattrs:
1219 localattrs.update(kwargs)
1220 attrs = localattrs
1221 else:
1222 attrs = kwargs
1223
1224 if isinstance(tag, type):
1225 # this presumably is a stanxml.Element. Instantiate first
1226 el = tag()
1227 elif hasattr(tag, "clone"):
1228 # this ought to be something t.w.template.Tag-like
1229 el = tag.clone()
1230 else:
1231 # assume it's a factory function
1232 el = tag()
1233
1234 return el(**attrs)[args]
1235 return factory
1236
1237
1238 # Within this abomination of code, the following is particularly nasty.
1239 # It *must* go.
1240
1241 class ModelBasedBuilder(MetaBuilder):
1242 """A meta builder that can create stan-like structures from meta
1243 information
1244
1245 It is constructed with with a tuple-tree of keys and DOM constructors;
1246 these must work like stan elements, which is, e.g., also true for our
1247 registrymodel elements.
1248
1249 Each node in the tree can be one of:
1250
1251 - a meta key and a callable,
1252 - this, and a sequence of child nodes
1253 - this, and a dictionary mapping argument names for the callable
1254 to meta keys of the node; the arguments extracted in this way
1255 are passed in a single dictionary localattrs.
1256
1257 The callable can also be None, which causes the corresponding items
1258 to be inlined into the parent (this is for flattening nested meta
1259 structures).
1260
1261 The meta key can also be None, which causes the factory to be called
1262 exactly once (this is for nesting flat meta structures).
1263 """
1264 # describing the constructors to mypy is too tedious for me now.
1265 def __init__(self, constructors: List[Any], format: str = "text"):
1266 self.constructors, self.format = constructors, format
1267
1268 def _buildNode(self,
1269 processContent: Callable[[List[Any], MetaValue], StanElement],
1270 metaItem: MetaItem,
1271 children: Sequence[StanElement] = (),
1272 macroPackage: Optional[MacroPackage] = None) -> List[StanElement]:
1273
1274 if not metaItem:
1275 return []
1276
1277 result: List[StanElement] = []
1278 for child in metaItem.children:
1279 content: List[StanElement] = []
1280 c = child.getContent(self.format, macroPackage=macroPackage)
1281 if c:
1282 content.append(cast(StanElement, c))
1283 childContent = self._build(children, child, macroPackage)
1284 if childContent:
1285 content.append(childContent)
1286 if content:
1287 result.append(processContent(content, child))
1288
1289 return result
1290
1291 # TODO: If you can't get rid of this horror, at least properly
1292 # type-annotate it.
1293 def _getItemsForConstructor(self,
1294 metaContainer: MetaMixin,
1295 macroPackage: Optional[MacroPackage],
1296 key: str,
1297 factory: Optional[Callable[..., StanElement]],
1298 children: Sequence[StanElement] = (),
1299 attrs: Dict[str, Any] = {}) -> List[StanElement]:
1300 if factory is not None:
1301 def processContent(childContent: List[Any], metaValue: MetaValue
1302 ) -> StanElement:
1303 moreAttrs: Dict[str, Any] = {}
1304 for argName, metaKey in attrs.items():
1305 val = metaValue.getMeta(metaKey)
1306 if val:
1307 moreAttrs[argName] = cast(MetaItem, val).getContent("text",
1308 macroPackage=macroPackage)
1309 return cast(StanElement,
1310 # factory is non-None here, but mypy doesn't see that
1311 [factory(childContent, localattrs=moreAttrs)]) # type: ignore
1312
1313 else:
1314 def processContent(childContent: List[Any], #noflake: conditional def
1315 metaValue: MetaValue) -> StanElement:
1316 return cast(StanElement, childContent)
1317
1318 if key is None:
1319 return [factory(self._build(children, metaContainer, macroPackage))]
1320 else:
1321 return self._buildNode(processContent,
1322 cast(MetaItem, metaContainer.getMeta(key, raiseOnFail=False)),
1323 children,
1324 macroPackage=macroPackage)
1325
1326 def _build(self,
1327 constructors: Any,
1328 metaContainer: MetaMixin,
1329 macroPackage: Optional[MacroPackage]) -> StanElement:
1330 result: List[StanElement] = []
1331 for item in constructors:
1332 if isinstance(item, str):
1333 result.append(cast(StanElement, item))
1334 else:
1335 try:
1336 result.extend(
1337 self._getItemsForConstructor(
1338 metaContainer,
1339 macroPackage,
1340 *item))
1341 except utils.Error:
1342 raise
1343 except:
1344 raise utils.logOldExc(utils.ReportableError(
1345 "Invalid constructor func in %s, meta container active %s"%(
1346 repr(item), repr(metaContainer))))
1347 return cast(StanElement, result)
1348
1349 def build(self,
1350 metaContainer: MetaMixin,
1351 macroPackage: Optional[MacroPackage] = None) -> StanElement:
1352 if macroPackage is None:
1353 macroPackage = cast(MacroPackage, metaContainer)
1354 return self._build(self.constructors, metaContainer, macroPackage)
1355
1356
1357 # Global meta, items get added
1358 CONFIG_META = MetaMixin()
1359
1360
1361 def makeFallbackMeta(reload: bool = False) -> None:
1362 """fills CONFIG_META with items from $configDir/defaultmeta.txt.
1363
1364 This is called from the module __init__ once typed meta from base
1365 is in (which means that any typed meta defined in other places won't
1366 become magic in fallback; regrettably, we can't hold off loading fallback
1367 meta much longer).
1368 """
1369 srcPath = config.get("configDir") / "defaultmeta.txt"
1370 if not srcPath.exists():
1371 # this will be made a bit later in dachs init
1372 return
1373 with open(srcPath, "rb") as f:
1374 content = f.read().decode("utf-8", "ignore")
1375 parseMetaStream(CONFIG_META, content, clearItems=reload)