Something went wrong. Try again.
Classic Unix mailbox files for Zig 0.16: an iterator to read, a predicate to delete, an atomic rewrite for every change.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us># SPDX-License-Identifier: MIT
"""Does anything else agree about where these messages start and stop?
mbox has no specification and four incompatible variants, so the only claimworth making about a mailbox this library wrote is that other software readsit -- and the only claim worth making about its reader is that it agrees withother software about mailboxes *they* wrote. Both directions are checked here,against the two second opinions that are actually deployed: procmail's`formail`, which is the splitter every mail script on earth reaches for, andPython's `mailbox` module, which is the most widely installed implementationof this format there is.
Each fixture pins a difference rather than a convenience. A body line thatwould be a boundary if it were not quoted is the whole reason the quotingexists; a message with no trailing newline is the one thing an mbox cannotstore faithfully; and a message whose body already contains `>From` is whattells mboxo and mboxrd apart.
This needs no virtual machine, which is worth saying because the siblingprojects' interoperability tests do: what is being tested here is two programsand a file, not a daemon, a user database or a network."""
import mailboximport subprocessimport sysimport tempfilefrom pathlib import Path
MBOX = sys.argv[1] if len(sys.argv) > 1 else "zig-mbox"FORMAIL = sys.argv[2] if len(sys.argv) > 2 else "formail"
failures = []
def check(name, got, want): if got == want: print(f"ok {name}") else: print(f"FAIL {name}\n got {got!r}\n want {want!r}") failures.append(name)
def run(*args, stdin=None): return subprocess.run( [MBOX, *args], input=stdin, capture_output=True, check=True ).stdout
def formail_count(path): """How many messages `formail -s` splits this mailbox into.""" out = subprocess.run( [FORMAIL, "-s", "sh", "-c", "cat >/dev/null; echo ."], stdin=open(path, "rb"), capture_output=True, check=True, ).stdout return out.count(b".")
# The messages, and why each one is here.FIXTURES = [ ("alice@example.com", "Subject: plain\n\nnothing unusual here\n"), # The line that would end this message early if it were stored as written. ("bob@example.net", "Subject: quoting\n\na line\nFrom the top of the body\n"), # Already quoted by whoever wrote it: what mboxo loses and mboxrd keeps. ("carol@example.org", "Subject: requoting\n\n>From a quoted line\n"), # The one thing a file of lines cannot hold as given. ("dave@example.com", "Subject: ragged\n\nno trailing newline"), # Nothing but headers. ("erin@example.net", "Subject: headers only\n"),]
def main(): tmp = Path(tempfile.mkdtemp())
# -- what this library writes, read by everything else ------------------- ours = tmp / "ours.mbox" for sender, message in FIXTURES: run("append", str(ours), "--sender", sender, "-", stdin=message.encode())
check("zig-mbox reads back what it wrote", len(run("list", str(ours)).splitlines()), len(FIXTURES)) check("formail splits it the same way", formail_count(ours), len(FIXTURES))
theirs = mailbox.mbox(str(ours), create=False) check("python's mailbox splits it the same way", len(theirs), len(FIXTURES)) check( "python reads the senders out of the postmarks", [m.get_unixfrom().split()[1] for m in theirs], [sender for sender, _ in FIXTURES], ) check( "python reads the subjects", [m.get("Subject") for m in theirs], [message.split("\n")[0][len("Subject: "):] for _, message in FIXTURES], ) # The quoted line reaches Python with its `>` still on, because the quoting # is how the message got here in one piece. Python does not undo it; this # library does, which is the difference between the two and is deliberate. check( "the dangerous line is quoted on disk", b"\n>From the top of the body\n" in ours.read_bytes(), True, ) check( "and comes back unquoted from this library", b"\nFrom the top of the body\n" in run("get", str(ours), "2"), True, ) # mboxrd quotes a line that was already quoted, which is what makes it # reversible -- and is exactly what mboxo does not do. check( "an already-quoted line is quoted again", b"\n>>From a quoted line\n" in ours.read_bytes(), True, ) check( "and comes back as the one `>` it had", run("get", str(ours), "3"), b"Subject: requoting\n\n>From a quoted line\n", ) check( "a message with no trailing newline gains exactly one", run("get", str(ours), "4"), b"Subject: ragged\n\nno trailing newline\n", )
# -- what everything else writes, read by this library -------------------- mine = tmp / "theirs.mbox" box = mailbox.mbox(str(mine), create=True) box.lock() for sender, message in FIXTURES: m = mailbox.mboxMessage(message) m.set_unixfrom(f"From {sender} Mon Jan 1 00:00:00 2024") box.add(m) box.flush() box.unlock() box.close()
check( "this library splits python's mailbox the same way", len(run("list", str(mine)).splitlines()), len(FIXTURES), ) check("formail agrees about python's mailbox too", formail_count(mine), len(FIXTURES)) # Python quotes mboxo-style -- a bare `From ` gains a `>`, and a line that # already had one is left alone -- so that is the variant its mailbox has # to be read as. Reading it as mboxrd would take a `>` off a line the # sender wrote, which is the whole difference between the two. check( "python's quoting is undone when read as the variant python wrote", b"\nFrom the top of the body\n" in run("get", str(mine), "2", "--variant", "mboxo"), True, ) check("and nothing in it is reported as damaged", run("check", str(mine)).count(b"0 complaints"), 1)
if failures: print(f"\n{len(failures)} of these did not hold: {', '.join(failures)}") return 1 print("\nall of it holds") return 0
if __name__ == "__main__": sys.exit(main())