From b41a7a99af17a81d31f6c37296dc8b0f2a7b8016 2017-12-19 14:13:44 From: Brett Smith Date: 2017-12-19 14:13:44 Subject: [PATCH] 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. --- diff --git a/CODE.rst b/CODE.rst index 20a95afe6c77af0ec2c8cf1245c24c69de3311ef..803aa9eb67f4e985fb7d8b7715a4fcc7775e803d 100644 --- a/CODE.rst +++ b/CODE.rst @@ -51,7 +51,7 @@ Hooks make arbitrary transformations to entry data dicts. Every entry data dict Initializes the hook with the user's configuration. ``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 ~~~~~~~~~ diff --git a/import2ledger/__main__.py b/import2ledger/__main__.py index 7520fd5aa58b1d8b71fea14bd4e2f144f9e0028e..76fb9210209f8002c30addbf68e00bfb4d45d5f1 100644 --- a/import2ledger/__main__.py +++ b/import2ledger/__main__.py @@ -41,11 +41,13 @@ class FileImporter: default_date = self.config.get_default_date() in_file.seek(0) for entry_data in importer(in_file): + entry_data['_hook_cancel'] = False for hook in self.hooks: hook.run(entry_data) - if not entry_data: + if entry_data['_hook_cancel']: break else: + del entry_data['_hook_cancel'] print(template.render(**entry_data), file=out_file, end='') def import_path(self, in_path): diff --git a/import2ledger/hooks/filter_by_date.py b/import2ledger/hooks/filter_by_date.py index c7dab317c66cfe5e6ef605e7fdcf033ec5a3db4c..4c0883033c68080c8cbcb6bded31493c3c7ca685 100644 --- a/import2ledger/hooks/filter_by_date.py +++ b/import2ledger/hooks/filter_by_date.py @@ -9,4 +9,4 @@ class FilterByDateHook: pass else: if not self.config.date_in_want_range(date): - entry_data.clear() + entry_data['_hook_cancel'] = True diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 583453e9c3e18f56e0e293fc0980b877314f3f0a..e30632a6e2d41f72d7bd8e11f82f8f46ace08617 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -58,7 +58,7 @@ def test_filter_by_date(entry_date, start_date, end_date, allowed): entry_data = {'date': entry_date} hook = filter_by_date.FilterByDateHook(DateRangeConfig(start_date, end_date)) hook.run(entry_data) - assert bool(entry_data) == allowed + assert entry_data.get('_hook_cancel', False) == (not allowed) class DefaultDateConfig: ONE_DAY = datetime.timedelta(days=1)