1
0
mirror of https://github.com/mikf/gallery-dl.git synced 2024-11-22 10:42:34 +01:00

[formatter] implement 'X' format specifier (#5770)

This commit is contained in:
Mike Fährmann 2024-06-21 20:49:52 +02:00
parent b707b31264
commit 8f50c04af2
No known key found for this signature in database
GPG Key ID: 5680CA389D365A88
3 changed files with 32 additions and 1 deletions

View File

@ -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>

View File

@ -423,6 +423,19 @@ def _parse_sort(format_spec, default):
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)
@ -469,9 +482,10 @@ _FORMAT_SPECIFIERS = {
"[": _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,
}

View File

@ -272,6 +272,13 @@ class TestFormatter(unittest.TestCase):
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")