| 1 |
""" |
| 2 |
A macro mechanism primarily for string replacement in resource descriptors. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import datetime |
| 12 |
import re |
| 13 |
import urllib.request, urllib.parse, urllib.error |
| 14 |
|
| 15 |
|
| 16 |
from gavo import utils |
| 17 |
from gavo.base import attrdef |
| 18 |
from gavo.base import common |
| 19 |
from gavo.base import complexattrs |
| 20 |
from gavo.base import config |
| 21 |
from gavo.base import meta |
| 22 |
from gavo.base import osinter |
| 23 |
from gavo.base import structure |
| 24 |
from gavo.utils.parsetricks import ( |
| 25 |
ZeroOrMore, Forward, |
| 26 |
ParseResults, ParserElement, |
| 27 |
Regex, Suppress, |
| 28 |
Literal, pyparsingWhitechars) |
| 29 |
|
| 30 |
from gavo.utils.dachstypes import cast, Any, Callable, List, Optional |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
class MacroError(common.StructureError): |
| 35 |
"""is raised when something bad happens during macro expansion. |
| 36 |
|
| 37 |
It is constructed with an error message, a macro name, and optionally |
| 38 |
a hint and a position. |
| 39 |
""" |
| 40 |
def __init__(self, |
| 41 |
message: str, |
| 42 |
macroName: str, |
| 43 |
hint: Optional[str] = None, |
| 44 |
pos: Optional[Any] = None) -> None: |
| 45 |
common.StructureError.__init__( |
| 46 |
self, macroName+" failed", pos=pos, hint=hint) |
| 47 |
self.args = (message, macroName, hint, pos) |
| 48 |
self.macroName, self.message = macroName, message |
| 49 |
|
| 50 |
def __str__(self) -> str: |
| 51 |
pos = f"{self.pos}" if self.pos else "unknown position" |
| 52 |
return f"In Element at {pos}: {self.message}" |
| 53 |
|
| 54 |
|
| 55 |
class MacroExpander: |
| 56 |
"""is a generic "macro" expander for scripts of all kinds. |
| 57 |
|
| 58 |
It is loosely inspired by TeX, but of course much simpler. See the |
| 59 |
syntax below. |
| 60 |
|
| 61 |
The macros themselves come from a MacroPackage object. There are |
| 62 |
a few of these around, implementing different functionality depending |
| 63 |
on the script context (i.e., whether it belongs to an RD, a DD, or |
| 64 |
a Table. |
| 65 |
|
| 66 |
All macros are just functions receiving and returning strings. The |
| 67 |
arguments are written as {arg1}{arg2}, where you can escape curly |
| 68 |
braces with a backslash. There must be no whitespace between |
| 69 |
a macro and its first argument. |
| 70 |
|
| 71 |
If you need to glue together a macro expansion and text following, |
| 72 |
use the glue sequence \\+ |
| 73 |
|
| 74 |
The main entry point to the class is the expand function below, |
| 75 |
taking a string possibly containing macro calls and returning |
| 76 |
a string. |
| 77 |
|
| 78 |
The construction of such a macro expander is relatively expensive, |
| 79 |
so it pays to cache them. MacroPackage below has a getExpander |
| 80 |
method that does the caching for you. |
| 81 |
""" |
| 82 |
def __init__(self, package: "MacroPackage") -> None: |
| 83 |
self.package = package |
| 84 |
self._macroGrammar = self._getMacroGrammar() |
| 85 |
|
| 86 |
def _execMacro(self, s: str, loc: int, toks: ParseResults) -> str: |
| 87 |
toks = toks.asList() |
| 88 |
macName, args = toks[0], toks[1:] |
| 89 |
return self.package.execMacro(macName, args) |
| 90 |
|
| 91 |
def expand(self, aString: str) -> str: |
| 92 |
return utils.pyparseTransform(self._macroGrammar, aString) |
| 93 |
|
| 94 |
def _getMacroGrammar(self, debug: bool = False) -> ParserElement: |
| 95 |
with pyparsingWhitechars(" \t"): |
| 96 |
macro = Forward() |
| 97 |
quoteEscape = (Literal("\\{").addParseAction(lambda *args: "{") | |
| 98 |
Literal("\\}").addParseAction(lambda *args: "}")) |
| 99 |
charRun = Regex(r"[^}\\]+").leaveWhitespace() |
| 100 |
argElement = macro | quoteEscape | charRun |
| 101 |
argument = Suppress("{") + ZeroOrMore(argElement) + Suppress("}") |
| 102 |
argument.addParseAction(lambda s, pos, toks: "".join(toks)) |
| 103 |
arguments = ZeroOrMore(argument) |
| 104 |
arguments.setWhitespaceChars("") |
| 105 |
macroName = Regex("[A-Za-z_][A-Za-z_0-9]+") |
| 106 |
macroName.setWhitespaceChars("") |
| 107 |
macro << Suppress( "\\" ) + macroName + arguments |
| 108 |
macro.addParseAction(self._execMacro) |
| 109 |
literalBackslash = Literal("\\\\") |
| 110 |
literalBackslash.addParseAction(lambda *args: "\\") |
| 111 |
suppressedLF = Literal("\\\n") |
| 112 |
suppressedLF.addParseAction(lambda *args: " ") |
| 113 |
glue = Literal("\\+") |
| 114 |
glue.addParseAction(lambda *args: "") |
| 115 |
return literalBackslash | suppressedLF | glue | macro |
| 116 |
|
| 117 |
|
| 118 |
class ExpansionDelegator: |
| 119 |
"""A mixin to make a class expand macros by delegating everything to |
| 120 |
its parent. |
| 121 |
|
| 122 |
This is intended for base.Structures that have a parent attribute; |
| 123 |
by mixing this in, they use their parents to expand macros for them. |
| 124 |
""" |
| 125 |
def expand(self, aString: str) -> str: |
| 126 |
# parent has to be provided by the class mixing this in. |
| 127 |
return self.parent.expand(aString) # type: ignore |
| 128 |
|
| 129 |
|
| 130 |
class MacroPackage(common.StructCallbacks): |
| 131 |
r"""A function dispatcher for MacroExpander. |
| 132 |
|
| 133 |
Basically, you inherit from this class and define macro_xxx functions. |
| 134 |
MacroExpander can then call \xxx, possibly with arguments. |
| 135 |
""" |
| 136 |
def getSourcePosition(self) -> str: |
| 137 |
# This is supposed to be mixed into structs, which I don't think |
| 138 |
# I can convey to mypy |
| 139 |
return super().getSourcePosition() # type: ignore |
| 140 |
|
| 141 |
def __findMacro(self, macName: str) -> Callable[..., str]: |
| 142 |
fun = getattr(self, "macro_"+macName, None) |
| 143 |
if fun is not None: |
| 144 |
return fun |
| 145 |
|
| 146 |
# this is a bit of a hack so subordinate objects see macDefs from |
| 147 |
# their RDs; generally, we don't inherit macros, as they are bound |
| 148 |
# to types in DaCHS. |
| 149 |
if hasattr(self, "rd"): |
| 150 |
fun = getattr(self.rd, "macro_"+macName, None) |
| 151 |
if fun is not None: |
| 152 |
return fun |
| 153 |
|
| 154 |
raise MacroError( |
| 155 |
"No macro \\%s available in a %s context"%( |
| 156 |
macName, self.__class__.__name__), |
| 157 |
macName, |
| 158 |
pos=self.getSourcePosition(), |
| 159 |
hint="%s objects have the following macros: %s."%( |
| 160 |
self.__class__.__name__, ", ".join(self.listMacros()))) |
| 161 |
|
| 162 |
def listMacros(self) -> List[str]: |
| 163 |
return [n[6:] for n in dir(self) if n.startswith("macro_")] |
| 164 |
|
| 165 |
def execMacro(self, macName: str, args: List[str]) -> str: |
| 166 |
fun = self.__findMacro(macName) |
| 167 |
try: |
| 168 |
return fun(*args) |
| 169 |
except TypeError: |
| 170 |
raise utils.logOldExc(MacroError( |
| 171 |
"Invalid macro arguments to \\%s: %s"%(macName, args), macName, |
| 172 |
hint="You supplied too few or too many arguments")) |
| 173 |
except utils.Error: |
| 174 |
raise |
| 175 |
except Exception as msg: |
| 176 |
argRepr = "}{".join(utils.safe_str(a) for a in args) |
| 177 |
if argRepr: |
| 178 |
argRepr = "{%s}"%argRepr |
| 179 |
|
| 180 |
raise utils.logOldExc(MacroError( |
| 181 |
"While expanding macro \\%s%s: %s"%(macName, argRepr, msg), |
| 182 |
macName, |
| 183 |
pos=self.getSourcePosition(), |
| 184 |
hint="This means that the code dealing with your arguments" |
| 185 |
" was throroughly confused by what you passed. If you really" |
| 186 |
" cannot see why it was, file a bug.")) |
| 187 |
|
| 188 |
def getExpander(self) -> MacroExpander: |
| 189 |
try: |
| 190 |
return self.__macroExpander |
| 191 |
except AttributeError: |
| 192 |
self.__macroExpander: MacroExpander = MacroExpander(self) |
| 193 |
return self.getExpander() |
| 194 |
|
| 195 |
def expand(self, stuff: str) -> str: |
| 196 |
return self.getExpander().expand(stuff) |
| 197 |
|
| 198 |
def macro_quote(self, arg: str) -> str: |
| 199 |
"""returns the argument in quotes (with internal quotes backslash-escaped |
| 200 |
if necessary). |
| 201 |
""" |
| 202 |
return '"%s"'%(arg.replace('"', '\\"')) |
| 203 |
|
| 204 |
def macro_sqlquote(self, arg: str) -> str: |
| 205 |
"""returns the argument as a quoted string, unless it is 'NULL' or |
| 206 |
None, in which case just NULL is returned. |
| 207 |
|
| 208 |
We also escape % (as %%) because where DaCHS uses this, the strings |
| 209 |
will go through psycopg, and naked percents will make it try argument |
| 210 |
replacement. |
| 211 |
""" |
| 212 |
if arg is None or arg=='NULL': |
| 213 |
return "NULL" |
| 214 |
return "'%s'"%arg.replace("'", "''").replace('%', '%%') |
| 215 |
|
| 216 |
def macro_sql_standardPubDID(self, fromCol: str = "accref") -> str: |
| 217 |
"""returns a SQL expression returning a DaCHS standard pubDID generated |
| 218 |
from the accref (or something overridden) column. |
| 219 |
|
| 220 |
This is convenient in obscore or ssa views when the underlying table |
| 221 |
just has accrefs. If your code actually uses the pubDID to search |
| 222 |
in the table (and it probably shouldn't), better use an actual column |
| 223 |
and index it. |
| 224 |
""" |
| 225 |
auth = config.get("ivoa", "authority") |
| 226 |
return "'ivo://%s/~?' || gavo_urlescape(%s)"%( |
| 227 |
auth.replace("'", "''"), |
| 228 |
fromCol) |
| 229 |
|
| 230 |
def macro_reSub(self, pattern: str, replacement: str, string: str) -> str: |
| 231 |
"""returns the string with the python RE pattern replaced with |
| 232 |
replacement. |
| 233 |
|
| 234 |
This is directly handed through to python re.sub, so you can (but |
| 235 |
probably shouldn't) play all the RE tricks you can in python (e.g., |
| 236 |
back references). |
| 237 |
|
| 238 |
If you find yourself having to use reSub, you should regard that as |
| 239 |
an alarm sign that you're probably doing it wrong. |
| 240 |
|
| 241 |
Oh: closing curly braces can be included in the argument by |
| 242 |
backslash-escaping them. |
| 243 |
""" |
| 244 |
return re.sub(pattern, replacement, string) |
| 245 |
|
| 246 |
def macro_if(self, cond: str, val: str) -> str: |
| 247 |
"""returns val if cond is not either empty or 0 after stripping, |
| 248 |
the empty string otherwise. |
| 249 |
""" |
| 250 |
if cond.strip() in ('', '0'): |
| 251 |
return "" |
| 252 |
return val |
| 253 |
|
| 254 |
|
| 255 |
class StandardMacroMixin(MacroPackage): |
| 256 |
"""is a mixin providing some macros for scripting's MacroExpander. |
| 257 |
|
| 258 |
The class mixing in needs to provide its resource descriptor in the |
| 259 |
rd attribute. |
| 260 |
""" |
| 261 |
def macro_magicEmpty(self, val: str) -> str: |
| 262 |
"""returns __EMPTY__ if val is empty. |
| 263 |
|
| 264 |
This is necessary when feeding possibly empty params from mixin |
| 265 |
parameters (don't worry if you don't understand this). |
| 266 |
""" |
| 267 |
if val: |
| 268 |
return val |
| 269 |
else: |
| 270 |
return "__EMPTY__" |
| 271 |
|
| 272 |
def macro_rdId(self) -> str: |
| 273 |
"""the identifier of the current resource descriptor. |
| 274 |
""" |
| 275 |
# rd must come from the class mixing this in. |
| 276 |
return self.rd.sourceId # type: ignore |
| 277 |
|
| 278 |
def macro_rdIdDotted(self) -> str: |
| 279 |
"""the identifier for the current resource descriptor with slashes replaced |
| 280 |
with dots (so they work as the "host part" in URIs. |
| 281 |
""" |
| 282 |
# rd must come from the class mixing this in. |
| 283 |
return self.rd.sourceId.replace("/", ".") # type: ignore |
| 284 |
|
| 285 |
def macro_schema(self) -> str: |
| 286 |
"""the schema of the current resource descriptor. |
| 287 |
""" |
| 288 |
# rd must come from the class mixing this in. |
| 289 |
return self.rd.schema # type: ignore |
| 290 |
|
| 291 |
def macro_resdir(self) -> str: |
| 292 |
"""the input-relative resource directory of the current resource |
| 293 |
descriptor. |
| 294 |
|
| 295 |
This never has a trailing slash. |
| 296 |
""" |
| 297 |
# rd must come from the class mixing this in. |
| 298 |
return str(self.rd.getRelResdir()).rstrip("/") # type: ignore |
| 299 |
|
| 300 |
def macro_RSTservicelink(self, |
| 301 |
serviceId: str, |
| 302 |
title: Optional[str] = None) -> str: |
| 303 |
"""a link to an internal service; id is <rdId>/<serviceId>/<renderer>, |
| 304 |
title, if given, is the anchor text. |
| 305 |
|
| 306 |
The result is a link in the short form for restructured test. |
| 307 |
""" |
| 308 |
if title is None: |
| 309 |
title = serviceId |
| 310 |
return "`%s <%s>`_"%(title, osinter.makeSitePath(serviceId)) |
| 311 |
|
| 312 |
def macro_RSTtable(self, tableName:str) -> str: |
| 313 |
"""adds an reStructured test link to a tableName pointing to its table |
| 314 |
info. |
| 315 |
""" |
| 316 |
return "`%s <%s>`_"%(tableName, |
| 317 |
osinter.makeSitePath("tableinfo/%s"%tableName)) |
| 318 |
|
| 319 |
def macro_internallink(self, relPath: str) -> str: |
| 320 |
"""an absolute URL from a path relative to the DC root. |
| 321 |
""" |
| 322 |
return osinter.makeAbsoluteURL(relPath, canonical=True) |
| 323 |
|
| 324 |
def macro_urlquote(self, string: str) -> str: |
| 325 |
"""wraps urllib.quote. |
| 326 |
""" |
| 327 |
return urllib.parse.quote(string) |
| 328 |
|
| 329 |
def macro_today(self) -> str: |
| 330 |
"""today's date in ISO representation. |
| 331 |
""" |
| 332 |
return str(datetime.date.today()) |
| 333 |
|
| 334 |
def macro_getConfig(self, section: str, name: Optional[str] = None) -> str: |
| 335 |
"""the current value of configuration item {section}{name}. |
| 336 |
|
| 337 |
You can also only give one argument to access settings from the |
| 338 |
general section. |
| 339 |
""" |
| 340 |
if name is None: |
| 341 |
section, name = "general", section |
| 342 |
val = config.get(section, name) |
| 343 |
if isinstance(val, str): |
| 344 |
return val |
| 345 |
else: |
| 346 |
return str(val) |
| 347 |
|
| 348 |
def macro_metaString(self, |
| 349 |
metaKey: str, |
| 350 |
default: Optional[str] = None) -> str: |
| 351 |
"""the value of metaKey on the macro expander. |
| 352 |
|
| 353 |
This will raise an error when the meta Key is not available unless |
| 354 |
you give a default. It will also raise an error if metaKey is not |
| 355 |
atomic (i.e., single-valued). Use metaSeq for meta items that |
| 356 |
may have multiple values. |
| 357 |
|
| 358 |
Because it's sometimes useful, if the expander itself doesn't |
| 359 |
have metadat, this goes up in the RD tree until it finds something |
| 360 |
that has metadata. |
| 361 |
""" |
| 362 |
mc = self |
| 363 |
while mc and not hasattr(mc, "getMeta"): |
| 364 |
# parent is provided by the class mixing this in |
| 365 |
mc = mc.parent # type: ignore |
| 366 |
|
| 367 |
try: |
| 368 |
try: |
| 369 |
# getMeta is provided by the class mixing this in |
| 370 |
val = mc.getMeta(metaKey, raiseOnFail=True) # type: ignore |
| 371 |
except meta.NoMetaKey: |
| 372 |
if default is not None: |
| 373 |
return default |
| 374 |
raise |
| 375 |
|
| 376 |
return val.getContent(macroPackage=self |
| 377 |
).replace("\n", " ") # undo default line breaking |
| 378 |
|
| 379 |
except meta.MetaError as exc: |
| 380 |
exc.carrier = cast(meta.MetaMixin, self) |
| 381 |
exc.key = metaKey |
| 382 |
if hasattr(self, "getSourcePosition"): |
| 383 |
# we're making the attribute for the benefit of the error message |
| 384 |
# formatter. |
| 385 |
exc.pos = self.getSourcePosition() # type: ignore |
| 386 |
raise |
| 387 |
|
| 388 |
def macro_metaSeq(self, |
| 389 |
metaKey: str, |
| 390 |
default: str = '', |
| 391 |
joiner: str = ', ') -> str: |
| 392 |
"""returns all values of metaKey on the current macro expander joined |
| 393 |
by joiner. |
| 394 |
|
| 395 |
This will be an empty string if there is no corresponding metadata (or |
| 396 |
default, if passed). |
| 397 |
""" |
| 398 |
# iterMeta provided by the class mixing us in |
| 399 |
vals = list(self.iterMeta(metaKey, propagate=True)) # type:ignore |
| 400 |
if vals: |
| 401 |
return joiner.join(str(val) for val in vals) |
| 402 |
else: |
| 403 |
return default |
| 404 |
|
| 405 |
def macro_upper(self, aString: str) -> str: |
| 406 |
"""returns aString uppercased. |
| 407 |
|
| 408 |
There's no guarantees for characters outside ASCII. |
| 409 |
""" |
| 410 |
return aString.upper() |
| 411 |
|
| 412 |
def macro_lower(self, aString: str) -> str: |
| 413 |
"""returns aString lowercased. |
| 414 |
|
| 415 |
There's no guarantees for characters outside ASCII. |
| 416 |
""" |
| 417 |
return aString.lower() |
| 418 |
|
| 419 |
def macro_decapitalize(self, aString: str) -> str: |
| 420 |
"""returns aString with the first character lowercased. |
| 421 |
""" |
| 422 |
if aString: |
| 423 |
return aString[0].lower()+aString[1:] |
| 424 |
return "" |
| 425 |
|
| 426 |
def macro_test(self, *args: str) -> str: |
| 427 |
"""always "test macro expansion". |
| 428 |
""" |
| 429 |
return "test macro expansion" |
| 430 |
|
| 431 |
|
| 432 |
@structure.buildstructure |
| 433 |
class MacDef(structure.Structure): |
| 434 |
"""A macro definition within an RD. |
| 435 |
|
| 436 |
The macro defined is available on the parent; macros are expanded |
| 437 |
within the parent (behaviour is undefined if you try a recursive expansion). |
| 438 |
""" |
| 439 |
name_ = "macDef" |
| 440 |
|
| 441 |
_name = attrdef.UnicodeAttribute("name", |
| 442 |
description="Name the macro will be available as", |
| 443 |
copyable=True, |
| 444 |
default=utils.Undefined) |
| 445 |
_raw = attrdef.BooleanAttribute("raw", |
| 446 |
description="If true, macros in the content will not be expanded in place.", |
| 447 |
copyable=True, |
| 448 |
default=False) |
| 449 |
_content = structure.DataContent( |
| 450 |
description="Replacement text of the macro") |
| 451 |
|
| 452 |
def validate(self) -> None: |
| 453 |
super().validate() |
| 454 |
if len(self.name)<2: |
| 455 |
raise common.LiteralParseError("name", self.name, hint= |
| 456 |
"Macro names must have at least two characters.") |
| 457 |
|
| 458 |
def onElementComplete(self) -> None: |
| 459 |
super().onElementComplete() |
| 460 |
# we probably should make clear that MacDef parents need to be |
| 461 |
# MacroExpanders; in practice, that's RD anyway. |
| 462 |
if not self.raw: |
| 463 |
try: |
| 464 |
self.content_: str = cast(MacroExpander, self.parent |
| 465 |
).expand(self.content_) |
| 466 |
except MacroError as ex: |
| 467 |
ex.pos = self.getSourcePosition() |
| 468 |
raise |
| 469 |
def mac() -> str: |
| 470 |
return self.content_ |
| 471 |
setattr(self.parent, "macro_"+self.name, mac) |
| 472 |
|
| 473 |
|
| 474 |
def MacDefAttribute(**kwargs: Any) -> complexattrs.StructListAttribute: |
| 475 |
return complexattrs.StructListAttribute( |
| 476 |
"macDefs", |
| 477 |
childFactory=MacDef, |
| 478 |
**kwargs) |