hooks: Filter entries by setting entry_data['_hook_cancel'] to True.

The current method only works for plain dicts and other simple mappings.
Mapping that may still contain items after .clear(), like ChainMap, can't
rely on the old method.
This commit is contained in:
Brett Smith 2017-12-19 09:01:58 -05:00
parent 34b71baaf7
commit b41a7a99af
4 changed files with 6 additions and 4 deletions

View file

@ -51,7 +51,7 @@ Hooks make arbitrary transformations to entry data dicts. Every entry data dict
Initializes the hook with the user's configuration. Initializes the hook with the user's configuration.
``run(entry_data)`` ``run(entry_data)``
This method makes the hook's transformations to the entry data dict, if any. If this method clears the entry data dict, that entry will not be output. This method makes the hook's transformations to the entry data dict, if any. If this method sets ``entry_data['_hook_cancel']`` to a truthy value, that entry will not be output.
Templates Templates
~~~~~~~~~ ~~~~~~~~~

View file

@ -41,11 +41,13 @@ class FileImporter:
default_date = self.config.get_default_date() default_date = self.config.get_default_date()
in_file.seek(0) in_file.seek(0)
for entry_data in importer(in_file): for entry_data in importer(in_file):
entry_data['_hook_cancel'] = False
for hook in self.hooks: for hook in self.hooks:
hook.run(entry_data) hook.run(entry_data)
if not entry_data: if entry_data['_hook_cancel']:
break break
else: else:
del entry_data['_hook_cancel']
print(template.render(**entry_data), file=out_file, end='') print(template.render(**entry_data), file=out_file, end='')
def import_path(self, in_path): def import_path(self, in_path):

View file

@ -9,4 +9,4 @@ class FilterByDateHook:
pass pass
else: else:
if not self.config.date_in_want_range(date): if not self.config.date_in_want_range(date):
entry_data.clear() entry_data['_hook_cancel'] = True

View file

@ -58,7 +58,7 @@ def test_filter_by_date(entry_date, start_date, end_date, allowed):
entry_data = {'date': entry_date} entry_data = {'date': entry_date}
hook = filter_by_date.FilterByDateHook(DateRangeConfig(start_date, end_date)) hook = filter_by_date.FilterByDateHook(DateRangeConfig(start_date, end_date))
hook.run(entry_data) hook.run(entry_data)
assert bool(entry_data) == allowed assert entry_data.get('_hook_cancel', False) == (not allowed)
class DefaultDateConfig: class DefaultDateConfig:
ONE_DAY = datetime.timedelta(days=1) ONE_DAY = datetime.timedelta(days=1)