Debian Codegraph @

DisplayCAL/util_str.py

raw
1 """String utility functions for ASCII conversion, safe filenames, and Unicode handling.
2
3 It also includes error handling utilities and custom string-like classes.
4 """
5
6 from __future__ import annotations
7
8 import codecs
9 import re
10 import string
11 import sys
12 import unicodedata
13 from functools import reduce
14 from typing import TYPE_CHECKING
15
16 if TYPE_CHECKING:
17 if sys.version_info >= (3, 11):
18 from typing import Self
19 else:
20 from typing_extensions import Self
21
22
23 env_errors = (EnvironmentError,)
24 if sys.platform == "win32":
25 import pywintypes
26
27 env_errors = (*env_errors, pywintypes.error, pywintypes.com_error)
28
29 from DisplayCAL.encoding import get_encodings
30
31 fs_enc = get_encodings()[1]
32
33 ascii_printable = "".join(
34 [
35 getattr(string, name)
36 for name in ("digits", "ascii_letters", "punctuation", "whitespace")
37 ]
38 )
39
40 # Control chars are defined as charcodes in the decimal range 0-31 (inclusive)
41 # except whitespace characters, plus charcode 127 (DEL)
42 control_chars = "".join([chr(i) for i in list(range(9)) + list(range(14, 32)) + [127]])
43
44 # Safe character substitution - can be used for filenames
45 # i.e. no \/:*?"<>| will be added through substitution
46 # Contains only chars that are not normalizable
47 safesubst = {
48 # Latin-1 supplement
49 "\u00a2": "c", # Cent sign
50 "\u00a3": "GBP", # Pound sign
51 "\u00a5": "JPY", # Yen sign
52 "\u00a9": "(C)", # U+00A9 copyright sign
53 "\u00ac": "!", # Not sign
54 "\u00ae": "(R)", # U+00AE registered sign
55 "\u00b0": "deg", # Degree symbol
56 "\u00b1": "+-",
57 "\u00c4": "Ae", # Capital letter A with diaresis (Umlaut)
58 "\u00c5": "Aa", # Capital letter A with ring above
59 "\u00c6": "AE",
60 "\u00d6": "Oe", # Capital letter O with diaresis (Umlaut)
61 "\u00dc": "Ue", # Capital letter U with diaresis (Umlaut)
62 "\u00d7": "x", # U+00D7 multiplication sign
63 "\u00df": "ss",
64 "\u00e4": "ae", # Small letter a with diaresis (Umlaut)
65 "\u00e5": "aa", # Small letter a with ring above
66 "\u00e6": "ae",
67 "\u00f6": "oe", # Small letter o with diaresis (Umlaut)
68 "\u00fc": "ue", # Small letter u with diaresis (Umlaut)
69 # Latin extended A
70 "\u0152": "OE",
71 "\u0153": "oe",
72 # General punctuation
73 "\u2010": "-",
74 "\u2011": "-",
75 "\u2012": "-",
76 "\u2013": "-", # U+2013 en dash
77 "\u2014": "--", # U+2014 em dash
78 "\u2015": "---", # U+2015 horizontal bar
79 "\u2018": "'",
80 "\u2019": "'",
81 "\u201a": ",",
82 "\u201b": "'",
83 "\u201c": "''",
84 "\u201d": "''",
85 "\u201e": ",,",
86 "\u201f": "''",
87 "\u2032": "'",
88 "\u2033": "''",
89 "\u2034": "'''",
90 "\u2035": "'",
91 "\u2036": "''",
92 "\u2037": "'''",
93 "\u2053": "~",
94 # Superscripts and subscripts
95 "\u207b": "-", # Superscript minus
96 "\u208b": "-", # Subscript minus
97 # Currency symbols
98 "\u20a1": "CRC", # Costa Rica 'Colon'
99 "\u20a6": "NGN", # Nigeria 'Naira'
100 "\u20a9": "KRW", # South Korea 'Won'
101 "\u20aa": "ILS", # Isreael 'Sheqel'
102 "\u20ab": "VND", # Vietnam 'Dong'
103 "\u20ac": "EUR",
104 "\u20ad": "LAK", # Laos 'Kip'
105 "\u20ae": "MNT", # Mongolia 'Tugrik'
106 "\u20b2": "PYG", # Paraguay 'Guarani'
107 "\u20b4": "UAH", # Ukraine 'Hryvnja'
108 "\u20b5": "GHS", # Ghana 'Cedi'
109 "\u20b8": "KZT", # Kasachstan 'Tenge'
110 "\u20b9": "INR", # Indian 'Rupee'
111 "\u20ba": "TRY", # Turkey 'Lira'
112 "\u20bc": "AZN", # Aserbaidchan 'Manat'
113 "\u20bd": "RUB", # Russia 'Ruble'
114 "\u20be": "GEL", # Georgia 'Lari'
115 # Letter-like symbols
116 "\u2117": "(P)",
117 # Mathematical operators
118 "\u2212": "-", # U+2212 minus sign
119 "\u2260": "!=",
120 # Enclosed alphanumerics
121 "\u2460": "(1)",
122 "\u2461": "(2)",
123 "\u2462": "(3)",
124 "\u2463": "(4)",
125 "\u2464": "(5)",
126 "\u2465": "(6)",
127 "\u2466": "(7)",
128 "\u2467": "(8)",
129 "\u2468": "(9)",
130 "\u2469": "(10)",
131 "\u246a": "(11)",
132 "\u246b": "(12)",
133 "\u246c": "(13)",
134 "\u246d": "(14)",
135 "\u246e": "(15)",
136 "\u246f": "(16)",
137 "\u2470": "(17)",
138 "\u2471": "(18)",
139 "\u2472": "(19)",
140 "\u2473": "(20)",
141 "\u24eb": "(11)",
142 "\u24ec": "(12)",
143 "\u24ed": "(13)",
144 "\u24ee": "(14)",
145 "\u24ef": "(15)",
146 "\u24f0": "(16)",
147 "\u24f1": "(17)",
148 "\u24f2": "(18)",
149 "\u24f3": "(19)",
150 "\u24f4": "(20)",
151 "\u24f5": "(1)",
152 "\u24f6": "(2)",
153 "\u24f7": "(3)",
154 "\u24f8": "(4)",
155 "\u24f9": "(5)",
156 "\u24fa": "(6)",
157 "\u24fb": "(7)",
158 "\u24fc": "(8)",
159 "\u24fd": "(9)",
160 "\u24fe": "(10)",
161 "\u24ff": "(0)",
162 # Dingbats
163 "\u2776": "(1)",
164 "\u2777": "(2)",
165 "\u2778": "(3)",
166 "\u2779": "(4)",
167 "\u277a": "(5)",
168 "\u277b": "(6)",
169 "\u277c": "(7)",
170 "\u277d": "(8)",
171 "\u277e": "(9)",
172 "\u277f": "(10)",
173 "\u2780": "(1)",
174 "\u2781": "(2)",
175 "\u2782": "(3)",
176 "\u2783": "(4)",
177 "\u2784": "(5)",
178 "\u2785": "(6)",
179 "\u2786": "(7)",
180 "\u2787": "(8)",
181 "\u2788": "(9)",
182 "\u2789": "(10)",
183 "\u278a": "(1)",
184 "\u278b": "(2)",
185 "\u278c": "(3)",
186 "\u278d": "(4)",
187 "\u278e": "(5)",
188 "\u278f": "(6)",
189 "\u2790": "(7)",
190 "\u2791": "(8)",
191 "\u2792": "(9)",
192 "\u2793": "(10)",
193 }
194
195 # Extended character substitution - can NOT be used for filenames
196 # Contains only chars that are not normalizable
197 subst = dict(safesubst)
198 subst.update(
199 {
200 # Latin-1 supplement
201 "\u00a6": "|",
202 "\u00ab": "<<",
203 "\u00bb": ">>",
204 "\u00bc": "1/4",
205 "\u00bd": "1/2",
206 "\u00be": "3/4",
207 "\u00f7": ":",
208 # General punctuation
209 "\u201c": '"',
210 "\u201d": '"',
211 "\u201f": '"',
212 "\u2033": '"',
213 "\u2036": '"',
214 "\u2039": "<",
215 "\u203a": ">",
216 "\u203d": "!?",
217 "\u2044": "/",
218 # Number forms
219 "\u2153": "1/3",
220 "\u2154": "2/3",
221 "\u215b": "1/8",
222 "\u215c": "3/8",
223 "\u215d": "5/8",
224 "\u215e": "7/8",
225 # Arrows
226 "\u2190": "<-",
227 "\u2192": "->",
228 "\u2194": "<->",
229 # Mathematical operators
230 "\u226a": "<<",
231 "\u226b": ">>",
232 "\u2264": "<=",
233 "\u2265": "=>",
234 }
235 )
236
237
238 class StrList(list):
239 """A list of strings that behaves like a string.
240
241 It's a list. It's a string. It's a list of strings that behaves like a
242 string! And like a list.
243 """
244
245 def __init__(self, seq=None) -> None:
246 if seq is None:
247 seq = ()
248 list.__init__(self, seq)
249
250 def __iadd__(self, text) -> Self:
251 """Append text to the list.
252
253 Args:
254 text (str): The text to append.
255
256 Returns:
257 StrList: The updated StrList object.
258 """
259 self.append(text)
260 return self
261
262 def __getattr__(self, attr: str) -> str:
263 """Get the attribute of the string representation of the list.
264
265 Args:
266 attr (str): The attribute to get.
267
268 Returns:
269 str: The value of the attribute.
270 """
271 return getattr(str(self), attr)
272
273 def __str__(self) -> str:
274 """Return the string representation of the list.
275
276 Returns:
277 str: The string representation of the list.
278 """
279 return "".join(self)
280
281
282 def asciize(obj):
283 """Turn several unicode chars into an ASCII representation.
284
285 This function either takes a string or an exception as argument (when used
286 as error handler for encode or decode).
287 """
288 chars = b""
289 if isinstance(obj, Exception):
290 for char in obj.object[obj.start : obj.end]:
291 chars += subst.get(char, normalencode(char).strip() or b"?")
292 return chars, obj.end
293 return obj.encode("ASCII", "asciize")
294
295
296 codecs.register_error("asciize", asciize)
297
298
299 def safe_asciize(obj) -> bytes:
300 """Turn several unicode chars into an ASCII representation.
301
302 This function either takes a string or an exception as argument (when used
303 as error handler for encode or decode).
304
305 Args:
306 obj (str | bytes | Exception): A ``str``, ``bytes``, or ``Exception``
307 value.
308
309 Returns:
310 bytes: A ``bytes`` value that is ASCII safe.
311 """
312 if not isinstance(obj, (str, bytes, Exception)):
313 raise TypeError(
314 f"obj should be a str, bytes, or Exception, not {obj.__class__.__name__}"
315 )
316
317 if isinstance(obj, Exception):
318 chars = b""
319 for char in obj.object[obj.start : obj.end]:
320 if char in safesubst:
321 subst_char = safesubst[char]
322 else:
323 subst_char = b"_"
324 if char not in subst:
325 subst_char = normalencode(char).strip() or subst_char
326 chars += subst_char
327 return chars, obj.end
328
329 if isinstance(obj, bytes):
330 obj = obj.decode("utf-8")
331
332 return obj.encode("ASCII", "safe_asciize")
333
334
335 codecs.register_error("safe_asciize", safe_asciize)
336
337
338 def escape(obj):
339 """Turn unicode chars into escape codes.
340
341 This function either takes a string or an exception as argument (when used
342 as error handler for encode or decode).
343
344 """
345 chars = b""
346 if isinstance(obj, Exception):
347 for char in obj.object[obj.start : obj.end]:
348 chars += subst.get(char, "\\u{}".format(hex(ord(char))[2:].rjust(4, "0")))
349 return chars, obj.end
350 return obj.encode("ASCII", "escape")
351
352
353 # TODO: convert this to a decorator
354 codecs.register_error("escape", escape)
355
356
357 def make_ascii_printable(text, substitute=b""):
358 """Make ASCII printable.
359
360 Args:
361 text (bytes | str): A ``bytes`` or ``str`` value.
362 substitute (bytes | str): A ``bytes`` or ``str`` value.
363
364 Returns:
365 bytes | str: A bytes or str value that is ASCII printable.
366 """
367 buffer = []
368 joiner = ""
369 temp_ascii_printable = ascii_printable
370 if isinstance(text, bytes):
371 joiner = b""
372 temp_ascii_printable = ascii_printable.encode("utf-8")
373 if isinstance(substitute, str):
374 substitute = substitute.encode("utf-8")
375 elif isinstance(substitute, bytes):
376 substitute = substitute.decode("utf-8")
377
378 for i in range(len(text)):
379 char = text[i : i + 1]
380 if char in temp_ascii_printable:
381 buffer.append(char)
382 else:
383 buffer.append(substitute)
384 return joiner.join(buffer)
385
386
387 def make_filename_safe(unistr, encoding=fs_enc, substitute="_", concat=True):
388 """Make sure string is safe to use as filename.
389
390 I.e. turn characters that are invalid in the filesystem encoding into ASCII
391 equivalents and replace characters that are invalid in filenames with
392 substitution character.
393 """
394 if not isinstance(unistr, (str, bytes)):
395 raise TypeError(
396 f"unistr should be a str or bytes, not {unistr.__class__.__name__}"
397 )
398 # Turn characters that are invalid in the filesystem encoding into ASCII
399 # substitution character '?'
400 # NOTE that under Windows, encoding with the filesystem encoding may
401 # substitute some characters even in "strict" replacement mode depending
402 # on the Windows language setting for non-Unicode programs! (Python 2.x
403 # under Windows supports Unicode by wrapping the win32 ASCII API, so it is
404 # a non-Unicode program from that point of view. This problem presumably
405 # doesn't exist with Python 3.x which uses the win32 Unicode API)
406 if isinstance(unistr, str):
407 # str
408 unidec = unistr.encode(encoding, "replace").decode(encoding, "replace")
409 pattern = r"[\\/:*?\"<>|]"
410 plus = "+"
411 uniout = ""
412 question_mark = "?"
413 if isinstance(substitute, bytes):
414 substitute = substitute.decode(encoding)
415 else:
416 # bytes
417 unidec = unistr.decode(encoding, "replace").encode(encoding, "replace")
418 pattern = rb"[\\/:*?\"<>|]"
419 plus = b"+"
420 uniout = b""
421 question_mark = b"?"
422 if isinstance(substitute, str):
423 substitute = substitute.encode(encoding)
424
425 # Replace substitution character '?' with ASCII equivalent of original char
426 for i in range(len(unidec)):
427 c = unidec[i : i + 1]
428 if c == question_mark:
429 c = safe_asciize(unistr[i : i + 1]) # this will always be bytes
430 if isinstance(unistr, str):
431 c = c.decode(encoding)
432 uniout += c
433 # Remove invalid chars
434 if concat:
435 pattern += plus
436
437 return re.sub(pattern, substitute, uniout)
438
439
440 def normalencode(unistr, form="NFKD", encoding="ASCII", errors="ignore"):
441 """Return encoded normal form of unicode string."""
442 return unicodedata.normalize(form, unistr).encode(encoding, errors)
443
444
445 def box(text, width=80, collapse=False):
446 """Create a box around text (monospaced font required for display)."""
447 content_width = width - 4
448 text = wrap(str(text), content_width)
449 lines = text.splitlines()
450 if collapse:
451 content_width = 0
452 for line in lines:
453 content_width = max(len(line), content_width)
454 width = content_width + 4
455 horizontal_line = "\u2500" * (width - 2)
456 box = [f"\u250c{horizontal_line}\u2510"]
457 box.extend(f"\u2502 {line.ljust(content_width)} \u2502" for line in lines)
458 box.append(f"\u2514{horizontal_line}\u2518")
459 return "\n".join(box)
460
461
462 def center(text, width=None):
463 """Center (mono-spaced) text.
464
465 If no width is given, the longest line
466 (after breaking at each newline) is used as max width.
467
468 """
469 text = text.split("\n")
470 if width is None:
471 width = 0
472 for line in text:
473 width = max(width, len(line))
474 for i, line in enumerate(text):
475 text[i] = line.center(width)
476 return "\n".join(text)
477
478
479 def create_replace_function(template, values):
480 """Create a replace function for use with e.g. re.sub."""
481
482 def replace_function(match, template=template, values=values):
483 template = match.expand(template)
484 return template % values
485
486 return replace_function
487
488
489 def ellipsis_(text: str | bytes, maxlen: int = 64, pos: str = "r") -> str | bytes:
490 """Truncate text to maxlen characters and add ellipsis if it was longer.
491
492 Ellipsis position can be 'm' (middle) or 'r' (right).
493
494 Args:
495 text (str | bytes): A ``str`` or ``bytes`` value.
496 maxlen (int): Maximum length of the string.
497 pos (str): Position of the ellipsis ('m' or 'r').
498
499 Returns:
500 str | bytes: A ``str`` or ``bytes`` value that is truncated to
501 the maximum length and has an ellipsis added if it was longer.
502 """
503 if len(text) <= maxlen:
504 return text
505
506 if pos not in ("m", "r"):
507 raise ValueError(f"pos must be 'm' or 'r', not {pos!r}")
508
509 ellipsis_char = "\u2026"
510
511 if isinstance(text, bytes):
512 ellipsis_char = b"u\xc2\x826"
513 if pos == "r":
514 return text[: maxlen - 1] + ellipsis_char
515 # elif pos == "m":
516 return text[: int(maxlen / 2)] + ellipsis_char + text[int(-maxlen / 2 + 1) :]
517
518
519 def hexunescape(match):
520 """To be used with re.sub."""
521 return chr(int(match.group(1), 16))
522
523
524 def indent(text, prefix, predicate=None):
525 # From Python 3.7 textwrap module
526 """Add 'prefix' to the beginning of selected lines in 'text'.
527
528 If 'predicate' is provided, 'prefix' will only be added to the lines
529 where 'predicate(line)' is True. If 'predicate' is not provided,
530 it will default to adding 'prefix' to all non-empty lines that do not
531 consist solely of whitespace characters.
532 """
533 if predicate is None:
534
535 def predicate(line):
536 return line.strip()
537
538 def prefixed_lines():
539 for line in text.splitlines(True):
540 yield (prefix + line if predicate(line) else line)
541
542 return "".join(prefixed_lines())
543
544
545 def universal_newlines(txt):
546 """Return txt with all new line formats converted to POSIX newlines."""
547 if not isinstance(txt, (str, bytes)):
548 raise TypeError(f"txt should be a str or bytes, not {txt.__class__.__name__}")
549 if isinstance(txt, str):
550 return txt.replace("\r\n", "\n").replace("\r", "\n")
551 # elif isinstance(txt, bytes):
552 return txt.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
553
554
555 def replace_control_chars(txt, replacement=" ", collapse=False):
556 """Replace all control characters.
557
558 Default replacement character is ' ' (space).
559 If the 'collapse' keyword argument evaluates to True, consecutive
560 replacement characters are collapsed to a single one.
561
562 """
563 txt = strtr(txt, dict(list(zip(control_chars, [replacement] * len(control_chars)))))
564 if collapse:
565 while replacement * 2 in txt:
566 txt = txt.replace(replacement * 2, replacement)
567 return txt
568
569
570 def safe_basestring(obj, enc="utf-8", errors="replace"):
571 """Return a string or bytes representation of obj.
572
573 Return obj if isinstance(obj, basestring). Otherwise, return unicode(obj),
574 string(obj), or repr(obj), whichever succeeds first.
575 """
576 if isinstance(obj, env_errors):
577 # Possible variations of environment-type errors:
578 # - instance with 'errno', 'strerror', 'filename' and 'args' attributes
579 # (created by EnvironmentError with three arguments)
580 # NOTE: The 'args' attribute will contain only the first two arguments
581 # - instance with 'errno', 'strerror' and 'args' attributes
582 # (created by EnvironmentError with two arguments)
583 # - instance with just 'args' attribute
584 # (created by EnvironmentError with one or more than three arguments)
585 # - urllib2.URLError with empty 'args' attribute but 'reason' and
586 # 'filename' attributes
587 # - pywintypes.error with 'funcname', 'message', 'strerror', 'winerror'
588 # and 'args' attributes
589 if hasattr(obj, "reason"):
590 if isinstance(obj.reason, str):
591 obj.args = (obj.reason,)
592 elif isinstance(obj.reason, bytes):
593 obj.args = (str(obj.reason, enc, errors),)
594 elif isinstance(obj.reason, (list, tuple)):
595 obj.args = tuple(obj.reason)
596 else:
597 obj.args = (str(obj.reason),)
598 error = []
599 if getattr(obj, "winerror", None) is not None:
600 # pywintypes.error or WindowsError
601 error.append(f"[Windows Error {obj.winerror}]")
602 elif getattr(obj, "errno", None) is not None:
603 error.append(f"[Errno {obj.errno}]")
604 if getattr(obj, "strerror", None) is not None:
605 if getattr(obj, "filename", None) is not None:
606 error.append(obj.strerror.rstrip(":.") + ":")
607 elif getattr(obj, "funcname", None) is not None:
608 # pywintypes.error
609 error.append(obj.funcname + ": " + obj.strerror)
610 else:
611 error.append(obj.strerror)
612 if not error:
613 error = list(obj.args)
614 if getattr(obj, "filename", None) is not None:
615 error.append(obj.filename)
616
617 temp_error = []
618 for arg in error:
619 if isinstance(arg, str):
620 temp_error.append(arg)
621 elif isinstance(arg, bytes):
622 temp_error.append(str(arg, enc, errors))
623 else:
624 temp_error.append(str(arg))
625 error = temp_error
626 obj = " ".join(error)
627 elif isinstance(obj, KeyError) and obj.args:
628 obj = f"Key does not exist: {obj.args[0]!r}"
629 oobj = obj
630 if not isinstance(obj, str):
631 try:
632 obj = str(obj, enc, errors)
633 except (UnicodeDecodeError, TypeError):
634 obj = repr(obj)
635
636 if isinstance(oobj, Exception) and not isinstance(oobj, Warning):
637 module = getattr(oobj, "__module__", "")
638 package = safe_basestring.__module__.split(".")[0] # Our own package
639 if not module.startswith(package + "."):
640 clspth = ".".join([_f for _f in [module, oobj.__class__.__name__] if _f])
641 if not obj.startswith(clspth + ":") and obj != clspth:
642 obj = ": ".join([_f for _f in [clspth, obj] if _f])
643 return obj
644
645
646 def safe_str(obj, enc=fs_enc, errors="replace"):
647 """Return string representation of obj."""
648 return safe_basestring(obj, enc=enc, errors=errors)
649
650
651 def strtr(txt, replacements):
652 """String multi-replace, a bit like PHP's strtr.
653
654 replacements can be a dict, a list or a string.
655 If list or string, all matches are replaced with the empty string ("").
656
657 """
658 if hasattr(replacements, "items"):
659 replacements = iter(replacements.items())
660 elif isinstance(replacements, str):
661 for srch in replacements:
662 txt = txt.replace(srch, "")
663 elif isinstance(replacements, bytes):
664 for srch in replacements:
665 txt = txt.replace(srch, b"")
666 return txt
667 for srch, sub in replacements:
668 if isinstance(txt, bytes):
669 if not isinstance(srch, bytes):
670 srch = srch.encode("utf-8")
671 if not isinstance(sub, bytes):
672 sub = sub.encode("utf-8")
673 elif isinstance(txt, str):
674 if not isinstance(srch, str):
675 srch = srch.decode("utf-8")
676 if not isinstance(sub, str):
677 sub = sub.decode("utf-8")
678 txt = txt.replace(srch, sub)
679 return txt
680
681
682 def wrap(text, width=70):
683 r"""A word-wrap function that preserves existing line breaks and spaces.
684
685 Expects that existing line breaks are posix newlines (\n).
686 """
687 return reduce(
688 lambda line, word, width=width: "{}{}{}".format(
689 line,
690 " \n"[
691 (
692 len(line) - line.rfind("\n") - 1 + len(word.split("\n", 1)[0])
693 >= width
694 )
695 ],
696 word,
697 ),
698 text.split(" "),
699 )