2021-09-27 02:37:04 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2023-02-09 15:50:55 +01:00
|
|
|
# Copyright 2021-2023 Mike Fährmann
|
2021-09-27 02:37:04 +02:00
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License version 2 as
|
|
|
|
# published by the Free Software Foundation.
|
|
|
|
|
|
|
|
"""String formatters"""
|
|
|
|
|
2021-10-27 23:48:00 +02:00
|
|
|
import os
|
2022-07-08 12:51:03 +02:00
|
|
|
import time
|
2021-09-27 02:37:04 +02:00
|
|
|
import string
|
|
|
|
import _string
|
2021-10-30 21:34:28 +02:00
|
|
|
import datetime
|
2021-09-27 02:37:04 +02:00
|
|
|
import operator
|
|
|
|
from . import text, util
|
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
NONE = util.NONE
|
2021-09-27 02:37:04 +02:00
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
|
|
|
|
def parse(format_string, default=NONE, fmt=format):
|
2022-07-04 22:35:59 +02:00
|
|
|
key = format_string, default, fmt
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
return _CACHE[key]
|
|
|
|
except KeyError:
|
2021-09-27 19:24:02 +02:00
|
|
|
pass
|
|
|
|
|
|
|
|
cls = StringFormatter
|
|
|
|
if format_string.startswith("\f"):
|
|
|
|
kind, _, format_string = format_string.partition(" ")
|
|
|
|
kind = kind[1:]
|
|
|
|
|
|
|
|
if kind == "T":
|
|
|
|
cls = TemplateFormatter
|
|
|
|
elif kind == "E":
|
|
|
|
cls = ExpressionFormatter
|
|
|
|
elif kind == "M":
|
|
|
|
cls = ModuleFormatter
|
2022-03-18 13:31:01 +01:00
|
|
|
elif kind == "F":
|
|
|
|
cls = FStringFormatter
|
2021-09-27 19:24:02 +02:00
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
formatter = _CACHE[key] = cls(format_string, default, fmt)
|
2021-09-27 19:24:02 +02:00
|
|
|
return formatter
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
|
|
|
|
class StringFormatter():
|
|
|
|
"""Custom, extended version of string.Formatter
|
|
|
|
|
|
|
|
This string formatter implementation is a mostly performance-optimized
|
|
|
|
variant of the original string.Formatter class. Unnecessary features have
|
|
|
|
been removed (positional arguments, unused argument check) and new
|
|
|
|
formatting options have been added.
|
|
|
|
|
|
|
|
Extra Conversions:
|
|
|
|
- "l": calls str.lower on the target value
|
|
|
|
- "u": calls str.upper
|
|
|
|
- "c": calls str.capitalize
|
|
|
|
- "C": calls string.capwords
|
2022-12-26 07:46:41 +01:00
|
|
|
- "g": calls text.slugify()
|
|
|
|
- "j": calls json.dumps
|
2021-09-27 02:37:04 +02:00
|
|
|
- "t": calls str.strip
|
2022-12-26 07:46:41 +01:00
|
|
|
- "T": calls util.datetime_to_timestamp_string()
|
2021-09-27 02:37:04 +02:00
|
|
|
- "d": calls text.parse_timestamp
|
2022-12-26 07:46:41 +01:00
|
|
|
- "s": calls str()
|
2021-09-27 02:37:04 +02:00
|
|
|
- "S": calls util.to_string()
|
2022-12-26 07:46:41 +01:00
|
|
|
- "U": calls urllib.parse.unescape
|
|
|
|
- "r": calls repr()
|
|
|
|
- "a": calls ascii()
|
2021-09-27 02:37:04 +02:00
|
|
|
- Example: {f!l} -> "example"; {f!u} -> "EXAMPLE"
|
|
|
|
|
2022-12-26 07:46:41 +01:00
|
|
|
# Go to _CONVERSIONS and _SPECIFIERS below to se all of them, read:
|
|
|
|
# https://github.com/mikf/gallery-dl/blob/master/docs/formatting.md
|
|
|
|
|
2021-09-27 02:37:04 +02:00
|
|
|
Extra Format Specifiers:
|
|
|
|
- "?<before>/<after>/":
|
|
|
|
Adds <before> and <after> to the actual value if it evaluates to True.
|
|
|
|
Otherwise the whole replacement field becomes an empty string.
|
|
|
|
Example: {f:?-+/+-/} -> "-+Example+-" (if "f" contains "Example")
|
|
|
|
-> "" (if "f" is None, 0, "")
|
|
|
|
|
|
|
|
- "L<maxlen>/<replacement>/":
|
|
|
|
Replaces the output with <replacement> if its length (in characters)
|
|
|
|
exceeds <maxlen>. Otherwise everything is left as is.
|
|
|
|
Example: {f:L5/too long/} -> "foo" (if "f" is "foo")
|
|
|
|
-> "too long" (if "f" is "foobar")
|
|
|
|
|
|
|
|
- "J<separator>/":
|
|
|
|
Joins elements of a list (or string) using <separator>
|
|
|
|
Example: {f:J - /} -> "a - b - c" (if "f" is ["a", "b", "c"])
|
|
|
|
|
|
|
|
- "R<old>/<new>/":
|
|
|
|
Replaces all occurrences of <old> with <new>
|
|
|
|
Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r")
|
|
|
|
"""
|
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
def __init__(self, format_string, default=NONE, fmt=format):
|
2021-09-27 02:37:04 +02:00
|
|
|
self.default = default
|
2022-07-04 22:35:59 +02:00
|
|
|
self.format = fmt
|
2021-09-27 02:37:04 +02:00
|
|
|
self.result = []
|
|
|
|
self.fields = []
|
|
|
|
|
|
|
|
for literal_text, field_name, format_spec, conv in \
|
|
|
|
_string.formatter_parser(format_string):
|
|
|
|
if literal_text:
|
|
|
|
self.result.append(literal_text)
|
|
|
|
if field_name:
|
|
|
|
self.fields.append((
|
|
|
|
len(self.result),
|
|
|
|
self._field_access(field_name, format_spec, conv),
|
|
|
|
))
|
|
|
|
self.result.append("")
|
|
|
|
|
|
|
|
if len(self.result) == 1:
|
|
|
|
if self.fields:
|
|
|
|
self.format_map = self.fields[0][1]
|
|
|
|
else:
|
|
|
|
self.format_map = lambda _: format_string
|
|
|
|
del self.result, self.fields
|
|
|
|
|
|
|
|
def format_map(self, kwdict):
|
|
|
|
"""Apply 'kwdict' to the initial format_string and return its result"""
|
|
|
|
result = self.result
|
|
|
|
for index, func in self.fields:
|
|
|
|
result[index] = func(kwdict)
|
|
|
|
return "".join(result)
|
|
|
|
|
|
|
|
def _field_access(self, field_name, format_spec, conversion):
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = self._parse_format_spec(format_spec, conversion)
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
if "|" in field_name:
|
|
|
|
return self._apply_list([
|
|
|
|
parse_field_name(fn)
|
|
|
|
for fn in field_name.split("|")
|
|
|
|
], fmt)
|
|
|
|
else:
|
|
|
|
key, funcs = parse_field_name(field_name)
|
2021-10-27 23:48:00 +02:00
|
|
|
if key in _GLOBALS:
|
|
|
|
return self._apply_globals(_GLOBALS[key], funcs, fmt)
|
2021-09-27 02:37:04 +02:00
|
|
|
if funcs:
|
|
|
|
return self._apply(key, funcs, fmt)
|
|
|
|
return self._apply_simple(key, fmt)
|
|
|
|
|
|
|
|
def _apply(self, key, funcs, fmt):
|
|
|
|
def wrap(kwdict):
|
|
|
|
try:
|
|
|
|
obj = kwdict[key]
|
|
|
|
for func in funcs:
|
|
|
|
obj = func(obj)
|
|
|
|
except Exception:
|
|
|
|
obj = self.default
|
|
|
|
return fmt(obj)
|
|
|
|
return wrap
|
|
|
|
|
2021-10-27 23:48:00 +02:00
|
|
|
def _apply_globals(self, gobj, funcs, fmt):
|
|
|
|
def wrap(_):
|
|
|
|
try:
|
2021-10-30 21:34:28 +02:00
|
|
|
obj = gobj()
|
2021-10-27 23:48:00 +02:00
|
|
|
for func in funcs:
|
|
|
|
obj = func(obj)
|
|
|
|
except Exception:
|
|
|
|
obj = self.default
|
|
|
|
return fmt(obj)
|
|
|
|
return wrap
|
|
|
|
|
2021-09-27 02:37:04 +02:00
|
|
|
def _apply_simple(self, key, fmt):
|
|
|
|
def wrap(kwdict):
|
|
|
|
return fmt(kwdict[key] if key in kwdict else self.default)
|
|
|
|
return wrap
|
|
|
|
|
|
|
|
def _apply_list(self, lst, fmt):
|
|
|
|
def wrap(kwdict):
|
|
|
|
for key, funcs in lst:
|
|
|
|
try:
|
2021-10-30 21:34:28 +02:00
|
|
|
obj = _GLOBALS[key]() if key in _GLOBALS else kwdict[key]
|
2021-09-27 02:37:04 +02:00
|
|
|
for func in funcs:
|
|
|
|
obj = func(obj)
|
|
|
|
if obj:
|
|
|
|
break
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
obj = self.default
|
|
|
|
return fmt(obj)
|
|
|
|
return wrap
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _parse_format_spec(self, format_spec, conversion):
|
|
|
|
fmt = _build_format_func(format_spec, self.format)
|
|
|
|
if not conversion:
|
|
|
|
return fmt
|
|
|
|
|
|
|
|
conversion = _CONVERSIONS[conversion]
|
|
|
|
if fmt is self.format:
|
|
|
|
return conversion
|
|
|
|
else:
|
|
|
|
return lambda obj: fmt(conversion(obj))
|
|
|
|
|
2021-09-27 02:37:04 +02:00
|
|
|
|
2021-09-27 19:24:02 +02:00
|
|
|
class TemplateFormatter(StringFormatter):
|
|
|
|
"""Read format_string from file"""
|
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
def __init__(self, path, default=NONE, fmt=format):
|
2021-09-27 19:24:02 +02:00
|
|
|
with open(util.expand_path(path)) as fp:
|
|
|
|
format_string = fp.read()
|
2022-07-04 22:35:59 +02:00
|
|
|
StringFormatter.__init__(self, format_string, default, fmt)
|
2021-09-27 19:24:02 +02:00
|
|
|
|
|
|
|
|
|
|
|
class ExpressionFormatter():
|
|
|
|
"""Generate text by evaluating a Python expression"""
|
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
def __init__(self, expression, default=NONE, fmt=None):
|
2021-09-27 19:24:02 +02:00
|
|
|
self.format_map = util.compile_expression(expression)
|
|
|
|
|
|
|
|
|
|
|
|
class ModuleFormatter():
|
|
|
|
"""Generate text by calling an external function"""
|
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
def __init__(self, function_spec, default=NONE, fmt=None):
|
2021-09-27 19:24:02 +02:00
|
|
|
module_name, _, function_name = function_spec.partition(":")
|
|
|
|
module = __import__(module_name)
|
|
|
|
self.format_map = getattr(module, function_name)
|
|
|
|
|
|
|
|
|
2022-03-18 13:31:01 +01:00
|
|
|
class FStringFormatter():
|
2022-12-12 16:02:01 +01:00
|
|
|
"""Generate text by evaluating an f-string literal"""
|
2022-03-18 13:31:01 +01:00
|
|
|
|
2022-12-06 22:26:46 +01:00
|
|
|
def __init__(self, fstring, default=NONE, fmt=None):
|
2022-03-18 13:31:01 +01:00
|
|
|
self.format_map = util.compile_expression("f'''" + fstring + "'''")
|
|
|
|
|
|
|
|
|
2021-09-27 02:37:04 +02:00
|
|
|
def parse_field_name(field_name):
|
|
|
|
first, rest = _string.formatter_field_name_split(field_name)
|
|
|
|
funcs = []
|
|
|
|
|
2022-05-09 23:04:08 +02:00
|
|
|
if first[0] == "'":
|
|
|
|
funcs.append(operator.itemgetter(first[1:-1]))
|
|
|
|
first = "_lit"
|
|
|
|
|
2021-09-27 02:37:04 +02:00
|
|
|
for is_attr, key in rest:
|
|
|
|
if is_attr:
|
|
|
|
func = operator.attrgetter
|
|
|
|
else:
|
|
|
|
func = operator.itemgetter
|
|
|
|
try:
|
|
|
|
if ":" in key:
|
2022-06-25 16:45:34 +02:00
|
|
|
key = _slice(key)
|
2021-09-27 02:37:04 +02:00
|
|
|
except TypeError:
|
|
|
|
pass # key is an integer
|
|
|
|
|
|
|
|
funcs.append(func(key))
|
|
|
|
|
|
|
|
return first, funcs
|
|
|
|
|
|
|
|
|
2022-06-25 16:45:34 +02:00
|
|
|
def _slice(indices):
|
|
|
|
start, _, stop = indices.partition(":")
|
|
|
|
stop, _, step = stop.partition(":")
|
|
|
|
return slice(
|
|
|
|
int(start) if start else None,
|
|
|
|
int(stop) if stop else None,
|
|
|
|
int(step) if step else None,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _build_format_func(format_spec, default):
|
2021-09-27 02:37:04 +02:00
|
|
|
if format_spec:
|
2022-07-04 22:35:59 +02:00
|
|
|
return _FORMAT_SPECIFIERS.get(
|
|
|
|
format_spec[0], _default_format)(format_spec, default)
|
|
|
|
return default
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_optional(format_spec, default):
|
2022-07-10 13:30:45 +02:00
|
|
|
before, after, format_spec = format_spec.split(_SEPARATOR, 2)
|
2021-09-27 02:37:04 +02:00
|
|
|
before = before[1:]
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = _build_format_func(format_spec, default)
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
def optional(obj):
|
|
|
|
return before + fmt(obj) + after if obj else ""
|
|
|
|
return optional
|
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _parse_slice(format_spec, default):
|
2022-06-25 16:45:34 +02:00
|
|
|
indices, _, format_spec = format_spec.partition("]")
|
|
|
|
slice = _slice(indices[1:])
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = _build_format_func(format_spec, default)
|
2022-06-25 16:45:34 +02:00
|
|
|
|
|
|
|
def apply_slice(obj):
|
|
|
|
return fmt(obj[slice])
|
|
|
|
return apply_slice
|
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _parse_maxlen(format_spec, default):
|
2022-07-10 13:30:45 +02:00
|
|
|
maxlen, replacement, format_spec = format_spec.split(_SEPARATOR, 2)
|
2021-09-27 02:37:04 +02:00
|
|
|
maxlen = text.parse_int(maxlen[1:])
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = _build_format_func(format_spec, default)
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
def mlen(obj):
|
|
|
|
obj = fmt(obj)
|
|
|
|
return obj if len(obj) <= maxlen else replacement
|
|
|
|
return mlen
|
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _parse_join(format_spec, default):
|
2022-07-10 13:30:45 +02:00
|
|
|
separator, _, format_spec = format_spec.partition(_SEPARATOR)
|
2022-08-16 16:41:19 +02:00
|
|
|
join = separator[1:].join
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = _build_format_func(format_spec, default)
|
2021-09-27 02:37:04 +02:00
|
|
|
|
2022-08-16 16:41:19 +02:00
|
|
|
def apply_join(obj):
|
|
|
|
if isinstance(obj, str):
|
|
|
|
return fmt(obj)
|
|
|
|
return fmt(join(obj))
|
|
|
|
return apply_join
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _parse_replace(format_spec, default):
|
2022-07-10 13:30:45 +02:00
|
|
|
old, new, format_spec = format_spec.split(_SEPARATOR, 2)
|
2021-09-27 02:37:04 +02:00
|
|
|
old = old[1:]
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = _build_format_func(format_spec, default)
|
2021-09-27 02:37:04 +02:00
|
|
|
|
|
|
|
def replace(obj):
|
|
|
|
return fmt(obj.replace(old, new))
|
|
|
|
return replace
|
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _parse_datetime(format_spec, default):
|
2022-07-10 13:30:45 +02:00
|
|
|
dt_format, _, format_spec = format_spec.partition(_SEPARATOR)
|
2021-11-20 23:04:34 +01:00
|
|
|
dt_format = dt_format[1:]
|
2022-07-04 22:35:59 +02:00
|
|
|
fmt = _build_format_func(format_spec, default)
|
2021-11-20 23:04:34 +01:00
|
|
|
|
|
|
|
def dt(obj):
|
|
|
|
return fmt(text.parse_datetime(obj, dt_format))
|
|
|
|
return dt
|
|
|
|
|
|
|
|
|
2022-07-08 12:51:03 +02:00
|
|
|
def _parse_offset(format_spec, default):
|
2022-07-10 13:30:45 +02:00
|
|
|
offset, _, format_spec = format_spec.partition(_SEPARATOR)
|
2022-07-08 12:51:03 +02:00
|
|
|
offset = offset[1:]
|
|
|
|
fmt = _build_format_func(format_spec, default)
|
|
|
|
|
|
|
|
if not offset or offset == "local":
|
|
|
|
is_dst = time.daylight and time.localtime().tm_isdst > 0
|
|
|
|
offset = -(time.altzone if is_dst else time.timezone)
|
|
|
|
else:
|
|
|
|
hours, _, minutes = offset.partition(":")
|
|
|
|
offset = 3600 * int(hours)
|
|
|
|
if minutes:
|
|
|
|
offset += 60 * (int(minutes) if offset > 0 else -int(minutes))
|
|
|
|
|
|
|
|
offset = datetime.timedelta(seconds=offset)
|
|
|
|
|
|
|
|
def off(obj):
|
|
|
|
return fmt(obj + offset)
|
|
|
|
return off
|
|
|
|
|
|
|
|
|
2022-11-21 21:44:42 +01:00
|
|
|
def _parse_sort(format_spec, default):
|
|
|
|
args, _, format_spec = format_spec.partition(_SEPARATOR)
|
|
|
|
fmt = _build_format_func(format_spec, default)
|
|
|
|
|
|
|
|
if "d" in args or "r" in args:
|
|
|
|
def sort_desc(obj):
|
|
|
|
return fmt(sorted(obj, reverse=True))
|
|
|
|
return sort_desc
|
|
|
|
else:
|
|
|
|
def sort_asc(obj):
|
|
|
|
return fmt(sorted(obj))
|
|
|
|
return sort_asc
|
|
|
|
|
|
|
|
|
2022-07-04 22:35:59 +02:00
|
|
|
def _default_format(format_spec, default):
|
2021-09-27 02:37:04 +02:00
|
|
|
def wrap(obj):
|
|
|
|
return format(obj, format_spec)
|
|
|
|
return wrap
|
2022-05-09 23:04:08 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Literal():
|
|
|
|
# __getattr__, __getattribute__, and __class_getitem__
|
|
|
|
# are all slower than regular __getitem__
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def __getitem__(key):
|
|
|
|
return key
|
|
|
|
|
|
|
|
|
|
|
|
_literal = Literal()
|
2022-07-04 22:35:59 +02:00
|
|
|
|
|
|
|
_CACHE = {}
|
2022-07-10 13:30:45 +02:00
|
|
|
_SEPARATOR = "/"
|
2022-07-04 22:35:59 +02:00
|
|
|
_GLOBALS = {
|
|
|
|
"_env": lambda: os.environ,
|
|
|
|
"_lit": lambda: _literal,
|
|
|
|
"_now": datetime.datetime.now,
|
|
|
|
}
|
|
|
|
_CONVERSIONS = {
|
|
|
|
"l": str.lower,
|
|
|
|
"u": str.upper,
|
|
|
|
"c": str.capitalize,
|
|
|
|
"C": string.capwords,
|
2023-02-09 15:50:55 +01:00
|
|
|
"j": util.json_dumps,
|
2022-07-04 22:35:59 +02:00
|
|
|
"t": str.strip,
|
|
|
|
"T": util.datetime_to_timestamp_string,
|
|
|
|
"d": text.parse_timestamp,
|
|
|
|
"U": text.unescape,
|
2022-08-23 21:14:55 +02:00
|
|
|
"g": text.slugify,
|
2022-07-04 22:35:59 +02:00
|
|
|
"S": util.to_string,
|
|
|
|
"s": str,
|
|
|
|
"r": repr,
|
|
|
|
"a": ascii,
|
|
|
|
}
|
|
|
|
_FORMAT_SPECIFIERS = {
|
|
|
|
"?": _parse_optional,
|
|
|
|
"[": _parse_slice,
|
|
|
|
"D": _parse_datetime,
|
|
|
|
"L": _parse_maxlen,
|
|
|
|
"J": _parse_join,
|
2022-07-08 12:51:03 +02:00
|
|
|
"O": _parse_offset,
|
2022-07-04 22:35:59 +02:00
|
|
|
"R": _parse_replace,
|
2022-11-21 21:44:42 +01:00
|
|
|
"S": _parse_sort,
|
2022-07-04 22:35:59 +02:00
|
|
|
}
|