Debian Codegraph @

gavo/utils/misctricks.py

raw
1 """
2 Various helpers that didn't fit into any other xTricks.
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 base64
12 import collections
13 import functools
14 import io
15 import os
16 import re
17 import struct
18 import time
19 import threading
20 import urllib.request as urlrequest
21 import zlib
22
23 from docutils import core as rstcore
24 from docutils import nodes
25 from docutils import utils as rstutils
26 from docutils.parsers.rst import roles
27 from docutils.parsers.rst import directives
28 from docutils.parsers.rst.states import Inliner
29
30 from gavo.utils import excs
31
32 from gavo.utils.dachstypes import (Any, BinaryIO, Callable, Dict,
33 Filename, Generator, Generic, List, Optional, NoReturn,
34 Sequence, StrOrBytes,
35 StrToStrMap, Tuple, Type, TypeVar, Union, cast)
36
37
38 BIBCODE_PATTERN = re.compile(r"[012]\d\d\d\w[^ ]{14}$")
39
40 def couldBeABibcode(s: str) -> bool:
41 """returns true if we think that the string s is a bibcode.
42
43 This is based on matching against BIBCODE_PATTERN.
44 """
45 return bool(BIBCODE_PATTERN.match(s))
46
47
48 _RSTRoleReturnType = Tuple[List[nodes.Node], List[str]]
49 _RSTRoleFunction = Callable[[str, str, str, int, Inliner,
50 Optional[dict], Optional[List[str]]], _RSTRoleReturnType]
51
52 class RSTExtensions:
53 """a register for local RST extensions.
54
55 This is for both directives and interpreted text roles.
56
57 We need these as additional markup in examples; these always
58 introduce local rst interpreted text roles, which always
59 add some class to the node in question (modifications are possible).
60
61 These classes are then changed to properties as the HTML fragments
62 from RST translation are processed by the _Example nevow data factory.
63
64 To add a new text role, say::
65
66 RSTExtensions.addRole(roleName, roleFunc=None)
67
68 You can pass in a full role function as discussed in
69 ...docs/howto/rst-roles.html#define-the-role-function
70 It must, however, add a dachs-ex-<roleName> class to the node. The
71 default function produces a nodes.emphasis item with the proper class.
72
73 In a pinch, you can pass a propertyName argument to addRole if the
74 desired property name is distinct from the role name in the RST.
75 This is used by tapquery and taprole since we didn't want to change
76 our examples when the standard changed.
77
78 To add a directive, say::
79
80 RSTExtensions.addDirective(dirName, dirClass)
81
82 In HTML, these classes become properties named like the role name
83 (except you can again use propertyName in a pinch).
84 """
85 classToProperty: Dict[str, str] = {}
86
87 @classmethod
88 def addDirective(cls,
89 name: str,
90 implementingClass: type,
91 propertyName: Optional[str]=None) -> None:
92 directives.register_directive(name, implementingClass)
93 cls.classToProperty["dachs-ex-"+name] = propertyName or name
94
95 @classmethod
96 def makeTextRole(cls,
97 roleName: str,
98 roleFunc: Optional[_RSTRoleFunction]=None, propertyName=None
99 ) -> None:
100 """creates a new text role for roleName.
101
102 See class docstring.
103 """
104 if roleFunc is None:
105 roleFunc = cls._makeDefaultRoleFunc(roleName)
106 # I am too lazy to figure out the complex signature in the next line
107 roles.register_local_role(roleName, roleFunc) # type: ignore
108 cls.classToProperty["dachs-ex-"+roleName] = propertyName or roleName
109
110 @classmethod
111 def _makeDefaultRoleFunc(cls, roleName: str) -> _RSTRoleFunction:
112 """returns an RST interpreted text role parser function returning
113 an emphasis node with a dachs-ex-roleName class.
114 """
115 def roleFunc(name, rawText, text, lineno, inliner,
116 options={}, content=[]):
117 node = nodes.emphasis(rawText, text)
118 node["classes"] = ["dachs-ex-"+roleName]
119 return [node], []
120
121 return roleFunc
122
123 # Generally useful RST extensions (for roles useful in examples,
124 # see examplesrender)
125 def _bibcodeRoleFunc(name: str, rawText: str, text: str, lineno: int,
126 inliner: Inliner,
127 options: Optional[dict]={}, content: Optional[List[str]]=[]
128 ) -> _RSTRoleReturnType:
129 if not couldBeABibcode(text):
130 raise ValueError("Probably not a bibcode: '%s'"%text)
131 node = nodes.reference(rawText, text,
132 refuri="http://adsabs.harvard.edu/abs/%s"%text)
133 node["classes"] = ["bibcode-link"]
134 return [node], []
135
136 RSTExtensions.makeTextRole("bibcode", _bibcodeRoleFunc)
137 del _bibcodeRoleFunc
138
139 # RST extensions for documentation writing
140
141 _explicitTitleRE = re.compile(r'^(.+?)\s*(?<!\x00)<(.*?)>$', re.DOTALL)
142
143 def _dachsdocRoleFunc(name: str, rawText: str, text: str, lineno: int,
144 inliner: Inliner,
145 options: Optional[dict]={}, content: Optional[List[str]]=[]
146 ) -> _RSTRoleReturnType:
147 # inspired by sphinx extlinks
148 text = rstutils.unescape(text)
149 mat = _explicitTitleRE.match(text)
150 if mat:
151 title, url = mat.groups()
152 else:
153 title, url = text.split("/")[-1], text
154 url = "http://docs.g-vo.org/DaCHS/"+url
155 return [nodes.reference(title, title, internal=False, refuri=url)
156 ], []
157
158 RSTExtensions.makeTextRole("dachsdoc", _dachsdocRoleFunc)
159 del _dachsdocRoleFunc
160
161 def _dachsrefRoleFunc(name: str, rawText: str, text: str, lineno: int,
162 inliner: Inliner,
163 options: Optional[dict]={}, content: Optional[List[str]]=[]
164 ) -> _RSTRoleReturnType:
165 # this will guess a link into the ref documentation
166 text = rstutils.unescape(text)
167 fragId = re.sub("[^a-z0-9]+", "-", text.lower()).strip("-")
168 url = "http://docs.g-vo.org/DaCHS/ref.html#"+fragId
169 return [nodes.reference(text, text, internal=False, refuri=url)
170 ], []
171
172 RSTExtensions.makeTextRole("dachsref", _dachsrefRoleFunc)
173 del _dachsrefRoleFunc
174
175 def _samplerdRoleFunc(name: str, rawText: str, text: str, lineno: int,
176 inliner: Inliner,
177 options: Optional[dict]={}, content: Optional[List[str]]=[]
178 ) -> _RSTRoleReturnType:
179 # this will turn into a link to a file in the GAVO svn
180 # (usually for RDs)
181 text = rstutils.unescape(text)
182 url = "http://svn.ari.uni-heidelberg.de/svn/gavo/hdinputs/"+text+".rd"
183 return [nodes.reference(text, text, internal=False, refuri=url)
184 ], []
185
186 RSTExtensions.makeTextRole("samplerd", _samplerdRoleFunc)
187 del _samplerdRoleFunc
188
189
190 class UndefinedType(type):
191 """the metaclass for Undefined.
192
193 Used internally.
194 """
195 def __str__(cls):
196 raise excs.StructureError("%s cannot be stringified."%cls.__name__)
197
198 def __repr__(cls):
199 return "<Undefined>"
200
201 def __bool__(cls):
202 return False
203
204
205 class Undefined(metaclass=UndefinedType):
206 """a sentinel for all kinds of undefined values.
207
208 Do not instantiate.
209
210 >>> Undefined()
211 Traceback (most recent call last):
212 TypeError: Undefined cannot be instantiated.
213 >>> bool(Undefined)
214 False
215 >>> repr(Undefined)
216 '<Undefined>'
217 >>> str(Undefined)
218 Traceback (most recent call last):
219 gavo.utils.excs.StructureError: Undefined cannot be stringified.
220 """
221
222 def __init__(self):
223 raise TypeError("Undefined cannot be instantiated.")
224
225
226 class NotGivenType(type):
227 def __str__(self) -> NoReturn:
228 raise excs.StructureError(
229 "%s cannot be stringified"%self.__class__.__name__)
230
231 def __repr__(self) -> str:
232 return "<Not given/empty>"
233
234 def __bool__(self) -> bool:
235 return False
236
237
238 class NotGiven(object, metaclass=NotGivenType):
239 """A sentinel class for defaultless values that can remain undefined.
240 """
241
242
243
244 class RateLimiter:
245 """A class that helps limit rates of events.
246
247 You construct it with a timeout (in seconds) and then protect things you want
248 to rate-limit with "if rl.inDeadtime(key): skip". The key is an identifier
249 for what it is that you want to limit (e.g., the sort of an event, so that
250 different events can share a rate limiter).
251
252 If you have many events that usually need rate limiting, you'd have
253 to revisit this implementation -- this is really for when rate limiting
254 is the exception.
255 """
256 def __init__(self, timeout: float):
257 self.timeout = timeout
258 self.lastEvents: Dict[str, float] = {}
259
260 def inDeadtime(self, key: str):
261 now = time.time()
262
263 # no reason to have this work in 1970
264 if self.lastEvents.get(key, 0)+self.timeout>now:
265 return True
266
267 self.lastEvents[key] = now
268 return False
269
270
271 @functools.total_ordering
272 class QuotedName:
273 """A string-like thing basically representing SQL delimited identifiers.
274
275 This has some features that make handling these relatively painless
276 in ADQL code.
277
278 The most horrible feature is that these hash and compare as their embedded
279 names, except to other QuotedNamess.
280
281 SQL-92, in 5.2, roughly says:
282
283 delimited identifiers compare literally with each other,
284 delimited identifiers compare with regular identifiers after the
285 latter are all turned to upper case. But since postgres turns everything
286 to lower case, we do so here, too.
287
288 >>> n1, n2, n3 = QuotedName("foo"), QuotedName('foo"l'), QuotedName("foo")
289 >>> n1==n2,n1==n3,hash(n1)==hash("foo")
290 (False, True, True)
291 >>> print(n1, n2)
292 "foo" "foo""l"
293 >>> "Foo"<n1, n1>"bar"
294 (False, True)
295 >>> QuotedName('7oh-no"+rob').makeIdentifier()
296 'id7oh2dno222brob'
297 """
298 def __init__(self, name: str):
299 self.name = name
300
301 def __hash__(self) -> int:
302 return hash(self.name)
303
304 def __eq__(self, other: Any) -> bool:
305 if isinstance(other, QuotedName):
306 return self.name==other.name
307 elif isinstance(other, str):
308 return self.name==other.lower()
309 else:
310 return False
311
312 def __lt__(self, other: Any) -> bool:
313 if isinstance(other, QuotedName):
314 return self.name<other.name
315 elif isinstance(other, str):
316 return self.name<other.lower()
317 else:
318 return False
319
320 def __str__(self) -> str:
321 return '"%s"'%(self.name.replace('"', '""'))
322
323 def __repr__(self) -> str:
324 return 'QuotedName(%s)'%repr(self.name)
325
326 def isRegularLower(self) -> bool:
327 return not not re.match("[a-z][a-z0-9_]*$", self.name)
328
329 def lower(self): # service to ADQL name resolution
330 return self
331
332 def flatten(self) -> str: # ADQL query serialization
333 return str(self)
334
335 def capitalize(self) -> str: # service for table head and such
336 return self.name.capitalize()
337
338 def makeIdentifier(self) -> str:
339 """returns self as something usable as a SQL regular identifier.
340
341 This will be rather unreadable if there's a substantial number
342 of non-letters in there, and of course there's no absolute
343 guarantee that doesn't clash with actual identifiers.
344
345 This is *not* for SQL serialisation but mainly for generating sqlKey,
346 where this kind of thing ends up in %(name)s patterns.
347 """
348 id = re.sub("[^a-zA-Z0-9]", lambda mat: "%x"%ord(mat.group(0)), self.name)
349 if not re.match("[a-zA-Z]", id):
350 id = "id"+id
351 return id
352
353 def __add__(self, other: str): # for disambiguateColumns
354 return QuotedName(self.name+other)
355
356 @classmethod
357 def parse(cls, literal):
358 """returns a QuotedName if literal starts with quoted/, literal
359 unchanged otherwise.
360 """
361 if isinstance(literal, cls):
362 return literal
363 if literal.startswith("quoted/"):
364 return cls(literal[7:])
365 return literal
366
367 def unparse(self):
368 return "quoted/"+self.name
369
370
371 _StreamData = TypeVar('_StreamData', bytes, str)
372
373 class StreamBuffer(Generic[_StreamData]):
374 """a buffer that takes data in arbitrary chunks and returns
375 them in chops of chunkSize bytes.
376
377 There's a lock in place so you can access add and get from
378 different threads.
379
380 When everything is written, you must all doneWriting.
381 """
382 chunkSize = 50000
383
384 def __init__(self, chunkSize: Optional[int]=None, binary: bool=True):
385 self.buffer: collections.deque = collections.deque()
386 if chunkSize is not None:
387 self.chunkSize = chunkSize
388 self.curSize = 0
389 self.lock = threading.Lock()
390 self.finished = False
391 # annotation problem: understand how to make mypy grok this
392 self.joiner: _StreamData = b"" if binary else "" # type: ignore
393
394 def add(self, data: _StreamData) -> None:
395 with self.lock:
396 self.buffer.append(data)
397 self.curSize += len(data)
398
399 def get(self, numBytes: Optional[int]=None) -> Optional[_StreamData]:
400 if numBytes is None:
401 numBytes = self.chunkSize
402
403 if self.curSize<numBytes and not self.finished:
404 return None
405 if not self.buffer:
406 return None
407
408 with self.lock:
409 items, sz = [], 0
410 # collect items till we've got a chunk
411 while self.buffer:
412 item = self.buffer.popleft()
413 sz += len(item)
414 self.curSize -= len(item)
415 items.append(item)
416 if sz>=numBytes:
417 break
418
419 # make a chunk and push back what we didn't need
420 chunk = self.joiner.join(items)
421 leftOver = chunk[numBytes:]
422 if leftOver:
423 self.buffer.appendleft(leftOver)
424 self.curSize += len(leftOver)
425 chunk = chunk[:numBytes]
426
427 return chunk
428
429 # XXX TODO: refactor get and getToChar to use as much common code
430 # as sensible
431 def getToChar(self, char: _StreamData) -> Optional[_StreamData]:
432 """returns the the buffer up to the first occurrence of char.
433
434 If char is not present in the buffer, the function returns None.
435 """
436 with self.lock:
437 items, sz = [], 0
438 # collect items till we've got our character
439 while self.buffer:
440 item = self.buffer.popleft()
441 sz += len(item)
442 self.curSize -= len(item)
443 items.append(item)
444 if char in item:
445 break
446 else:
447 # didn't break out of the loop, i.e., no char found.
448 # items now contains the entire buffer.
449 self.buffer.clear()
450 self.buffer.append(self.joiner.join(items))
451 self.curSize = sz
452 return None
453
454 # char is in the last element of items
455 items[-1], leftOver = items[-1].split(char, 1)
456 chunk = self.joiner.join(items)
457 if leftOver:
458 self.buffer.appendleft(leftOver)
459 self.curSize += len(leftOver)
460 return chunk+char
461
462 raise AssertionError("This cannot happen") # pragma: no cover
463
464 def getRest(self) -> _StreamData:
465 """returns the entire buffer as far as it is left over.
466 """
467 result = self.joiner.join(self.buffer)
468 self.buffer = collections.deque()
469 return result
470
471 def doneWriting(self) -> None:
472 self.finished = True
473
474
475 _T = TypeVar("_T")
476
477 def grouped(n: int, seq: Sequence[_T]) -> List[List[_T]]:
478 """yields items of seq in groups n elements.
479
480 If len(seq)%n!=0, the last elements are discarded.
481
482 >>> list(grouped(2, range(5)))
483 [(0, 1), (2, 3)]
484 >>> list(grouped(3, range(9)))
485 [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
486 """
487 # annotation problem: understand why mypy doesn't understand this
488 return list(zip(*([iter(seq)]*n))) # type: ignore
489
490
491 # annotation problem: https://github.com/python/mypy/issues/3737
492 def getfirst(args: Dict[str, _T], key: str, default: _T=Undefined) -> _T: # type: ignore
493 """returns the first value of key in the web argument-like object args.
494
495 args is a dictionary mapping keys to lists of values. If key is present,
496 the first element of the list is returned; else, or if the list is
497 empty, default if given. If not, a Validation error for the requested
498 column is raised.
499
500 Finally, if args[key] is neither list nor tuple (in an ininstance
501 sense), it is returned unchanged.
502
503 >>> getfirst({'x': [1,2,3]}, 'x')
504 1
505 >>> getfirst({'x': []}, 'x')
506 Traceback (most recent call last):
507 gavo.utils.excs.ValidationError: Field x: Missing mandatory parameter x
508 >>> getfirst({'x': []}, 'y')
509 Traceback (most recent call last):
510 gavo.utils.excs.ValidationError: Field y: Missing mandatory parameter y
511 >>> print(getfirst({'x': []}, 'y', None))
512 None
513 >>> getfirst({'x': 'abc'}, 'x')
514 'abc'
515 """
516 try:
517 val = args[key]
518 if isinstance(val, (list, tuple)):
519 return val[0]
520 else:
521 return val
522 except (KeyError, IndexError):
523 if default is Undefined:
524 raise excs.ValidationError("Missing mandatory parameter %s"%key,
525 colName=key)
526 return default
527
528
529 def sendUIEvent(eventName: str, *args) -> None:
530 """sends an eventName to the DC event dispatcher.
531
532 If no event dispatcher is available, do nothing.
533
534 The base.ui object that DaCHS uses for event dispatching
535 is only available to sub-packages above base. Other code should not
536 use or need it under normal circumstances, but if it does, it can
537 use this.
538
539 All other code should use ``base.ui.notify<eventName>(*args)`` directly.
540 """
541 try:
542 from gavo.base import ui
543 getattr(ui, "notify"+eventName)(*args)
544 except ImportError:
545 pass
546
547
548 def logOldExc(exc: Exception) -> Exception:
549 """logs the mutation of the currently handled exception to exc.
550
551 This just does a notifyExceptionMutation using sendUIEvent; it should
552 only be used by code at or below base.
553 """
554 sendUIEvent("ExceptionMutation", exc)
555 return exc
556
557
558 def getFortranRec(f: BinaryIO) -> Optional[bytes]:
559 """reads a "fortran record" from f and returns the payload.
560
561 A "fortran record" comes from an unformatted file and has a
562 4-byte payload length before and after the payload. Native endianness
563 is assumed here.
564
565 If the two length specs do not match, a ValueError is raised.
566
567 Of course, f must be open in binary mode.
568 """
569 try:
570 startPos: Union[int, str] = f.tell()
571 except IOError:
572 startPos = "(stdin)"
573 rawLength = f.read(4)
574 if rawLength==b'': # EOF
575 return None
576 recLen = struct.unpack("i", rawLength)[0]
577 data = f.read(recLen)
578 rawPost = f.read(4)
579 if not rawPost:
580 raise ValueError("Record starting at %s has no postamble"%startPos)
581 postambleLen = struct.unpack("i", rawPost)[0]
582 if recLen!=postambleLen:
583 raise ValueError("Record length at record (%d) and did not match"
584 " postamble declared length (%d) at %s"%(
585 recLen, postambleLen, startPos))
586 return data
587
588
589 def iterFortranRecs(f: BinaryIO, skip: int=0) -> Generator[bytes, None, None]:
590 """iterates over the fortran records in f.
591
592 For details, see getFortranRec.
593 """
594 while True:
595 rec = getFortranRec(f)
596 if rec is None:
597 break
598 if skip>0:
599 skip -= 1
600 continue
601 yield rec
602
603
604 def getWithCache(url: str, cacheDir: Filename, extraHeaders: dict={}) -> bytes:
605 """returns the content of url, from a cache if possible.
606
607 Of course, you only want to use this if there's some external guarantee
608 that the resource behind url doesn't change. No expiry mechanism is
609 present here.
610 """
611 if not os.path.isdir(cacheDir):
612 os.makedirs(cacheDir)
613 cacheName = os.path.join(cacheDir, re.sub(r"[^\w]+", "", url)+".cache")
614 if os.path.exists(cacheName):
615 with open(cacheName, "rb") as f:
616 return f.read()
617 else:
618 with urlrequest.urlopen(url) as f:
619 doc = f.read()
620 with open(cacheName, "wb") as f:
621 f.write(doc)
622 urlrequest.urlcleanup()
623 return doc
624
625
626 def rstxToHTMLWithWarning(source: str, **userOverrides) -> Tuple[str, str]:
627 """returns HTML and a string with warnings for a piece of ReStructured
628 text.
629
630 source can be a unicode string or a byte string in utf-8.
631
632 userOverrides will be added to the overrides argument of docutils'
633 core.publish_parts.
634 """
635 sourcePath, destinationPath = None, None
636 if not isinstance(source, str):
637 source = source.decode("utf-8")
638
639 warnAccum = io.StringIO()
640 overrides = {'input_encoding': 'unicode',
641 'raw_enabled': True,
642 'doctitle_xform': None,
643 'warning_stream': warnAccum,
644 'initial_header_level': 4}
645 overrides.update(userOverrides)
646
647 parts = rstcore.publish_parts(
648 source=source+"\n", source_path=sourcePath,
649 destination_path=destinationPath,
650 writer_name='html', settings_overrides=overrides)
651 return parts["fragment"], warnAccum.getvalue()
652
653
654 def rstxToHTML(source: str, **userOverrides) -> str:
655 """returns HTML for a piece of ReStructured text.
656
657 source can be a unicode string or a byte string in utf-8.
658
659 userOverrides will be added to the overrides argument of docutils'
660 core.publish_parts.
661 """
662 return rstxToHTMLWithWarning(source, **userOverrides)[0]
663
664
665 class CaseSemisensitiveDict(dict):
666 """A dictionary allowing case-insensitive access to its content.
667
668 This is used for DAL renderers which, unfortunately, are supposed
669 to be case insensitive. Since case insensitivity is at least undesirable
670 for service-specific keys, we go a semi-insenstitve approach here:
671 First, we try literal matches, if that does not work, we try matching
672 against an all-uppercase version.
673
674 Name clashes resulting from different names being mapped to the
675 same normalized version are handled in some random way. Don't do this.
676 And don't rely on case normalization if at all possible.
677
678 Only strings are allowed as keys here. This class is not concerned
679 with the values.
680 >>> d = CaseSemisensitiveDict({"a": 1, "A": 2, "b": 3})
681 >>> d["a"], d["A"], d["b"], d["B"]
682 (1, 2, 3, 3)
683 >>> d["B"] = 9; d["b"], d["B"]
684 (3, 9)
685 >>> del d["b"]; d["b"], d["B"]
686 (9, 9)
687 >>> "B" in d, "b" in d, "u" in d
688 (True, True, False)
689 >>> d.pop("a"), list(d.keys())
690 (1, ['A', 'B'])
691 """
692 def __init__(self, *args, **kwargs):
693 dict.__init__(self, *args, **kwargs)
694 self._normCasedCache = None
695
696 def __getitem__(self, key: str) -> Any:
697 try:
698 return dict.__getitem__(self, key)
699 except KeyError:
700 pass # try again with normalized case.
701 return self._normCased[key.upper()]
702
703 def __setitem__(self, key: str, value: Any) -> None:
704 self._normCasedCache = None
705 dict.__setitem__(self, key, value)
706
707 def __contains__(self, key: object) -> bool:
708 key = cast(str, key)
709 return dict.__contains__(self, key) or key.upper() in self._normCased
710
711 def __delitem__(self, key: str) -> None:
712 self.pop(key, None)
713
714 def get(self, key: str, default: Any=None) -> Any:
715 try:
716 return self[key]
717 except KeyError:
718 return default
719
720 def pop(self, key: str, default: Any=KeyError) -> Any:
721 try:
722 return dict.pop(self, key)
723 except KeyError:
724 pass # try again with normalized case.
725 try:
726 return self._normCased.pop(key.upper())
727 except KeyError:
728 if default is not KeyError:
729 return default
730 raise
731
732 def copy(self):
733 return CaseSemisensitiveDict(dict.copy(self))
734
735 @property
736 def _normCased(self) -> Dict[str, Any]:
737 if self._normCasedCache is None:
738 self._normCasedCache = dict((k.upper(), v)
739 for k, v in self.items())
740 return self._normCasedCache
741
742 @classmethod
743 def fromDict(cls: Type['CaseSemisensitiveDict'],
744 aDict: Union[dict, 'CaseSemisensitiveDict']) -> 'CaseSemisensitiveDict':
745 if isinstance(aDict, CaseSemisensitiveDict):
746 return aDict
747 else:
748 return cls(aDict)
749
750
751 def getCleanBytes(b: StrOrBytes) -> bytes:
752 """returns the bytes b in an ASCII representation.
753
754 This is zlib-compressed base64 stuff. b can be a string, too, in which
755 case it's utf-8 encoded before marshalling.
756 """
757 if isinstance(b, str):
758 b = b.encode("utf-8")
759 return base64.b64encode(
760 zlib.compress(b)).replace(b"\n", b"")
761
762
763 def getDirtyBytes(b: bytes) -> bytes:
764 """returns b decoded and uncompressed.
765
766 This is the inverse operation of getCleanBytes. b must be bytes, and
767 bytes is what you get back.
768 """
769 return zlib.decompress(
770 base64.b64decode(b))
771
772
773 ######################### pyparsing-based key-value lines.
774
775 from gavo.utils.parsetricks import (
776 Word,alphas, QuotedString, Regex, OneOrMore,
777 pyparsingWhitechars, pyparseString)
778
779 def _makeKVLGrammar():
780 with pyparsingWhitechars(" \t"):
781 keyword = Word(alphas+"_")("key")
782 keyword.setName("Keyword")
783 value = (QuotedString(quoteChar="'", escChar='\\')
784 | Regex("[^'= \t]*"))("value")
785 value.setName("Simple value or quoted string")
786 pair = keyword - "=" - value
787 pair.setParseAction(lambda s,p,t: (t["key"], t["value"]))
788 line = OneOrMore(pair)
789 line.setParseAction(lambda s,p,t: dict(list(t)))
790
791 return line
792
793 _KVL_GRAMMAR = _makeKVLGrammar()
794
795
796 def parseKVLine(aString: str):
797 """returns a dictionary for a "key-value line".
798
799 key-value lines represent string-valued dictionaries
800 following postgres libpq/dsn (see PQconnectdb docs;
801 it's keyword=value, whitespace-separated, with
802 whitespace allowed in values through single quoting,
803 and backslash-escaping
804 """
805 return pyparseString(_KVL_GRAMMAR, aString, parseAll=True)[0]
806
807 _IDENTIFIER_PATTERN = re.compile("[A-Za-z_]+$")
808
809 def makeKVLine(aDict: StrToStrMap) -> str:
810 """serializes a dictionary to a key-value line.
811
812 See parseKVLine for details.
813 """
814 parts = []
815 for key, value in aDict.items():
816 if not _IDENTIFIER_PATTERN.match(key):
817 raise ValueError("'%s' not allowed as a key in key-value lines"%key)
818 value = str(value)
819 if not _IDENTIFIER_PATTERN.match(value):
820 value = "'%s'"%value.replace("\\", "\\\\"
821 ).replace("'", "\\'")
822 parts.append("%s=%s"%(key, value))
823 return " ".join(sorted(parts))
824
825
826 if __name__=="__main__": # pragma: no cover
827 import doctest
828 doctest.testmod()