Skip to content

Commit

Permalink
implement L<maxlen>/<replacement>/ format option
Browse files Browse the repository at this point in the history
The L option allows for the contents of a format field to be replaced
with <replacement> if its length is greater than <maxlen>.

Example:
{f:L5/too long/} -> "foo"      (if "f" is "foo")
                 -> "too long" (if "f" is "foobar")

(#92) (#94)
  • Loading branch information
mikf committed Jul 29, 2018
1 parent 5f27cfe commit e0dd8df
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
11 changes: 11 additions & 0 deletions gallery_dl/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<maxlen>/<replacement>/":
Replaces the output with <replacement> if its length (in characters)
exceeds <maxlen>. 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,
Expand Down Expand Up @@ -331,6 +337,11 @@ def format_field(value, format_spec):
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):
Expand Down
8 changes: 8 additions & 0 deletions test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,14 @@ def test_slicing(self):
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)
Expand Down

0 comments on commit e0dd8df

Please sign in to comment.