From e0dd8dff5f626a42678a916780b31f0193aef7ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Sun, 29 Jul 2018 13:52:07 +0200 Subject: [PATCH] implement L// format option The L option allows for the contents of a format field to be replaced with if its length is greater than . Example: {f:L5/too long/} -> "foo" (if "f" is "foo") -> "too long" (if "f" is "foobar") (#92) (#94) --- gallery_dl/util.py | 11 +++++++++++ test/test_util.py | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index 0f700b95..7cbd2051 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -284,6 +284,12 @@ class Formatter(): Otherwise the whole replacement field becomes an empty string. Example: {f:?-+/+-/} -> "-+Example+-" (if "f" contains "Example") -> "" (if "f" is None, 0, "") + + - "L//": + Replaces the output with if its length (in characters) + exceeds . Otherwise everything is left as is. + Example: {f:L5/too long/} -> "foo" (if "f" is "foo") + -> "too long" (if "f" is "foobar") """ conversions = { "l": str.lower, @@ -331,6 +337,11 @@ class Formatter(): return "" before, after, format_spec = format_spec.split("/", 2) return before[1:] + format(value, format_spec) + after + if format_spec[0] == "L": + maxlen, replacement, format_spec = format_spec.split("/", 2) + maxlen = text.parse_int(maxlen[1:]) + value = format(value, format_spec) + return value if len(value) <= maxlen else replacement return format(value, format_spec) def get_field(self, field_name, kwargs): diff --git a/test/test_util.py b/test/test_util.py index 787ec3aa..cff31964 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -210,6 +210,14 @@ class TestFormatter(unittest.TestCase): self._run_test("{a[:50]}", v[:50]) self._run_test("{a[:]}" , v) + def test_maxlen(self): + v = self.kwdict["a"] + self._run_test("{a:L5/foo/}" , "foo") + self._run_test("{a:L50/foo/}", v) + self._run_test("{a:L50/foo/>50}", " " * 39 + v) + self._run_test("{a:L50/foo/>51}", "foo") + self._run_test("{a:Lab/foo/}", "foo") + def _run_test(self, format_string, result, default=None): formatter = util.Formatter(default) output = formatter.vformat(format_string, self.kwdict)