small refactor

This commit is contained in:
Balakrishnan Balasubramanian 2023-06-11 20:14:50 -04:00
parent 12ac18a03e
commit 9e8a5c0c2e
2 changed files with 22 additions and 19 deletions

View File

@ -51,7 +51,11 @@ class Config(Jata):
matches: list[Match]
def parse_rules(cfg: Config) -> list[tuple[str, Callable[[str], bool], bool]]:
CheckerFn = Callable[[str], bool]
Checker = tuple[str, CheckerFn, bool]
def parse_checkers(cfg: Config) -> list[Checker]:
def make_match_fn(m: Match):
if m.addrs and m.addr_rexs:
@ -71,27 +75,26 @@ def parse_rules(cfg: Config) -> list[tuple[str, Callable[[str], bool], bool]]:
}
matches[DEFAULT_MATCH_ALL] = lambda _: True
def flat_rules():
for mbox in cfg.boxes:
for rule in mbox.rules:
rule = Rule(rule)
def make_checker(mbox_name: str, rule: Rule) -> Checker:
fn = matches[rule.match_name]
if rule.negate:
match_fn = lambda malias, fn=fn: not fn(malias)
match_fn = lambda malias: not fn(malias)
else:
match_fn = fn
yield (mbox.name, match_fn, rule.stop_check)
return mbox_name, match_fn, rule.stop_check
return list(flat_rules())
return [
make_checker(mbox.name, Rule(rule)) for mbox in cfg.boxes
for rule in mbox.rules
]
def get_mboxes(
addr: str, rules: list[tuple[str, Callable[[str], bool],
bool]]) -> list[str]:
def get_mboxes(addr: str, checks: list[Checker]) -> list[str]:
def inner():
for mbox, match_fn, stop_check in rules:
for mbox, match_fn, stop_check in checks:
if match_fn(addr):
if mbox != DEFAULT_NULL_MBOX:
yield mbox
if stop_check:
return

View File

@ -61,12 +61,12 @@ class TestConfig(unittest.TestCase):
def test_parse_rules(self) -> None:
cfg = config.Config(TEST_CONFIG)
op = config.parse_rules(cfg)
op = config.parse_checkers(cfg)
self.assertEqual(len(op), 3)
def test_get_mboxes(self) -> None:
cfg = config.Config(TEST_CONFIG)
rules = config.parse_rules(cfg)
rules = config.parse_checkers(cfg)
self.assertEqual(config.get_mboxes("foo@bar.com", rules), ['spam'])
self.assertEqual(config.get_mboxes("foo@mydomain.com", rules), ['all'])
self.assertEqual(config.get_mboxes("first.last@mydomain.com", rules),