| 1 |
""" |
| 2 |
Base classes and common code for grammars. |
| 3 |
|
| 4 |
NOTE: If you add grammars, you have to enter manually them in |
| 5 |
rscdef.builtingrammars.GRAMMAR_REGISTRY (we don't want to import all |
| 6 |
the mess in this package just to make that). |
| 7 |
""" |
| 8 |
|
| 9 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 10 |
#c |
| 11 |
#c This program is free software, covered by the GNU GPL. See the |
| 12 |
#c COPYING file in the source distribution. |
| 13 |
|
| 14 |
|
| 15 |
import codecs |
| 16 |
import io |
| 17 |
import re |
| 18 |
import os |
| 19 |
import select |
| 20 |
import subprocess |
| 21 |
|
| 22 |
from gavo import base |
| 23 |
from gavo import rscdef |
| 24 |
from gavo import utils |
| 25 |
from gavo.rscdef import procdef |
| 26 |
from gavo.rscdef import rowtriggers |
| 27 |
|
| 28 |
|
| 29 |
class REAttribute(base.UnicodeAttribute): |
| 30 |
"""An attribute containing (compiled) RE |
| 31 |
""" |
| 32 |
def parse(self, value): |
| 33 |
if value is None or not value: |
| 34 |
return None |
| 35 |
try: |
| 36 |
return re.compile(value) |
| 37 |
except re.error as msg: |
| 38 |
raise base.ui.logOldExc(base.LiteralParseError(self.name_, value, |
| 39 |
hint="A python regular expression was expected here. Compile" |
| 40 |
" complained: %s"%str(msg))) |
| 41 |
|
| 42 |
def unparse(self, value): |
| 43 |
if value is None: |
| 44 |
return "" |
| 45 |
else: |
| 46 |
return value.pattern |
| 47 |
|
| 48 |
|
| 49 |
class FilteredInputFile(object): |
| 50 |
"""a pseudo-file that allows piping data through a shell command. |
| 51 |
|
| 52 |
It supports read, readline, and close. Close closes the original |
| 53 |
file, too. |
| 54 |
|
| 55 |
Warning: the command passed in will be shell-expanded (which is fair |
| 56 |
since you can pass in any command you want anyway). |
| 57 |
|
| 58 |
If you pass silent=True, stderr will be redirected to /dev/null. |
| 59 |
This is probably only attractive for unit tests and such. |
| 60 |
""" |
| 61 |
def __init__(self, filterCommand, origFile, silent=False): |
| 62 |
self.filterCommand, self.origFile = filterCommand, origFile |
| 63 |
|
| 64 |
processArgs = {"shell": True, |
| 65 |
"stdin": subprocess.PIPE, |
| 66 |
"stdout": subprocess.PIPE, |
| 67 |
"close_fds": True} |
| 68 |
if silent: |
| 69 |
processArgs["stderr"] = utils.devnull() |
| 70 |
|
| 71 |
self.process = subprocess.Popen([self.filterCommand], **processArgs) |
| 72 |
self.fromChild, self.toChild = self.process.stdout, self.process.stdin |
| 73 |
self.buffer = utils.StreamBuffer(2**14) |
| 74 |
self.PIPE_BUF = select.PIPE_BUF |
| 75 |
|
| 76 |
origClose = self.origFile.close |
| 77 |
self.origFile.close = self._makeCloser(origClose) |
| 78 |
|
| 79 |
def _makeCloser(self, origClose): |
| 80 |
def _(): |
| 81 |
origClose() |
| 82 |
if self.process.returncode is None: |
| 83 |
self.process.terminate() |
| 84 |
# not checking the return code here; if the client closed |
| 85 |
# while the child was still running, an error from it would |
| 86 |
# not count as an error. |
| 87 |
self.process.wait() |
| 88 |
if self.fromChild: |
| 89 |
self.fromChild.close() |
| 90 |
if self.toChild: |
| 91 |
self.toChild.close() |
| 92 |
return _ |
| 93 |
|
| 94 |
def _fillChildBuffer(self): |
| 95 |
"""feeds the child new data, closing the source file if all data |
| 96 |
has been fed. |
| 97 |
""" |
| 98 |
data = self.origFile.read(self.PIPE_BUF) |
| 99 |
if data==b"": |
| 100 |
# source file exhausted, tell child we're done |
| 101 |
self.toChild.close() |
| 102 |
self.toChild = None |
| 103 |
else: |
| 104 |
self.toChild.write(data) |
| 105 |
|
| 106 |
def _readAll(self): |
| 107 |
allChunks = [] |
| 108 |
while True: |
| 109 |
data = self.read(2**20) |
| 110 |
if data==b"": |
| 111 |
break |
| 112 |
allChunks.append(data) |
| 113 |
return b"".join(allChunks) |
| 114 |
|
| 115 |
def _fillBuffer(self): |
| 116 |
"""tries to obtain another chunk of data from the child, feeding |
| 117 |
it new data if possible. |
| 118 |
""" |
| 119 |
if self.toChild: |
| 120 |
writeList = [self.toChild] |
| 121 |
else: |
| 122 |
writeList = [] |
| 123 |
readReady, writeReady, _ = select.select( |
| 124 |
[self.fromChild], writeList, []) |
| 125 |
|
| 126 |
if writeReady: |
| 127 |
self._fillChildBuffer() |
| 128 |
|
| 129 |
if readReady: |
| 130 |
data = self.fromChild.read(self.PIPE_BUF) |
| 131 |
if data==b"": |
| 132 |
self.buffer.doneWriting() |
| 133 |
if self.process.wait(): |
| 134 |
raise IOError("Child exited with return code %s"% |
| 135 |
self.process.wait()) |
| 136 |
self.buffer.add(data) |
| 137 |
|
| 138 |
def read(self, nBytes=None): |
| 139 |
if nBytes is None: |
| 140 |
return self._readAll() |
| 141 |
|
| 142 |
while self.buffer.curSize<nBytes and not self.buffer.finished: |
| 143 |
self._fillBuffer() |
| 144 |
|
| 145 |
return self.buffer.get(nBytes) or b"" |
| 146 |
|
| 147 |
def readline(self): |
| 148 |
# let's do a quick one ourselves rather than inherit from file |
| 149 |
# just for this; this just works with unix line ends. |
| 150 |
while True: |
| 151 |
val = self.buffer.getToChar(b"\n") |
| 152 |
if val is None: |
| 153 |
if self.buffer.finished: |
| 154 |
return self.buffer.getRest() |
| 155 |
else: |
| 156 |
self._fillBuffer() |
| 157 |
else: |
| 158 |
return val |
| 159 |
|
| 160 |
def __iter__(self): |
| 161 |
while True: |
| 162 |
res = self.readline() |
| 163 |
if not res: |
| 164 |
break |
| 165 |
yield res |
| 166 |
|
| 167 |
def close(self): |
| 168 |
self.origFile.close() |
| 169 |
|
| 170 |
|
| 171 |
class Rowfilter(procdef.ProcApp): |
| 172 |
"""A generator for rows coming from a grammar. |
| 173 |
|
| 174 |
Rowfilters receive rows (i.e., dictionaries) as yielded by a grammar |
| 175 |
under the name row. Additionally, the embedding row iterator is |
| 176 |
available under the name rowIter. |
| 177 |
|
| 178 |
Macros are expanded within the embedding grammar. |
| 179 |
|
| 180 |
The procedure definition *must* result in a generator, i.e., there must |
| 181 |
be at least one yield; in general, this will typically be a ``yield row``, |
| 182 |
but a rowfilter may swallow or create as many rows as desired. |
| 183 |
|
| 184 |
If you forget to have a yield in the rowfilter source, you'll get a |
| 185 |
"NoneType is not iterable" error that's a bit hard to understand. |
| 186 |
|
| 187 |
Here, you can only access whatever comes from the grammar. You can |
| 188 |
access grammar keys in late parameters as row[key] or, if key is |
| 189 |
like an identifier, as @key. |
| 190 |
""" |
| 191 |
name_ = "rowfilter" |
| 192 |
requiredType="rowfilter" |
| 193 |
formalArgs = "row, rowIter" |
| 194 |
|
| 195 |
def getFuncCode(self): |
| 196 |
return rscdef.replaceProcDefAt(procdef.ProcApp.getFuncCode(self), "row") |
| 197 |
|
| 198 |
|
| 199 |
def _identityRowfilter(row, rowIter): |
| 200 |
yield row |
| 201 |
|
| 202 |
|
| 203 |
def compileRowfilter(filters): |
| 204 |
"""returns an iterator that "pipes" the rowfilters in filters. |
| 205 |
|
| 206 |
This means that the output of filters[0] is used as arguments to |
| 207 |
filters[1] and so on. |
| 208 |
|
| 209 |
If filters is empty, an identity function is returned. |
| 210 |
""" |
| 211 |
if not filters: |
| 212 |
return _identityRowfilter |
| 213 |
|
| 214 |
iters = [f.compile() for f in filters] #noflake: code gen |
| 215 |
src = [ |
| 216 |
"def iterPipe(row, rowIter):", |
| 217 |
" for item0 in iters[0](row, rowIter):"] |
| 218 |
for ind in range(1, len(filters)): |
| 219 |
src.append("%s for item%d in iters[%d](item%d, rowIter):"%( |
| 220 |
" "*ind, ind, ind, ind-1)) |
| 221 |
src.append("%s yield item%d"%(" "*len(filters), len(filters)-1)) |
| 222 |
d = locals() |
| 223 |
exec("\n".join(src), d) |
| 224 |
return d["iterPipe"] |
| 225 |
|
| 226 |
|
| 227 |
class SourceFieldApp(rscdef.ProcApp): |
| 228 |
"""A procedure application that returns a dictionary added to all |
| 229 |
incoming rows. |
| 230 |
|
| 231 |
Use this to programmatically provide information that can be computed |
| 232 |
once but that is then added to all rows coming from a single source, usually |
| 233 |
a file. This could be useful to add information on the source of a |
| 234 |
record or the like. |
| 235 |
|
| 236 |
The code must return a dictionary. The source that is about to be parsed is |
| 237 |
passed in as sourceToken. When parsing from files, this simply is the file |
| 238 |
name. The data the rows will be delivered to is available as "data", which |
| 239 |
is useful for adding or retrieving meta information. |
| 240 |
""" |
| 241 |
name_ = "sourceFields" |
| 242 |
|
| 243 |
requriedType = "sourceFields" |
| 244 |
formalArgs = "sourceToken, data" |
| 245 |
|
| 246 |
|
| 247 |
class MapKeys(base.Structure): |
| 248 |
"""Mapping of names, specified in long or short forms. |
| 249 |
|
| 250 |
mapKeys is necessary in grammars like keyValueGrammar or fitsProdGrammar. |
| 251 |
In these, the source files themselves give key names. Within the GAVO |
| 252 |
DC, keys are required to be valid python identifiers (i.e., match |
| 253 |
``[A-Za-z_][A-Za-z_0-9]*``). If keys coming in do not have this form, |
| 254 |
mapping can force proper names. |
| 255 |
|
| 256 |
mapKeys could also be used to make incoming names more suitable for |
| 257 |
matching with shell patterns (like in rowmaker idmaps). |
| 258 |
""" |
| 259 |
name_ = "mapKeys" |
| 260 |
|
| 261 |
_content = base.DataContent(description="Simple mappings in the form" |
| 262 |
"<dest>:<src>{,<dest>:<src>}") |
| 263 |
_mappings = base.DictAttribute("maps", keyName="dest", description= |
| 264 |
"Map source names given in content to the name given in dest.", |
| 265 |
itemAttD=base.UnicodeAttribute("map"), inverted=True, |
| 266 |
aliases=["map"], copyable=True) |
| 267 |
|
| 268 |
def _parseShortenedMap(self, literal): |
| 269 |
literal = literal.strip().rstrip(",") |
| 270 |
try: |
| 271 |
for dest, src in (p.split(":") for p in literal.split(",")): |
| 272 |
src = src.strip() |
| 273 |
if src not in self.maps: |
| 274 |
self.maps[src] = dest.strip() |
| 275 |
else: |
| 276 |
raise base.StructureError( |
| 277 |
"%s clobbers an existing source within the key map."%src) |
| 278 |
except ValueError: |
| 279 |
raise base.ui.logOldExc(base.LiteralParseError(self.name_, literal, |
| 280 |
hint="A key-value enumeration of the format k:v {,k:v}" |
| 281 |
" is expected here")) |
| 282 |
|
| 283 |
def onElementComplete(self): |
| 284 |
if self.content_: |
| 285 |
self._parseShortenedMap(self.content_) |
| 286 |
super().onElementComplete() |
| 287 |
|
| 288 |
def doMap(self, aDict): |
| 289 |
"""returns dict with the keys mapped according to the defined mappings. |
| 290 |
""" |
| 291 |
if self.maps: |
| 292 |
newDict = {} |
| 293 |
for k, v in aDict.items(): |
| 294 |
newDict[self.maps.get(k, k)] = v |
| 295 |
return newDict |
| 296 |
else: |
| 297 |
return aDict |
| 298 |
|
| 299 |
|
| 300 |
class RowIterator(object): |
| 301 |
"""An object that encapsulates the a source being parsed by a |
| 302 |
grammar. |
| 303 |
|
| 304 |
RowIterators are returned by Grammars' parse methods. Iterate |
| 305 |
over them to retrieve the rows contained in the source. |
| 306 |
|
| 307 |
You can also call getParameters on them to retrieve document-global |
| 308 |
values (e.g., the parameters of a VOTable, a global header of |
| 309 |
a FITS table). |
| 310 |
|
| 311 |
The getLocator method should return some string that aids the user |
| 312 |
in finding out why something went wrong (file name, line number, etc.) |
| 313 |
|
| 314 |
This default implementation works for when source is a sequence |
| 315 |
of dictionaries. You will, in general, want to override |
| 316 |
_iteRows and getLocator, plus probably __init__ (to prepare external |
| 317 |
resources) and getParameters (if you have them; make sure to update |
| 318 |
any parameters you have with self.sourceRow as shown in the default |
| 319 |
getParameters implementation). |
| 320 |
|
| 321 |
RowIterators are supposed to be self-destructing, i.e., they should |
| 322 |
release any external resources they hold when _iterRows runs out of |
| 323 |
items. |
| 324 |
|
| 325 |
_iterRows should arrange for the instance variable recNo to be incremented |
| 326 |
by one for each item returned. |
| 327 |
""" |
| 328 |
notify = True |
| 329 |
|
| 330 |
def __init__(self, grammar, sourceToken, sourceRow=None): |
| 331 |
self.grammar, self.sourceToken = grammar, sourceToken |
| 332 |
self.sourceRow = sourceRow |
| 333 |
self.recNo = 0 |
| 334 |
|
| 335 |
def __iter__(self): |
| 336 |
if self.notify: |
| 337 |
base.ui.notifyNewSource(self.sourceToken) |
| 338 |
baseIter = self._iterRowsProcessed() |
| 339 |
|
| 340 |
if self.grammar.ignoreOn: |
| 341 |
rowSource = self._filteredIter(baseIter) |
| 342 |
else: |
| 343 |
rowSource = baseIter |
| 344 |
|
| 345 |
try: |
| 346 |
try: |
| 347 |
for row in rowSource: |
| 348 |
# handle dispatched grammars here, too |
| 349 |
if isinstance(row, tuple): |
| 350 |
d = row[1] |
| 351 |
else: |
| 352 |
d = row |
| 353 |
|
| 354 |
if isinstance(d, dict): |
| 355 |
d["parser_"] = self |
| 356 |
|
| 357 |
yield row |
| 358 |
except Exception: |
| 359 |
base.ui.notifySourceError() |
| 360 |
raise |
| 361 |
|
| 362 |
finally: |
| 363 |
self.finalize() |
| 364 |
|
| 365 |
def finalize(self): |
| 366 |
if self.notify: |
| 367 |
base.ui.notifySourceFinished() |
| 368 |
|
| 369 |
def _filteredIter(self, baseIter): |
| 370 |
for row in baseIter: |
| 371 |
if not self.grammar.ignoreOn(row): |
| 372 |
yield row |
| 373 |
|
| 374 |
def _iterRowsProcessed(self): |
| 375 |
if self.grammar.isDispatching: |
| 376 |
for item in self._iterRows(): |
| 377 |
if not isinstance(item, tuple): |
| 378 |
# That's mainly for rsc.FLUSH |
| 379 |
yield item |
| 380 |
else: |
| 381 |
dest, row = item |
| 382 |
if self.sourceRow and isinstance(row, dict): |
| 383 |
row.update(self.sourceRow) |
| 384 |
for procRow in self.rowfilter(row, self): |
| 385 |
yield dest, procRow |
| 386 |
else: |
| 387 |
for row in self._iterRows(): |
| 388 |
if self.sourceRow and isinstance(row, dict): |
| 389 |
row.update(self.sourceRow) |
| 390 |
for procRow in self.rowfilter(row, self): |
| 391 |
yield procRow |
| 392 |
|
| 393 |
def _iterRows(self): |
| 394 |
if False: |
| 395 |
yield None |
| 396 |
self.grammar = None # don't wait for garbage collection |
| 397 |
|
| 398 |
def getParameters(self): |
| 399 |
res = {"parser_": self} |
| 400 |
if self.sourceRow: |
| 401 |
res.update(self.sourceRow) |
| 402 |
return res |
| 403 |
|
| 404 |
def getLocator(self): |
| 405 |
return "(unknown position -- locator missing)" |
| 406 |
|
| 407 |
|
| 408 |
def wrapFileFor(fileobj, desiredMode, enc): |
| 409 |
"""wraps or unwraps fileobj so that it matches the open mode desiredMode. |
| 410 |
|
| 411 |
If there's a "b" in desiredMode, this will return fileobj.raw if it's |
| 412 |
there. Otherwise, it'll wrap it into a codec.getreader for enc. |
| 413 |
""" |
| 414 |
# I guess there's no good way to figure out if fileobj is binary or |
| 415 |
# text; so let's have a bit of heuristics. |
| 416 |
if hasattr(fileobj, "mode"): |
| 417 |
foundMode = fileobj.mode |
| 418 |
elif isinstance(fileobj, io.BytesIO): |
| 419 |
foundMode = "rb" |
| 420 |
elif isinstance(fileobj, io.StringIO): |
| 421 |
foundMode = "r" |
| 422 |
else: |
| 423 |
foundMode = "r" if hasattr(fileobj, "raw") else "rb" |
| 424 |
|
| 425 |
if "b" in desiredMode: |
| 426 |
if "b" in foundMode: |
| 427 |
return fileobj |
| 428 |
else: |
| 429 |
return fileobj.raw |
| 430 |
|
| 431 |
else: |
| 432 |
if "b" in foundMode: |
| 433 |
return codecs.getreader(enc)(fileobj) |
| 434 |
else: |
| 435 |
return fileobj |
| 436 |
|
| 437 |
|
| 438 |
class FileRowIterator(RowIterator): |
| 439 |
"""is a RowIterator base for RowIterators reading files. |
| 440 |
|
| 441 |
It analyzes the sourceToken to see if it's a string, in which case |
| 442 |
it opens it as a file name and leaves the file object in self.inputFile. |
| 443 |
|
| 444 |
Otherwise, it assumes sourceToken already is a file object and binds |
| 445 |
it to self.inputFile. It then tries to come up with a sensible designation |
| 446 |
for sourceToken. |
| 447 |
|
| 448 |
It also inspects the parent grammar for a gunzip attribute. If it is |
| 449 |
present and true, the input file will be unzipped transparently. Don't |
| 450 |
add more features like this; preFilter is a lot more flexible. |
| 451 |
|
| 452 |
Classes using this reading binary data will want to set fileMode |
| 453 |
to rb. If they don't what's returned is strings. |
| 454 |
""" |
| 455 |
fileMode = "r" |
| 456 |
|
| 457 |
def __init__(self, grammar, sourceToken, **kwargs): |
| 458 |
RowIterator.__init__(self, grammar, sourceToken, **kwargs) |
| 459 |
self.curLine = 1 |
| 460 |
try: |
| 461 |
self._openFile() |
| 462 |
except IOError as ex: |
| 463 |
raise base.ui.logOldExc( |
| 464 |
base.SourceParseError("I/O operation failed (%s)"%str(ex), |
| 465 |
source=str(sourceToken), location="start")) |
| 466 |
|
| 467 |
def _openFile(self): |
| 468 |
preFilter = None |
| 469 |
# we'll use at the end to generate a sourceToken for display purposes |
| 470 |
parsingFrom = self.sourceToken |
| 471 |
if hasattr(parsingFrom, "name"): |
| 472 |
# it' probably an open file |
| 473 |
parsingFrom = self.sourceToken.name |
| 474 |
if not isinstance(parsingFrom, str): |
| 475 |
parsingFrom = repr(parsingFrom) |
| 476 |
|
| 477 |
if hasattr(self.grammar, "gunzip") and self.grammar.gunzip: |
| 478 |
preFilter = "zcat" |
| 479 |
preFilter = preFilter or ( |
| 480 |
hasattr(self.grammar, "preFilter") and self.grammar.preFilter) |
| 481 |
|
| 482 |
# need to handle preFilter first, as that needs a binary file. |
| 483 |
curSrc = self.sourceToken |
| 484 |
if preFilter: |
| 485 |
if isinstance(curSrc, str): |
| 486 |
curSrc = open(curSrc, "rb") |
| 487 |
else: |
| 488 |
curSrc = curSrc |
| 489 |
curSrc = FilteredInputFile(preFilter, curSrc) |
| 490 |
|
| 491 |
if isinstance(curSrc, str): |
| 492 |
curSrc = open(curSrc, "rb") |
| 493 |
|
| 494 |
# now curSrc is a binary file. If a normal file mode |
| 495 |
# is requested, wrap it into a codec. |
| 496 |
if "b" not in self.fileMode: |
| 497 |
curSrc = wrapFileFor( |
| 498 |
curSrc, self.fileMode, self.grammar.enc or "ascii") |
| 499 |
|
| 500 |
self.inputFile = curSrc |
| 501 |
self.sourceToken = parsingFrom |
| 502 |
|
| 503 |
def finalize(self): |
| 504 |
RowIterator.finalize(self) |
| 505 |
if hasattr(self.inputFile, "close"): |
| 506 |
self.inputFile.close() |
| 507 |
|
| 508 |
|
| 509 |
class FileRowAttributes(base.StructCallbacks): |
| 510 |
"""A mixin for grammars with FileRowIterators. |
| 511 |
|
| 512 |
This provides some attributes that FileRowIterators interpret, e.g., |
| 513 |
preFilter. |
| 514 |
""" |
| 515 |
_gunzip = base.BooleanAttribute("gunzip", description="Unzip sources" |
| 516 |
" while reading? (Deprecated, use preFilter='zcat')", default=False) |
| 517 |
_preFilter = base.UnicodeAttribute("preFilter", description="Shell" |
| 518 |
" command to pipe the input through before passing it on to the" |
| 519 |
" grammar. Classical examples include zcat or bzcat, but you" |
| 520 |
" can commit arbitrary shell atrocities here.", |
| 521 |
copyable=True) |
| 522 |
|
| 523 |
def completeElement(self, ctx): |
| 524 |
if ctx.restricted: |
| 525 |
if self.preFilter is not None: |
| 526 |
raise base.RestrictedElement("preFilter") |
| 527 |
super().completeElement(ctx) |
| 528 |
|
| 529 |
|
| 530 |
class GrammarMacroMixin(base.StandardMacroMixin): |
| 531 |
"""A collection of macros available to rowfilters. |
| 532 |
|
| 533 |
NOTE: All macros should return only one single physical python line, |
| 534 |
or they will mess up the calculation of what constructs caused errors. |
| 535 |
""" |
| 536 |
def macro_inputRelativePath(self, liberalChars="True"): |
| 537 |
"""returns an expression giving the current source's path |
| 538 |
relative to inputsDir |
| 539 |
|
| 540 |
liberalChars can be a boolean literal (True, False, etc); if false, |
| 541 |
a value error is raised if characters that will result in trouble |
| 542 |
with the product mixin are within the result path. |
| 543 |
|
| 544 |
In rowmakers fed by grammars with //products#define, better use |
| 545 |
@prodtblAccref. |
| 546 |
""" |
| 547 |
return ('str(utils.getRelativePath(rowIter.sourceToken,' |
| 548 |
' base.getConfig("inputsDir"), liberalChars=%s))'%( |
| 549 |
base.parseBooleanLiteral(liberalChars))) |
| 550 |
|
| 551 |
def macro_fullDLURL(self, dlService, accref="rowIter.sourceToken"): |
| 552 |
r"""returns a python expression giving a link to the full current data |
| 553 |
set retrieved through the datalink service. |
| 554 |
|
| 555 |
You would write \fullDLURL{dlsvc} here, and the macro will expand into |
| 556 |
something like http://yourserver/currd/dlsvc/dlget?ID=ivo://whatever. |
| 557 |
|
| 558 |
dlService is the id of the datalink service in the current RD. |
| 559 |
|
| 560 |
accref is where to the get dataset's accref from; the default takes |
| 561 |
the file name, but you will need to override that when, e.g., multiple |
| 562 |
datasets are produced from one file. |
| 563 |
|
| 564 |
This is intended for "virtual" data where the dataset is generated |
| 565 |
on the fly through datalink. |
| 566 |
""" |
| 567 |
baseURL = self.rd.getById(dlService).getURL("dlget") |
| 568 |
return ("'%%s?ID=%%s'%%(%s," |
| 569 |
f" urllib.parse.quote_plus(getStandardPubDID({accref})))"%( |
| 570 |
repr(baseURL))) |
| 571 |
|
| 572 |
def macro_dlMetaURI(self, dlService): |
| 573 |
r"""like fullDLURL, except it points to the datalink metadata. |
| 574 |
|
| 575 |
This is intended for binding to //products#define's datalink |
| 576 |
parameter. |
| 577 |
|
| 578 |
If you need the value in a rowmaker, grab it from @prodtblDatalink. |
| 579 |
""" |
| 580 |
baseURL = self.rd.getById(dlService).getURL("dlmeta") |
| 581 |
return ("'%%s?ID=%%s'%%(%s," |
| 582 |
" urllib.parse.quote_plus(getStandardPubDID(rowIter.sourceToken)))"%( |
| 583 |
repr(baseURL))) |
| 584 |
|
| 585 |
def macro_standardPreviewPath(self): |
| 586 |
"""returns an expression for the standard path for a custom preview. |
| 587 |
|
| 588 |
This consists of resdir, the name of the previewDir property on the |
| 589 |
embedding DD, and the flat name of the accref (which this macro |
| 590 |
assumes to see in its namespace as accref; this is usually the |
| 591 |
case in //products#define, which is where this macro would typically be |
| 592 |
used). |
| 593 |
|
| 594 |
As an alternative, there is the splitPreviewPath macro, which does not |
| 595 |
mogrify the file name. In particular, do not use standardPreviewPath |
| 596 |
when you have more than a few 1e4 files, as it will have all these |
| 597 |
files in a single, flat directory, and that can become a chore. |
| 598 |
|
| 599 |
See the introduction to custom previews for details. |
| 600 |
""" |
| 601 |
constantPrefix = os.path.join( |
| 602 |
rscdef.getInputsRelativePath(self.parent.rd.resdir, liberalChars=True), |
| 603 |
self.parent.getProperty("previewDir"))+"/" |
| 604 |
return (repr(constantPrefix) |
| 605 |
+"+getFlatName(accref)") |
| 606 |
|
| 607 |
def macro_splitPreviewPath(self, ext): |
| 608 |
"""returns an expression for the split standard path for a custom |
| 609 |
preview. |
| 610 |
|
| 611 |
As standardPreviewPath, except that the directory hierarchy of the data |
| 612 |
files will be reproduced in previews. For ext, you should typically pass |
| 613 |
the extension appropriate for the preview (like {.png} or {.jpeg}). |
| 614 |
|
| 615 |
See the introduction to custom previews for details. |
| 616 |
""" |
| 617 |
constantPrefix = os.path.join( |
| 618 |
rscdef.getInputsRelativePath(self.parent.rd.resdir), |
| 619 |
self.parent.getProperty("previewDir"))+"/" |
| 620 |
return (repr(constantPrefix) |
| 621 |
+"+accref+'%s'"%ext) |
| 622 |
|
| 623 |
def macro_sourceDate(self): |
| 624 |
"""returns an expression giving the timestamp of the current source. |
| 625 |
""" |
| 626 |
return ('datetime.datetime.utcfromtimestamp(' |
| 627 |
'os.path.getmtime(rowIter.sourceToken))') |
| 628 |
|
| 629 |
def macro_srcstem(self): |
| 630 |
"""returns python code for the stem of the source file currently parsed in a rowmaker. |
| 631 |
|
| 632 |
Example: if you're currently parsing /tmp/foo.bar, the stem is foo. |
| 633 |
""" |
| 634 |
return 'getFileStem(rowIter.sourceToken)' |
| 635 |
|
| 636 |
def macro_rootlessPath(self): |
| 637 |
"""returns an expression giving the current source's path with |
| 638 |
the resource descriptor's root removed. |
| 639 |
""" |
| 640 |
return ('utils.getRelativePath(rowIter.sourceToken,' |
| 641 |
' rowIter.grammar.rd.resdir)') |
| 642 |
|
| 643 |
def macro_inputSize(self): |
| 644 |
"""returns an expression giving the size of the current source. |
| 645 |
""" |
| 646 |
return 'os.path.getsize(rowIter.sourceToken)' |
| 647 |
|
| 648 |
def macro_colNames(self, tableRef): |
| 649 |
"""returns a comma-separated list of column names for a table reference. |
| 650 |
|
| 651 |
This is convenient if an input file matches the table structure; you |
| 652 |
can then simply say things like <reGrammar names="\\\\colName{someTable}"/>. |
| 653 |
""" |
| 654 |
return ",".join(c.name for c in self.rd.getById(tableRef)) |
| 655 |
|
| 656 |
def macro_property(self, property): |
| 657 |
"""returns the value of property on the parent DD. |
| 658 |
""" |
| 659 |
return self.parent.getProperty(property) |
| 660 |
|
| 661 |
|
| 662 |
class Grammar(base.Structure, GrammarMacroMixin): |
| 663 |
"""An abstract grammar. |
| 664 |
|
| 665 |
Grammars are configured via their structure parameters. Their |
| 666 |
parse(sourceToken) method returns an object that iterates over rawdicts |
| 667 |
(dictionaries mapping keys to (typically) strings) that can then be fed |
| 668 |
through rowmakers; it also has a method getParameters that returns |
| 669 |
global properties of the whole document (like parameters in VOTables; |
| 670 |
this will be empty for many kinds of grammars). |
| 671 |
|
| 672 |
RowIterators will return a reference to themselves in the raw dicts in the |
| 673 |
parser_ key unless you override their _iterRowsProcessed method (which you |
| 674 |
shouldn't). This is used by rowmaker macros. |
| 675 |
|
| 676 |
What exactly sourceToken is is up to the concrete grammar. While |
| 677 |
typically it's a file name, it might be a sequence of dictionaries, |
| 678 |
a twisted web request, or whatever. |
| 679 |
|
| 680 |
To derive a concrete Grammar, define a RowIterator for your source |
| 681 |
and set the rowIterator class attribute to it. |
| 682 |
""" |
| 683 |
name_ = "grammar" |
| 684 |
|
| 685 |
_encoding = base.UnicodeAttribute("enc", default=None, description= |
| 686 |
"Encoding of the source file(s).", copyable=True) |
| 687 |
_rowfilters = base.StructListAttribute("rowfilters", |
| 688 |
description="Row filters for this grammar.", |
| 689 |
childFactory=Rowfilter, copyable=True) |
| 690 |
_ignoreOn = base.StructAttribute("ignoreOn", default=None, copyable=True, |
| 691 |
description="Conditions for ignoring certain input records. These" |
| 692 |
" triggers drop an input record entirely. In modern RDs, prefer" |
| 693 |
" rowfilters raising SkipThis.", |
| 694 |
childFactory=rowtriggers.IgnoreOn) |
| 695 |
_sourceFields = base.StructAttribute("sourceFields", default=None, |
| 696 |
copyable=True, description="Code returning a dictionary of values" |
| 697 |
" added to all returned rows.", childFactory=SourceFieldApp) |
| 698 |
_properties = base.PropertyAttribute(copyable=True) |
| 699 |
_original = base.OriginalAttribute() |
| 700 |
_rd = rscdef.RDAttribute() |
| 701 |
|
| 702 |
# isDispatching is used by various special grammars to signify the |
| 703 |
# grammar returns rowdicts for multiple makers. See those. |
| 704 |
# Here, we just fix it to false so clients can rely on the attribute's |
| 705 |
# existence. |
| 706 |
isDispatching = False |
| 707 |
|
| 708 |
rowIterator = RowIterator |
| 709 |
|
| 710 |
def getSourceFields(self, sourceToken, data): |
| 711 |
"""returns a dict containing user-defined fields to be added to |
| 712 |
all results. |
| 713 |
""" |
| 714 |
if self.sourceFields is None: |
| 715 |
return None |
| 716 |
if not hasattr(self, "_compiledSourceFields"): |
| 717 |
self._compiledSourceFields = self.sourceFields.compile() |
| 718 |
return self._compiledSourceFields(sourceToken, data) |
| 719 |
|
| 720 |
def parse(self, sourceToken, targetData=None): |
| 721 |
ri = self.rowIterator(self, sourceToken, |
| 722 |
sourceRow=self.getSourceFields(sourceToken, targetData)) |
| 723 |
ri.rowfilter = compileRowfilter(self.rowfilters) |
| 724 |
return ri |
| 725 |
|
| 726 |
|
| 727 |
class NullGrammar(Grammar): |
| 728 |
"""A grammar that never returns any rows. |
| 729 |
""" |
| 730 |
name_ = "nullGrammar" |
| 731 |
|
| 732 |
|
| 733 |
class TransparentGrammar(Grammar): |
| 734 |
"""A grammar that returns its sourceToken as the row iterator. |
| 735 |
|
| 736 |
This only makes sense in extreme situations and never without custom |
| 737 |
code. If you're not sure you need this, you don't want to know about |
| 738 |
it. |
| 739 |
""" |
| 740 |
name_ = "transparentGrammar" |
| 741 |
|
| 742 |
def parse(self, sourceToken, targetData=None): |
| 743 |
return sourceToken |