[util] restructure formatter for better exception propagation

pull/54/head
Mike Fährmann 7 years ago
parent 0386503c80
commit 8e6a767109
No known key found for this signature in database
GPG Key ID: 5680CA389D365A88

@ -252,16 +252,13 @@ class Formatter():
"a": ascii, "a": ascii,
} }
def __init__(self, format_string): def vformat(self, format_string, kwargs):
self.formatter_rules = tuple(_string.formatter_parser(format_string))
def format_map(self, kwargs):
"""Apply 'kwargs' to the initial format_string and return its result""" """Apply 'kwargs' to the initial format_string and return its result"""
result = [] result = []
append = result.append append = result.append
for literal_text, field_name, format_spec, conversion in \ for literal_text, field_name, format_spec, conversion in \
self.formatter_rules: _string.formatter_parser(format_string):
if literal_text: if literal_text:
append(literal_text) append(literal_text)
@ -311,7 +308,8 @@ class PathFormat():
"filename", extractor.filename_fmt) "filename", extractor.filename_fmt)
self.directory_fmt = extractor.config( self.directory_fmt = extractor.config(
"directory", extractor.directory_fmt) "directory", extractor.directory_fmt)
self.filename_formatter = Formatter(self.filename_fmt) self.formatter = Formatter()
self.has_extension = False self.has_extension = False
self.keywords = {} self.keywords = {}
self.directory = self.realdirectory = "" self.directory = self.realdirectory = ""
@ -345,7 +343,7 @@ class PathFormat():
try: try:
segments = [ segments = [
text.clean_path( text.clean_path(
Formatter(segment).format_map(keywords).strip()) self.formatter.vformat(segment, keywords).strip())
for segment in self.directory_fmt for segment in self.directory_fmt
] ]
except Exception as exc: except Exception as exc:
@ -375,7 +373,7 @@ class PathFormat():
"""Use filename-keywords and directory to build a full path""" """Use filename-keywords and directory to build a full path"""
try: try:
filename = text.clean_path( filename = text.clean_path(
self.filename_formatter.format_map(self.keywords)) self.formatter.vformat(self.filename_fmt, self.keywords))
except Exception as exc: except Exception as exc:
raise exception.FormatError(exc, "filename") raise exception.FormatError(exc, "filename")

@ -176,8 +176,8 @@ class TestFormatter(unittest.TestCase):
self._run_test("{name}{title4:? **/''/}", "Name") self._run_test("{name}{title4:? **/''/}", "Name")
def _run_test(self, format_string, result): def _run_test(self, format_string, result):
formatter = util.Formatter(format_string) formatter = util.Formatter()
output = formatter.format_map(self.kwdict) output = formatter.vformat(format_string, self.kwdict)
self.assertEqual(output, result, format_string) self.assertEqual(output, result, format_string)

Loading…
Cancel
Save