1
0
mirror of https://github.com/mikf/gallery-dl.git synced 2024-11-25 04:02:32 +01:00

[formatter] implement 'A' format specifier (#6036)

This commit is contained in:
Mike Fährmann 2024-08-16 20:34:23 +02:00
parent 01e8433889
commit 78ae0ba9f7
No known key found for this signature in database
GPG Key ID: 5680CA389D365A88
3 changed files with 30 additions and 0 deletions

View File

@ -202,6 +202,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>A&lt;op&gt;&lt;value&gt;/</code></td>
<td>Apply arithmetic operation <code>&lt;op&gt;</code> (<code>+</code>, <code>-</code>, <code>*</code>) to the current value</td>
<td><code>{num:A+1/}</code></td>
<td><code>"2"</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>

View File

@ -325,6 +325,23 @@ def _parse_slice(format_spec, default):
return apply_slice
def _parse_arithmetic(format_spec, default):
op, _, format_spec = format_spec.partition(_SEPARATOR)
fmt = _build_format_func(format_spec, default)
value = int(op[2:])
op = op[1]
if op == "+":
return lambda obj: fmt(obj + value)
if op == "-":
return lambda obj: fmt(obj - value)
if op == "*":
return lambda obj: fmt(obj * value)
return fmt
def _parse_conversion(format_spec, default):
conversions, _, format_spec = format_spec.partition(_SEPARATOR)
convs = [_CONVERSIONS[c] for c in conversions[1:]]
@ -480,6 +497,7 @@ _CONVERSIONS = {
_FORMAT_SPECIFIERS = {
"?": _parse_optional,
"[": _parse_slice,
"A": _parse_arithmetic,
"C": _parse_conversion,
"D": _parse_datetime,
"J": _parse_join,

View File

@ -25,6 +25,7 @@ class TestFormatter(unittest.TestCase):
"b": "äöü",
"j": "げんそうきょう",
"d": {"a": "foo", "b": 0, "c": None},
"i": 2,
"l": ["a", "b", "c"],
"n": None,
"s": " \n\r\tSPACE ",
@ -267,6 +268,11 @@ class TestFormatter(unittest.TestCase):
"{a:Sort-reverse}", # starts with 'S', contains 'r'
"['w', 'r', 'o', 'l', 'h', 'd', 'O', 'L', 'L', 'E', ' ']")
def test_specifier_arithmetic(self):
self._run_test("{i:A+1}", "3")
self._run_test("{i:A-1}", "1")
self._run_test("{i:A*3}", "6")
def test_specifier_conversions(self):
self._run_test("{a:Cl}" , "hello world")
self._run_test("{h:CHC}" , "Foo & Bar")