Debian Codegraph @

gallery_dl/formatter.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2021-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """String formatters"""
10
11 import os
12 import sys
13 import time
14 import string
15 import _string
16 import operator
17 from . import text, util, dt
18
19 NONE = util.NONE
20
21
22 def parse(format_string, default=NONE, fmt=format):
23 key = format_string, default, fmt
24
25 try:
26 return _CACHE[key]
27 except KeyError:
28 pass
29
30 if format_string and format_string[0] == "\f":
31 kind, _, format_string = format_string.partition(" ")
32 try:
33 cls = _FORMATTERS[kind[1:]]
34 except KeyError:
35 import logging
36 logging.getLogger("formatter").error(
37 "Invalid formatter type '%s'", kind[1:])
38 cls = StringFormatter
39 else:
40 cls = StringFormatter
41
42 try:
43 formatter = _CACHE[key] = cls(format_string, default, fmt)
44 except Exception as exc:
45 import logging
46 logging.getLogger("formatter").error(
47 "Invalid format string '%s' (%s: %s)",
48 format_string, exc.__class__.__name__, exc)
49 raise
50
51 return formatter
52
53
54 class StringFormatter():
55 """Custom, extended version of string.Formatter
56
57 This string formatter implementation is a mostly performance-optimized
58 variant of the original string.Formatter class. Unnecessary features have
59 been removed (positional arguments, unused argument check) and new
60 formatting options have been added.
61
62 Extra Conversions:
63 - "l": calls str.lower on the target value
64 - "u": calls str.upper
65 - "c": calls str.capitalize
66 - "C": calls string.capwords
67 - "g": calls text.slugify()
68 - "j": calls json.dumps
69 - "t": calls str.strip
70 - "T": calls dt.to_ts_string()
71 - "d": calls dt.parse_ts()
72 - "s": calls str()
73 - "S": calls util.to_string()
74 - "U": calls urllib.parse.unescape
75 - "r": calls repr()
76 - "a": calls ascii()
77 - Example: {f!l} -> "example"; {f!u} -> "EXAMPLE"
78
79 # Go to _CONVERSIONS and _SPECIFIERS below to see all of them, read:
80 # https://gdl-org.github.io/docs/formatting.html
81
82 Extra Format Specifiers:
83 - "?<before>/<after>/":
84 Adds <before> and <after> to the actual value if it evaluates to True.
85 Otherwise the whole replacement field becomes an empty string.
86 Example: {f:?-+/+-/} -> "-+Example+-" (if "f" contains "Example")
87 -> "" (if "f" is None, 0, "")
88
89 - "L<maxlen>/<replacement>/":
90 Replaces the output with <replacement> if its length (in characters)
91 exceeds <maxlen>. Otherwise everything is left as is.
92 Example: {f:L5/too long/} -> "foo" (if "f" is "foo")
93 -> "too long" (if "f" is "foobar")
94
95 - "J<separator>/":
96 Joins elements of a list (or string) using <separator>
97 Example: {f:J - /} -> "a - b - c" (if "f" is ["a", "b", "c"])
98
99 - "R<old>/<new>/":
100 Replaces all occurrences of <old> with <new>
101 Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r")
102 """
103
104 def __init__(self, format_string, default=NONE, fmt=format):
105 self.default = default
106 self.format = fmt
107 self.result = []
108 self.fields = []
109
110 for literal_text, field_name, format_spec, conv in \
111 _string.formatter_parser(format_string):
112 if literal_text:
113 self.result.append(literal_text)
114 if field_name:
115 self.fields.append((
116 len(self.result),
117 self._field_access(field_name, format_spec, conv),
118 ))
119 self.result.append("")
120
121 if len(self.result) == 1:
122 if self.fields:
123 self.format_map = self.fields[0][1]
124 else:
125 self.format_map = lambda _: format_string
126 del self.result, self.fields
127 elif fmt is not format:
128 self.format_map = self.format_map_safe
129
130 def format_map(self, kwdict):
131 """Apply 'kwdict' to the initial format_string and return its result"""
132 result = self.result
133 for index, func in self.fields:
134 result[index] = func(kwdict)
135 return "".join(result)
136
137 def format_map_safe(self, kwdict):
138 """Like 'format_map', but ensures all items are 'str'"""
139 result = self.result
140 for index, func in self.fields:
141 result[index] = str(func(kwdict))
142 return "".join(result)
143
144 def _field_access(self, field_name, format_spec, conversion):
145 fmt = self._parse_format_spec(format_spec, conversion)
146
147 if "|" in field_name:
148 return self._apply_list([
149 parse_field_name(fn)
150 for fn in field_name.split("|")
151 ], fmt)
152 else:
153 key, funcs = parse_field_name(field_name)
154 return self._apply(key, funcs, fmt)
155
156 def _apply(self, key, funcs, fmt):
157 if key in _GLOBALS:
158 def wrap(_):
159 try:
160 obj = gobj()
161 for func in funcs:
162 obj = func(obj)
163 except Exception:
164 obj = self.default
165 return fmt(obj)
166 gobj = _GLOBALS[key]
167 elif funcs:
168 def wrap(kwdict):
169 try:
170 obj = kwdict[key]
171 for func in funcs:
172 obj = func(obj)
173 except Exception:
174 obj = self.default
175 return fmt(obj)
176 else:
177 def wrap(kwdict):
178 return fmt(kwdict[key] if key in kwdict else self.default)
179 del funcs
180 return wrap
181
182 def _apply_list(self, lst, fmt):
183 def wrap(kwdict):
184 for key, funcs in lst:
185 try:
186 obj = _GLOBALS[key]() if key in _GLOBALS else kwdict[key]
187 for func in funcs:
188 obj = func(obj)
189 if obj:
190 break
191 except Exception:
192 obj = None
193 else:
194 if obj is None:
195 obj = self.default
196 return fmt(obj)
197 return wrap
198
199 def _parse_format_spec(self, format_spec, conversion):
200 fmt = _build_format_func(format_spec, self.format)
201 if not conversion:
202 return fmt
203
204 conversion = _CONVERSIONS[conversion]
205 if fmt is self.format:
206 return conversion
207 else:
208 return lambda obj: fmt(conversion(obj))
209
210
211 class ExpressionFormatter():
212 """Generate text by evaluating a Python expression"""
213
214 def __init__(self, expression, default=NONE, fmt=None):
215 self.format_map = util.compile_expression(expression)
216
217
218 class FStringFormatter():
219 """Generate text by evaluating an f-string literal"""
220
221 def __init__(self, fstring, default=NONE, fmt=None):
222 self.format_map = util.compile_expression(f'f"""{fstring}"""')
223
224
225 def _init_jinja():
226 import jinja2
227 from . import config
228
229 if opts := config.getg("jinja"):
230 JinjaFormatter.env = env = jinja2.Environment(
231 **opts.get("environment") or {})
232 else:
233 JinjaFormatter.env = jinja2.Environment()
234 return
235
236 if policies := opts.get("policies"):
237 env.policies.update(policies)
238
239 if path := opts.get("filters"):
240 module = util.import_file(path).__dict__
241 env.filters.update(
242 module["__filters__"] if "__filters__" in module else module)
243
244 if path := opts.get("tests"):
245 module = util.import_file(path).__dict__
246 env.tests.update(
247 module["__tests__"] if "__tests__" in module else module)
248
249
250 class JinjaFormatter():
251 """Generate text by evaluating a Jinja template string"""
252 env = None
253
254 def __init__(self, source, default=NONE, fmt=None):
255 if self.env is None:
256 _init_jinja()
257 self.format_map = self.env.from_string(source).render
258
259
260 class ModuleFormatter():
261 """Generate text by calling an external function"""
262
263 def __init__(self, function_spec, default=NONE, fmt=None):
264 module_name, _, function_name = function_spec.rpartition(":")
265 module = util.import_file(module_name)
266 self.format_map = getattr(module, function_name)
267
268
269 class TemplateFormatter(StringFormatter):
270 """Read format_string from file"""
271
272 def __init__(self, path, default=NONE, fmt=format):
273 with open(util.expand_path(path), encoding="utf-8") as fp:
274 format_string = fp.read()
275 StringFormatter.__init__(self, format_string, default, fmt)
276
277
278 class TemplateFStringFormatter(FStringFormatter):
279 """Read f-string from file"""
280
281 def __init__(self, path, default=NONE, fmt=None):
282 with open(util.expand_path(path), encoding="utf-8") as fp:
283 fstring = fp.read()
284 FStringFormatter.__init__(self, fstring, default, fmt)
285
286
287 class TemplateJinjaFormatter(JinjaFormatter):
288 """Generate text by evaluating a Jinja template"""
289
290 def __init__(self, path, default=NONE, fmt=None):
291 with open(util.expand_path(path), encoding="utf-8") as fp:
292 source = fp.read()
293 JinjaFormatter.__init__(self, source, default, fmt)
294
295
296 def parse_field_name(field_name):
297 if field_name[0] == "'":
298 return "_lit", (operator.itemgetter(field_name[1:-1]),)
299
300 first, rest = _string.formatter_field_name_split(field_name)
301 funcs = []
302
303 for is_attr, key in rest:
304 if is_attr:
305 func = _attrgetter
306 else:
307 func = operator.itemgetter
308 try:
309 if ":" in key:
310 if key[0] == "b":
311 func = _bytesgetter
312 key = _slice(key[1:])
313 else:
314 key = _slice(key)
315 elif key[0] == "-":
316 key = int(key)
317 else:
318 key = key.strip("\"'")
319 except TypeError:
320 pass # key is an integer
321
322 funcs.append(func(key))
323
324 return first, funcs
325
326
327 def _slice(indices):
328 start, _, stop = indices.partition(":")
329 stop, _, step = stop.partition(":")
330 return slice(
331 int(start) if start else None,
332 int(stop) if stop else None,
333 int(step) if step else None,
334 )
335
336
337 def _attrgetter(key):
338
339 if key.isdecimal() or key[0] == "-":
340 try:
341 return operator.itemgetter(int(key))
342 except ValueError:
343 pass
344
345 def apply_key(obj):
346 try:
347 return obj[key]
348 except (TypeError, KeyError):
349 return getattr(obj, key)
350 return apply_key
351
352
353 def _bytesgetter(slice):
354
355 def apply_slice_bytes(obj):
356 return obj.encode(_ENCODING)[slice].decode(_ENCODING, "ignore")
357
358 return apply_slice_bytes
359
360
361 def _build_format_func(format_spec, default):
362 if format_spec:
363 return _FORMAT_SPECIFIERS.get(
364 format_spec[0], _default_format)(format_spec, default)
365 return default
366
367
368 def _parse_optional(format_spec, default):
369 before, after, format_spec = format_spec.split(_SEPARATOR, 2)
370 before = before[1:]
371 fmt = _build_format_func(format_spec, default)
372
373 def optional(obj):
374 return f"{before}{fmt(obj)}{after}" if obj else ""
375 return optional
376
377
378 def _parse_slice(format_spec, default):
379 indices, _, format_spec = format_spec.partition("]")
380 fmt = _build_format_func(format_spec, default)
381
382 if indices[1] == "b":
383 slice_bytes = _bytesgetter(_slice(indices[2:]))
384
385 def apply_slice(obj):
386 return fmt(slice_bytes(obj))
387
388 else:
389 slice = _slice(indices[1:])
390
391 def apply_slice(obj):
392 return fmt(obj[slice])
393
394 return apply_slice
395
396
397 def _parse_arithmetic(format_spec, default):
398 op, _, format_spec = format_spec.partition(_SEPARATOR)
399 fmt = _build_format_func(format_spec, default)
400
401 value = int(op[2:])
402 op = op[1]
403
404 if op == "+":
405 return lambda obj: fmt(obj + value)
406 if op == "-":
407 return lambda obj: fmt(obj - value)
408 if op == "*":
409 return lambda obj: fmt(obj * value)
410
411 return fmt
412
413
414 def _parse_conversion(format_spec, default):
415 conversions, _, format_spec = format_spec.partition(_SEPARATOR)
416 convs = [_CONVERSIONS[c] for c in conversions[1:]]
417 fmt = _build_format_func(format_spec, default)
418
419 if len(conversions) <= 2:
420
421 def convert_one(obj):
422 return fmt(conv(obj))
423 conv = _CONVERSIONS[conversions[1]]
424 return convert_one
425
426 def convert_many(obj):
427 for conv in convs:
428 obj = conv(obj)
429 return fmt(obj)
430 convs = [_CONVERSIONS[c] for c in conversions[1:]]
431 return convert_many
432
433
434 def _parse_maxlen(format_spec, default):
435 maxlen, replacement, format_spec = format_spec.split(_SEPARATOR, 2)
436 fmt = _build_format_func(format_spec, default)
437
438 if maxlen[1] == "b":
439 maxlen = text.parse_int(maxlen[2:])
440
441 def mlen(obj):
442 obj = fmt(obj)
443 return obj if len(obj.encode(_ENCODING)) <= maxlen else replacement
444 else:
445 maxlen = text.parse_int(maxlen[1:])
446
447 def mlen(obj):
448 obj = fmt(obj)
449 return obj if len(obj) <= maxlen else replacement
450 return mlen
451
452
453 def _parse_identity(format_spec, default):
454 return util.identity
455
456
457 def _parse_join(format_spec, default):
458 separator, _, format_spec = format_spec.partition(_SEPARATOR)
459 join = separator[1:].join
460 fmt = _build_format_func(format_spec, default)
461
462 def apply_join(obj):
463 if isinstance(obj, str):
464 return fmt(obj)
465 return fmt(join(obj))
466 return apply_join
467
468
469 def _parse_map(format_spec, default):
470 key, _, format_spec = format_spec.partition(_SEPARATOR)
471 key = key[1:]
472 fmt = _build_format_func(format_spec, default)
473
474 def map_(obj):
475 if not obj or isinstance(obj, str):
476 return fmt(obj)
477
478 results = []
479 for item in obj:
480 if isinstance(item, dict):
481 value = item.get(key, ...)
482 results.append(default if value is ... else value)
483 else:
484 results.append(item)
485 return fmt(results)
486
487 return map_
488
489
490 def _parse_replace(format_spec, default):
491 old, new, format_spec = format_spec.split(_SEPARATOR, 2)
492 old = old[1:]
493 fmt = _build_format_func(format_spec, default)
494
495 def replace(obj):
496 return fmt(obj.replace(old, new))
497 return replace
498
499
500 def _parse_datetime(format_spec, default):
501 dt_format, _, format_spec = format_spec.partition(_SEPARATOR)
502 dt_format = dt_format[1:]
503 fmt = _build_format_func(format_spec, default)
504
505 def dt_parse(obj):
506 return fmt(dt.parse(obj, dt_format))
507 return dt_parse
508
509
510 def _parse_offset(format_spec, default):
511 offset, _, format_spec = format_spec.partition(_SEPARATOR)
512 offset = offset[1:]
513 fmt = _build_format_func(format_spec, default)
514
515 if not offset or offset == "local":
516 def off(dt_utc):
517 local = time.localtime(dt.to_ts(dt_utc))
518 return fmt(dt_utc + dt.timedelta(0, local.tm_gmtoff))
519 else:
520 hours, _, minutes = offset.partition(":")
521 offset = 3600 * int(hours)
522 if minutes:
523 offset += 60 * (int(minutes) if offset > 0 else -int(minutes))
524 offset = dt.timedelta(0, offset)
525
526 def off(obj):
527 return fmt(obj + offset)
528 return off
529
530
531 def _parse_sort(format_spec, default):
532 args, _, format_spec = format_spec.partition(_SEPARATOR)
533 fmt = _build_format_func(format_spec, default)
534
535 if "d" in args or "r" in args:
536 def sort(obj):
537 return fmt(sorted(obj, reverse=True))
538 else:
539 def sort(obj):
540 return fmt(sorted(obj))
541 return sort
542
543
544 def _parse_limit(format_spec, default):
545 limit, hint, format_spec = format_spec.split(_SEPARATOR, 2)
546 fmt = _build_format_func(format_spec, default)
547
548 if limit[1] == "b":
549 hint = hint.encode(_ENCODING)
550 limit = int(limit[2:])
551 limit_hint = limit - len(hint)
552
553 def apply_limit(obj):
554 objb = obj.encode(_ENCODING)
555 if len(objb) > limit:
556 obj = (objb[:limit_hint] + hint).decode(_ENCODING, "ignore")
557 return fmt(obj)
558 else:
559 limit = int(limit[1:])
560 limit_hint = limit - len(hint)
561
562 def apply_limit(obj):
563 if len(obj) > limit:
564 obj = obj[:limit_hint] + hint
565 return fmt(obj)
566 return apply_limit
567
568
569 def _default_format(format_spec, default):
570 def wrap(obj):
571 return format(obj, format_spec)
572 return wrap
573
574
575 class Literal():
576 # __getattr__, __getattribute__, and __class_getitem__
577 # are all slower than regular __getitem__
578
579 def __getitem__(self, key):
580 return key
581
582
583 _literal = Literal()
584
585 _CACHE = {}
586 _ENCODING = sys.getfilesystemencoding()
587 _SEPARATOR = "/"
588 _FORMATTERS = {
589 "E" : ExpressionFormatter,
590 "F" : FStringFormatter,
591 "J" : JinjaFormatter,
592 "M" : ModuleFormatter,
593 "S" : StringFormatter,
594 "T" : TemplateFormatter,
595 "TF": TemplateFStringFormatter,
596 "FT": TemplateFStringFormatter,
597 "TJ": TemplateJinjaFormatter,
598 "JT": TemplateJinjaFormatter,
599 }
600 _GLOBALS = {
601 "_env": lambda: os.environ,
602 "_lit": lambda: _literal,
603 "_now": dt.datetime.now,
604 "_nul": lambda: util.NONE,
605 }
606 _CONVERSIONS = {
607 "l": str.lower,
608 "u": str.upper,
609 "c": str.capitalize,
610 "C": string.capwords,
611 "j": util.json_dumps,
612 "t": str.strip,
613 "n": len,
614 "L": util.code_to_language,
615 "T": dt.to_ts_string,
616 "d": dt.parse_ts,
617 "D": dt.convert,
618 "q": text.quote,
619 "Q": text.unquote,
620 "U": text.unescape,
621 "H": lambda s: text.unescape(text.remove_html(s)),
622 "g": text.slugify,
623 "R": text.extract_urls,
624 "W": text.sanitize_whitespace,
625 "S": util.to_string,
626 "s": str,
627 "r": repr,
628 "a": ascii,
629 "i": int,
630 "f": float,
631 }
632 _FORMAT_SPECIFIERS = {
633 "?": _parse_optional,
634 "[": _parse_slice,
635 "A": _parse_arithmetic,
636 "C": _parse_conversion,
637 "D": _parse_datetime,
638 "I": _parse_identity,
639 "J": _parse_join,
640 "L": _parse_maxlen,
641 "M": _parse_map,
642 "O": _parse_offset,
643 "R": _parse_replace,
644 "S": _parse_sort,
645 "X": _parse_limit,
646 }