diff --git a/gallery_dl/util.py b/gallery_dl/util.py index 91fa0a61..0a263c01 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -# Copyright 2017-2018 Mike Fährmann +# Copyright 2017-2019 Mike Fährmann # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as @@ -306,6 +306,10 @@ class Formatter(): exceeds . Otherwise everything is left as is. Example: {f:L5/too long/} -> "foo" (if "f" is "foo") -> "too long" (if "f" is "foobar") + + - "J/": + Joins elements of a list (or string) using + Example: {f:J - /} -> "a - b - c" (if "f" is ["a", "b", "c"]) """ conversions = { "l": str.lower, @@ -361,6 +365,8 @@ class Formatter(): func = self._format_optional elif format_spec[0] == "L": func = self._format_maxlen + elif format_spec[0] == "J": + func = self._format_join else: func = self._format_default fmt = func(format_spec) @@ -419,6 +425,15 @@ class Formatter(): maxlen = text.parse_int(maxlen[1:]) return wrap + @staticmethod + def _format_join(format_spec): + def wrap(obj): + obj = separator.join(obj) + return format(obj, format_spec) + separator, _, format_spec = format_spec.partition("/") + separator = separator[1:] + return wrap + @staticmethod def _format_default(format_spec): def wrap(obj): diff --git a/test/test_util.py b/test/test_util.py index 3a87757a..2a1909c0 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -# Copyright 2015-2018 Mike Fährmann +# Copyright 2015-2019 Mike Fährmann # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as @@ -147,6 +147,7 @@ class TestFormatter(unittest.TestCase): kwdict = { "a": "hElLo wOrLd", "b": "äöü", + "l": ["a", "b", "c"], "u": "%27%3C%20/%20%3E%27", "name": "Name", "title1": "Title", @@ -231,6 +232,18 @@ class TestFormatter(unittest.TestCase): self._run_test("{a:L50/foo/>51}", "foo") self._run_test("{a:Lab/foo/}", "foo") + def test_join(self): + self._run_test("{l:J}" , "abc") + self._run_test("{l:J,}" , "a,b,c") + self._run_test("{l:J,/}" , "a,b,c") + self._run_test("{l:J,/>20}" , " a,b,c") + self._run_test("{l:J - }" , "a - b - c") + self._run_test("{l:J - /}" , "a - b - c") + self._run_test("{l:J - />20}", " a - b - c") + + self._run_test("{a:J/}" , self.kwdict["a"]) + self._run_test("{a:J, /}" , ", ".join(self.kwdict["a"])) + def _run_test(self, format_string, result, default=None): formatter = util.Formatter(format_string, default) output = formatter.format_map(self.kwdict)