diff options
| author | Danilo M. <danix@danix.xyz> | 2026-11-16 12:24:22 +0100 |
|---|---|---|
| committer | Danilo M. <danix@danix.xyz> | 2026-11-16 12:24:22 +0100 |
| commit | 227258a199283089ec16e4798988277cf5062e67 (patch) | |
| tree | 66500eb7a9f84b2ab85c3bbf1ab1c771c4eb48dd | |
| parent | 21da4ee6c225d2b0b04fc51e17f39f446740a35a (diff) | |
| download | qtmaildir-227258a199283089ec16e4798988277cf5062e67.tar.gz qtmaildir-227258a199283089ec16e4798988277cf5062e67.zip | |
feat(hooks): let a rule move new mail to spam or trash
A rule may carry "move": "spam" | "trash", an account role rather than a
folder name. The post-new hook moves each matching tag:new message into
its own account's configured folder under a fresh Maildir name in cur/,
records the renames with one notmuch new --no-hooks, then tags +spam or
+deleted, -inbox and the account-relative moved-from: origin. unread is
never touched. A message with several files, in no account, or whose
account has no folder for the role is logged and left alone, and a
configured folder that does not exist is never created.
Also fixes _quote, which escaped quotes with a backslash notmuch does not
honour, so an id holding a quote matched nothing on the carve-out path.
Item 214.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rwxr-xr-x | assets/hooks/mailrules.py | 24 | ||||
| -rwxr-xr-x | assets/hooks/post-new | 182 | ||||
| -rwxr-xr-x | assets/hooks/qtmaildirconf.py | 29 | ||||
| -rwxr-xr-x | assets/hooks/test_mailrules.py | 47 | ||||
| -rwxr-xr-x | assets/hooks/test_post_new.py | 269 | ||||
| -rwxr-xr-x | assets/hooks/test_qtmaildirconf.py | 20 |
6 files changed, 562 insertions, 9 deletions
diff --git a/assets/hooks/mailrules.py b/assets/hooks/mailrules.py index dbb80a5..e96e0ad 100755 --- a/assets/hooks/mailrules.py +++ b/assets/hooks/mailrules.py @@ -41,7 +41,12 @@ DEFAULT_STAGE = 50 # Fields this version understands. Anything else in a rule object is kept in # `unknown` and written back untouched, which is what makes the file neutral # rather than this tool's file that another program may read. -KNOWN_KEYS = {"id", "stage", "enabled", "add", "remove", "query", "note"} +KNOWN_KEYS = {"id", "stage", "enabled", "add", "remove", "query", "note", + "move"} + +# What `move` may say. Mirrors qtmaildirconf.MOVE_ROLES and the C++ reader; +# see "Changing the rule format" in AGENTS.md. +MOVE_ROLES = ("spam", "trash") # An id is a handle, not a display name: a UI selects on it and a diff tracks # it. Tags may contain '/' and may be renamed; ids may not. @@ -54,6 +59,7 @@ class Rule: query: str add: list = field(default_factory=list) remove: list = field(default_factory=list) + move: str = "" stage: int = DEFAULT_STAGE enabled: bool = True note: str = "" @@ -194,6 +200,9 @@ def _rule_to_dict(rule): "query": rule.query, "note": rule.note, } + # Only when set, so a file with no moves is byte-identical after a save. + if rule.move: + out["move"] = rule.move out.update(rule.unknown) return out @@ -236,9 +245,17 @@ def _parse_rule(obj, index, seen, warnings): add = [t for t in obj.get("add", []) if isinstance(t, str) and t.strip()] remove = [t for t in obj.get("remove", []) if isinstance(t, str) and t.strip()] - if not add and not remove: + + move = obj.get("move", "") + if move and move not in MOVE_ROLES: + warnings.append( + f"rule '{rule_id}': move '{move}' is not spam or trash; " + f"ignoring the move") + move = "" + + if not add and not remove and not move: warnings.append( - f"rule '{rule_id}': adds and removes nothing; dropped") + f"rule '{rule_id}': adds, removes and moves nothing; dropped") return None try: @@ -254,6 +271,7 @@ def _parse_rule(obj, index, seen, warnings): query=query, add=add, remove=remove, + move=move, stage=stage, enabled=bool(obj.get("enabled", True)), note=obj.get("note", "") if isinstance(obj.get("note", ""), str) else "", diff --git a/assets/hooks/post-new b/assets/hooks/post-new index cad566c..f05712f 100755 --- a/assets/hooks/post-new +++ b/assets/hooks/post-new @@ -33,8 +33,12 @@ Install: copy to <database.path>/.notmuch/hooks/post-new, with mailrules.py importable (same directory, or on PYTHONPATH). """ +import itertools +import os +import socket import subprocess import sys +import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -74,8 +78,14 @@ def log(message): def _quote(value): - """Escape a Message-ID for a double-quoted notmuch term.""" - return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + """A Message-ID as a double-quoted notmuch term. + + The quote is DOUBLED. notmuch has no backslash escape inside a quoted + term, so the old backslash form matched nothing for an id holding a + quote, measured, and such a message was never moved or carved out. Same + rule as SearchTerm::quote() in the application. + """ + return '"' + value.replace('"', '""') + '"' def not_arrival_only(query, folders): @@ -255,6 +265,157 @@ def run_tag(arguments, query): return True +_counter = itertools.count(1) + + +def fresh_name(old_name): + """A fresh, unique Maildir filename keeping `old_name`'s flags suffix. + + Port of MaildirName::fresh() in the application, and for its reason: the + `,U=<n>` infix mbsync writes is meaningful only within one folder, and + carrying it across a folder boundary produced `Maildir error: duplicate + UID` on real mail (item 162). A file coming from new/ has no `:2,` yet; + it gets an empty one, since it is going into cur/. + """ + sep = old_name.find(":2,") + info = old_name[sep:] if sep >= 0 else ":2," + host = (socket.gethostname() or "localhost").replace("/", "_") \ + .replace(":", "_") + now = time.time() + return (f"{int(now)}.M{int(now * 1000) % 1000}P{os.getpid()}" + f"Q{next(_counter)}.{host}{info}") + + +def account_of(path, root, pairs): + """The (maildir, folder) pair whose account holds `path`, or None. + + Longest maildir wins, so an account nested inside another's directory + resolves to itself. Compared as paths, never with startswith. + """ + best = None + for maildir, folder in pairs: + if _within(path, root / maildir) and ( + best is None or len(maildir) > len(best[0])): + best = (maildir, folder) + return best + + +def origin_of(path, root, maildir): + """The folder `path` sits in, relative to its ACCOUNT, without cur/new. + + The format MainWindow::originTagFor() writes and Restore reads: + `acct/Inbox/new/x` is `Inbox`. + """ + parts = path.parent.relative_to(root / maildir).parts + if parts and parts[-1] in ("cur", "new"): + parts = parts[:-1] + return "/".join(parts) + + +def apply_moves(rules): + """Move what each move rule matches into its account's role folder. + + True when done, including when there was nothing to do. False when a + notmuch step failed, so the caller leaves tag:new in place. A message + that cannot be moved (several files, no account, no folder for the role, + a failed rename) is logged and left where it is; that is not a failure. + """ + claimed = {} + for rule in rules: + if not rule.move: + continue + ids = search(mailrules.scoped_query(rule, SCOPE), "messages") + if ids is None: + return False + for message_id in ids: + if message_id in claimed: + log(f"rule '{rule.id}': {message_id} already claimed by " + f"rule '{claimed[message_id].id}'") + continue + claimed[message_id] = rule + + if not claimed: + return True + + root = mail_root() + if root is None: + log("no mail root; moving nothing") + return False + + pairs = {role: qtmaildirconf.role_folders(role) + for role in qtmaildirconf.MOVE_ROLES} + + to_tag = [] + renamed = False + for message_id, rule in claimed.items(): + paths = search(f"id:{_quote(message_id)}", "files") + if paths is None: + return False + if len(paths) != 1: + log(f"rule '{rule.id}': {message_id} has {len(paths)} files; " + f"not moved") + continue + + source = Path(paths[0]) + account = account_of(source, root, pairs[rule.move]) + if account is None or not account[1]: + log(f"rule '{rule.id}': {message_id} is in no account with a " + f"{rule.move} folder; not moved") + continue + + maildir, folder = account + target = root / maildir / folder + if _within(source, target): + to_tag.append((message_id, rule.move, "")) + continue + + # The configured folder must already exist. Creating it is how a + # mistyped name reaches the server (item 103); cur/ inside a real + # folder is safe to create. + if not target.is_dir(): + log(f"rule '{rule.id}': {target} does not exist; not moved") + continue + + origin = origin_of(source, root, maildir) + try: + (target / "cur").mkdir(exist_ok=True) + os.rename(source, target / "cur" / fresh_name(source.name)) + except OSError as exc: + log(f"rule '{rule.id}': cannot move {message_id}: {exc}") + continue + renamed = True + to_tag.append((message_id, rule.move, origin)) + + if renamed: + # Records each rename against the message id it already has, so the + # tags survive and no new.tags apply. --no-hooks, or this hook would + # run itself. + # + # ponytail: this also indexes any file that landed after the outer + # `notmuch new`, and the closing `-new` then consumes its marker + # unseen by the rules. Under mailsync.sh mbsync has finished and the + # lock is held, so nothing lands. If the hook ever runs beside a live + # mbsync, scope the closing `-new` to the ids seen before this call. + result = subprocess.run(["notmuch", "new", "--no-hooks", "--quiet"], + capture_output=True, text=True) + if result.returncode != 0: + log(f"notmuch new after moving failed: {result.stderr.strip()}") + return False + + for message_id, role, origin in to_tag: + # What Mark spam and Delete add, minus `unread`: the hook still never + # removes that unattended (PROTECTED_REMOVALS). + arguments = ["+spam" if role == "spam" else "+deleted", "-inbox"] + if origin: + arguments.append(f"+moved-from:{origin}") + if not run_tag(arguments, f"id:{_quote(message_id)}"): + return False + + log(f"moved {sum(1 for _, _, o in to_tag if o)} message(s), " + f"tagged {len(to_tag)}") + return True + + def main(): store = mailrules.load() @@ -278,7 +439,7 @@ def main(): for warning in store.warnings: log(warning) - applied = 0 + applied = [] for rule in mailrules.ordered(store.rules): # Skip the rule, do not abort the run. A single over-reaching rule # must not cost the tagging every other rule would have done, and @@ -291,11 +452,20 @@ def main(): f"skipped, this hook does not remove those unattended") continue + # A move-only rule has no tag operations, and `notmuch tag` with none + # is an error, so it skips straight to the moves below. + arguments = mailrules.tag_arguments(rule) query = mailrules.scoped_query(rule, SCOPE) - if not run_tag(mailrules.tag_arguments(rule), query): + if arguments and not run_tag(arguments, query): log(f"rule '{rule.id}' failed; leaving tag:new in place") return 1 - applied += 1 + applied.append(rule) + + # After every tag stage, so a later rule still sees mail in its arrival + # folder; before the marker goes, because the marker scopes the moves. + if not apply_moves(applied): + log("moving failed; leaving tag:new in place") + return 1 # AFTER the rules and BEFORE the marker is consumed. After, so a rule can # still see its own non-arrival mail with `inbox` on it and match the way @@ -310,7 +480,7 @@ def main(): if not run_tag(["-new"], SCOPE): return 1 - log(f"applied {applied} rule(s)") + log(f"applied {len(applied)} rule(s)") return 0 diff --git a/assets/hooks/qtmaildirconf.py b/assets/hooks/qtmaildirconf.py index 882c94a..5238fa0 100755 --- a/assets/hooks/qtmaildirconf.py +++ b/assets/hooks/qtmaildirconf.py @@ -139,3 +139,32 @@ def _quote(value): reason. """ return value.replace("\\", "\\\\").replace('"', '\\"') + + +# The folders a rule may MOVE mail into, by role. A rule names a role, never a +# folder: a folder name that does not exist is created by the move and reaches +# the server (item 103), and a role resolves per account, so one rule serves +# mail from every account. +MOVE_ROLES = ("spam", "trash") + + +def role_folders(role, path=None): + """Every account's (maildir, folder) pair for a move role. + + Every account naming a maildir is listed, with an EMPTY folder when it + has none for the role. Leaving it out would let an account nested inside + another's directory resolve to the enclosing account and move its mail + into a folder that belongs to someone else. `spam` and `trash` are + mandatory to the application, which warns about a missing one; here a + missing one just means that account's mail is not moved. + """ + if path is None: + path = default_path() + + pairs = [] + for _key, section in _accounts(path): + maildir = section.get("maildir", "").strip() + folder = section.get(role, "").strip() + if maildir: + pairs.append((maildir, folder)) + return pairs diff --git a/assets/hooks/test_mailrules.py b/assets/hooks/test_mailrules.py index b1f31c9..6613fc0 100755 --- a/assets/hooks/test_mailrules.py +++ b/assets/hooks/test_mailrules.py @@ -266,6 +266,53 @@ def test_tag_arguments(): assert mailrules.tag_arguments(rule) == ["+one", "+two", "-three"] +def test_a_move_rule_loads_and_round_trips(): + with tempfile.TemporaryDirectory() as tmp: + path = write_rules(tmp, {"version": 1, "rules": [ + {"id": "junk", "query": "from:spammer@example.net", + "move": "spam"}]}) + store = mailrules.load(path) + assert store.warnings == [], store.warnings + # A move-only rule is a rule: it adds and removes nothing. + assert [r.id for r in store.rules] == ["junk"] + assert store.rules[0].move == "spam" + assert "move" not in store.rules[0].unknown + mailrules.save(store, path) + assert json.loads(path.read_text())["rules"][0]["move"] == "spam" + + +def test_a_rule_without_a_move_writes_no_move_key(): + """Absent stays absent. Writing `"move": ""` on every rule would rewrite + every file either reader saves, a diff nobody made.""" + with tempfile.TemporaryDirectory() as tmp: + path = write_rules(tmp, {"version": 1, "rules": [ + {"id": "x", "add": ["x"], "query": "from:a@example.com"}]}) + mailrules.save(mailrules.load(path), path) + assert "move" not in json.loads(path.read_text())["rules"][0] + + +def test_an_unknown_move_role_is_ignored_and_the_tags_still_apply(): + """The hook must never guess a destination, and must not lose the rule's + harmless tagging over it either.""" + with tempfile.TemporaryDirectory() as tmp: + path = write_rules(tmp, {"version": 1, "rules": [ + {"id": "odd", "add": ["x"], "query": "from:a@example.com", + "move": "Archive"}]}) + store = mailrules.load(path) + assert store.rules[0].move == "" + assert store.rules[0].add == ["x"] + assert len(store.warnings) == 1 and "Archive" in store.warnings[0] + + +def test_a_rule_whose_only_action_is_a_bad_move_is_dropped(): + with tempfile.TemporaryDirectory() as tmp: + path = write_rules(tmp, {"version": 1, "rules": [ + {"id": "odd", "query": "from:a@example.com", "move": "archive"}]}) + store = mailrules.load(path) + assert store.rules == [] + assert len(store.warnings) == 2, store.warnings + + def run_all(): for name, fn in sorted(globals().items()): if name.startswith("test_") and callable(fn): diff --git a/assets/hooks/test_post_new.py b/assets/hooks/test_post_new.py index 074bf24..c58613c 100755 --- a/assets/hooks/test_post_new.py +++ b/assets/hooks/test_post_new.py @@ -31,6 +31,7 @@ Run: ./test_post_new.py (requires notmuch on PATH) import json import os +import shutil import subprocess import tempfile from pathlib import Path @@ -497,6 +498,274 @@ def test_no_qtmaildir_config_leaves_every_tag_alone(): assert count(env, "tag:inbox") == 4 +def setup_move(tmp): + """Two accounts with spam folders, one also with a trash folder, and + mail from a spammer in both inboxes beside one real message. + + Account two names no trash folder on purpose: a trash rule must leave its + mail alone rather than invent one. + """ + root = Path(tmp) / "Mail" + for sub in ("acct-one/Inbox", "acct-one/Spam", "acct-one/Trash", + "acct-two/Inbox", "acct-two/[Provider]/Spam"): + for part in ("new", "cur", "tmp"): + (root / sub / part).mkdir(parents=True) + + make_message(root / "acct-one/Inbox", "junk-one", + "spammer@example.net", "buy now") + make_message(root / "acct-one/Inbox", "keep-one", + "friend@example.org", "hello") + make_message(root / "acct-two/Inbox", "junk-two", + "spammer@example.net", "buy again") + + config = Path(tmp) / "notmuch-config" + config.write_text( + f"[database]\npath={root}\n\n" + f"[new]\ntags=new;unread;inbox\n\n" + f"[user]\nname=Test\nprimary_email=you@example.org\n") + + env = dict(os.environ) + env["NOTMUCH_CONFIG"] = str(config) + env["XDG_CONFIG_HOME"] = str(Path(tmp) / "config") + + conf = Path(env["XDG_CONFIG_HOME"]) / "qtmaildir" / "qtmaildir.conf" + conf.parent.mkdir(parents=True) + conf.write_text( + "[account.one]\nmaildir = acct-one\nspam = Spam\ntrash = Trash\n" + "[account.two]\nmaildir = acct-two\nspam = [Provider]/Spam\n") + + subprocess.run(["notmuch", "new"], env=env, capture_output=True, + check=True) + return env, root + + +SPAM_RULE = {"id": "junk", "query": "from:spammer@example.net", + "move": "spam"} + + +def names(folder): + return sorted(p.name for p in folder.iterdir()) + + +def test_the_hook_can_move_when_notmuch_new_itself_runs_it(): + """The design's one unverified assumption: that `notmuch new --no-hooks` + can run INSIDE post-new, because the outer `notmuch new` has released the + write lock by the time it calls the hook. Every other test runs the hook + directly and cannot see this. If it fails, stop: the fallback (moving from + mailsync.sh instead) is a design change for the user.""" + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + write_rules(env, [SPAM_RULE]) + + hooks = root / ".notmuch" / "hooks" + hooks.mkdir(parents=True) + os.symlink(HOOK, hooks / "post-new") + + make_message(root / "acct-one/Inbox", "junk-three", + "spammer@example.net", "and again") + result = subprocess.run(["notmuch", "new"], env=env, + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + assert count(env, "tag:spam") == 3, result.stderr + assert count(env, "tag:new") == 0 + assert names(root / "acct-one/Inbox/new") == ["keep-one"] + + +def test_a_move_rule_puts_spam_in_each_accounts_own_spam_folder(): + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + write_rules(env, [SPAM_RULE]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + + # The files moved, each into ITS account's folder, under fresh names + # in cur/ carrying a flags suffix. + assert names(root / "acct-one/Inbox/new") == ["keep-one"] + assert names(root / "acct-two/Inbox/new") == [] + one = names(root / "acct-one/Spam/cur") + two = names(root / "acct-two/[Provider]/Spam/cur") + assert len(one) == 1 and len(two) == 1, (one, two) + assert one[0] != "junk-one" and one[0].endswith(":2,") + + # notmuch followed the rename and kept the message, not a fresh copy. + assert files(env, 'path:"acct-one/Spam/**"') == 1 + assert files(env, 'path:"acct-two/[Provider]/Spam/**"') == 1 + assert files(env, 'path:"acct-one/Inbox/**"') == 1 + + assert count(env, "tag:spam") == 2 + assert count(env, "tag:spam and tag:inbox") == 0 + # unread is the protection that reaches the server; it stays. + assert count(env, "tag:spam and tag:unread") == 2 + # Account-relative, the format Restore reads. + assert count(env, 'tag:"moved-from:Inbox"') == 2 + assert count(env, "tag:new") == 0 + assert count(env, "id:keep-one@example.org and tag:inbox") == 1 + + +def test_a_trash_rule_skips_an_account_with_no_trash_folder(): + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + write_rules(env, [dict(SPAM_RULE, move="trash")]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + + assert len(names(root / "acct-one/Trash/cur")) == 1 + assert count(env, "id:junk-one@example.org and tag:deleted") == 1 + assert count(env, "id:junk-one@example.org and tag:spam") == 0 + + assert names(root / "acct-two/Inbox/new") == ["junk-two"] + assert count(env, "id:junk-two@example.org and tag:inbox") == 1 + assert count(env, "id:junk-two@example.org and tag:deleted") == 0 + assert "not moved" in result.stderr + + +def test_the_first_move_rule_in_stage_order_wins(): + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + write_rules(env, [ + dict(SPAM_RULE, id="late", stage=50), + dict(SPAM_RULE, id="early", stage=10, move="trash"), + ]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + + assert len(names(root / "acct-one/Trash/cur")) == 1 + assert names(root / "acct-one/Spam/cur") == [] + assert "claimed" in result.stderr + + +def test_a_message_with_two_files_is_not_moved(): + """Item 166's shape: one Message-ID, a file in each account. One message + cannot carry two origins, so it is left where it is and logged.""" + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + shutil.copy(root / "acct-one/Inbox/new/junk-one", + root / "acct-two/Inbox/new/junk-one-copy") + subprocess.run(["notmuch", "new"], env=env, capture_output=True, + check=True) + write_rules(env, [SPAM_RULE]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + + assert "junk-one" in names(root / "acct-one/Inbox/new") + assert "junk-one-copy" in names(root / "acct-two/Inbox/new") + assert count(env, "id:junk-one@example.org and tag:spam") == 0 + assert "2 files" in result.stderr + + +def test_a_file_already_in_the_spam_folder_is_tagged_not_renamed(): + """Mail a provider filed itself, and the retry after a run whose rename + succeeded and whose tagging failed. Tagged, with no origin to record.""" + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + make_message(root / "acct-one/Spam", "already", + "spammer@example.net", "filed by the provider") + subprocess.run(["notmuch", "new"], env=env, capture_output=True, + check=True) + write_rules(env, [SPAM_RULE]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + + assert names(root / "acct-one/Spam/new") == ["already"] + assert count(env, "id:already@example.org and tag:spam") == 1 + assert count(env, "id:already@example.org and tag:inbox") == 0 + tags = subprocess.run( + ["notmuch", "search", "--output=tags", "id:already@example.org"], + env=env, capture_output=True, text=True, check=True).stdout + assert "moved-from:" not in tags, tags + + +def test_a_rule_skipped_for_a_protected_removal_moves_nothing(): + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + write_rules(env, [dict(SPAM_RULE, remove=["unread"])]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + assert names(root / "acct-one/Spam/cur") == [] + + +def test_a_nested_account_without_the_role_is_not_moved_into_its_parent(): + """An account whose maildir sits inside another's must resolve to itself. + If it has no trash folder its mail stays put; falling through to the + enclosing account would move it into ANOTHER account's folder, which + mbsync then carries to that account's server.""" + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + nested = root / "acct-one/lists/Inbox" + for part in ("new", "cur", "tmp"): + (nested / part).mkdir(parents=True) + make_message(nested, "junk-nested", "spammer@example.net", "list spam") + conf = Path(env["XDG_CONFIG_HOME"]) / "qtmaildir" / "qtmaildir.conf" + conf.write_text(conf.read_text() + + "[account.lists]\nmaildir = acct-one/lists\n") + subprocess.run(["notmuch", "new"], env=env, capture_output=True, + check=True) + write_rules(env, [dict(SPAM_RULE, move="trash")]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + assert names(nested / "new") == ["junk-nested"] + assert count(env, "id:junk-nested@example.org and tag:deleted") == 0 + # The enclosing account's own mail still moves. + assert len(names(root / "acct-one/Trash/cur")) == 1 + + +def test_a_moved_file_keeps_its_flags_and_loses_its_uid(): + """mbsync delivers read mail into cur/ as `<name>,U=<n>:2,<flags>`. The + flags must survive (losing S marks it unread on the server) and the UID + must not (item 162's duplicate-UID error).""" + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + (root / "acct-one/Inbox/cur/junk-read,U=7:2,FS").write_text( + "From: spammer@example.net\nTo: you@example.org\n" + "Subject: already read\nMessage-Id: <junk-read@example.org>\n" + "Date: Mon, 11 Aug 2026 10:00:00 +0000\n\nbody\n") + subprocess.run(["notmuch", "new"], env=env, capture_output=True, + check=True) + write_rules(env, [SPAM_RULE]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + moved = names(root / "acct-one/Spam/cur") + assert len(moved) == 2, moved + assert sum(1 for n in moved if n.endswith(":2,FS")) == 1, moved + assert not any(",U=" in n for n in moved), moved + + +def test_a_message_id_holding_a_quote_still_moves(): + """notmuch has no backslash escape inside a quoted term; a quote is + DOUBLED. A backslash-escaped id matches nothing, and the message was + logged as having 0 files and left in the inbox.""" + with tempfile.TemporaryDirectory() as tmp: + env, root = setup_move(tmp) + make_message(root / "acct-one/Inbox", 'q"uote', + "spammer@example.net", "quoted id") + subprocess.run(["notmuch", "new"], env=env, capture_output=True, + check=True) + write_rules(env, [SPAM_RULE]) + + result = subprocess.run([str(HOOK)], env=env, capture_output=True, + text=True) + assert result.returncode == 0, result.stderr + assert names(root / "acct-one/Inbox/new") == ["keep-one"], result.stderr + assert len(names(root / "acct-one/Spam/cur")) == 2 + + def run_all(): for name, fn in sorted(globals().items()): if name.startswith("test_") and callable(fn): diff --git a/assets/hooks/test_qtmaildirconf.py b/assets/hooks/test_qtmaildirconf.py index 89565d9..3575d45 100755 --- a/assets/hooks/test_qtmaildirconf.py +++ b/assets/hooks/test_qtmaildirconf.py @@ -190,6 +190,26 @@ def test_a_folder_containing_a_quote_cannot_break_out_of_the_query(): assert "\\\"" in query or '""' in query +def test_role_folders_pair_each_account_with_its_folder(): + with tempfile.TemporaryDirectory() as tmp: + path = write_config(tmp, + "[account.one]\nmaildir = acct-one\nspam = Spam\ntrash = Trash\n" + "[account.two]\nmaildir = acct-two\nspam = [Provider]/Spam\n") + assert qtmaildirconf.role_folders("spam", path) == [ + ("acct-one", "Spam"), ("acct-two", "[Provider]/Spam")] + # acct-two names no trash folder: it is still listed, with an empty + # folder, so a nested account resolves to ITSELF and is skipped rather + # than falling through to the enclosing account's folder. + assert qtmaildirconf.role_folders("trash", path) == [ + ("acct-one", "Trash"), ("acct-two", "")] + + +def test_role_folders_need_a_maildir(): + with tempfile.TemporaryDirectory() as tmp: + path = write_config(tmp, "[account.one]\nspam = Spam\n") + assert qtmaildirconf.role_folders("spam", path) == [] + + def main(): tests = [value for name, value in sorted(globals().items()) if name.startswith("test_") and callable(value)] |
