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

View File

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