Debian Codegraph @

gavo/utils/texttricks.py

raw
1 """
2 Formatting, text manipulation, string constants, and such.
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 calendar
12 import datetime
13 import functools
14 import itertools
15 import os
16 import pathlib
17 import quopri
18 import random
19 import re
20 import string
21 import time
22 from email import utils as emailutils
23 from email import message as emailmessage
24
25 from gavo.utils.dachstypes import (Any, Filename, Generator, Iterator,
26 Optional, SourceToken, StrToStrMap, TextIO, Tuple, Union)
27
28 from gavo.imp import angle_formats
29 from gavo.utils import codetricks
30 from gavo.utils import misctricks
31 from gavo.utils.excs import SourceParseError, StructureError
32
33 floatRE = r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?"
34 dateRE = re.compile(r"\d\d\d\d-\d\d-\d\d$")
35 datetimeRE = re.compile(r"\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ?$")
36 identifierPattern = re.compile(r"[A-Za-z_][A-Za-z0-9_]*$")
37 isoTimestampFmt = "%Y-%m-%dT%H:%M:%SZ"
38 isoTimestampFmtNoTZ = "%Y-%m-%dT%H:%M:%S"
39 entityrefPat = re.compile(r"&([^;])+;")
40 looksLikeURLPat = re.compile(r"[a-z]{2,5}://")
41 sqlStringPat = re.compile(r"'([^']+|'')*'")
42
43
44 # file names that don't cause headaches in URLs and are otherwise reasonably
45 # benign (so, let's disallow shell metachars while we're at it).
46 _SAFE_FILENAME = re.compile("[,-:=@-Z_a-z{}~-]+$")
47
48 xmlEntities = {
49 'lt': '<',
50 'gt': '>',
51 'amp': '&',
52 'apos': "'",
53 'quot': '"',
54 }
55
56
57 def formatSize(val: float, sf: int=1) -> str:
58 """returns a human-friendly representation of a file size.
59 """
60 if val<1e3:
61 return "%d Bytes"%int(val)
62 elif val<1e6:
63 return "%.*fkiB"%(sf, val/1024.)
64 elif val<1e9:
65 return "%.*fMiB"%(sf, val/1024./1024.)
66 else:
67 return "%.*fGiB"%(sf, val/1024./1024./1024)
68
69
70 def makeEllipsis(aStr: str, maxLen: int=60, ellChars: str="...") -> str:
71 """returns aStr cropped to maxLen if necessary.
72
73 Cropped strings are returned with an ellipsis marker.
74 """
75 aStr = re.sub(r"\s+", " ", aStr)
76 if len(aStr)>maxLen:
77 return aStr[:maxLen-len(ellChars)]+ellChars
78 return aStr
79
80
81 def makeLeftEllipsis(aStr: str, maxLen: int=60):
82 """returns aStr shortened to maxLen by dropping prefixes if necessary.
83
84 Cropped strings are returned with an ellipsis marker.
85
86 >>> makeLeftEllipsis("0123456789"*2, 11)
87 '...23456789'
88 """
89 aStr = re.sub(r"\s+", " ", aStr)
90 if len(aStr)>maxLen:
91 return "..."+aStr[-maxLen+3:]
92 return aStr
93
94
95 def makeSourceEllipsis(sourceToken: SourceToken) -> str:
96 """returns a string hopefully representative for a source token.
97
98 These are, in particular, passed around within rsc.makeData. Usually,
99 these are (potentially long) strings, but now and then they can be
100 other things with appallingly long reprs. When DaCHS messages
101 need to refer to such sources, this function is used to come up
102 with representative strings.
103 """
104 if isinstance(sourceToken, str):
105 return makeLeftEllipsis(sourceToken)
106 else:
107 return makeEllipsis(repr(sourceToken), maxLen=160)
108
109
110 @codetricks.document
111 def getFileStem(fPath: str):
112 """returns the file stem of a file path.
113
114 The base name is what remains if you take the base name and split off
115 extensions. The extension here starts with the last dot in the file name,
116 except up to one of some common compression extensions (.gz, .xz, .bz2,
117 .Z, .z) is stripped off the end if present before determining the extension.
118
119 >>> getFileStem("/foo/bar/baz.x.y")
120 'baz.x'
121 >>> getFileStem("/foo/bar/baz.x.gz")
122 'baz'
123 >>> getFileStem("/foo/bar/baz")
124 'baz'
125 """
126 for ext in [".gz", ".xz", ".bz2", ".Z", ".z"]:
127 if fPath.endswith(ext):
128 fPath = fPath[:-len(ext)]
129 break
130 return os.path.splitext(os.path.basename(fPath))[0]
131
132
133 def formatSimpleTable(
134 data: list[list[Any]],
135 stringify: bool=True,
136 titles: Optional[list[str]]=None) -> str:
137 """returns a string containing a text representation of tabular data.
138
139 All columns of data are simply stringified, then the longest member
140 determines the width of the text column. The behaviour if data
141 does not contain rows of equal length is unspecified; data must
142 contain at least one row.
143
144 If you have serialised the values in data yourself, pass stringify=False.
145
146 If you pass titles, it must be a sequence of strings; they are then
147 used as table headers; the shorter of data[0] and titles will determine
148 the number of columns displayed.
149 """
150 if stringify:
151 data = [[str(v) for v in row] for row in data]
152
153 if not data:
154 return ""
155
156 colWidthes = [max(len(row[colInd]) for row in data)
157 for colInd in range(len(data[0]))]
158 if titles is not None:
159 colWidthes = [max(len(t), l) for t, l in zip(titles, colWidthes)]
160
161 fmtStr = " ".join("%%%ds"%w for w in colWidthes)
162 table = "\n".join(fmtStr%tuple(row) for row in data)
163 if titles is not None:
164 table = fmtStr%tuple(titles)+"\n\n"+table
165 return table
166
167
168 @codetricks.document
169 def getRelativePath(
170 fullPath: Filename,
171 rootPath: Filename,
172 liberalChars: bool=True) -> Filename:
173 """returns rest if fullPath has the form rootPath/rest and raises a
174 ValueError otherwise.
175
176 This accepts either strings or pathlib.Path-s and returns an object of the
177 type of fullPath (pathlib functionality since 2.9.3).
178
179 Pass ``liberalChars=False`` to make this raise a ValueError when
180 URL-dangerous characters (blanks, amperands, pluses, non-ASCII, and
181 similar) are present in the result. This is mainly for products.
182 """
183 if isinstance(fullPath, pathlib.PurePath):
184 res: Filename = fullPath.relative_to(rootPath)
185 else:
186 if not fullPath.startswith(str(rootPath)):
187 raise ValueError(f"{fullPath} does not start with {rootPath}")
188 res = os.path.relpath(fullPath, str(rootPath))
189 # backwards compatibility hack
190 if res==".":
191 res = ""
192
193 if not liberalChars and not _SAFE_FILENAME.match(str(res)):
194 raise ValueError("File path '%s' contains characters known to"
195 " the DaCHS authors to be hazardous in URLs. Please defuse the name"
196 " before using it for published names (or see howDoI)."%res)
197
198 return res
199
200
201 def resolvePath(rootPath: str, relPath: str) -> str:
202 """joins relPath to rootPath and makes sure the result really is
203 in rootPath.
204 """
205 relPath = relPath.lstrip("/")
206 fullPath = os.path.realpath(os.path.join(rootPath, relPath))
207 if not fullPath.startswith(rootPath):
208 raise ValueError(
209 "Full path %s does not start with resource root %s"%(fullPath, rootPath))
210 if not os.path.exists(fullPath):
211 raise ValueError(
212 "Invalid path %s. This should not happen."%(fullPath))
213 return fullPath
214
215
216 def fixIndentation(code: str, newIndent: str, governingLine: int=0) -> str:
217 """returns code with all whitespace from governingLine removed from
218 every line and newIndent prepended to every line.
219
220 governingLine lets you select a line different from the first one
221 for the determination of the leading white space. Lines before that
222 line are left alone.
223
224 >>> fixIndentation(" foo\\n bar", "")
225 'foo\\nbar'
226 >>> fixIndentation(" foo\\n bar", " ")
227 ' foo\\n bar'
228 >>> fixIndentation(" foo\\n bar\\n baz", "", 1)
229 'foo\\nbar\\n baz'
230 >>> fixIndentation(" foo\\nbar", "")
231 Traceback (most recent call last):
232 gavo.utils.excs.StructureError: Bad indent in line 'bar'
233 """
234 codeLines = [line for line in code.split("\n")]
235 reserved, codeLines = codeLines[:governingLine], codeLines[governingLine:]
236 while codeLines:
237 if codeLines[0].strip():
238 if mat := re.match(r"^\s*", codeLines[0]):
239 firstIndent = mat.group()
240 break
241 else:
242 reserved.append(codeLines.pop(0))
243 if codeLines:
244 fixedLines = []
245 for line in codeLines:
246 if not line.strip():
247 fixedLines.append(newIndent)
248 else:
249 if line[:len(firstIndent)]!=firstIndent:
250 raise StructureError("Bad indent in line %s"%repr(line))
251 fixedLines.append(newIndent+line[len(firstIndent):])
252 else:
253 fixedLines = codeLines
254 reserved = [newIndent+l.lstrip() for l in reserved]
255 return "\n".join(reserved+fixedLines)
256
257
258 @functools.lru_cache()
259 def _getREForPercentExpression(format: str) -> re.Pattern:
260 """helps parsePercentExpression.
261 """
262 parts = re.split(r"(%\w)", format)
263 newReParts = []
264 for ind, p in enumerate(parts):
265 if p.startswith("%"):
266 # the time-parsing hack explained in the docstring:
267 if ind+2<len(parts) and parts[ind+1]=="":
268 if p[1] in "HMS":
269 newReParts.append("(?P<%s>..)"%p[1])
270 else:
271 raise ValueError(
272 "At %s: conversions with no intervening literal not supported."% p)
273 else:
274 newReParts.append("(?P<%s>.*?)"%p[1])
275 else:
276 newReParts.append(re.escape(p))
277 return re.compile("".join(newReParts)+"$")
278
279
280 def parsePercentExpression(literal: str, format: str) -> dict:
281 """returns a dictionary of parts in the %-template format.
282
283 format is a template with %<conv> conversions, no modifiers are
284 allowed. Each conversion is allowed to contain zero or more characters
285 matched stingily. Successive conversions without intervening literals
286 aren't really supported. There's a hack for strptime-type times, though:
287 H, M, and S just eat two characters each if there's no separator.
288
289 This is really only meant as a quick hack to support times like 25:33.
290
291 >>> r=parsePercentExpression("12,xy:33,","%a:%b,%c"); r["a"], r["b"], r["c"]
292 ('12,xy', '33', '')
293 >>> sorted(parsePercentExpression("2357-x", "%H%M-%u").items())
294 [('H', '23'), ('M', '57'), ('u', 'x')]
295 >>> r = parsePercentExpression("12,13,14", "%a:%b,%c")
296 Traceback (most recent call last):
297 ValueError: '12,13,14' cannot be parsed using format '%a:%b,%c'
298 """
299 mat = _getREForPercentExpression(format).match(literal)
300 if not mat:
301 raise ValueError("'%s' cannot be parsed using format '%s'"%(
302 literal, format))
303 return mat.groupdict()
304
305
306 def parseAssignments(assignments: str) -> StrToStrMap:
307 """returns a name mapping dictionary from a list of assignments.
308
309 This is the preferred form of communicating a mapping from external names
310 to field names in records to macros -- in a string that contains
311 ":"-seprated pairs separated by whitespace, like "a:b b:c", where
312 the incoming names are leading, the desired names are trailing.
313
314 If you need defaults to kick in when the incoming data is None, try
315 _parseDestWithDefault in the client function.
316
317 This function parses a dictionary mapping original names to desired names.
318
319 >>> parseAssignments("a:b b:c")
320 {'a': 'b', 'b': 'c'}
321 """
322 return dict([(lead, trail) for lead, trail in
323 [litPair.split(":") for litPair in assignments.split()]])
324
325
326 @codetricks.document
327 def hmsToDeg(hms: str, sepChar: Optional[str]=None) -> float:
328 """returns the time angle (h m s.decimals) as a float in degrees.
329
330 >>> "%3.8f"%hmsToDeg("22 23 23.3")
331 '335.84708333'
332 >>> "%3.8f"%hmsToDeg("22:23:23.3", ":")
333 '335.84708333'
334 >>> "%3.8f"%hmsToDeg("222323.3", "")
335 '335.84708333'
336 >>> hmsToDeg("junk")
337 Traceback (most recent call last):
338 ValueError: Invalid time with sepChar None: 'junk'
339 """
340 hms = hms.strip()
341 try:
342 if sepChar=="":
343 parts = [hms[:2], hms[2:4], hms[4:]]
344 else:
345 parts = hms.split(sepChar)
346 if len(parts)==3:
347 hours, minutes, seconds = parts
348 elif len(parts)==2:
349 hours, minutes = parts
350 seconds = "0"
351 else:
352 raise ValueError("Too many parts")
353 timeSeconds = int(hours)*3600+float(minutes)*60+float(seconds or "0")
354 except ValueError:
355 raise ValueError("Invalid time with sepChar %s: %s"%(
356 repr(sepChar), repr(hms)))
357 return timeSeconds/3600/24*360
358
359
360 @codetricks.document
361 def dmsToDeg(dmsAngle: str, sepChar: Optional[str]=None) -> float:
362 """returns the degree minutes seconds-specified dmsAngle as a
363 float in degrees.
364
365 >>> "%3.8f"%dmsToDeg("45 30.6")
366 '45.51000000'
367 >>> "%3.8f"%dmsToDeg("45:30.6", ":")
368 '45.51000000'
369 >>> "%3.8f"%dmsToDeg("-45 30 7.6")
370 '-45.50211111'
371 >>> dmsToDeg("junk")
372 Traceback (most recent call last):
373 ValueError: Invalid dms value with sepChar None: 'junk'
374 """
375 dmsAngle = dmsAngle.strip()
376 sign = 1
377 if dmsAngle.startswith("+"):
378 dmsAngle = dmsAngle[1:].strip()
379 elif dmsAngle.startswith("-"):
380 sign, dmsAngle = -1, dmsAngle[1:].strip()
381 try:
382 if sepChar=="":
383 parts = [dmsAngle[:2], dmsAngle[2:4], dmsAngle[4:]]
384 else:
385 parts = dmsAngle.split(sepChar)
386 if len(parts)==3:
387 deg, min, sec = parts
388 elif len(parts)==2:
389 deg, min = parts
390 sec = "0"
391 else:
392 raise ValueError("Invalid # of parts")
393 arcSecs = sign*(int(deg)*3600+float(min)*60+float(sec or "0"))
394 except ValueError:
395 raise misctricks.logOldExc(
396 ValueError("Invalid dms value with sepChar %s: %s"%(
397 repr(sepChar), repr(dmsAngle))))
398 return arcSecs/3600
399
400
401 def fracHoursToDeg(fracHours: float) -> float:
402 """returns the time angle fracHours given in decimal hours in degrees.
403 """
404 return float(fracHours)*360./24.
405
406
407 @codetricks.document
408 def degToHms(deg: float,
409 sepChar: str=" ",
410 secondFracs: int=3,
411 truncate: bool=False) -> str:
412 """converts a float angle in degrees to an time angle (hh:mm:ss.mmm).
413
414 This takes a lot of optional arguments:
415
416 * sepChar is the char separating the components
417 * secondFracs is the number for fractional seconds to generate
418 * truncate can be set to True if fractional seconds should be truncated
419 rather then rounded (as necessary for building IAU identifiers)
420
421 >>> degToHms(0, sepChar=":")
422 '00:00:00.000'
423 >>> degToHms(122.057, secondFracs=1)
424 '08 08 13.7'
425 >>> degToHms(122.057, secondFracs=1, truncate=True)
426 '08 08 13.6'
427 >>> degToHms(-0.055, secondFracs=0)
428 '-00 00 13'
429 >>> degToHms(-0.055, secondFracs=0, truncate=True)
430 '-00 00 13'
431 >>> degToHms(-1.056, secondFracs=0)
432 '-00 04 13'
433 >>> degToHms(-1.056, secondFracs=0)
434 '-00 04 13'
435 >>> degToHms(359.9999999)
436 '24 00 00.000'
437 >>> degToHms(359.2222, secondFracs=4, sepChar=":")
438 '23:56:53.3280'
439 >>> "%.4f"%hmsToDeg(degToHms(256.25, secondFracs=9))
440 '256.2500'
441 """
442 if truncate:
443 return angle_formats.hours_to_string(
444 deg/360*24, sep=(sepChar, sepChar),
445 precision=secondFracs+8, pad=True)[:-8].rstrip(".")
446
447 return angle_formats.hours_to_string(
448 deg/360*24, sep=(sepChar, sepChar), precision=secondFracs, pad=True)
449
450
451 @codetricks.document
452 def hoursToHms(decimal_hours: float,
453 sepChar: str=":", secondFracs:int =0) -> str:
454 """returns a time span in hours in sexagesmal time (h:m:s).
455
456 The optional arguments are as for degToHms.
457
458 >>> hoursToHms(0)
459 '00:00:00'
460 >>> hoursToHms(23.5)
461 '23:30:00'
462 >>> hoursToHms(23.55)
463 '23:33:00'
464 >>> hoursToHms(23.525)
465 '23:31:30'
466 >>> hoursToHms(23.553, secondFracs=2)
467 '23:33:10.80'
468 >>> hoursToHms(123.553, secondFracs=2)
469 '123:33:10.80'
470 """
471 return angle_formats.hours_to_string(
472 decimal_hours, sep=(sepChar, sepChar), precision=secondFracs, pad=True)
473
474
475 @codetricks.document
476 def degToDms(deg: float,
477 sepChar: str=" ",
478 secondFracs: int=2,
479 preserveLeading: bool=False,
480 truncate: bool=False,
481 addSign: bool=True) -> str:
482 """converts a float angle in degrees to a sexagesimal string.
483
484 This takes a lot of optional arguments:
485
486 * sepChar is the char separating the components
487 * secondFracs is the number for fractional seconds to generate
488 * preserveLeading can be set to True if leading zeroes should be
489 preserved
490 * truncate can be set to True if fractional seconds should be truncated
491 rather then rounded (as necessary for building IAU identifiers)
492 * addSign, if true, makes the function return a + in front of positive
493 values (the default)
494
495 >>> degToDms(-3.24722, "", 0, True, True)
496 '-031449'
497 >>> degToDms(0)
498 '+0 00 00.00'
499 >>> degToDms(0, addSign=False)
500 '0 00 00.00'
501 >>> degToDms(-0.25, sepChar=":")
502 '-0:15:00.00'
503 >>> degToDms(-23.50, secondFracs=4)
504 '-23 30 00.0000'
505 >>> "%.4f"%dmsToDeg(degToDms(-25.6835, sepChar=":"), sepChar=":")
506 '-25.6835'
507 """
508 if truncate:
509 secondFracs += 8
510
511 fmted = angle_formats.degrees_to_string(
512 deg, sep=(sepChar, sepChar), precision=secondFracs,
513 pad=preserveLeading)
514
515 if truncate:
516 fmted = fmted[:-8].rstrip(".")
517
518 if addSign and deg>=0:
519 fmted = "+"+fmted
520
521 return fmted
522
523
524 @codetricks.document
525 def makeIAUId(prefix: str,
526 long: float, lat: float,
527 longSec: int=0, latSec: int=0) -> str:
528 """returns an (equatorial) IAU identifier for an object at long and lat.
529
530 The rules are given on https://cds.unistra.fr/Dic/iau-spec.html
531
532 The prefix, including the system identifier, you have to pass in.
533 You cannot build identifiers using only minutes precision.
534 If you want to include sub-arcsec precision, pass in longSec and/or
535 latSec (the number of factional seconds to preserve).
536 """
537 longPart = degToHms(long, "", longSec, True)
538 latPart = degToDms(lat, "", latSec, True, True)
539 return f"{prefix}{longPart}{latPart}"
540
541
542 def datetimeToRFC2616(dt: datetime.datetime) -> str:
543 """returns a UTC datetime object in the format required by http.
544
545 This may crap when you fuzz with the locale. In general, when handling
546 "real" times within the DC, prefer unix timestamps over datetimes and
547 use the other ``*RFC2616`` functions.
548 """
549 return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')
550
551
552 def parseRFC2616Date(s: str) -> float:
553 """returns seconds since unix epoch representing UTC from the HTTP-compatible
554 time specification s.
555 """
556 parts = emailutils.parsedate_tz(s)
557 assert parts is not None
558 return emailutils.mktime_tz(parts)
559
560
561 # The following timegm implementation is due to Frederik Lundh
562 def _d(y: int, m: int, d: int,
563 days: Tuple[int, ...]=(0,31,59,90,120,151,181,212,243,273,304,334,365)
564 ) -> int:
565 return (((y - 1901)*1461)//4 + days[m-1] + d + (
566 (m > 2 and not y % 4 and (y % 100 or not y % 400)) and 1))
567
568 def timegm(tm: time.struct_time, epoch: float=_d(1970,1,1)):
569 year, month, day, h, m, s = tm[:6]
570 return (_d(year, month, day) - epoch)*86400 + h*3600 + m*60 + s
571
572
573 def formatRFC2616Date(secs: Optional[float]=None) -> str:
574 """returns an RFC2616 date string for UTC seconds since unix epoch.
575 """
576 if secs is None:
577 secs = time.time()
578 return emailutils.formatdate(secs, localtime=False, usegmt=True)
579
580
581 _isoDTRE = re.compile(r"(?P<year>\d\d\d\d)-?(?P<month>\d\d)-?(?P<day>\d\d)"
582 r"(?:[T ](?P<hour>\d\d):?(?P<minute>\d\d):?"
583 r"(?P<seconds>\d\d)(?P<secFracs>\.\d*)?Z?(\+00:00)?)?$")
584
585
586 @codetricks.document
587 def parseISODT(literal: str, useTime: bool=False) -> datetime.datetime:
588 """returns a datetime object for a ISO time literal.
589
590 There's no real timezone support yet, but we accept and ignore various
591 ways of specifying UTC.
592
593 By default, this uses plain python datetime because it usually covers a large
594 date range than the time module. The downside is that it does not know about
595 leap seconds. Pass useTime=True to go through time tuples, which know how to
596 deal with them (but may not deal with dates far in the past or future).
597
598 >>> parseISODT("1998-12-14")
599 datetime.datetime(1998, 12, 14, 0, 0)
600 >>> parseISODT("1998-12-14T13:30:12")
601 datetime.datetime(1998, 12, 14, 13, 30, 12)
602 >>> parseISODT("1998-12-14T13:30:12Z")
603 datetime.datetime(1998, 12, 14, 13, 30, 12)
604 >>> parseISODT("1998-12-14T13:30:12.224Z")
605 datetime.datetime(1998, 12, 14, 13, 30, 12, 224000)
606 >>> parseISODT("19981214T133012Z")
607 datetime.datetime(1998, 12, 14, 13, 30, 12)
608 >>> parseISODT("19981214T133012+00:00")
609 datetime.datetime(1998, 12, 14, 13, 30, 12)
610 >>> parseISODT("2016-12-31T23:59:60")
611 Traceback (most recent call last):
612 ValueError: second must be in 0..59
613 >>> parseISODT("2016-12-31T23:59:60", useTime=True)
614 datetime.datetime(2017, 1, 1, 0, 0)
615 >>> parseISODT("junk")
616 Traceback (most recent call last):
617 ValueError: Bad ISO datetime literal: junk (required format: yyyy-mm-ddThh:mm:ssZ)
618 """
619 if isinstance(literal, datetime.datetime):
620 return literal
621
622 literal = literal.rstrip("Z")
623 mat = _isoDTRE.match(literal.strip())
624 if not mat:
625 raise ValueError("Bad ISO datetime literal: %s"
626 " (required format: yyyy-mm-ddThh:mm:ssZ)"%literal)
627 parts = mat.groupdict()
628 if parts["hour"] is None:
629 parts["hour"] = parts["minute"] = parts["seconds"] = 0
630 if parts["secFracs"] is None:
631 parts["secFracs"] = 0
632 else:
633 parts["secFracs"] = "0"+parts["secFracs"]
634
635 if useTime:
636 return datetime.datetime.utcfromtimestamp(
637 calendar.timegm((
638 # type calculus broken for RE results in mypy 1.0.1
639 int(parts["year"]), int(parts["month"]), int(parts["day"]), # type: ignore
640 int(parts["hour"]), int(parts["minute"]), int(parts["seconds"]), # type: ignore
641 -1, -1, -1)))
642
643 else:
644 return datetime.datetime(int(parts["year"]), int(parts["month"]), # type: ignore
645 int(parts["day"]), int(parts["hour"]), int(parts["minute"]), # type: ignore
646 int(parts["seconds"]), int(float(parts["secFracs"])*1000000)) # type: ignore
647
648
649 _SUPPORTED_DT_FORMATS =[
650 '%Y-%m-%dT%H:%M:%S',
651 '%Y-%m-%d %H:%M:%S',
652 '%Y-%m-%d',]
653
654 def parseDefaultDatetime(literal: Optional[Union[str, datetime.datetime]]
655 ) -> Optional[datetime.datetime]:
656 """returns a datetime from string or passes through datetimes and Nones.
657
658 The function will try to parse a string in various ways; we will
659 try not to drop formats from one minor version to the next.
660 """
661 if literal is None or isinstance(literal, datetime.datetime):
662 return literal
663 if literal.endswith("Z"):
664 literal = literal[:-1]
665
666 for format in _SUPPORTED_DT_FORMATS:
667 try:
668 return datetime.datetime(
669 *time.strptime(literal, format)[:6])
670 except ValueError:
671 pass
672
673 return parseISODT(literal)
674
675
676 def parseDefaultDate(literal: Optional[Union[str, datetime.date]]
677 ) -> Optional[datetime.date]:
678 """parseDefaultDatetime's little sister.
679 """
680 if literal is None or isinstance(literal, datetime.date):
681 return literal
682 return datetime.date(*time.strptime(literal, '%Y-%m-%d')[:3])
683
684
685 def parseDefaultTime(literal: Optional[Union[str, datetime.time]]
686 ) -> Optional[datetime.time]:
687 """parseDefaultDatetime's other little sister.
688 """
689 if literal is None or isinstance(literal, datetime.time):
690 return literal
691 # as long as we're building on top of time, we can't do fractional seconds
692 return datetime.time(*time.strptime(literal, '%H:%M:%S')[3:6])
693
694
695 def roundToSeconds(dt: datetime.datetime) -> datetime.datetime:
696 """returns a datetime instance rounded to whole seconds.
697
698 This also recklessly clears any time zone marker. So, don't pass
699 in anything with a meaningful time zone.
700 """
701 if dt.microsecond>500000:
702 return dt.replace(microsecond=0, tzinfo=None
703 )+datetime.timedelta(seconds=1)
704 else:
705 return dt.replace(microsecond=0, tzinfo=None)
706
707
708 def formatISODT(dt: datetime.datetime) -> str:
709 """returns some ISO8601 representation of a datetime instance.
710
711 The reason for preferring this function over a simple str is that
712 datetime's default representation is too difficult for some other
713 code (e.g., itself); hence, this code suppresses any microsecond part
714 and always adds a Z (where strftime works, utils.isoTimestampFmt produces
715 an identical string).
716
717 The behaviour of this function for timezone-aware datetimes is undefined.
718
719 For convenience, None is returned as None.
720
721 Also for convenience, you can pass in a string; this will then be parsed
722 first, which provides both some basic format validation and guaranteed
723 DALI-compliant serialisation.
724
725 >>> formatISODT(datetime.datetime(2015, 10, 20, 12, 34, 22, 250))
726 '2015-10-20T12:34:22Z'
727 >>> formatISODT(datetime.datetime(1815, 10, 20, 12, 34, 22, 250))
728 '1815-10-20T12:34:22Z'
729 >>> formatISODT(datetime.datetime(2018, 9, 21, 23, 59, 59, 640000))
730 '2018-09-22T00:00:00Z'
731 """
732 if dt is None:
733 return None
734 if isinstance(dt, str):
735 dt = parseDefaultDatetime(dt)
736
737 return roundToSeconds(dt).isoformat()+"Z"
738
739
740 @codetricks.document
741 def formatFloat(f: float) -> str:
742 """returns floating-point numbers somewhat suitable for human consumption.
743
744 The idea of this function is to slowly migrate ad-hoc formatting of
745 this kind that's in all kind of different places in DaCHS here and
746 thus have a central knob we can eventually use to adapt to tastes.
747
748 >>> formatFloat(1)
749 '1'
750 >>> formatFloat(1/3)
751 '0.333333'
752 >>> formatFloat(-1/3e20)
753 '-3.33333e-21'
754 >>> import math;formatFloat(math.pi)
755 '3.14159'
756 >>> formatFloat(20000000.23)
757 '2e+07'
758 """
759 return "{:.6g}".format(f)
760
761
762 class NameMap(object):
763 """is a name mapper fed from a simple text file.
764
765 The text file format simply is:
766
767 <target-id> "TAB" <src-id>{whitespace <src-id>}
768
769 src-ids have to be encoded quoted-printable when they contain whitespace
770 or other "bad" characters ("="!). You can have #-comments and empty
771 lines.
772
773 The file is supposed to be ASCII, with non-ASCII encoded quoted-printable.
774 The qp-decoded strings are assumed to be utf-8 encoded, but there's a
775 constructor argument to change that.
776 """
777 def __init__(self, src: Filename, missingOk: bool=False, enc: str="utf-8"):
778 self._parseSrc(src, missingOk, enc)
779
780 def __contains__(self, name: str) -> bool:
781 return name in self.namesDict
782
783 def _parseSrc(self, src: Filename, missingOk: bool, enc: str) -> None:
784 self.namesDict: StrToStrMap = {}
785 try:
786 f = open(src, "rb")
787 except IOError:
788 if not missingOk:
789 raise
790 else:
791 return
792 try:
793 for ln in f:
794 if ln.startswith(b"#") or not ln.strip():
795 continue
796 ob, names = re.split(b"\t+", ln)
797 for name in names.lower().split():
798 self.namesDict[quopri.decodestring(name).decode(enc)
799 ] = ob.decode(enc)
800 except ValueError:
801 raise misctricks.logOldExc(ValueError(
802 "Syntax error in %s: Line %s not understood."%(src, repr(ln))))
803 f.close()
804
805 def resolve(self, name: str) -> str:
806 return self.namesDict[name.lower()]
807
808
809 _STANDARD_ENTITIES = {
810 'lt': '<',
811 'gt': '>',
812 'amp': '&',
813 'apos': "'",
814 'quot': '"',
815 }
816
817
818 def _decodeEntityref(matob: re.Match) -> str:
819 entRef = matob.group(1)
820 if entRef in _STANDARD_ENTITIES:
821 return _STANDARD_ENTITIES[entRef]
822 elif entRef.startswith("#x"):
823 return chr(int(entRef[2:], 16))
824 elif entRef.startswith("#"):
825 return chr(int(entRef[1:]))
826 else:
827 raise ValueError("Unknown entity reference: &%s;"%entRef)
828
829
830 def replaceXMLEntityRefs(unicodeString: str) -> str:
831 """retplaces all known HTML entities in unicodeString with actual unicode
832 chars.
833
834 (and dies on unknown entities).
835
836 TODO: this is unused and probably not very useful to clients. Discard?
837 """
838 return entityrefPat.sub(_decodeEntityref, unicodeString)
839
840
841 def ensureOneSlash(s: str) -> str:
842 """returns s with exactly one trailing slash.
843 """
844 return s.rstrip("/")+"/"
845
846
847 _SimpleTextGenerator = Generator[Tuple[int, str], None, None]
848
849 def _iterSimpleTextNoContinuation(f: TextIO
850 ) -> _SimpleTextGenerator:
851 """helps iterSimpleText.
852 """
853 for (lineNumber, curLine) in enumerate(f):
854 curLine = curLine.strip()
855 if curLine and not curLine.startswith("#"):
856 yield (lineNumber+1), curLine
857
858
859 @codetricks.document
860 def iterSimpleText(f: TextIO) -> _SimpleTextGenerator:
861 """iterates over ``(physLineNumber, line)`` in f with some usual
862 conventions for simple data files.
863
864 You should use this function to read from simple configuration and/or
865 table files that don't warrant a full-blown grammar/rowmaker combo.
866 The intended use is somewhat like this::
867
868 with open(rd.getAbsPath("res/mymeta")) as f:
869 for lineNumber, content in iterSimpleText(f):
870 try:
871 ...
872 except Exception, exc:
873 sys.stderr.write("Bad input line %s: %s"%(lineNumber, exc))
874
875 The grammar rules are, specifically:
876
877 * leading and trailing whitespace is stripped
878 * empty lines are ignored
879 * lines beginning with a hash are ignored
880 * lines ending with a backslash are joined with the following line;
881 to have intervening whitespace, have a blank in front of the backslash.
882 """
883 iter = _iterSimpleTextNoContinuation(f)
884 try:
885 while True:
886 lineNumber, curLine = next(iter)
887
888 while curLine.endswith("\\"):
889 try:
890 lineNumber, newStuff = next(iter)
891 except StopIteration:
892 raise SourceParseError("File ends with a backslash",
893 location="line %d"%lineNumber)
894 curLine = curLine[:-1]+newStuff
895
896 yield lineNumber, curLine
897 except StopIteration: # all done, leave loop
898 pass
899
900
901 _RANDOM_STRING_OK_CHARS = string.ascii_letters+string.digits+"_.,"
902
903 def getRandomString(length: int) -> str:
904 """returns a random string of harmless printable characters.
905 """
906 return "".join(
907 random.choice(_RANDOM_STRING_OK_CHARS) for c in range(length))
908
909
910 def safe_str(val: Any) -> str:
911 """returns a reasonable string from pretty much anything.
912 """
913 if isinstance(val, str):
914 return val
915 elif isinstance(val, bytes):
916 return val.decode("ascii", "ignore")
917 else:
918 return str(val)
919
920
921 def bytify(s: Union[str, bytes]) -> bytes:
922 """returns s utf-8 encoded if it is a string, unmodified otherwise.
923 """
924 if isinstance(s, str):
925 return s.encode("utf-8")
926 return s
927
928
929 def debytify(b: Union[str, bytes], enc: str="ascii"):
930 """returns a bytestring b as a normal string.
931
932 This will return b unless it's bytes. If it is bytes, it will be
933 decoded as enc (and the thing will fail when the encoding is wrong).
934 """
935 if isinstance(b, bytes):
936 return b.decode(enc, "ignore")
937 return b
938
939
940 DEFUSE_NONPRINTABLE = bytes.maketrans(bytes(range(32)), b" "*32)
941
942 def defuseFileName(fName: Union[Filename, bytes], replaceSlash: bool=True):
943 """returns fName without any non-ASCII or slashes but in a way that
944 people can still work out what the file name has been.
945
946 This is basically a quoted-printable encoding. What's returned is
947 a string that's guaranteed to be ASCII only. With replaceSlash=False,
948 it can also double as a reasonable asciification.
949 """
950 if isinstance(fName, pathlib.Path):
951 fName = str(fName)
952
953 nameBytes = fName.encode("utf-8") if isinstance(fName, str) else fName
954 res = quopri.encodestring(nameBytes
955 ).translate(DEFUSE_NONPRINTABLE
956 ).decode("ascii")
957 if replaceSlash:
958 res = res.replace('/', "=2F")
959 return res
960
961
962 def isSQLTextLiteral(s):
963 """returns True if s would parse as a SQL string literal.
964
965 Surrounding whitespace is ok.
966
967 >>> isSQLTextLiteral("'abc'")
968 True
969 >>> isSQLTextLiteral("abc")
970 False
971 >>> isSQLTextLiteral("'it''s isn''t its' ")
972 True
973 >>> isSQLTextLiteral(" ''")
974 True
975 >>> isSQLTextLiteral("'it's malformed'")
976 False
977 >>> isSQLTextLiteral("'a literal' || 'expression is not allowed either'")
978 False
979 """
980 # this is a bit obscure vs. just matching a $ at the end of the string
981 # because sre had a bug in python 3.13 that would send it into an
982 # some sort of exponential runtime
983 stripped = s.strip()
984 mat = sqlStringPat.match(stripped)
985 if mat:
986 return len(mat.group(0))==len(stripped)
987 return False
988
989 def parseAccept(aString: str) -> StrToStrMap:
990 """parses an RFC 2616 accept header and returns a dict mapping media
991 type patterns to their (unparsed) parameters.
992
993 If aString is None, an empty dict is returned
994
995 If we ever want to do fancy things with http content negotiation, this
996 will be further wrapped to provide something implementing the complex
997 RFC 2616 rules; this primitive interface really is intended for telling
998 apart browsers (which accept text/html) from other clients (which
999 hopefully do not) at this point.
1000
1001 >>> sorted(parseAccept("text/html, text/*; q=0.2; level=3").items())
1002 [('text/*', 'q=0.2; level=3'), ('text/html', '')]
1003 >>> parseAccept(None)
1004 {}
1005 """
1006 res = {}
1007 if aString is not None:
1008 for item in aString.split(","):
1009 if ";" in item:
1010 key, params = item.split(";", 1)
1011 else:
1012 key, params = item, ""
1013 res[key.strip()] = params.strip()
1014
1015 return res
1016
1017
1018 def parseMediaType(mediaType: str) -> Tuple[str, dict]:
1019 """returns a pair of basic, lowercased media type and a parameter
1020 dictionary for an RFC 2045 media type.
1021
1022 Except for lowercasing the type, normalisation follows whatever the mail
1023 package does, which is probably too little.
1024
1025 Regrettably, EmailMessage's parsing code silently falls back to text/plain
1026 when it cannot make out anything. We can't use that, so we have extra
1027 logic that doubts text/plain and raises a ValueError if it suspects
1028 that's a hallucination.
1029
1030 >>> parseMediaType("application/x-VOTable+xml;serialisation=tabledata; content=datalink")
1031 ('application/x-votable+xml', {'serialisation': 'tabledata', 'content': 'datalink'})
1032 >>> parseMediaType("not a media type at all.")
1033 Traceback (most recent call last):
1034 ValueError: Cannot parse media type 'not a media type at all.'
1035 """
1036 # yeah, it's weird to construct an email message here, but it's what
1037 # the purgers of the cgi module wanted
1038 m = emailmessage.EmailMessage()
1039 m.add_header("content-type", mediaType)
1040 baseType = "{}/{}".format(m.get_content_maintype(), m.get_content_subtype())
1041 if baseType=="text/plain":
1042 if not mediaType.lower().startswith(baseType):
1043 raise ValueError(f"Cannot parse media type '{mediaType}'")
1044
1045 return baseType, dict(m["content-type"].params)
1046
1047
1048 def spinner(delay: float = 1) -> Iterator[str]:
1049 """returns an endless iterator that returns an ascii spinner item per
1050 delay seconds.
1051 """
1052 for item in itertools.cycle("-\\|/"):
1053 yield item
1054 time.sleep(delay)
1055
1056
1057 if __name__=="__main__": # pragma: no cover
1058 import doctest
1059 doctest.testmod()