Skip to content

Commit

Permalink
[formatter] implement 'C' format specifier (#5647)
Browse files Browse the repository at this point in the history
to apply a conversion after ':' or
to apply multiple conversions

for example {tags:CSl} or {tags:J - /Cl}
to convert list to string and lowercase it
  • Loading branch information
mikf committed Jun 5, 2024
1 parent 9b99d2c commit 1ce5de0
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ Format specifiers can be used for advanced formatting by using the options provi
<td><code>{foo:Ro/()/}</code></td>
<td><code>F()()&nbsp;Bar</code></td>
</tr>
<tr>
<td><code>C&lt;conversion(s)&gt;/</code></td>
<td>Apply <a href="#conversions">Conversions</a> to the current value</td>
<td><code>{tags:CSgc/}</code></td>
<td><code>"Sun-tree-water"</code></td>
</tr>
<tr>
<td><code>S&lt;order&gt;/</code></td>
<td>Sort a list. <code>&lt;order&gt;</code> can be either <strong>a</strong>scending or <strong>d</strong>escending/<strong>r</strong>everse. (default: <strong>a</strong>)</td>
Expand Down
21 changes: 21 additions & 0 deletions gallery_dl/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,26 @@ def apply_slice(obj):
return apply_slice


def _parse_conversion(format_spec, default):
conversions, _, format_spec = format_spec.partition(_SEPARATOR)
convs = [_CONVERSIONS[c] for c in conversions[1:]]
fmt = _build_format_func(format_spec, default)

if len(conversions) <= 2:

def convert_one(obj):
return fmt(conv(obj))
conv = _CONVERSIONS[conversions[1]]
return convert_one

def convert_many(obj):
for conv in convs:
obj = conv(obj)
return fmt(obj)
convs = [_CONVERSIONS[c] for c in conversions[1:]]
return convert_many


def _parse_maxlen(format_spec, default):
maxlen, replacement, format_spec = format_spec.split(_SEPARATOR, 2)
maxlen = text.parse_int(maxlen[1:])
Expand Down Expand Up @@ -447,6 +467,7 @@ def __getitem__(key):
_FORMAT_SPECIFIERS = {
"?": _parse_optional,
"[": _parse_slice,
"C": _parse_conversion,
"D": _parse_datetime,
"L": _parse_maxlen,
"J": _parse_join,
Expand Down
5 changes: 5 additions & 0 deletions test/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,11 @@ def test_sort(self):
"{a:Sort-reverse}", # starts with 'S', contains 'r'
"['w', 'r', 'o', 'l', 'h', 'd', 'O', 'L', 'L', 'E', ' ']")

def test_specifier_conversions(self):
self._run_test("{a:Cl}" , "hello world")
self._run_test("{h:CHC}" , "Foo & Bar")
self._run_test("{l:CSulc}", "A, b, c")

def test_chain_special(self):
# multiple replacements
self._run_test("{a:Rh/C/RE/e/RL/l/}", "Cello wOrld")
Expand Down

0 comments on commit 1ce5de0

Please sign in to comment.