Skip to content

Commit

Permalink
[formatter] implement 'X' format specifier (#5770)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikf committed Jun 21, 2024
1 parent b707b31 commit 8f50c04
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
10 changes: 10 additions & 0 deletions docs/formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,16 @@ Format specifiers can be used for advanced formatting by using the options provi
<td><code>{foo:L3/long/}</code></td>
<td><code>long</code></td>
</tr>
<tr>
<td rowspan="2"><code>X&lt;maxlen&gt;/&lt;ext&gt;/</code></td>
<td rowspan="2">Limit output to <code>&lt;maxlen&gt;</code> characters. Cut output and add <code>&lt;ext&gt;</code> to its end if its length exceeds <code>&lt;maxlen&gt;</code></td>
<td><code>{foo:X15/&nbsp;.../}</code></td>
<td><code>Foo&nbsp;Bar</code></td>
</tr>
<tr>
<td><code>{foo:L6/&nbsp;.../}</code></td>
<td><code>Fo&nbsp;...</code></td>
</tr>
<tr>
<td><code>J&lt;separator&gt;/</code></td>
<td>Concatenates elements of a list with <code>&lt;separator&gt;</code> using <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a></td>
Expand Down
16 changes: 15 additions & 1 deletion gallery_dl/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,19 @@ def sort_asc(obj):
return sort_asc


def _parse_limit(format_spec, default):
limit, hint, format_spec = format_spec.split(_SEPARATOR, 2)
limit = int(limit[1:])
limit_hint = limit - len(hint)
fmt = _build_format_func(format_spec, default)

def apply_limit(obj):
if len(obj) > limit:
obj = obj[:limit_hint] + hint
return fmt(obj)
return apply_limit


def _default_format(format_spec, default):
def wrap(obj):
return format(obj, format_spec)
Expand Down Expand Up @@ -469,9 +482,10 @@ def __getitem__(key):
"[": _parse_slice,
"C": _parse_conversion,
"D": _parse_datetime,
"L": _parse_maxlen,
"J": _parse_join,
"L": _parse_maxlen,
"O": _parse_offset,
"R": _parse_replace,
"S": _parse_sort,
"X": _parse_limit,
}
7 changes: 7 additions & 0 deletions test/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,13 @@ def test_specifier_conversions(self):
self._run_test("{h:CHC}" , "Foo & Bar")
self._run_test("{l:CSulc}", "A, b, c")

def test_specifier_limit(self):
self._run_test("{a:X20/ */}", "hElLo wOrLd")
self._run_test("{a:X10/ */}", "hElLo wO *")

with self.assertRaises(ValueError):
self._run_test("{a:Xfoo/ */}", "hello wo *")

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 8f50c04

Please sign in to comment.