improve exception handling for placeholder replacement

do not ignore bad placeholders and just return empty string,
this could have bad consequences, e.g. with --prefix '{invalidplaceholder}':
a typo in the placeholder name would cause the prefix to be the empty string.
This commit is contained in:
Thomas Waldmann 2016-06-21 22:46:12 +02:00
parent 52007dbd43
commit ad1729401f
2 changed files with 11 additions and 12 deletions

View File

@ -69,6 +69,10 @@ class NoManifestError(Error):
"""Repository has no manifest."""
class PlaceholderError(Error):
"""Formatting Error: "{}".format({}): {}({})"""
def check_extension_modules():
from . import platform
if hashindex.API_VERSION != 2:
@ -552,18 +556,10 @@ def dir_is_tagged(path, exclude_caches, exclude_if_present):
def format_line(format, data):
# TODO: Filter out unwanted properties of str.format(), because "format" is user provided.
try:
return format.format(**data)
except (KeyError, ValueError) as e:
# this should catch format errors
print('Error in lineformat: "{}" - reason "{}"'.format(format, str(e)))
except Exception as e:
# something unexpected, print error and raise exception
print('Error in lineformat: "{}" - reason "{}"'.format(format, str(e)))
raise
return ''
raise PlaceholderError(format, data, e.__class__.__name__, str(e))
def replace_placeholders(text):

View File

@ -10,7 +10,7 @@ import msgpack
import msgpack.fallback
import time
from ..helpers import Location, format_file_size, format_timedelta, format_line, make_path_safe, \
from ..helpers import Location, format_file_size, format_timedelta, format_line, PlaceholderError, make_path_safe, \
prune_within, prune_split, get_cache_dir, get_keys_dir, Statistics, is_slow_msgpack, \
yes, TRUISH, FALSISH, DEFAULTISH, \
StableDict, int_to_bigint, bigint_to_int, parse_timestamp, CompressionSpec, ChunkerParams, \
@ -887,5 +887,8 @@ def test_format_line():
def test_format_line_erroneous():
data = dict(foo='bar baz')
assert format_line('{invalid}', data) == '' # TODO: rather raise exception
data = dict()
with pytest.raises(PlaceholderError):
assert format_line('{invalid}', data)
with pytest.raises(PlaceholderError):
assert format_line('{}', data)