filters: Add filter_meta_match function.
This commit is contained in:
parent
26762e11ef
commit
4420873c96
2 changed files with 27 additions and 0 deletions
|
@ -14,10 +14,14 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
import re
|
||||
|
||||
from . import data
|
||||
|
||||
from typing import (
|
||||
Iterable,
|
||||
Pattern,
|
||||
Union,
|
||||
)
|
||||
from .beancount_types import (
|
||||
MetaKey,
|
||||
|
@ -25,6 +29,7 @@ from .beancount_types import (
|
|||
)
|
||||
|
||||
Postings = Iterable[data.Posting]
|
||||
Regexp = Union[str, Pattern]
|
||||
|
||||
def filter_meta_equal(postings: Postings, key: MetaKey, value: MetaValue) -> Postings:
|
||||
for post in postings:
|
||||
|
@ -33,3 +38,11 @@ def filter_meta_equal(postings: Postings, key: MetaKey, value: MetaValue) -> Pos
|
|||
yield post
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def filter_meta_match(postings: Postings, key: MetaKey, regexp: Regexp) -> Postings:
|
||||
for post in postings:
|
||||
try:
|
||||
if re.search(regexp, post.meta[key]):
|
||||
yield post
|
||||
except (KeyError, TypeError):
|
||||
pass
|
||||
|
|
|
@ -81,3 +81,17 @@ def test_filter_meta_equal(cc_txn_pair, key, value, expected_indexes):
|
|||
postings = data.Posting.from_entries(cc_txn_pair)
|
||||
actual = filters.filter_meta_equal(postings, key, value)
|
||||
check_filter(actual, cc_txn_pair, expected_indexes)
|
||||
|
||||
@pytest.mark.parametrize('key,regexp,expected_indexes', [
|
||||
('entity', '^Smith-', range(5)),
|
||||
('receipt', r'\.pdf$', range(5)),
|
||||
('receipt', 'Receipt', range(3)),
|
||||
('statement', '.', [4]),
|
||||
('metadate', 'foo', ()),
|
||||
('BadKey', '.', ()),
|
||||
('emptykey', '.', ()),
|
||||
])
|
||||
def test_filter_meta_match(cc_txn_pair, key, regexp, expected_indexes):
|
||||
postings = data.Posting.from_entries(cc_txn_pair)
|
||||
actual = filters.filter_meta_match(postings, key, regexp)
|
||||
check_filter(actual, cc_txn_pair, expected_indexes)
|
||||
|
|
Loading…
Reference in a new issue