From 8e6a76710905a356653287a9fce464a514f53596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Fri, 6 Oct 2017 15:47:06 +0200 Subject: [PATCH] [util] restructure formatter for better exception propagation --- gallery_dl/util.py | 14 ++++++-------- test/test_util.py | 4 ++-- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index 22efdc93..1ba032db 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -252,16 +252,13 @@ class Formatter(): "a": ascii, } - def __init__(self, format_string): - self.formatter_rules = tuple(_string.formatter_parser(format_string)) - - def format_map(self, kwargs): + def vformat(self, format_string, kwargs): """Apply 'kwargs' to the initial format_string and return its result""" result = [] append = result.append for literal_text, field_name, format_spec, conversion in \ - self.formatter_rules: + _string.formatter_parser(format_string): if literal_text: append(literal_text) @@ -311,7 +308,8 @@ class PathFormat(): "filename", extractor.filename_fmt) self.directory_fmt = extractor.config( "directory", extractor.directory_fmt) - self.filename_formatter = Formatter(self.filename_fmt) + self.formatter = Formatter() + self.has_extension = False self.keywords = {} self.directory = self.realdirectory = "" @@ -345,7 +343,7 @@ class PathFormat(): try: segments = [ text.clean_path( - Formatter(segment).format_map(keywords).strip()) + self.formatter.vformat(segment, keywords).strip()) for segment in self.directory_fmt ] except Exception as exc: @@ -375,7 +373,7 @@ class PathFormat(): """Use filename-keywords and directory to build a full path""" try: filename = text.clean_path( - self.filename_formatter.format_map(self.keywords)) + self.formatter.vformat(self.filename_fmt, self.keywords)) except Exception as exc: raise exception.FormatError(exc, "filename") diff --git a/test/test_util.py b/test/test_util.py index 6e4e22d7..690bd288 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -176,8 +176,8 @@ class TestFormatter(unittest.TestCase): self._run_test("{name}{title4:? **/''/}", "Name") def _run_test(self, format_string, result): - formatter = util.Formatter(format_string) - output = formatter.format_map(self.kwdict) + formatter = util.Formatter() + output = formatter.vformat(format_string, self.kwdict) self.assertEqual(output, result, format_string)