~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
ci(pre-commit): enforce reserved email domains in source content (#4967)
LearningCircuit1e449b678183
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 124f700d9a..e7c107f9f2 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -139,6 +139,13 @@ repos:always_run: truepass_filenames: falsedescription: "Ensure commits by a declared project author use that author's declared identity"+ - id: check-email-domains+ name: Email domain consistency+ entry: .pre-commit-hooks/check-email-domains.py+ language: script+ always_run: true+ pass_filenames: false+ description: "Emails in source content should use a reserved domain (example.com/.test), a noreply alias, or a declared author"- id: file-whitelist-checkname: File Whitelist Security Checkentry: .pre-commit-hooks/file-whitelist-check.shdiff --git a/.pre-commit-hooks/check-email-domains.py b/.pre-commit-hooks/check-email-domains.pynew file mode 100755index 0000000000..06aca49998--- /dev/null+++ b/.pre-commit-hooks/check-email-domains.py@@ -0,0 +1,1392 @@+#!/usr/bin/env python3+"""Email-domain consistency check.++Email addresses committed to source *content* should use a domain reserved for+examples and tests: an RFC-2606 documentation domain (``example.com`` / ``.org``+/ ``.net`` and subdomains), an RFC-6761 reserved suffix (``.test`` /+``.invalid`` / ``.localhost`` / ``.example``), a GitHub+``@users.noreply.github.com`` alias, a GitHub service address, or an address a+project author declared in ``pyproject.toml``. Keeping fixtures and docs on the+domains reserved for that purpose is good hygiene (and keeps real addresses out+of the tree). This is the content-side companion to ``check-author-identity``,+which applies the same principle to commit metadata.++Internationalized addresses are detected in both encodings — Unicode+(U-label) domains such as ``bücher.example`` and their ASCII punycode+(A-label) form (``xn--`` TLDs), including labels with combining marks,+ASCII-letter-led Latin-extended labels, and mixed-script labels such as+``a中`` / ``中a`` in any label position, the final label included — and+so are explicitly delimited mixed-script local parts, Hiragana local parts,+and RFC 5321 quoted local parts (``"john doe"@…``), Unicode+local parts (``müller@…``) and pure-CJK local parts (``用户@…`` /+``ユーザー@…``). A quoted local part that itself contains an address+yields only the whole address, never a phantom inner match.++Unspaced CJK prose (Han, Hangul, Katakana — like Hiragana) never widens+the FINAL domain label, though a mixed-script label is still recognized+where more domain follows, and as the final label when the label itself+mixes scripts — while the Hiragana block never widens a label anywhere,+explicit delimiters included; a ``,``, ``;`` or ``&`` separator — bare or opening a+``KEY=`` assignment of any label shape — and every other bare+separator (``!``, ``$``, ``(``, ``*``, ``~``, ``'``, ``=``) ends URI+userinfo suppression, so an address separately written on the same line+is still seen (a URI password containing such a separator needs the+allow marker); Python+matrix multiplication between dotted operands (``self.left`` @+``matrix.transpose``) in ``.py``/``.pyi`` files — with string-literal+state tracked across the lines of a multi-line triple-quoted literal,+across backslash-continued ordinary strings, and rebuilt at every hunk+entry from the post-image content rather than assumed to start in code+(when that content cannot be loaded, suppression is dropped for the+file so it fails toward extraction), PEP 701 f-string and Python 3.14 template-string literals —+single- or triple-quoted, including one left open by a raw newline+inside a replacement field or by a backslash inside a field's nested+string — scanned brace-aware so same-quote replacement fields never+flip the parity and hide an address inside the literal — is an+operator rather than an address; and a HiDPI asset basename+(png/svg/webp/gif/jpeg/avif/ico/bmp/tif/apng) may contain ``+``/``%``+and end a sentence (a trailing ``.`` after the extension does not+un-suppress it). Git C-quoted diff paths (``"b/caf\303\251.py"``) are+decoded before suffix checks, keeping the original bytes (surrogate+escapes) so index lookups resolve names that are not valid UTF-8.++It checks only NEWLY-ADDED lines (the ``+`` side of the diff), so existing+content is never re-flagged and no allow-list churn is needed — a new fixture+should simply use a reserved domain (``[email protected]``, ``[email protected]``). For a+line that legitimately needs a non-reserved address (a real support address in+a doc, a security fixture that must use a real host), add the case-insensitive+``email-domains: allow`` substring anywhere on that same line.++- In CI on a pull request, it checks the PR's added lines (``merge-base..head``)+ and reads the allow-list from the *base* ref so a PR cannot authorize an+ address by editing ``pyproject.toml`` in the same change.+- Locally at the pre-commit stage, it checks the staged diff's added lines.++Those two are the only sources of added lines. Outside a ``pull_request``+(or ``pull_request_target``) event — a ``push``, ``merge_group`` or+``workflow_call`` run — and locally with a clean index, the diff is empty,+so the hook has nothing to scan and exits 0 without checking anything. Only+a *failure to resolve* a range fails closed; an absent range is vacuous.++A flagged address and Git command output are not printed, but the affected+repository path is, with the 1-based line number of the offending added line+(``path:line``) so a false positive can be located without the address+appearing in the log. Range-resolution failures fail *closed*.+"""++from __future__ import annotations++import json+import os+import re+import subprocess+import sys+import tomllib+import unicodedata+from bisect import bisect_right+from collections.abc import Callable+from pathlib import Path++NOREPLY_SUFFIX = "@users.noreply.github.com"+GITHUB_SERVICE_ADDRESSES = {"[email protected]", "[email protected]"}+# ``--src-prefix``/``--dst-prefix`` pin the unified-header prefixes: a+# local ``diff.noprefix`` config would emit a ``b/…`` file's real path+# verbatim, the hardcoded ``b/`` strip would then resolve the WRONG+# post-image (a root decoy) and rebuild hunk-entry state from it.+DIFF_FLAGS = (+ "--no-color",+ "--no-ext-diff",+ "--no-textconv",+ "--text",+ "--src-prefix=a/",+ "--dst-prefix=b/",+)++# RFC-2606 reserved second-level domains (documentation/testing).+RESERVED_DOMAINS = {"example.com", "example.org", "example.net"}+# RFC-2606 / RFC-6761 reserved suffixes. ``.example.com`` etc. cover subdomains+# such as ``smtp.example.com``; ``.example`` covers the reserved TLD.+RESERVED_SUFFIXES = (+ ".example.com",+ ".example.org",+ ".example.net",+ ".test",+ ".invalid",+ ".localhost",+ ".example",+)+# Only these GitHub service addresses legitimately appear in clone URLs / CI+# output. Other addresses at github.com are not a safe allow-list category.++# Dependency lockfiles record third-party author emails we neither own nor+# control; they are machine-generated, so checking their added lines only+# surfaces upstream identities. Matched by basename (a lockfile is a lockfile+# wherever it lives).+SKIP_BASENAMES = {+ "package-lock.json",+ "pdm.lock",+ "yarn.lock",+ "pnpm-lock.yaml",+ "poetry.lock",+ "uv.lock",+ "Pipfile.lock",+ "Cargo.lock",+ "Gemfile.lock",+ "composer.lock",+}++# Per-line opt-out marker: a case-insensitive substring anywhere on the added+# line allows a non-reserved address on that line.+ALLOW_MARKER = "email-domains: allow"+++def _combining_mark_fragment() -> str:+ """Regex fragment matching one combining mark (categories Mn/Mc).++ ``re`` has no ``\\p{M}``; derive the ranges from the running+ interpreter's Unicode tables so U-labels containing marks (Devanagari+ matras, Arabic vowel signs, NFD Latin diacritics) match without a+ hand-maintained table. The scan covers the ENTIRE codepoint space:+ combining marks exist far above the BMP (Coptic U+2CEF, Tifinagh+ U+2D7F, Devanagari Extended, adaption marks, variation selectors up+ to U+E01EF), and any lower ceiling would truncate a domain at its+ last below-ceiling character: ``[email protected]`` followed by U+2CEF+ must never be accepted as the bare, reserved-looking+ ``[email protected]``. Marks below U+0300 are spacing symbols, so the+ scan starts there.++ The runs are split at the BMP boundary: a flat class of BMP marks+ compiles to a bitmap, but a single supplementary member flattens the+ whole class into linear range scans. Supplementary marks therefore sit+ behind a coarse plane test that fails in one comparison for any BMP+ character, keeping plain-ASCII scanning as fast as before.++ The class is derived from the RUNNING interpreter's Unicode table, so+ it is exactly as new as that interpreter: a codepoint assigned as a+ mark only in a later UCD is a mark under a newer Python and ordinary+ prose under an older one (U+11F5A is Mn in UCD 16 / Python 3.14 and+ unassigned in UCD 15 / Python 3.12, which this repository also runs).+ That is deliberate — a hand-pinned table would go stale and silently+ truncate domains — but it means the *tests* must pin behaviour to+ codepoints assigned in the OLDEST Unicode table in use, so every+ interpreter in CI agrees.+ """+ runs: list[tuple[int, int]] = []+ run_start = previous = -1+ category = unicodedata.category+ for codepoint in range(0x0300, sys.maxunicode + 1):+ if category(chr(codepoint))[0] != "M":+ continue+ if run_start < 0:+ run_start = previous = codepoint+ elif codepoint == previous + 1:+ previous = codepoint+ else:+ runs.append((run_start, previous))+ run_start = previous = codepoint+ if run_start >= 0:+ runs.append((run_start, previous))++ def _escape(codepoint: int) -> str:+ return (+ f"\\u{codepoint:04X}"+ if codepoint <= 0xFFFF+ else f"\\U{codepoint:08X}"+ )++ # No mark run straddles the BMP boundary today; split anyway so the+ # partition stays exhaustive for any future Unicode table.+ bmp_runs: list[tuple[int, int]] = []+ sup_runs: list[tuple[int, int]] = []+ for low, high in runs:+ if high <= 0xFFFF:+ bmp_runs.append((low, high))+ elif low > 0xFFFF:+ sup_runs.append((low, high))+ else:+ bmp_runs.append((low, 0xFFFF))+ sup_runs.append((0x10000, high))++ def _class_body(runs_list: list[tuple[int, int]]) -> str:+ return "".join(+ _escape(low) if low == high else f"{_escape(low)}-{_escape(high)}"+ for low, high in runs_list+ )++ bmp_class = f"[{_class_body(bmp_runs)}]"+ if not sup_runs:+ return bmp_class+ return (+ rf"(?:{bmp_class}|(?=[\U00010000-\U0010FFFF])"+ rf"[{_class_body(sup_runs)}])"+ )+++# Final domain label, all-ASCII forms: an all-letter TLD ("com", "de") or an+# IDNA A-label ("xn--p1ai"), so the ASCII punycode form of an+# internationalized domain counts as a domain too.+_FINAL_LABEL = (+ r"(?:[A-Za-z]{2,63}"+ r"|[Xx][Nn]--[A-Za-z0-9](?:[A-Za-z0-9-]{0,55}[A-Za-z0-9])?)"+)+_ASCII_DOMAIN = (+ r"(?=[A-Za-z0-9.-]{1,253}(?![A-Za-z0-9-]|\.[A-Za-z0-9-]))"+ r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+"+ + _FINAL_LABEL+ + r"(?![A-Za-z0-9_%+-]|\.[A-Za-z0-9-])"+)++# U-label characters are deliberately partitioned into disjoint classes.+# The previous overlapping ASCII / Unicode alternatives let a failing final+# label lookahead re-split every ASCII character, causing exponential time.+_MARK = _combining_mark_fragment()+_HIRAGANA = r"[\u3041-\u3096]"+# Han, Hangul and Katakana bases (plus CJK signs such as iteration marks+# and Hangzhou numerals): word characters, so without an explicit rule they+# would widen a domain label. Unspaced prose in these scripts glues onto a+# completed address exactly like Hiragana, so a base from this set only+# continues a label that is already CJK-led; after any other base it is+# prose and terminates the domain instead. Ranges are the stable CJK+# letter blocks, including halfwidth kana and supplementary Han.+_CJK_PROSE = (+ r"[\u1100-\u11FF\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303A"+ r"\u3131-\u318F\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97C"+ r"\uAC00-\uD7A3\uF900-\uFAFF\u30A1-\u30FF\uFF66-\uFF9F"+ r"\U00020000-\U0002FA1F\U00030000-\U000323AF]"+)+# Everything the label grammars exclude besides ``_``: the Hiragana block+# (Hiragana prose boundary) and the CJK prose ranges above.+_NOT_PROSE = (+ r"\u3040-\u309F\u1100-\u11FF\u3005-\u3007\u3021-\u3029\u3031-\u3035"+ r"\u3038-\u303A\u3131-\u318F\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFF"+ r"\uA960-\uA97C\uAC00-\uD7A3\uF900-\uFAFF\u30A1-\u30FF\uFF66-\uFF9F"+ r"\U00020000-\U0002FA1F\U00030000-\U000323AF"+)+_NON_H_LABEL_CHAR = rf"(?:[^\W_{_NOT_PROSE}]|-|{_MARK})"+_NON_H_LABEL_EDGE = rf"[^\W_{_NOT_PROSE}]"+# Starts with a letter/digit; may end with a letter/digit or combining mark,+# but never a hyphen. This admits valid labels such as ``q̇``. CJK bases are+# absent from a non-CJK run: they end it (as prose), never widen it.+_NON_CJK_LABEL = (+ rf"(?>{_NON_H_LABEL_EDGE}"+ rf"(?:{_NON_H_LABEL_CHAR}{{0,61}}"+ rf"(?:{_NON_H_LABEL_EDGE}|{_MARK}))?)"+)+_CJK_LABEL = (+ rf"(?>{_CJK_PROSE}"+ rf"(?:(?:{_CJK_PROSE}|{_MARK}){{0,61}}"+ rf"(?:{_CJK_PROSE}|{_MARK}))?)"+)+# A label in a position where more domain must follow may mix scripts+# (``a中`` / ``中a`` round-trip through IDNA to ``xn--`` A-labels), so it+# accepts any word character. Atomic labels keep rejected candidates+# linear; the outer loop remains backtrackable for a trailing domain dot.+# The FINAL label keeps the stricter grammars below first: a CJK base+# directly after an all-ASCII final label is unspaced prose (the+# unspaced-prose rule), never a wider domain.+_MIXED_LABEL = (+ rf"(?>[^\W_]"+ rf"(?:(?:[^\W_]|-|{_MARK}){{0,61}}"+ rf"(?:[^\W_]|{_MARK}))?)"+)+# Mixed-script FINAL label: same shape as ``_MIXED_LABEL`` but required+# to contain a CJK base, so a lone-ASCII-letter TLD cannot slip through+# this door (``foo.a`` stays unmatchable) and pure-Hiragana prose after+# an ASCII base (``foo.aです``) keeps the Hiragana boundary. The Hiragana+# block is subtracted from the class as an explicit code-point range:+# relying on alternative ordering alone kept that boundary only while+# nothing forced backtracking past it, so inside explicit delimiters —+# where the match must reach the closing delimiter — the label widened+# through Hiragana prose (``テストをご確認ください``) and glued the prose+# tail onto the domain as a phantom undeclared address. An explicit+# range cut cannot drift with the interpreter's Unicode tables, unlike+# the ambient ``\w`` membership it replaces.+_MIXED_FINAL_CHAR = rf"(?:[^\W_\u3040-\u309F]|-|{_MARK})"+_MIXED_FINAL_EDGE = r"[^\W_\u3040-\u309F]"+_MIXED_FINAL_LABEL = (+ rf"(?>(?={_MIXED_FINAL_CHAR}{{0,61}}{_CJK_PROSE})"+ rf"{_MIXED_FINAL_EDGE}(?:{_MIXED_FINAL_CHAR}{{0,61}}"+ rf"(?:{_MIXED_FINAL_EDGE}|{_MARK}))?)"+)+_NON_ASCII_LABEL_CHAR = rf"(?:[^\W_\x00-\x7F{_NOT_PROSE}]|{_MARK})"+_IDN_FINAL_LABEL = (+ rf"(?>(?:{_HIRAGANA}+(?:{_CJK_LABEL}|{_NON_CJK_LABEL})"+ rf"|{_HIRAGANA}*{_CJK_LABEL}"+ rf"|{_HIRAGANA}*(?={_NON_H_LABEL_CHAR}{{0,62}}{_NON_ASCII_LABEL_CHAR})"+ rf"{_NON_CJK_LABEL})|{_HIRAGANA}+)"+)++# Whole-domain bound: at most 253 label/dot characters ending at a real+# boundary (RFC 1035), checked once for every extractor below.+_DOMAIN_RUN = rf"(?:[-.]|[^\W_]|{_MARK})"+_DOMAIN_BOUND = (+ rf"(?={_DOMAIN_RUN}{{1,253}}"+ rf"(?!(?:[^\W_]|-|{_MARK})|\.(?:[^\W_]|-|{_MARK})))"+)+# A glued word character (except hiragana prose), %, +, or - is a near miss+# such as ``[email protected]`` rather than an address. A further dotted label+# is likewise not a boundary; ordinary URI and prose delimiters are.+_LABEL_START = rf"(?:[^\W_]|-|{_MARK})"+_FINAL_GUARD = rf"(?!(?:[^\W_{_NOT_PROSE}]|[%_+-])|\.{_LABEL_START})"++# One domain grammar for every email form: any labels, then a final label+# that is a U-label, all-ASCII, or mixed-script. Trying the U-label form+# first prevents phantom ASCII prefixes of mixed Unicode labels; the+# mixed final label is last so ASCII-label-plus-CJK-prose still prefers+# the shorter ASCII domain (the unspaced-prose rule).+_DOMAIN = (+ _DOMAIN_BOUND+ + rf"(?:{_MIXED_LABEL}\.)+"+ + rf"(?:{_IDN_FINAL_LABEL}|{_FINAL_LABEL}|{_MIXED_FINAL_LABEL})"+ + _FINAL_GUARD+)+# Local parts are Unicode-aware (SMTPUTF8-style ``müller@…``): any word+# character outside the CJK prose ranges, the ASCII specials ``._%+-``,+# and combining marks. The lookbehind uses the same class so a Unicode+# local part is never entered mid-token (``ller@…`` must not match when+# the declared author is ``müller``).+_LOCAL_PART_CHAR = rf"(?:[^\W_{_NOT_PROSE}]|[._%+-]|{_MARK})"+# Pure-CJK local parts (``用户@…`` / ``ユーザー@…``) are valid SMTPUTF8+# addresses too. A CJK run is admitted only when it contains no ASCII+# word character: a mixed run (``宛先はuser``) is prose around an ASCII+# address, which the dot-atom branch above already extracts whole.+# Hiragana stays out — the Hiragana prose boundary — so ``宛先はユーザー@…``+# yields ``ユーザー@…`` and nothing wider, and the lookbehind again+# forbids entering the run mid-token.+_CJK_LOCAL_PART = (+ rf"(?>(?<!{_CJK_PROSE}|{_MARK})"+ rf"{_CJK_PROSE}(?:{_CJK_PROSE}|{_MARK}){{0,63}})"+)+# Preserve interior apostrophes and exclamation marks without consuming a quote that+# merely opens a source string. Explicit delimiters below cover complete+# identities with leading punctuation or mixed-script local parts.+_LOCAL_CONTINUATION = rf"(?:{_LOCAL_PART_CHAR}|[!'])"+_HIRAGANA_LOCAL_PART = (+ rf"(?>(?<!{_HIRAGANA}|{_MARK})"+ rf"{_HIRAGANA}(?:{_HIRAGANA}|{_MARK}){{0,63}})"+)+EMAIL_RE = re.compile(+ rf"(?:(?<!{_LOCAL_PART_CHAR}){_LOCAL_PART_CHAR}{_LOCAL_CONTINUATION}{{0,63}}"+ rf"|{_CJK_LOCAL_PART}|{_HIRAGANA_LOCAL_PART})@" + _DOMAIN,+)+# RFC 5321 quoted-string local part ("john doe"@…): a valid address form+# the dot-atom pattern above cannot see.+QUOTED_EMAIL_RE = re.compile(r'"(?:[^"\\\n]|\\.){1,64}"@' + _DOMAIN)+++# Angle brackets, quotes and Markdown code delimiters make the full address+# boundary explicit. Within them, Unicode local parts and final labels cannot+# be mistaken for surrounding prose — except that the Hiragana block never+# widens a label even here: a prose tail before the closing delimiter+# (``テストをご確認ください``) is prose, not a longer domain. Keep the+# remaining unspaced-prose rules outside these delimiters, where the text+# is inherently ambiguous.+#+# Two of the delimiters — the apostrophe and the backtick — are themselves+# legal local-part punctuation, so each wrapper DROPS its own character from+# the class it encloses. Otherwise a DOUBLED delimiter reads as delimiter+# plus a one-character local part: a Markdown-quoted decorator written with+# two backticks around "@router.get" parsed as an address whose local part+# was a lone backtick, on the non-reserved domain ``router.get`` — a pure+# false positive on ordinary prose. Tripled and mixed wrappers fall to the+# same rule together with the word-character requirement below: a delimited+# local part must contain at least one ``[^\W_]`` character, so a run of+# pure punctuation is never an identity. Real local parts (``user``,+# ``o'connor``, ``!lead``) all carry one, and the lookahead cannot cross the+# ``@`` that ends the local part, so the character it finds always lies+# inside the local part the class then matches.+_DELIMITED_LOCAL_PUNCTUATION = "._!#$%&'*+/=?^`{|}~-"+_DELIMITED_LOCAL_WORD = r"(?=[^@\n]{0,63}[^\W_])"+++def _delimited_local(wrapper: str) -> str:+ """Delimited local-part pattern, minus ``wrapper``'s own character."""+ punctuation = re.escape(+ "".join(c for c in _DELIMITED_LOCAL_PUNCTUATION if c != wrapper)+ )+ return (+ _DELIMITED_LOCAL_WORD + rf"(?:[^\W_]|[{punctuation}]|{_MARK}){{1,64}}"+ )+++def _delimited_address(wrapper: str) -> str:+ """Delimited address (dot-atom or RFC 5321 quoted) for one wrapper."""+ return (+ rf'(?:{_delimited_local(wrapper)}|"(?:[^"\\\n]|\\.){{1,64}}")@'+ + _DOMAIN+ )+++# The same two delimiters occur INSIDE words (``can't``, a backtick in+# transliteration), where they open nothing. An opening apostrophe or+# backtick preceded by a local-part character is therefore not a delimiter:+# without this, dropping the wrapper from its own class merely moved the+# boundary one word inwards and ``'can'[email protected]'`` re-entered at the+# apostrophe as ``[email protected]``. The bare matcher already guards its local+# part with the same lookbehind. ``<`` and ``"`` are not local-part+# characters, so they keep the RFC 5322 ``Name<addr>`` form.+#+# That blanket rule is too blunt for the one preceding run that is not a+# word continuing into the quote: a Python string prefix. ``f'…'``,+# ``rf'…'``, ``u'…'``, ``b'…'`` all put a local-part character (the+# prefix letter) directly before the quote, so the plain lookbehind+# above also swallowed ``f'{user}@example.com'`` — the prefix, not a+# word, was what preceded the opener. A run of 1-2 letters from+# ``rRbBuUfFtT`` immediately before the quote, itself preceded by+# start-of-line or a non-word character, is therefore still an opener:+# ``_STRING_PREFIX_OPENER`` restates the exclusion as "not preceded by a+# local-part character UNLESS that preceding run is such a prefix".+# Python's ``re`` forbids differently-sized alternatives inside one+# lookbehind, so the three cases are three independent zero-width+# assertions joined by ordinary alternation, each internally fixed-width.+# This does not special-case a JS tagged template+# (``` tag`${u}@corp.example` ```): a tag name can be any identifier+# length, and admitting an opener after an arbitrary identifier would+# undo the ``can't`` guard for every prose word immediately followed by+# a backtick. What this carve-out reaches is narrower than "any address+# led by an interpolation": it only fires when the interpolation opens+# the literal AND the address is the whole literal — nothing before the+# interpolation, nothing after the domain but the closing delimiter.+# Leading text (``f"mailto:{u}@corp.example"``), trailing text+# (``f"{u}@corp.example, cc"``), an interpolation that is not the very+# first thing in the literal, tagged or not+# (``` html`Hi ${u}@corp.example` ```, untagged+# `` `Hi ${u}@corp.example` ``), and a ``str.format()`` call+# (``"{}@corp.example".format(u)``) are all unreported. A literal+# address anywhere in the template (``` tag`[email protected]` ```) is+# still caught by the bare matcher regardless of the tag, since it+# starts its own token right after the backtick. An UNTAGGED template+# opens like any other quote — the backtick itself is preceded by a+# non-local-part character — so `` `${u}@corp.example` `` (interpolation+# leading, filling the whole template) is caught with no carve-out+# needed; a 1-2 letter tag drawn from ``_STRING_PREFIX_CHARS`` reaches+# the same case via the carve-out above+# (``` f`${u}@corp.example` ```); any other tag+# (``` tag`${u}@corp.example` ```) does not.+_STRING_PREFIX_CHARS = "rRbBuUfFtT"+_STRING_PREFIX_OPENER = (+ rf"(?:(?<!{_LOCAL_PART_CHAR})"+ rf"|(?<=[{_STRING_PREFIX_CHARS}])(?<!\w[{_STRING_PREFIX_CHARS}])"+ rf"|(?<=[{_STRING_PREFIX_CHARS}]{{2}})(?<!\w[{_STRING_PREFIX_CHARS}]{{2}})"+ rf")"+)+_INTRAWORD_DELIMITERS = ("'", "`")+DELIMITED_EMAIL_RES = tuple(+ re.compile(+ (_STRING_PREFIX_OPENER if left in _INTRAWORD_DELIMITERS else "")+ + re.escape(left)+ + rf"(?P<email>{_delimited_address(left)})"+ + re.escape(right)+ + r"(?!@)"+ )+ for left, right in (("<", ">"), ('"', '"'), ("'", "'"), ("`", "`"))+)+++def _delimited_email_spans(content: str) -> list[tuple[int, int, str, int]]:+ """Disjoint explicit boundaries, outermost first for nested matches."""+ candidates = sorted(+ (+ (m.start(), m.end(), m.group("email"), m.start("email"))+ for pattern in DELIMITED_EMAIL_RES+ for m in pattern.finditer(content)+ ),+ key=lambda item: (item[0], -item[1]),+ )+ spans: list[tuple[int, int, str, int]] = []+ for start, end, email, address_start in candidates:+ if spans and start < spans[-1][1]:+ continue+ spans.append((start, end, email, address_start))+ return spans+++_URI_HOST = rf"(?:{_MIXED_LABEL}\.)+(?:{_FINAL_LABEL}|{_MIXED_LABEL})"+# RFC 3986 userinfo is pct-encoded, but real-world connection strings+# (MongoDB and friends) put raw "@" characters inside the password+# ("mongodb://admin:p@ss@db…"), so a raw "@" (and the ":" of+# "user:password") is allowed inside the userinfo span; the host still+# has to parse, which anchors the far end. Every other separator — ","+# ";" "&" whether bare or opening a "KEY=" assignment of any label+# length or shape, and bare "!" "$" "(" "*" "~" "'" "=" — ENDS the+# span. Crossing them let the span swallow a separately written real+# address as the URI host: in "postgres://[email protected],victim@…" the+# host parsed as the victim's domain and the hook failed open. The+# price is conscious: a password that itself contains one of those+# separators is no longer suppressed and needs the allow marker.+_URI_USERINFO_ATOM = (+ r"(?:%[0-9A-Fa-f]{2}|\$\{[A-Za-z_][A-Za-z0-9_]*\}|"+ r"[A-Za-z0-9._@:+-])"+)+URI_USERINFO_RE = re.compile(+ r"(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{0,254}://"+ r"(?P<userinfo>(?:"+ + _URI_USERINFO_ATOM+ + r"){1,193})@"+ + _URI_HOST+ + r"(?::[0-9]{1,5})?(?![^\W_.:-])"+)+# Pixel-density assets include fractional scales such as ``@1.5x``. The+# basename may contain ``+``/``%`` and interior ``!``/apostrophes — including+# a Python string-prefix letter and its opening quote, which the prefix+# carve-out above (``_STRING_PREFIX_OPENER``) can also read as opening a+# delimited address whose local part starts a few characters INTO this+# span, not at its start (``u'[email protected]'``: this pattern's own match+# starts at ``u``, but the delimited address it must suppress starts at+# ``i``). The suppression below therefore covers the whole span, not just+# its start offset — a start-only suppression left that inner offset+# unsuppressed and the address was reported. A sentence-final ``.`` right+# after the extension (``Use [email protected].``) is prose punctuation, not a+# longer filename — but a ``.`` followed by more basename characters+# still breaks the asset boundary.+#+# The same prefix carve-out also opens an f-string INTERPOLATED basename+# (``f'{stem}@3x.webp'``, ``f"{name}@2x.png"``): the delimited local part+# there includes ``{``/``}`` (they are legal RFC 5322 local-part+# punctuation, matched by ``_delimited_local`` above), so this pattern's+# own basename class matches them too — otherwise its match could not+# reach far enough left to cover that address's start, and it would stay+# a start-only-style gap even with the full-span fix. A double-quoted+# f-string needs ``"`` (``\x22``, to keep the enclosing raw string simple)+# in that same class for the same reason: only a single quote was needed+# before the prefix carve-out existed to consume it too.+#+# This widening only reaches as far left as the interpolation's own+# braces — neither ``/`` nor ``$`` is in this basename class, so a path+# qualifier ahead of the interpolation, or a JS ``${...}`` interpolation,+# is NOT covered: the asset match itself can only start after the ``/``+# or ``$``, so its span starts later than the delimited address does,+# that address's own start offset falls outside the suppressed range,+# and it is still reported. That is a false positive, not a missed real+# address — none of the examples below is genuine — and the hook fails+# toward reporting rather than staying silent about them:+# ``u'img/[email protected]'`` (email-domains: allow)+# ``f'{d}/[email protected]'`` (email-domains: allow)+# ```` f`${x}@2x.png` ```` (email-domains: allow)+HIDPI_ASSET_RE = re.compile(+ r"(?P<asset>(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-][A-Za-z0-9._%+!'\x22{}-]{0,127}@[0-9]+(?:\.[0-9]+)?x\."+ r"(?:avif|gif|jpe?g|png|svg|webp|ico|bmp|tiff?|apng))(?![A-Za-z0-9_%+-]|\.[A-Za-z0-9_%+-])",+ re.IGNORECASE,+)+# scp-style remotes carry a colon and then a path that may be a single+# component ("[email protected]:myrepo.git") or a slash tree ("…:/srv/…").+SCP_REMOTE_RE = re.compile(+ r"(?P<remote>(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-][A-Za-z0-9._%+!'-]{0,63}@"+ + _ASCII_DOMAIN+ + r"):(?:[^\s,;<>()[\]\"'`]*/[^\s,;<>()[\]\"'`]*"+ + r"|[^\s,;<>()[\]\"'`]*\.git(?![^\s,;<>()[\]\"'`]))"+)++# A ONE-character local part sitting immediately after a backslash is an+# escape sequence, not an identity: ``"\[email protected]"`` in a Python string,+# ``'\[email protected]'`` in YAML, ``\r``/``\\`` in JSON or Markdown code all read as+# escape letter plus a dotted attribute path, and the extractor used to+# report the escape letter as a local part on the non-reserved domain+# ``router.get``. Only the single-character shape is suppressed, and the+# offset it suppresses is added to ``suppressed_offsets`` before any+# finding is built: the match is never reported at all, not merely+# allow-listed, so ``email-domains: allow`` has nothing to act on — a+# genuine one-character local part directly after a backslash (``\a@…``)+# can only be written some other way. A real address written after a+# backslash (``\\user@…`` -> local part ``user``) is unaffected and is+# still extracted, because there ``user`` is more than the one character+# this pattern matches. That same width limit means a MULTI-character+# escape — ``\x41@…``, ``\u00e9@…``, an octal ``\101@…`` — is not+# suppressed either: the pattern only ever consumes one character between+# the backslash and the ``@``, so a longer escape's tail (``x41``,+# ``u00e9``, ``101``) is left to the ordinary local-part matcher and+# reported like any other address.+_ESCAPED_SINGLE_LOCAL_RE = re.compile(r"\\(?P<local>[^\\@\n])@")++# PEP 465 matrix multiplication: in Python source, an unspaced ``[email protected]``+# chain (dotted operands on either side of ``@``) is an operator+# expression, not an address. Applies only to ``.py``/``.pyi``+# lines, only to an operand in code context (after an operator or keyword),+# and only outside string literals and comments — quoted or commented+# addresses are still scanned, including inside multi-line triple-quoted+# literals whose state is carried across lines by ``_py_code_spans``.+_PY_MATMUL_RE = re.compile(+ r"(?:^|[\s=(,+\-*/%&|^!~<>\[\{}:]"+ r"|\b(?:and|or|not|in|is|if|else|elif|while|for|return|yield|await|"+ r"assert|del|lambda)[ \t]+)"+ r"(?P<expr>[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*"+ r"@[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+)"+)+++class _PyStringState:+ """Quote state carried across a Python file's post-image lines.++ Triple-quoted literals span newlines, and an ordinary single- or+ double-quoted string joined to the next physical line by a+ backslash-newline does too, so the facts a line needs from its+ predecessors are the quote character of an unclosed ``\"\"\"`` /+ ``'''`` opener and of a backslash-continued ordinary string (both+ ``\"\"`` when the line starts in code). Without them, each added+ diff line was classified in isolation: a docstring body line counted+ as code (matmul-suppressing an address inside it), and a+ backslash-continued ordinary string lost its state at the newline.+ ``fstring`` marks a carried quote opened on a prefixed f-string: its+ replacement fields may nest same-quote strings, so the continuation+ line is scanned with the f-string rules, not quote parity. PEP 701+ also lets a raw newline sit inside a replacement field (and a+ triple-quoted f-string span lines in its literal part), so an open+ f-string is carried whatever the line ends on — ``quote`` then holds+ the full closing delimiter (one quote character, or three), with+ ``depth``/``nested`` preserving the field-nesting and nested-string+ scan position for a backslash inside a field's string.+ """++ __slots__ = ("triple", "quote", "fstring", "depth", "nested")++ def __init__(self) -> None:+ self.triple = ""+ self.quote = ""+ self.fstring = False+ self.depth = 0+ self.nested = ""++ def copy(self) -> _PyStringState:+ clone = _PyStringState()+ clone.triple = self.triple+ clone.quote = self.quote+ clone.fstring = self.fstring+ clone.depth = self.depth+ clone.nested = self.nested+ return clone+++# PEP 701 (Python 3.12) lets an interpolated replacement field reuse the+# enclosing quote character, so plain quote parity cannot find the+# closing quote of a prefixed string: in f"{" ... "}" the inner same+# quote would flip parity and the literal between the fields would be+# classified as code, matmul-suppressing an address written inside it.+# A quote preceded by one of these prefixes therefore switches to a+# brace-nesting scan that classifies the whole literal — replacement+# fields included — as string, never code (fail toward extraction).+# Template strings use the same replacement-field lexical rules as f-strings.+_FSTRING_PREFIXES = frozenset({"f", "fr", "rf", "t", "tr", "rt"})+++def _fstring_prefix_at(content: str, quote_index: int) -> bool:+ """True if the quote opens an interpolated f-string or template string."""+ start = quote_index+ while start > 0 and (+ content[start - 1].isalnum() or content[start - 1] == "_"+ ):+ start -= 1+ return content[start:quote_index].lower() in _FSTRING_PREFIXES+++def _scan_fstring_body(+ content: str,+ index: int,+ closer: str,+ depth: int = 0,+ nested: str = "",+) -> tuple[int, bool, bool, int, str]:+ """Scan an f-string literal starting inside its literal part.++ Tracks ``{``/``}`` replacement-field nesting and the string literals+ those fields may open (any quote character or triple-quote run,+ escapes included), so only a ``closer`` quote run in the literal+ part closes the f-string; ``{{`` and ``}}`` are escaped braces, not+ fields. ``closer`` is the full closing delimiter — one quote+ character, or the three of a triple-quoted f-string, so PEP 701's+ same-quote (even same-triple-quote) nesting cannot flip the parity+ either. ``depth`` and ``nested`` resume the scan mid-field (after a+ backslash continuation or a raw newline inside a replacement field).+ Returns the index just past the closing delimiter, whether the+ literal is still open at end of line, whether the line ends on an+ escaped character, and the field depth / open nested-string+ delimiter at that end.+ """+ length = len(content)+ escaped = False+ while index < length:+ char = content[index]+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif nested:+ if content.startswith(nested, index):+ index += len(nested)+ nested = ""+ continue+ elif depth:+ if char == "#":+ # Python 3.12 allows a comment inside a multi-line+ # replacement field; it runs to end of line (its ``}`` /+ # quotes are not field content), and the open field —+ # depth and nested string included — carries to the next+ # physical line instead of the comment tail being read+ # as the literal's code-span continuation.+ break+ if char == "{":+ depth += 1+ elif char == "}":+ depth -= 1+ elif char in "'\"":+ run = 1+ while (+ run < 3+ and index + run < length+ and content[index + run] == char+ ):+ run += 1+ if run >= 3:+ nested = char * 3+ index += 3+ continue+ if run == 2:+ index += 2 # an empty string token+ continue+ nested = char+ elif content.startswith(closer, index):+ return index + len(closer), False, False, depth, nested+ elif char == "{":+ if content.startswith("{{", index):+ index += 1+ else:+ depth = 1+ elif char == "}" and content.startswith("}}", index):+ index += 1+ index += 1+ return length, True, escaped, depth, nested+++def _py_code_spans(+ content: str, state: _PyStringState+) -> list[tuple[int, int]]:+ """Half-open [start, end) spans of ``content`` that are code, not string+ literal or comment.++ Tracks quote parity and backslash escapes within the line, ends the+ code region at a ``#`` outside a string, and carries an open+ triple-quoted string across lines through ``state``. An ordinary+ quote left open by a trailing backslash continues on the next+ physical line and is carried too; any other unterminated quote keeps+ only the tail classified as string. A quote opened on a prefixed+ f-string — single- or triple-quoted — switches to+ ``_scan_fstring_body``: PEP 701 same-quote nesting makes parity+ ambiguous there, so the whole literal — inner expressions included —+ is classified as string and an address inside it is never+ matmul-suppressed. An f-string left open at end of line (a raw+ newline inside a replacement field, or the multi-line literal part+ of a triple-quoted one) is carried through ``state`` along with its+ field depth and nested-string quote, so the continuation line is+ scanned with the f-string rules whatever the line ends on.+ """+ spans: list[tuple[int, int]] = []+ start = index = 0+ triple = state.triple+ quote = state.quote+ fstring = state.fstring+ depth = state.depth+ nested = state.nested+ escaped = False+ length = len(content)+ if quote and fstring:+ # A continued f-string resumes inside its literal part, field+ # nesting and nested-string quote included, so a backslash (or+ # raw newline) inside a field's string cannot close the literal+ # at the wrong quote.+ end, still_open, tail_escaped, depth, nested = _scan_fstring_body(+ content, 0, quote, depth, nested+ )+ if still_open:+ escaped = tail_escaped+ index = length # the whole line stays literal text+ else:+ start = index = end+ quote = ""+ fstring = False+ while index < length:+ char = content[index]+ if triple or quote:+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif triple:+ if char == triple and content.startswith(triple * 3, index):+ triple = ""+ start = index = index + 3+ continue+ elif char == quote:+ quote = ""+ start = index + 1+ elif char == "#":+ spans.append((start, index))+ break+ elif char in "'\"":+ # Only "is this at least a triple-quote run" matters, so the+ # count stops at three: re-counting a whole quote run per+ # character made a long run quadratic.+ run = 1+ while (+ run < 3+ and index + run < length+ and content[index + run] == char+ ):+ run += 1+ spans.append((start, index))+ if _fstring_prefix_at(content, index):+ # PEP 701 permits a same-quote (even same-triple-quote)+ # literal inside a replacement field, so the prefixed+ # run — of any length — is scanned brace-aware with its+ # own closing delimiter.+ closer = char * 3 if run >= 3 else char+ (+ end,+ still_open,+ tail_escaped,+ depth,+ nested,+ ) = _scan_fstring_body(content, index + len(closer), closer)+ if still_open:+ # Unterminated: the tail stays literal text, and the+ # open literal continues on the next line — via a+ # trailing backslash, or the raw newline PEP 701+ # allows inside a replacement field (and any newline+ # in a triple-quoted literal part).+ quote = closer+ fstring = True+ escaped = tail_escaped+ index = length+ else:+ start = index = end+ continue+ if run >= 3:+ triple = char+ start = index = index + 3+ continue+ quote = char+ index += 1+ else:+ if not (triple or quote):+ spans.append((start, length))+ state.triple = triple+ # A trailing backslash escapes the newline of an open ordinary+ # string: the literal continues on the next physical line. An open+ # f-string continues whatever the line ends on (PEP 701 raw+ # newlines), carrying its closing delimiter, field depth and+ # nested-string quote.+ state.quote = quote if quote and (escaped or fstring) else ""+ state.fstring = fstring and bool(state.quote)+ state.depth = depth if state.fstring else 0+ state.nested = nested if state.fstring else ""+ return spans+++def _git(*args: str) -> tuple[int, str]:+ """Run git; return (returncode, stdout). stderr is captured and discarded.++ ``errors="replace"`` keeps a non-UTF8 blob (e.g. a Latin-1 fixture) from+ crashing the decode; U+FFFD is a symbol rather than a letter, so a+ mangled blob cannot fabricate a domain label.+ """+ proc = subprocess.run(+ ["git", *args],+ capture_output=True,+ text=False,+ )+ return proc.returncode, proc.stdout.decode("utf-8", errors="replace")+++def parse_author_emails(text: str) -> set[str]:+ """Return lower-cased emails declared exactly in ``[project].authors``."""+ try:+ metadata = tomllib.loads(text)+ except tomllib.TOMLDecodeError:+ raise RuntimeError("could not parse project metadata") from None++ project = metadata.get("project")+ if project is None:+ return set()+ if not isinstance(project, dict):+ raise RuntimeError("invalid project metadata")++ authors = project.get("authors")+ if authors is None:+ return set()+ if not isinstance(authors, list):+ raise RuntimeError("invalid project authors")++ emails: set[str] = set()+ for author in authors:+ if not isinstance(author, dict):+ raise RuntimeError("invalid project author")+ email = author.get("email")+ if email is None:+ continue+ if not isinstance(email, str):+ raise RuntimeError("invalid project author email")+ normalized_email = email.strip().lower()+ if normalized_email:+ emails.add(normalized_email)+ return emails+++def is_allowed(email: str, declared: set[str]) -> bool:+ """True if ``email`` uses an allowed (reserved / service / declared) domain."""+ e = email.strip().lower()+ if "@" not in e:+ return True+ domain = e.rsplit("@", 1)[1]+ if e.endswith(NOREPLY_SUFFIX):+ return True+ if e in GITHUB_SERVICE_ADDRESSES:+ return True+ if domain in RESERVED_DOMAINS:+ return True+ if any(domain.endswith(sfx) for sfx in RESERVED_SUFFIXES):+ return True+ if e in declared:+ return True+ return False+++def _git_unquote_path(path: str) -> str:+ """Decode a Git C-quoted diff path such as ``"b/caf\\303\\251.py"``.++ Git quotes paths containing non-ASCII (or otherwise-ambiguous)+ characters, emitting backslash escapes whose octal forms are BYTES+ of the filename. Undecoded, ``Path(path).suffix`` keeps the+ trailing quote (``.py\\"``), so Python-file scoping — and matmul+ suppression with it — silently fails for non-ASCII paths. Decoding+ with ``surrogateescape`` also round-trips names that are not valid+ UTF-8: subprocess argv re-encodes lone surrogates back to the+ original bytes, so the ``git show`` post-image lookup resolves such+ a path instead of failing on a U+FFFD stand-in.+ """+ if len(path) < 2 or path[0] != '"' or path[-1] != '"':+ return path+ simple = {+ '"': b'"',+ "\\": b"\\",+ "a": b"\a",+ "b": b"\b",+ "f": b"\f",+ "n": b"\n",+ "r": b"\r",+ "t": b"\t",+ "v": b"\v",+ }+ body = path[1:-1]+ raw = bytearray()+ index = 0+ while index < len(body):+ char = body[index]+ if char != "\\":+ # Git never leaves a literal non-ASCII char inside a quoted+ # path, but encoding it keeps the decode total.+ raw += char.encode()+ index += 1+ continue+ escape = body[index + 1] if index + 1 < len(body) else ""+ if escape in simple:+ raw += simple[escape]+ index += 2+ elif escape and escape in "01234567":+ digits = escape+ index += 1+ while (+ index + 1 < len(body)+ and len(digits) < 3+ and body[index + 1] in "01234567"+ ):+ digits += body[index + 1]+ index += 1+ raw.append(int(digits, 8) & 0xFF)+ index += 1+ else:+ # Unknown escape (Git never emits one): keep it verbatim.+ raw += b"\\"+ index += 1+ return raw.decode("utf-8", errors="surrogateescape")+++_HUNK_HEADER = re.compile(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")+++def iter_added_emails(+ diff: str, post_image: Callable[[str], str | None] | None = None+):+ """Yield (path, email) for every email on an added (``+``) diff line.++ The ``(path, email, line)`` form is :func:`iter_added_findings`; this+ wrapper drops the line number for callers that only need the address.+ """+ for path, email, _line in iter_added_findings(diff, post_image=post_image):+ yield path, email+++def iter_added_findings(+ diff: str, post_image: Callable[[str], str | None] | None = None+):+ """Yield (path, email, line) for every email on an added (``+``) line.++ ``line`` is the 1-based line number of that added line in the file's+ post-image, counted from each hunk header's new-side start so a+ diagnostic can name ``path:line`` and a contributor can go straight to+ a false positive. Removed lines do not advance it; context lines do.+ A hunk header that does not parse yields ``0``, which the diagnostic+ renders as a bare path rather than a wrong location.++ Parses the unified diff with hunk-state tracking: ``diff --git`` starts a+ new file (headers follow), ``@@`` opens a hunk body. Inside a hunk, every+ ``+`` line is *content* — including a line whose text begins with ``++`` (it+ renders as ``+++…`` but is not a header there), which a naive+ ``startswith('+++ ')`` check would wrongly skip. ``+++`` header paths are+ C-unquoted (``_git_unquote_path``). Splits on ``\\n`` only (not+ ``str.splitlines``, which also breaks on U+2028 etc. and would let text+ after such a char slip past). Skips lockfiles and ``ALLOW_MARKER`` lines.++ For ``.py``/``.pyi`` files, string-literal state is carried across the+ post-image lines visible in the diff (context lines advance it too but+ are never scanned), so an address inside a multi-line triple-quoted+ literal — or a backslash-continued ordinary string — is never mistaken+ for code and matmul-suppressed. A hunk still does not START in a known+ lexical state: three context lines say nothing about an opener far+ above the hunk, and the gap between two hunks hides whatever closed+ the first one. When ``post_image`` maps a path to its post-image+ content (the staged index blob locally, the PR head blob in CI), the+ state at every hunk entry is rebuilt by scanning the real post-image+ above the hunk instead of assuming code. Each file's hunks arrive in+ ascending order, so one monotonic per-file scan serves them all and+ the whole reconstruction stays linear. A path whose post-image+ cannot be loaded (an index entry ``git show`` cannot resolve) fails+ toward extraction: matmul suppression is dropped for the whole file+ rather than guessed from an assumed-code entry state that would+ swallow an address sitting inside a docstring.+ """+ path = "?"+ in_hunk = False+ new_lineno = 0+ # False after an unparseable hunk header: ``new_lineno`` then stays at+ # its 0 sentinel instead of counting up from it, so EVERY added line+ # in that hunk reports the bare-path ``0`` the docstring promises, not+ # a wrong line number that happens to start from 0.+ new_lineno_known = True+ py_state = _PyStringState()+ # path -> (post-image lines, line count already scanned, state after+ # them); None marks a path the loader could not provide, which then+ # keeps the visible-lines approximation for state tracking but loses+ # matmul suppression entirely (py_unresolved) so it cannot fail open.+ py_scan: dict[str, tuple[list[str], int, _PyStringState] | None] = {}+ py_unresolved: set[str] = set()+ for raw in diff.split("\n"):+ line = raw[:-1] if raw.endswith("\r") else raw+ if line.startswith("diff --git "):+ in_hunk = False+ path = "?"+ new_lineno = 0+ new_lineno_known = True+ py_state = _PyStringState()+ continue+ if line.startswith("@@"):+ in_hunk = True+ header = _HUNK_HEADER.match(line)+ new_lineno_known = header is not None+ new_lineno = int(header.group(1)) if header is not None else 0+ if (+ header is not None+ and post_image is not None+ and Path(path).suffix in (".py", ".pyi")+ ):+ scan = py_scan.get(path)+ if scan is None and path not in py_scan:+ text = post_image(path)+ if text is None:+ py_scan[path] = None+ py_unresolved.add(path)+ else:+ scan = (+ text.replace("\r\n", "\n").split("\n"),+ 0,+ _PyStringState(),+ )+ py_scan[path] = scan+ if scan is not None:+ lines, upto, cached = scan+ target = max(+ min(int(header.group(1)) - 1, len(lines)), upto+ )+ entry = cached.copy()+ for index in range(upto, target):+ _py_code_spans(lines[index], entry)+ py_scan[path] = (lines, target, entry)+ # The hunk body advances its own copy; the cache keeps+ # the state exactly at ``target`` for the next entry.+ py_state = entry.copy()+ continue+ if not in_hunk:+ # File-header region: capture the post-image path.+ if line.startswith("+++ "):+ # Strip only Git's unified-header separator tab, not arbitrary+ # trailing whitespace: a file literally named "uv.lock " must+ # not be collapsed to the "uv.lock" skip basename.+ p = line[4:].split("\t", 1)[0]+ p = _git_unquote_path(p)+ path = p[2:] if p.startswith("b/") else p+ continue+ if line.startswith("+"):+ content = line[1:] # strip the single leading '+' diff marker+ lineno = new_lineno if new_lineno_known else 0+ if new_lineno_known:+ new_lineno += 1+ elif line.startswith(" "):+ # Context lines belong to the post-image: they still advance+ # the Python string-state so a literal opened on an unchanged+ # line closes correctly, but they are never scanned.+ if Path(path).suffix in (".py", ".pyi"):+ _py_code_spans(line[1:], py_state)+ if new_lineno_known:+ new_lineno += 1+ continue+ else:+ # A removed line or a "\\ No newline at end of file" marker: no+ # post-image line, so the new-side counter does not advance.+ continue+ # Advance the string-state past every Python post-image line, even+ # an opted-out one: a docstring body line still opens/closes literals.+ # An unresolvable post-image means the entry state is unknown, so+ # the file fails toward extraction: no span is code, matmul+ # suppression cannot apply, and addresses stay visible.+ code_spans = (+ _py_code_spans(content, py_state)+ if Path(path).suffix in (".py", ".pyi")+ and path not in py_unresolved+ else []+ )+ if ALLOW_MARKER in content.lower():+ continue # explicit per-line opt-out+ if Path(path).name in SKIP_BASENAMES:+ continue+ suppressed_offsets = {+ offset+ for match in URI_USERINFO_RE.finditer(content)+ for offset in range(match.start("userinfo"), match.end("userinfo"))+ }+ suppressed_offsets.update(+ offset+ for match in HIDPI_ASSET_RE.finditer(content)+ for offset in range(*match.span("asset"))+ )+ suppressed_offsets.update(+ match.start("remote") for match in SCP_REMOTE_RE.finditer(content)+ )+ suppressed_offsets.update(+ match.start("local")+ for match in _ESCAPED_SINGLE_LOCAL_RE.finditer(content)+ )+ if code_spans:+ code_starts = [span[0] for span in code_spans]+ for match in _PY_MATMUL_RE.finditer(content):+ expr_start, expr_end = match.span("expr")+ index = bisect_right(code_starts, expr_start) - 1+ if index >= 0 and expr_end <= code_spans[index][1]:+ suppressed_offsets.update(range(expr_start, expr_end))+ quoted_spans = [+ match.span() for match in QUOTED_EMAIL_RE.finditer(content)+ ]+ quoted_starts = [span[0] for span in quoted_spans]+ explicit_spans = []+ for span in _delimited_email_spans(content):+ quoted = bisect_right(quoted_starts, span[0]) - 1+ if quoted >= 0 and span[1] <= quoted_spans[quoted][1]:+ # Delimiters inside a quoted local part are literal text,+ # not a second address with a different domain.+ continue+ explicit_spans.append(span)+ explicit_starts = [span[0] for span in explicit_spans]+ emitted_explicit: set[int] = set()+ for pattern in (EMAIL_RE, QUOTED_EMAIL_RE):+ for m in pattern.finditer(content):+ if m.start() in suppressed_offsets:+ continue+ explicit = bisect_right(explicit_starts, m.start()) - 1+ if explicit >= 0 and m.end() <= explicit_spans[explicit][1]:+ _, _, email, address_start = explicit_spans[explicit]+ if (+ explicit not in emitted_explicit+ and address_start not in suppressed_offsets+ ):+ emitted_explicit.add(explicit)+ yield path, email, lineno+ continue+ quoted = bisect_right(quoted_starts, m.start()) - 1+ if pattern is EMAIL_RE and quoted >= 0:+ start, end = quoted_spans[quoted]+ if start < m.start() and m.end() < end:+ # A quoted local part shadows its inner address text.+ continue+ yield path, m.group(0), lineno+ for index, (_, _, email, address_start) in enumerate(explicit_spans):+ if (+ index not in emitted_explicit+ and address_start not in suppressed_offsets+ ):+ yield path, email, lineno+++def _resolve_merge_base(base: str, head: str) -> str:+ """Return merge-base(base, head). Raise on failure.++ Resolve from locally-available history FIRST and fetch only as a fallback,+ so the hook mutates no git state on the PR-CI path (full history is checked+ out there via ``fetch-depth: 0``).+ """+ rc, mb = _git("merge-base", base, head)+ if rc == 0 and mb.strip():+ return mb.strip()+ _git("fetch", "--quiet", "--depth=1000", "origin", head, base)+ rc, mb = _git("merge-base", base, head)+ if rc != 0 or not mb.strip():+ _git("fetch", "--quiet", "--unshallow", "origin")+ rc, mb = _git("merge-base", base, head)+ if rc != 0 or not mb.strip():+ raise RuntimeError("could not resolve the PR commit range")+ return mb.strip()+++def _post_image_loader(ref: str | None) -> Callable[[str], str | None]:+ """Return a path -> post-image content callable for state rebuilds.++ ``ref`` is the PR head SHA in CI; ``None`` addresses the staged+ index locally (the exact blob the staged diff was computed from).+ One ``git show`` per path, cached: a file with many hunks asks+ once. A path git cannot show (deleted, synthetic) yields None so+ the caller disables matmul suppression for that file rather than+ guessing its Python string state.+ """+ cache: dict[str, str | None] = {}++ def load(path: str) -> str | None:+ if path not in cache:+ rc, content = _git("show", f"{ref}:{path}" if ref else f":0:{path}")+ cache[path] = content if rc == 0 else None+ return cache[path]++ return load+++def _pr_context():+ """In PR CI: return (diff_text, base_pyproject_text, head_sha); the+ head SHA addresses the diff's post-image blobs so hunk-entry lexical+ state can be rebuilt. None if not PR CI.++ Raises RuntimeError on an unresolvable range (caller fails closed).+ """+ is_pr_event = os.environ.get("GITHUB_EVENT_NAME", "") in (+ "pull_request",+ "pull_request_target",+ )++ def give_up(reason: str):+ if is_pr_event:+ raise RuntimeError(reason)+ return++ event_path = os.environ.get("GITHUB_EVENT_PATH")+ if not (event_path and Path(event_path).exists()):+ return give_up("pull_request event but no event payload")+ try:+ with open(event_path, encoding="utf-8") as fh:+ payload = json.load(fh)+ except (OSError, ValueError):+ return give_up("could not read the PR event payload")+ pr = payload.get("pull_request") if isinstance(payload, dict) else None+ if not isinstance(pr, dict):+ return give_up("pull_request event missing its payload")+ base_ref = pr.get("base")+ head_ref = pr.get("head")+ if not isinstance(base_ref, dict) or not isinstance(head_ref, dict):+ return give_up("pull_request event missing base/head sha")+ base = base_ref.get("sha")+ head = head_ref.get("sha")+ if not (isinstance(base, str) and isinstance(head, str) and base and head):+ return give_up("pull_request event missing base/head sha")+ merge_base = _resolve_merge_base(base, head) # may raise -> fail closed+ # --no-color: a runner/user git config forcing color would prefix added+ # lines with ANSI escapes and break the leading-'+' detection.+ rc, diff = _git("diff", *DIFF_FLAGS, merge_base, head)+ if rc != 0:+ raise RuntimeError(f"PR diff failed (exit status {rc})")+ rc, base_pyproject = _git("show", f"{base}:pyproject.toml")+ if rc != 0:+ raise RuntimeError(+ f"base pyproject.toml show failed (exit status {rc})"+ )+ return diff, base_pyproject, head+++def _staged_context():+ """Local pre-commit: (staged diff, staged pyproject text, None ref)."""+ rc, diff = _git("diff", *DIFF_FLAGS, "--cached")+ if rc != 0:+ raise RuntimeError(f"staged diff failed (exit status {rc})")+ rc, pyproject = _git("show", ":pyproject.toml")+ if rc != 0:+ raise RuntimeError(+ f"staged pyproject.toml show failed (exit status {rc})"+ )+ return diff, pyproject, None+++def main() -> int:+ try:+ ctx = _pr_context()+ diff, pyproject, ref = ctx if ctx is not None else _staged_context()+ declared = parse_author_emails(pyproject)+ except RuntimeError as exc:+ print(f"email-domains: {exc}; failing closed.", file=sys.stderr)+ return 1++ offenders = sorted(+ {+ (path, lineno)+ for path, email, lineno in iter_added_findings(+ diff, post_image=_post_image_loader(ref)+ )+ if not is_allowed(email, declared)+ }+ )+ if offenders:+ print("Email domain check failed:\n", file=sys.stderr)+ for path, lineno in offenders:+ # Redact conservatively: any "@" in the path treats it as+ # potentially email-bearing. The strict EMAIL_RE rejects+ # token-suffixed paths (e.g. "[email protected]") and would leak them.+ # Keep each filename on one line, with unambiguous escaped+ # controls and backslashes. Escape non-ASCII code points too so+ # directional formatting cannot reorder the diagnostic.+ display_path = (+ "<path containing email>"+ if "@" in path+ else json.dumps(path, ensure_ascii=True)[1:-1]+ )+ # The line number locates the offending ADDED line in the+ # post-image, so a false positive can be read in context and+ # marked; it reveals nothing about the address itself. A hunk+ # header that did not parse leaves it 0 -> print the bare path.+ location = f"{display_path}:{lineno}" if lineno else display_path+ print(+ f" {location}: adds an email on a non-reserved domain",+ file=sys.stderr,+ )+ print(+ "\nUse a reserved example/test domain, declare a project author in "+ "pyproject.toml, use a GitHub `@users.noreply.github.com` alias, or "+ "add `email-domains: allow` on that line.\n"+ "(The address is not printed here.)",+ file=sys.stderr,+ )+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/hooks/test_check_email_domains.py b/tests/hooks/test_check_email_domains.pynew file mode 100644index 0000000000..047687143c--- /dev/null+++ b/tests/hooks/test_check_email_domains.py@@ -0,0 +1,2841 @@+"""Tests for the check-email-domains pre-commit hook.++No real address appears in this file: allowed cases use reserved domains+(``example.com`` / ``.test``) or GitHub noreply/service addresses, and+disallowed cases are ASSEMBLED at runtime from parts (via ``_addr``) so the+hook — which scans this file's own added lines in CI — never sees a literal+non-reserved address here.+"""++import importlib.util+import subprocess+import sys+from pathlib import Path+from time import perf_counter++import pytest++# Load the hook module by path (hyphenated filename isn't importable directly).+_HOOK_PATH = (+ Path(__file__).resolve().parents[2]+ / ".pre-commit-hooks"+ / "check-email-domains.py"+)+_spec = importlib.util.spec_from_file_location(+ "check_email_domains", _HOOK_PATH+)+mod = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(mod)+++def _addr(local: str, domain: str) -> str:+ """Assemble an address so no literal ``[email protected]`` sits in this source file."""+ return local + "@" + domain+++def _qaddr(local: str, domain: str) -> str:+ """Assemble a quoted local-part (RFC 5321 quoted-string) address."""+ return '"' + local + '"@' + domain+++def _decorator(attribute: str) -> str:+ """Assemble a decorator reference so no ``"@`` pair sits in this file.++ An adjacent closing quote and ``@`` read as an RFC 5321 quoted local+ part, which is exactly what the hook is built to find.+ """+ return "@" + attribute+++def _run_git(repo: Path, *args: str) -> None:+ subprocess.run(+ ["git", *args],+ cwd=repo,+ check=True,+ capture_output=True,+ text=True,+ )+++def _run_hook(repo: Path) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [sys.executable, str(_HOOK_PATH)],+ cwd=repo,+ check=False,+ capture_output=True,+ text=True,+ )+++PYPROJECT = """\+[project]+name = "x"+authors = [+ {name = "LearningCircuit", email = "[email protected]"},+ {name = "djpetti", email = "[email protected]"},+]+"""+++class TestParseAuthorEmails:+ def test_extracts_declared(self):+ got = mod.parse_author_emails(PYPROJECT)+ assert "[email protected]" in got+ assert "[email protected]" in got++ def test_empty_when_no_authors(self):+ assert mod.parse_author_emails("[project]\nname='x'\n") == set()++ @pytest.mark.parametrize(+ "text",+ [+ "name = 'x'\n",+ "[project]\nauthors = []\n",+ ],+ )+ def test_missing_or_empty_authors_is_an_empty_allowlist(self, text):+ assert mod.parse_author_emails(text) == set()++ def test_accepts_quoted_and_reordered_project_authors(self):+ addr = _addr("maintainer", "gmail.com")+ text = (+ "[project]\n"+ "authors = [{ email = '" + addr + '\', name = "Maintainer" }]\n'+ )+ assert mod.parse_author_emails(text) == {addr}++ @pytest.mark.parametrize("email", ["", " \t "])+ def test_ignores_blank_author_email(self, email):+ text = (+ "[project]\nauthors = [{name = 'Maintainer', email = '"+ + "'}]\n"+ )+ assert mod.parse_author_emails(text) == set()++ def test_ignores_unrelated_authors_key(self):+ # A nested/unrelated *authors line must not widen the allow-list.+ text = 'metadata_authors = ["' + _addr("real", "gmail.com") + '"]\n'+ assert mod.parse_author_emails(text) == set()++ def test_ignores_unrelated_authors_table(self):+ addr = _addr("real", "gmail.com")+ text = "[tool.metadata]\nauthors = [{email = '" + addr + "'}]\n"+ assert mod.parse_author_emails(text) == set()++ @pytest.mark.parametrize(+ "text",+ [+ "[project\nauthors = []\n",+ "project = 'not a table'\n",+ "[project]\nauthors = 'not a list'\n",+ "[project]\nauthors = ['not an author table']\n",+ "[project]\nauthors = [{email = 42}]\n",+ ],+ )+ def test_rejects_malformed_or_invalid_author_structure(self, text):+ with pytest.raises(RuntimeError):+ mod.parse_author_emails(text)+++class TestIsAllowed:+ @pytest.mark.parametrize(+ "email",+ [+ "[email protected]",+ _addr("user", "example.com"),+ _addr("smtp", "example.com"), # reserved 2LD+ _addr("pass", "smtp.example.com"), # reserved subdomain+ _addr("a", "b.test"),+ _addr("x", "host.invalid"),+ _addr("y", "svc.localhost"),+ _addr("z", "thing.example"),+ _addr("git", "github.com"), # service domain+ _addr("actions", "github.com"),+ _addr("u", "ünicode.example.com"), # U-label, reserved suffix+ _qaddr("john doe", "example.com"), # quoted local part+ ],+ )+ def test_allowed(self, email):+ assert mod.is_allowed(email, set()) is True++ @pytest.mark.parametrize(+ "email",+ [+ _addr("some.dev", "gmail.com"),+ _addr("first.last", "outlook.com"),+ _addr("me", "proton.me"),+ _addr("contact", "acme.io"),+ _addr("editor", "sciencedaily.com"),+ _addr("person", "example.xn--p1ai"), # punycode TLD+ _addr("person", "bücher.de"), # U-label domain+ _qaddr("john doe", "gmail.com"), # quoted local part+ ],+ )+ def test_disallowed(self, email):+ assert mod.is_allowed(email, set()) is False++ @pytest.mark.parametrize(+ "email",+ [+ _addr("a", "notexample.com"), # merely CONTAINS a reserved token+ _addr("a", "example.com.evil"), # reserved token not at the end+ _addr("a", "myexample.org"),+ _addr("a", "evilexample.net"),+ _addr("a", "github.com.evil"), # service token not at the end+ _addr("a", "notgithub.com"),+ ],+ )+ def test_near_miss_reserved_is_flagged(self, email):+ # The exact bypass class this hook exists to stop: a domain that only+ # *contains* a reserved token must still be flagged (guards against a+ # boundary loosening to a substring check).+ assert mod.is_allowed(email, set()) is False++ def test_declared_author_allowed(self):+ declared = {_addr("djpetti", "gmail.com")}+ assert mod.is_allowed(_addr("djpetti", "gmail.com"), declared) is True++ def test_case_insensitive(self):+ assert mod.is_allowed(_addr("USER", "EXAMPLE.COM"), set()) is True+ assert mod.is_allowed(_addr("Dev", "Gmail.Com"), set()) is False++ @pytest.mark.parametrize(+ "email",+ [+ _addr("GIT", "GITHUB.COM"),+ _addr("Actions", "GitHub.com"),+ ],+ )+ def test_exact_github_service_addresses_are_case_insensitive(self, email):+ assert mod.is_allowed(email, set()) is True++ @pytest.mark.parametrize(+ "email",+ [+ _addr("releases", "github.com"),+ _addr("git-bot", "github.com"),+ ],+ )+ def test_other_github_addresses_are_not_service_allowances(self, email):+ assert mod.is_allowed(email, set()) is False+++class TestIterAddedEmails:+ def _diff(self, path: str, added_line: str) -> str:+ return (+ f"diff --git a/{path} b/{path}\n"+ f"--- a/{path}\n+++ b/{path}\n@@ -0,0 +1 @@\n{added_line}\n"+ )++ def test_finds_added_email(self):+ bad = _addr("real.person", "gmail.com")+ got = list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ mail " + bad))+ )+ assert got == [("docs/x.md", bad)]++ @pytest.mark.parametrize(+ "local",+ [+ "_leading",+ "trailing_",+ "+leading",+ "trailing+",+ "%leading",+ "trailing%",+ "-leading",+ "trailing-",+ ],+ )+ def test_finds_disallowed_special_character_local_parts(self, local):+ bad = _addr(local, "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_punycode_tld_address(self):+ # The ASCII IDNA (A-label) form of an internationalized domain was+ # previously invisible: its final label is not all letters.+ bad = _addr("person", "example.xn--p1ai")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_uppercase_punycode_tld_address(self):+ bad = _addr("person", "example.XN--P1AI")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_unicode_domain_address(self):+ # A U-label domain (non-ASCII letters) was previously invisible.+ bad = _addr("person", "bücher.de")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_unicode_tld_address(self):+ bad = _addr("user", "пример.рф")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_unicode_subdomain_address(self):+ bad = _addr("user", "sub.bücher.de")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_quoted_local_part_address(self):+ # An RFC 5321 quoted-string local part contains a space and quotes,+ # so the dot-atom pattern cannot see it.+ bad = _qaddr("john doe", "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize(+ "bad",+ [+ _qaddr("john doe", "bücher.de"),+ _addr("user", "bücher١.de"),+ _addr("person", "bücher.1пример"),+ _addr("person", "bücher.१рф"),+ _qaddr("john doe", "bücher.1пример"),+ _qaddr("john doe", "bücher.१рф"),+ ],+ )+ def test_finds_composed_international_address_forms(self, bad):+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_idn_address_with_combining_marks(self):+ # Devanagari labels carry matras (combining marks): valid IDNA+ # (round-trips to xn--p1b6ci4b4b3a.xn--h2brj9c) but previously+ # invisible because the label charset rejected marks, so a staged+ # commit containing such an address exited 0.+ bad = _addr("user", "उदाहरण.भारत")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_finds_ascii_led_unicode_tld_address(self):+ # A U-label TLD that merely starts with an ASCII letter was+ # previously invisible: the final label had to start non-ASCII or+ # with a digit, so a two-letter extended TLD never matched.+ bad = _addr("user", "bücher.aü")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_ascii_led_unicode_tld_not_truncated(self):+ # The extractor must yield the whole address, never an ASCII+ # prefix of a Unicode domain: the allow-list compares full+ # addresses, so a truncated extraction failed even declared+ # authors on real TLDs like this one.+ bad = _addr("user", "example.vermögensberater")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_mixed_script_domain_yields_single_full_match(self):+ # Previously an ASCII-only matcher reported a truncated ASCII+ # prefix as a phantom second address next to the real (reserved)+ # one, so the line failed even though the full domain is allowed.+ bad = _addr("user", "www.exämple.example.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_quoted_local_part_on_reserved_domain_is_allowed(self):+ good = _qaddr("john doe", "example.com")+ got = list(mod.iter_added_emails(self._diff("docs/x.md", "+ " + good)))+ assert got == [("docs/x.md", good)]+ assert mod.is_allowed(got[0][1], set()) is True++ def test_unicode_label_on_reserved_suffix_is_allowed(self):+ good = _addr("u", "ünicode.example.com")+ got = list(mod.iter_added_emails(self._diff("docs/x.md", "+ " + good)))+ assert got == [("docs/x.md", good)]+ assert mod.is_allowed(got[0][1], set()) is True++ def test_unicode_local_part_extracted_whole(self):+ # the ASCII-only local-part class entered the token+ # mid-letter (`müller@…` was read as `ller@…`), so even a declared+ # author failed the exact allow-list comparison.+ bad = _addr("müller", "wichtig.de")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_unicode_local_part_not_entered_mid_token(self):+ # The lookbehind spans Unicode letters: only the whole token+ # matches, never a suffix of it.+ bad = _addr("müller", "wichtig.de")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ x" + bad))+ ) == [("docs/x.md", "x" + bad)]++ def test_cjk_text_glued_to_ascii_domain_not_absorbed(self):+ # CJK prose has no spaces, so sentence particles can sit right+ # after a domain; they must not become part of it (this address is+ # reserved and must pass).+ good = _addr("user", "example.com")+ line = "+ 連絡先 " + good + "です まで"+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", good)+ ]++ @pytest.mark.parametrize(+ ("line", "expected"),+ [+ ("+ " + _addr("user", "q\u0307.com"), _addr("user", "q\u0307.com")),+ (+ "+ " + _addr("user", "example.comрф"),+ _addr("user", "example.comрф"),+ ),+ (+ "+ " + _addr("user", "example.vermo\u0308gensberater"),+ _addr("user", "example.vermo\u0308gensberater"),+ ),+ (+ "+ Fixed login bug, reported by "+ + _addr("john.doe", "gmail.com")+ + ":auth-rewrite",+ _addr("john.doe", "gmail.com"),+ ),+ ],+ )+ def test_round_five_regressions_extract_full_unsuppressed_email(+ self, line, expected+ ):+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", expected)+ ]++ @pytest.mark.parametrize(+ "line",+ [+ "+ git clone "+ + _addr("git+deploy", "gitlab.com")+ + ":org/repo.git",+ "+ See <mongodb://admin:[email protected]> for details",+ "+ "+ + "a" * 33+ + "://user:"+ + _addr("password", "gmail.com")+ + "/x",+ '+ <img src="[email protected]">',+ ],+ )+ def test_round_five_non_email_syntax_is_suppressed(self, line):+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []++ def test_round_five_ascii_final_lookahead_is_linear(self):+ email = _addr("user", "x." + "b" * 26)+ started = perf_counter()+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + email))+ ) == [("docs/x.md", email)]+ assert perf_counter() - started < 1++ def test_high_combining_mark_domain_not_truncated(self):+ # U+2CEF (Coptic combining ni above) sits far above the old U+2100+ # mark ceiling: the extractor must yield the full address, so a+ # reserved-looking prefix can never mask a non-reserved domain.+ bad = _addr("u", "example.com⳯")+ got = list(mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad)))+ assert got == [("docs/x.md", bad)]+ assert mod.is_allowed(got[0][1], set()) is False++ def test_supplementary_combining_mark_domain_not_truncated(self):+ # The supplementary half of the mark class, pinned to U+101FD+ # (Phaistos disc combining oblique stroke): a mark since Unicode+ # 5.1, so UCD 15 (Python 3.12, which runs pre-commit here) and+ # UCD 16 (Python 3.14, which runs the docker test image) agree.+ # The class is derived from the RUNNING interpreter, so a newer+ # codepoint (U+11F5A: Mn in UCD 16, unassigned in UCD 15) would+ # make this assertion interpreter-dependent.+ bad = _addr("u", "example.com\U000101fd" + "evil.org")+ got = list(mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad)))+ assert got == [("docs/x.md", bad)]+ assert mod.is_allowed(got[0][1], set()) is False++ @pytest.mark.parametrize(+ "wrapper", ["`", "'", '"'], ids=["backtick", "apostrophe", "quote"]+ )+ @pytest.mark.parametrize("repeat", [2, 3], ids=["doubled", "tripled"])+ @pytest.mark.parametrize(+ "path", ["docs/x.md", "docs/x.rst", "src/app.py", "CHANGELOG.md"]+ )+ def test_repeated_delimiter_is_not_a_one_char_local_part(+ self, wrapper, repeat, path+ ):+ """A Markdown/rST-quoted decorator is prose, not an address.++ The delimiter characters are legal local-part punctuation, so a+ DOUBLED delimiter used to read as delimiter + local part + the+ dotted attribute path as its domain — flagging ordinary docs.+ """+ fence = wrapper * repeat+ for attribute in ("router.get", "pytest.mark.parametrize"):+ decorator = _decorator(attribute)+ line = "+ Decorate with " + fence + decorator + fence + " here."+ assert list(mod.iter_added_emails(self._diff(path, line))) == []++ @pytest.mark.parametrize(+ ("outer", "inner"),+ [+ ("`", "'"),+ ("'", "`"),+ ('"', "`"),+ ('"', "'"),+ ("`", '"'),+ ("'", '"'),+ ],+ )+ def test_mixed_delimiters_are_not_a_one_char_local_part(self, outer, inner):+ """Both nestings: the inner delimiter is never the local part."""+ decorator = _decorator("router.get")+ for close in (inner + outer, outer + inner):+ line = "+ Decorate with " + outer + inner + decorator + close+ assert (+ list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []+ )++ @pytest.mark.parametrize("local", ["user", "o'connor", "!lead"])+ def test_single_delimiters_still_bound_a_real_identity(self, local):+ """The wrapper-exclusion must not cost a genuine delimited address."""+ email = _addr(local, "nonreserved.tld")+ for left, right in (("`", "`"), ("<", ">")):+ if left in local:+ continue+ line = "+ Contact " + left + email + right + " please"+ got = list(mod.iter_added_emails(self._diff("docs/x.md", line)))+ assert got == [("docs/x.md", email)]+ assert mod.is_allowed(got[0][1], set()) is False++ def test_intraword_apostrophe_before_asset_stays_clean(self):+ """``'can'[email protected]'``: the apostrophe mid-word opens nothing.++ Removing the intraword lookbehind re-enters at the apostrophe and+ reads ``[email protected]`` as a delimited local part on the domain+ ``2x.png``.+ """+ line = "+ Use 'can'[email protected]' for the icon."+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []++ @pytest.mark.parametrize(+ "prefix", ["f", "F", "rf", "Rf", "u", "U", "b", "B", "t", "T"]+ )+ @pytest.mark.parametrize("wrapper", ["'", "`"])+ def test_string_prefix_before_quote_still_opens_delimiter(+ self, prefix, wrapper+ ):+ """A Python string prefix precedes the quote, not a plain word.++ ``f'{user}@example.com'`` puts the prefix letter — a local-part+ character — directly before the quote, same as the apostrophe in+ ``can't``. Without the string-prefix carve-out in the intraword+ lookbehind, this is indistinguishable from ``can't`` and the+ quote never opens, so the address inside goes unflagged.+ """+ local, domain = "user", "acme-corp.io"+ field = "{" + local + "}@" + domain+ line = "+ addr = " + prefix + wrapper + field + wrapper+ got = list(mod.iter_added_emails(self._diff("src/app.py", line)))+ assert got == [("src/app.py", field)]++ def test_ordinary_word_before_quote_still_stays_intraword(self):+ """A real word ending in a prefix letter is still not an opener.++ The original regression case (``It's Rob's [email protected], not an+ address.``) never closes its quote, so ``iter_added_emails`` had+ nothing address-shaped to find regardless of whether the+ negatives fire; it is kept only as a smoke case. The two+ HIDPI-asset assertions that follow it (``'Rob'[email protected]'``,+ ``'Burt'[email protected]'``) each wrap a genuine asset in a matching pair+ of quotes, but the asset text is suppressed regardless of the+ negatives — removing either one leaves both of these two+ unchanged, since the empty result comes from the HIDPI+ suppression, not from the quote staying closed. They pin nothing+ about the negatives and are kept only as asset-suppression smoke+ cases; the two assertions after them, on a non-asset address, are+ what actually isolates each negative — removing it changes the+ result there.++ ``Rob'sfoo nb'<addr>'``: the word ``nb`` ends in the SINGLE+ prefix letter ``b``, but the letter before it (``n``) is a word+ character, so the run ``b`` is not a bare 1-letter prefix bounded+ by a non-word character — the 1-letter negative+ ``(?<!\\w[prefix])`` must block it, or the apostrophe re-opens+ the quote one character early and a second, phantom finding+ (the address without its leading ``nb``) appears alongside the+ first. Removing only the 2-letter negative leaves this+ unaffected, since ``nb`` is not a 2-letter prefix run either.++ ``Curt'sfoo Burt'<addr>'``: the word ``Burt`` ends in the TWO+ prefix letters ``rt``, but the letter before them (``u``) is a+ word character too, so ``rt`` is not a bare 2-letter prefix+ either — the 2-letter negative ``(?<!\\w[prefix]{2})`` must also+ block it, or the same phantom finding appears. Removing only the+ 1-letter negative ALSO reopens it here, because the run's own+ last letter (``t``) is itself a 1-letter prefix candidate; that+ coupling is why the 1-letter case above, where the ending is a+ single letter and no 2-letter run exists at all, is needed to+ isolate the 1-letter negative on its own.+ """+ line = "+ It's Rob's [email protected], not an address."+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []+ line = "+ Use 'Rob'[email protected]' for the icon."+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []+ line = "+ Use 'Burt'[email protected]' for the icon."+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []++ # Non-asset addresses: the HIDPI suppression cannot mask these,+ # so each pins its own negative lookbehind for real.+ one_letter = _addr("x", "nonreserved.tld")+ line = "+ Rob'sfoo nb'" + one_letter + "'"+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", "nb'" + one_letter)+ ]+ two_letter = _addr("x", "nonreserved.tld")+ line = "+ Curt'sfoo Burt'" + two_letter + "'"+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", "Burt'" + two_letter)+ ]++ @pytest.mark.parametrize("escape", ["n", "t", "r", "f"])+ @pytest.mark.parametrize(+ "path", ["src/app.py", "docs/x.md", "cfg.yaml", "cfg.json"]+ )+ def test_backslash_escape_is_not_a_one_char_local_part(self, escape, path):+ """A backslash plus one letter is an escape, not a local part."""+ decorator = _decorator("router.get")+ line = '+ src = "line\\' + escape + decorator + '"'+ assert list(mod.iter_added_emails(self._diff(path, line))) == []+ doubled = '+ src = "line\\\\' + escape + decorator + '"'+ assert list(mod.iter_added_emails(self._diff(path, doubled))) == []++ def test_backslash_before_a_real_local_part_still_matches(self):+ """Only the ONE-character shape is an escape; ``\\user@…`` is not."""+ bad = _addr("user", "nonreserved.tld")+ line = "+ path = C:\\" + bad+ assert list(mod.iter_added_emails(self._diff("src/app.py", line))) == [+ ("src/app.py", bad)+ ]++ @pytest.mark.parametrize(+ "prose",+ ["请确认", "확인", "ヲ確認", "です"],+ )+ def test_cjk_prose_after_reserved_domain_not_absorbed(self, prose):+ # the Hiragana-only prose rule wrongly absorbed+ # unspaced Chinese, Korean and Katakana prose into the domain.+ good = _addr("user", "example.com")+ assert list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ 联系方式 " + good + prose)+ )+ ) == [("docs/x.md", good)]++ def test_cjk_prose_after_non_reserved_domain_still_flags(self):+ # The prose boundary ends the domain but must not hide the address.+ bad = _addr("user", "gmail.com")+ assert list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + bad + "请确认")+ )+ ) == [("docs/x.md", bad)]++ def test_cjk_led_domain_extracts_full(self):+ # CJK-led labels remain domains: no ASCII-prefix truncation either.+ bad = _addr("user", "百度.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize("domain", ["a中.com", "中a.com"])+ def test_finds_mixed_script_idn_label_address(self, domain):+ # valid mixed Latin+Han labels (Python's stdlib IDNA+ # codec round-trips `a中.com` to `xn--a-lq6a.com`) were invisible+ # to the label grammar, so a staged real address exited 0.+ assert "xn--" in domain.encode("idna").decode("ascii")+ bad = _addr("user", domain)+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_mixed_script_label_with_trailing_prose_not_absorbed(self):+ # The mixed-label widening must not reopen the unspaced-prose+ # hole: CJK after the FINAL label still terminates the domain.+ bad = _addr("user", "a中.com")+ assert list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + bad + "请确认")+ )+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize("local", ["用户", "ユーザー", "사용자"])+ def test_finds_cjk_local_part_address(self, local):+ # pure-CJK local parts are valid SMTPUTF8+ # addresses but were wholly invisible to the local-part grammar.+ bad = _addr(local, "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ def test_cjk_prose_before_cjk_local_part_not_absorbed(self):+ # The CJK run must not swallow preceding prose: Hiragana — the+ # Hiragana prose boundary — ends the local part, so the address is+ # extracted from ユーザー, never the wider 宛先はユーザー.+ good = _addr("ユーザー", "example.com")+ line = "+ 宛先は" + good+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", good)+ ]++ def test_mixed_ascii_cjk_run_yields_ascii_local_part(self):+ # A run mixing ASCII with CJK is prose around an ASCII address;+ # the dot-atom local part is extracted, never widened.+ bad = _addr("user", "gmail.com")+ line = "+ 地址为" + bad+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", bad)+ ]++ @pytest.mark.parametrize("domain", ["foo.a中", "foo.中a"])+ def test_finds_mixed_script_final_label_address(self, domain):+ # a mixed-script FINAL label (foo.a中 /+ # foo.中a round-trip IDNA to xn-- A-labels) was invisible: the+ # mixed grammar was only reachable before another dot.+ assert "xn--" in domain.encode("idna").decode("ascii")+ bad = _addr("user", domain)+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + bad))+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize(+ "separator",+ [";2FA_METHOD=", "&CONTACT=", "&2FA_METHOD="],+ )+ def test_digit_and_ampersand_labelled_email_not_swallowed_by_uri_userinfo(+ self, separator+ ):+ # digit-led labels were consumed as userinfo+ # atoms and `&` had no assignment guard, so the labelled real+ # address after the URL was suppressed.+ bad = _addr("user", "gmail.com")+ line = "+ URL=https://example.com" + separator + bad+ assert list(mod.iter_added_emails(self._diff("cfg.ini", line))) == [+ ("cfg.ini", bad)+ ]++ @pytest.mark.parametrize(+ "line",+ [+ "+ Use [email protected].",+ "+ Use [email protected]",+ "+ Use [email protected]",+ "+ Use [email protected]",+ ],+ )+ def test_common_hidpi_asset_extensions_suppressed(self, line):+ # ico/bmp/tif/tiff/apng density assets were+ # extracted as addresses and blocked contributors.+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []++ def test_quoted_local_inner_address_is_not_a_phantom(self):+ # a quoted local part containing an+ # address-shaped substring is ONE address on its domain; the+ # inner text must not be extracted as a second, phantom one.+ full = _qaddr(_addr("y", "gmail.com"), "example.com")+ got = list(mod.iter_added_emails(self._diff("docs/x.md", "+ " + full)))+ assert got == [("docs/x.md", full)]++ def test_quoted_phantom_suppression_keeps_later_email(self):+ # The phantom rule suppresses only matches strictly inside the+ # quoted span; a separate address later on the line still hits.+ full = _qaddr(_addr("y", "gmail.com"), "example.com")+ bad = _addr("contact", "gmail.com")+ line = "+ " + full + " contact " + bad+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", bad),+ ("docs/x.md", full),+ ]++ def test_deep_docstring_address_reconstructed_from_post_image(self):+ # the opener sits far above the hunk,+ # so its context lines cannot establish string state; the+ # entry state must be rebuilt from the post-image content.+ bad = _addr("user", "gmail.com")+ post_image = "\n".join(+ ['DOC = """'] + ["filler"] * 5 + ["contact " + bad, '"""']+ )+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -3,6 +3,7 @@\n"+ " filler\n filler\n filler\n"+ "+contact " + bad + "\n"+ " filler\n filler\n filler\n"+ )+ got = list(mod.iter_added_emails(diff, post_image=lambda _: post_image))+ assert got == [("calc.py", bad)]++ def test_disjoint_hunks_rebuild_state_from_post_image(self):+ # the unchanged closing+ # delimiter lives in the gap between two hunks, so carrying+ # hunk-one string state across it disabled matmul suppression+ # for valid code in hunk two.+ post_image = "\n".join(+ [+ 'DOC = r"""',+ "text",+ '"""',+ "CONST = 1",+ "pad",+ "pad",+ "result = left@" + "matrix.transpose",+ ]+ )+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -1 +1 @@\n"+ '-DOC = """\n'+ '+DOC = r"""\n'+ "@@ -4,3 +4,4 @@\n"+ " CONST = 1\n"+ " pad\n"+ " pad\n"+ "+result = left@" + "matrix.transpose\n"+ )+ assert (+ list(mod.iter_added_emails(diff, post_image=lambda _: post_image))+ == []+ )++ def test_unresolvable_post_image_fails_toward_extraction(self):+ # When the loader cannot provide a .py post-image (an index path+ # git cannot resolve), the hunk-entry lexical state is unknown;+ # assuming code swallowed this docstring address. The file must+ # instead lose matmul suppression entirely and fail toward+ # extraction.+ bad = _addr("user", "gmail.com")+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -3,6 +3,7 @@\n"+ " filler\n filler\n filler\n"+ "+contact " + bad + "\n"+ " filler\n filler\n filler\n"+ )+ assert list(mod.iter_added_emails(diff, post_image=lambda _: None)) == [+ ("calc.py", bad)+ ]++ def test_non_utf8_c_quoted_path_round_trips_bytes(self):+ # b"caf\xe9.py" (latin-1) is not valid UTF-8; decoding the+ # C-quoted header with surrogateescape — not a U+FFFD stand-in —+ # lets a `git show :path` argv re-encode the original bytes so+ # the post-image lookup resolves the file.+ got = mod._git_unquote_path('"b/caf\\351.py"')+ assert got == "b/caf\udce9.py"+ assert got.encode("utf-8", "surrogateescape") == b"b/caf\xe9.py"+ # Valid UTF-8 paths decode exactly as before.+ assert mod._git_unquote_path('"b/caf\\303\\251.py"') == "b/café.py"++ def test_backslash_continued_string_address_extracted(self):+ # Python permits an ordinary string to+ # continue across a backslash-newline; the joined lines are one+ # string literal, so the address on the middle line is string+ # content, never matmul-suppressed code.+ bad = _addr("user", "gmail.com")+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -1,3 +1,3 @@\n"+ ' DOC = "first\\\n'+ "+" + bad + "\\\n"+ ' third"\n'+ )+ assert list(mod.iter_added_emails(diff)) == [("calc.py", bad)]++ def test_dense_cjk_prose_guard_rejections_are_linear(self):+ # Atomic CJK/non-CJK labels keep prose-bounded candidates linear.+ emails = [+ _addr(f"user{index}", "example.com") for index in range(10_000)+ ]+ parts = [+ f"地址{index}为" + email + "请确认"+ for index, email in enumerate(emails)+ ]+ started = perf_counter()+ found = list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + ",".join(parts))+ )+ )+ assert found == [("docs/x.md", email) for email in emails]+ assert perf_counter() - started < 1++ @pytest.mark.parametrize(+ "line",+ [+ "+ URL=https://example.com;CONTACT=" + _addr("user", "gmail.com"),+ "+ URL=https://example.com; email=" + _addr("user", "gmail.com"),+ "+ links=https://example.com,contact=" + _addr("user", "gmail.com"),+ ],+ )+ def test_labelled_assignment_email_not_swallowed_by_uri_userinfo(+ self, line+ ):+ # `;`, `=` and `@` are all userinfo atoms, so the span used+ # to reinterpret `example.com;CONTACT=user` as a URI password and+ # hide the separately labelled real address on the same line.+ bad = _addr("user", "gmail.com")+ assert list(mod.iter_added_emails(self._diff("cfg.ini", line))) == [+ ("cfg.ini", bad)+ ]++ @pytest.mark.parametrize(+ "separator",+ [",", ";", "&", "!", "$", "(", "*", "~", "'", "="],+ )+ def test_bare_separator_address_not_swallowed_by_uri_userinfo(+ self, separator+ ):+ # Every one of these separators used to be a userinfo atom, so+ # ``postgres://[email protected],victim@…`` parsed as one URI: the+ # host became the victim's domain and the separately written+ # real address was hidden (the hook failed open). A bare+ # separator now ends the span.+ bad = _addr("victim", "gmail.com")+ line = "+ postgres://[email protected]" + separator + bad+ assert list(mod.iter_added_emails(self._diff("cfg.ini", line))) == [+ ("cfg.ini", bad)+ ]++ @pytest.mark.parametrize(+ "tail",+ [+ "," + "L" * 70 + "=" + _addr("victim", "gmail.com"),+ ",-contact=" + _addr("victim", "gmail.com"),+ ",.contact=" + _addr("victim", "gmail.com"),+ ],+ )+ def test_any_label_shape_after_separator_ends_userinfo(self, tail):+ # The boundary must not depend on the label after the separator:+ # an over-long (>= 64 chars) or "."/"-"-led label still ends the+ # userinfo span.+ bad = _addr("victim", "gmail.com")+ line = "+ postgres://[email protected]" + tail+ assert list(mod.iter_added_emails(self._diff("cfg.ini", line))) == [+ ("cfg.ini", bad)+ ]++ @pytest.mark.parametrize(+ ("line", "surfaced"),+ [+ (+ "+ postgresql://user:" + _addr("p!ass", "smtp.gmail.com"),+ _addr("p!ass", "smtp.gmail.com"),+ ),+ (+ "+ smtp://user:" + _addr("p$ass", "mail.gmail.com"),+ _addr("ass", "mail.gmail.com"),+ ),+ (+ "+ https://x-access-token:" + _addr("$GH_TOKEN", "github.com"),+ _addr("GH_TOKEN", "github.com"),+ ),+ (+ "+ https://u:p;" + _addr("ass", "gmail.com") + "/path",+ _addr("ass", "gmail.com"),+ ),+ ],+ )+ def test_separator_password_surfaces_tail_address(self, line, surfaced):+ # Conscious reversal: the userinfo span no longer crosses a bare+ # separator, so a password containing one is no longer+ # suppressed — the tail after it reads as an address and such a+ # line needs the ``email-domains: allow`` marker. ``!`` and+ # ``'`` are preserved interior local-part characters (the bare+ # local-identity tests pin that), so the surfaced address itself+ # may span the separator; the other separators are not+ # local-part characters and only the tail after them surfaces.+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", surfaced)+ ]++ def test_python_matmul_operator_not_flagged_in_py_file(self):+ # PEP 465 permits the operator without spaces.+ diff = self._diff("math.py", "+ result = left@" + "matrix.transpose")+ assert list(mod.iter_added_emails(diff)) == []++ @pytest.mark.parametrize(+ "line",+ [+ 'doc = f"{" contact ' + _addr("user", "gmail.com") + '}"',+ 'msg = f"{"x contact ' + _addr("user", "gmail.com") + '}"',+ 'd = f"{ {"k": "mail ' + _addr("user", "gmail.com") + '"}["k"] }"',+ 'w = rf"{" contact ' + _addr("user", "gmail.com") + '}"',+ ],+ )+ def test_pep701_same_quote_fstring_address_flagged(self, line):+ # PEP 701 (Python >= 3.12, the project's floor) lets a replacement+ # field reuse the enclosing quote, so each of these is ONE string+ # literal. Plain quote parity flipped at the inner quote, read the+ # literal text between the fields as code, and matmul-suppressed+ # the address written inside it (the hook failed open).+ bad = _addr("user", "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("app.py", "+" + line))+ ) == [("app.py", bad)]++ def test_matmul_suppression_resumes_after_closed_fstring(self):+ # The f-string scan must end at its real closing quote: code later+ # on the line is code again, and plain matmul stays suppressed.+ line = '+tag = f"{x}"; v = left@' + "matrix.transpose"+ assert list(mod.iter_added_emails(self._diff("app.py", line))) == []++ def test_fstring_expression_matmul_text_fails_toward_extraction(self):+ # Inside a prefixed literal the ambiguous region is classified as+ # string: even genuinely matmul-shaped replacement-field text is+ # surfaced for review rather than suppressed.+ line = '+y = f"{left@' + "matrix.transpose}"+ assert list(mod.iter_added_emails(self._diff("app.py", line))) == [+ ("app.py", _addr("left", "matrix.transpose"))+ ]++ @pytest.mark.parametrize(+ "line",+ [+ 'msg = f"""{""" contact ' + _addr("user", "gmail.com") + '"""}"""',+ 'msg = F"""{""" contact ' + _addr("user", "gmail.com") + '"""}"""',+ "msg = f'''{''' contact " + _addr("user", "gmail.com") + "'''}'''",+ ],+ )+ def test_pep701_triple_quoted_fstring_address_flagged(self, line):+ # A triple-quoted f-string is still an f-string: a quote run of+ # >= 3 used to take the plain-triple branch before the prefix+ # check, so the same-triple-quote literal inside the replacement+ # field closed the string early, the tail read as code, and the+ # matmul-shaped address inside was suppressed (fail-open).+ bad = _addr("user", "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("app.py", "+" + line))+ ) == [("app.py", bad)]++ def test_backslash_continued_field_matmul_text_still_flagged(self):+ # Conservative sibling of the nested-field resume: matmul-shaped+ # text inside a replacement field is classified as string and+ # surfaced for review (fail toward extraction), on a continued+ # line exactly as on a single line.+ shaped = _addr("left", "matrix.transpose")+ diff = (+ "diff --git a/app.py b/app.py\n"+ "--- a/app.py\n+++ b/app.py\n"+ "@@ -0,0 +1,2 @@\n"+ '+x = f"{1 + \\\n'+ "+" + shaped + "}\n"+ )+ assert list(mod.iter_added_emails(diff)) == [("app.py", shaped)]++ def test_backslash_continued_fstring_address_extracted(self):+ # A prefixed string continues across a backslash-newline like an+ # ordinary one; the carried state keeps the f-string rules.+ bad = _addr("user", "gmail.com")+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -1,3 +1,3 @@\n"+ ' DOC = f"first\\\n'+ "+" + bad + "\\\n"+ ' tail{x}"\n'+ )+ assert list(mod.iter_added_emails(diff)) == [("calc.py", bad)]++ def test_backslash_continued_fstring_nested_field_resumed(self):+ # The backslash-newline sits INSIDE a replacement field's nested+ # string. The resume used to restart at field depth zero with no+ # nested string, so the nested closer read as the f-string's own+ # closer and the appended address landed in code, where matmul+ # suppression hid it (fail-open).+ bad = _addr("user", "gmail.com")+ diff = (+ "diff --git a/app.py b/app.py\n"+ "--- a/app.py\n+++ b/app.py\n"+ "@@ -0,0 +1,2 @@\n"+ '+x = f"{"a\\\n'+ '+b" } contact ' + bad + '"\n'+ )+ assert list(mod.iter_added_emails(diff)) == [("app.py", bad)]++ def test_python_matmul_after_keyword_not_flagged(self):+ diff = self._diff("math.pyi", "+ return left@" + "matrix.transpose")+ assert list(mod.iter_added_emails(diff)) == []++ def test_python_matmul_dotted_left_operand_not_flagged(self):+ # only a bare identifier was accepted on the left, so a+ # dotted left operand (``self.left`` @ ``matrix.transpose``)+ # was extracted as an address.+ diff = self._diff(+ "math.py", "+ result = self.left@" + "matrix.transpose"+ )+ assert list(mod.iter_added_emails(diff)) == []++ def test_python_multiline_string_address_not_matmul_suppressed(self):+ # each added line was classified in isolation, so a+ # docstring body line counted as code and the matmul-shaped+ # address inside it was suppressed.+ bad = _addr("user", "gmail.com")+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -0,0 +3 @@\n"+ '+DOC = """\n'+ "+contact " + bad + "\n"+ '+"""\n'+ )+ assert list(mod.iter_added_emails(diff)) == [("calc.py", bad)]++ def test_python_multiline_string_opened_on_context_line(self):+ # Context lines belong to the post-image: a literal opened on an+ # unchanged line still shields the added line between its quotes.+ bad = _addr("user", "gmail.com")+ diff = (+ "diff --git a/calc.py b/calc.py\n"+ "--- a/calc.py\n+++ b/calc.py\n"+ "@@ -1,3 +1,3 @@\n"+ ' DOC = """\n'+ "+contact " + bad + "\n"+ ' """\n'+ )+ assert list(mod.iter_added_emails(diff)) == [("calc.py", bad)]++ def test_python_string_state_resets_between_files(self):+ # An unclosed docstring in one file must not leak into the next:+ # valid matmul code there would lose its suppression.+ diff = (+ "diff --git a/a.py b/a.py\n"+ "--- a/a.py\n+++ b/a.py\n"+ "@@ -0,0 +1 @@\n"+ '+DOC = """\n'+ "diff --git a/b.py b/b.py\n"+ "--- b/b.py\n+++ b/b.py\n"+ "@@ -0,0 +1 @@\n"+ "+y = left@" + "matrix.transpose\n"+ )+ assert list(mod.iter_added_emails(diff)) == []++ @pytest.mark.parametrize(+ "line",+ [+ '+ url = "' + _addr("user", "gmail.com") + '"',+ "+ # contact " + _addr("user", "gmail.com"),+ "+ x = 'a' + '" + _addr("user", "gmail.com") + "'",+ ],+ )+ def test_py_string_and_comment_addresses_still_flagged(self, line):+ # Matmul suppression is code-only: quoted and commented addresses+ # keep being extracted from Python files.+ bad = _addr("user", "gmail.com")+ assert list(mod.iter_added_emails(self._diff("app.py", line))) == [+ ("app.py", bad)+ ]++ def test_matmul_shaped_token_in_non_python_file_still_flagged(self):+ # The suppression is scoped to Python paths only.+ bad = _addr("left", "matrix.transpose")+ assert list(+ mod.iter_added_emails(self._diff("notes.txt", "+ result = " + bad))+ ) == [("notes.txt", bad)]++ @pytest.mark.parametrize(+ "line",+ [+ "+ .hero { background: url([email protected]); }",+ "+ .hero { background: url(a%[email protected]); }",+ ],+ )+ def test_hidpi_asset_with_plus_or_percent_basename_suppressed(self, line):+ # the asset basename charset excluded `+`/`%`, so the+ # sprite filename was read as an address on `2x.png`.+ assert list(mod.iter_added_emails(self._diff("style.css", line))) == []++ @pytest.mark.parametrize(+ "line", ["+ Use [email protected].", "+ Use [email protected]..."]+ )+ def test_hidpi_asset_sentence_punctuation_suppressed(self, line):+ # a sentence-final period right after the extension+ # defeated the asset boundary and the basename was read as an+ # address on `2x.png`.+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []++ def test_hidpi_asset_double_extension_still_extracted(self):+ # A `.` followed by more basename characters is a longer+ # filename, not sentence punctuation: the asset boundary must+ # still break so the token stays an address to review.+ bad = _addr("icon", "2x.png.jpg")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ Use " + bad))+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize(+ "line",+ [+ "+ addr = u'[email protected]'",+ "+ addr = rb'[email protected]'",+ "+ addr = f'{stem}@3x.webp'",+ '+ addr = f"{name}@2x.png"',+ ],+ )+ def test_prefixed_or_interpolated_hidpi_basename_suppressed(self, line):+ # A Python string-prefix letter (``u'…'``, ``rb'…'``) or an+ # f-string interpolation (``f'{stem}…'``, ``f"{name}…"``) sits+ # directly before, or inside, the asset basename. The delimited+ # address these forms open starts one or more characters INSIDE+ # the HIDPI asset match — at ``i`` of ``icon``, or at ``{`` of+ # ``{stem}``/``{name}`` — while the asset pattern's own match+ # starts at the prefix letter or at the interpolation's own+ # opening brace. A suppression keyed only to the asset match's+ # START offset never covers that inner offset, and the address+ # is reported; only suppressing every offset across the whole+ # asset span covers it. This is a regression pin for that full+ # span, not just its class widening to admit ``{``/``}``/``"``:+ # ``u'[email protected]'`` and ``rb'[email protected]'`` need only the+ # full-span suppression (their basenames contain no interpolation+ # characters); ``f'{stem}@3x.webp'`` and ``f"{name}@2x.png"``+ # need both the full span AND the widened basename class.+ assert list(mod.iter_added_emails(self._diff("src/app.py", line))) == []++ def test_idn_near_miss_suffix_not_matched(self):+ # Mirrors the ASCII "[email protected]" rejection for U-label domains.+ assert (+ list(+ mod.iter_added_emails(+ self._diff(+ "docs/x.md",+ "+ " + _addr("user", "bücher.com") + "-backup",+ )+ )+ )+ == []+ )++ def test_underscore_near_miss_suffix_not_matched(self):+ # Mirrors the "-backup" rejection for "_": "_" is a word+ # character, so "[email protected]_backup" is a filename-shaped near miss,+ # not an address to review.+ assert (+ list(+ mod.iter_added_emails(+ self._diff(+ "docs/x.md",+ "+ " + _addr("x", "y.com") + "_backup",+ )+ )+ )+ == []+ )++ def test_underscore_glued_tail_address_is_flagged(self):+ # The final-label guard left "_" out of its near-miss class, so+ # an allowed head with a real address glued on by "_" yielded+ # ONLY the allowed head: the visible tail address was never+ # surfaced (the hook exited 0). "_" must glue like "-" does:+ # the tail is extracted as the glued form and fails the check.+ line = (+ "+ see "+ + _addr("user", "example.com")+ + "_"+ + _addr("victim", "real.com")+ )+ glued = "example.com_" + _addr("victim", "real.com")+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == [+ ("docs/x.md", glued)+ ]++ @pytest.mark.parametrize(+ ("uri_prefix", "host"),+ [+ ("mailto://user:", "smtp.gmail.com"),+ ("smtp://user:", "mail.gmail.com"),+ ("postgresql://user:", "db.gmail.com"),+ ("mongodb://user:", "db.gmail.com"),+ ],+ )+ def test_skips_uri_authority_passwords(self, uri_prefix, host):+ credential = _addr("password", host)+ assert (+ list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + uri_prefix + credential)+ )+ )+ == []+ )++ @pytest.mark.parametrize(+ ("uri_prefix", "password", "host"),+ [+ ("mongodb://user:", "p:ass", "db.gmail.com"),+ # MongoDB-style connection strings allow a raw "@" inside the+ # password; the userinfo span must cover it so the tail after+ # it is not read as a phantom address.+ ("mongodb://admin:", "p@ss", "db.acme.io"),+ ("https://x-access-token:", "${GITHUB_TOKEN}", "github.com"),+ ],+ )+ def test_skips_punctuation_and_template_uri_passwords(+ self, uri_prefix, password, host+ ):+ credential = _addr(password, host)+ assert (+ list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + uri_prefix + credential)+ )+ )+ == []+ )++ @pytest.mark.parametrize(+ "line",+ [+ '+ <img src="[email protected]">',+ '+ <img src="[email protected]">',+ # Density assets exist at every integer scale, not just 2x/3x.+ '+ <img src="[email protected]">',+ "+ git clone " + _addr("git", "gitlab.com") + ":org/repo.git",+ # A single-component scp-style path is a valid remote.+ "+ git clone " + _addr("git", "gitlab.com") + ":myrepo.git",+ "+ scp file " + _addr("deploy", "server.company.com") + ":/srv/",+ "+ https://" + _addr("user", "gmail.com") + "/path",+ "+ git push https://"+ + _addr("x-access-token", "github.com")+ + "/org/repo.git",+ "+ smtp://user:password@bücher.de/mail",+ "+ smtp://user:[email protected]/mail",+ ],+ )+ def test_skips_non_email_at_sign_syntax(self, line):+ assert list(mod.iter_added_emails(self._diff("docs/x.md", line))) == []++ @pytest.mark.parametrize(+ "prefix",+ [+ "https://" + _addr("user", "gmail.com") + "/path contact ",+ "git clone " + _addr("git", "gitlab.com") + ":org/repo.git owner ",+ '<img src="[email protected]"> owner ',+ ],+ )+ def test_non_email_syntax_does_not_swallow_nearby_email(self, prefix):+ bad = _addr("contact", "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + prefix + bad))+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize(+ "prefix",+ [+ "label:",+ "mailto:",+ "https://host.example/path/",+ "https://host.example/?contact=",+ "links=https://example.com,mailto:",+ "See <https://example.com>:",+ '"https://example.com" ',+ "[link](https://example.com) ",+ ],+ )+ def test_finds_emails_outside_uri_authority_userinfo(self, prefix):+ bad = _addr("user", "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + prefix + bad))+ ) == [("docs/x.md", bad)]++ @pytest.mark.parametrize(+ "prefix",+ [+ "https://user|text:email:",+ "https://user`text:email:",+ "https://user}text:email:",+ r"https://user\text:email:",+ ],+ )+ def test_finds_email_after_invalid_uri_username_separator(self, prefix):+ bad = _addr("contact", "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + prefix + bad))+ ) == [("docs/x.md", bad)]++ def test_dense_email_matches_are_linear(self):+ emails = [_addr(f"user{index}", "gmail.com") for index in range(30_000)]+ started = perf_counter()+ found = list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + " ".join(emails))+ )+ )+ assert found == [("docs/x.md", email) for email in emails]+ assert perf_counter() - started < 1++ def test_dense_mixed_uri_and_email_matches_are_linear(self):+ credentials = [+ "smtp://user:" + _addr("p@ss", "smtp.gmail.com")+ for _ in range(5_000)+ ]+ emails = [_addr(f"user{index}", "gmail.com") for index in range(5_000)]+ started = perf_counter()+ found = list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + " ".join(credentials + emails))+ )+ )+ assert found == [("docs/x.md", email) for email in emails]+ assert perf_counter() - started < 1++ def test_dense_unicode_email_matches_are_linear(self):+ emails = [_addr(f"user{index}", "bücher.de") for index in range(10_000)]+ started = perf_counter()+ found = list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + " ".join(emails))+ )+ )+ assert found == [("docs/x.md", email) for email in emails]+ assert perf_counter() - started < 1++ def test_dense_guard_rejections_are_linear(self):+ # Every IDN candidate here FAILS the trailing guard (CJK text glued+ # straight after the domain). Atomic labels keep that failure cheap+ # instead of retrying every label split.+ emails = [+ _addr(f"user{index}", "example.com") for index in range(10_000)+ ]+ parts = [+ f"項目{index}は" + email + "です"+ for index, email in enumerate(emails)+ ]+ started = perf_counter()+ found = list(+ mod.iter_added_emails(+ self._diff("docs/x.md", "+ " + "、".join(parts))+ )+ )+ assert found == [("docs/x.md", email) for email in emails]+ assert perf_counter() - started < 1++ def test_ignores_removed_lines(self):+ bad = _addr("real.person", "gmail.com")+ diff = (+ "diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +0,0 @@\n- old "+ + bad+ + "\n"+ )+ assert list(mod.iter_added_emails(diff)) == []++ def test_ignores_context_lines(self):+ bad = _addr("real.person", "gmail.com")+ diff = "+++ b/x\n@@ -1 +1 @@\n unchanged " + bad + "\n"+ assert list(mod.iter_added_emails(diff)) == []++ def test_skips_lockfiles(self):+ bad = _addr("dep.author", "gmail.com")+ diff = self._diff("package-lock.json", "+ " + bad)+ assert list(mod.iter_added_emails(diff)) == []++ def test_plus_header_not_treated_as_content(self):+ # A real "+++ b/path" header (before any @@) must not be scanned.+ bad = _addr("x", "gmail.com")+ diff = f"+++ b/{bad}\n"+ assert list(mod.iter_added_emails(diff)) == []++ def test_plus_plus_content_inside_hunk_is_scanned(self):+ # A line whose CONTENT begins with '++' renders as '+++...' but is an+ # added content line inside the hunk, not a header. (regression)+ bad = _addr("victim", "gmail.com")+ diff = (+ "diff --git a/f.md b/f.md\n--- a/f.md\n+++ b/f.md\n"+ "@@ -1 +1,2 @@\n ctx\n+++ note " + bad + "\n"+ )+ assert list(mod.iter_added_emails(diff)) == [("f.md", bad)]++ def test_content_line_cannot_hijack_path_into_skip(self):+ # A '++ x/pdm.lock' content line must not corrupt path into a skip and+ # suppress the rest of the hunk. (regression)+ bad = _addr("victim", "gmail.com")+ diff = (+ "diff --git a/f.md b/f.md\n--- a/f.md\n+++ b/f.md\n"+ "@@ -1 +1,3 @@\n ctx\n++ x/pdm.lock\n+" + bad + "\n"+ )+ assert list(mod.iter_added_emails(diff)) == [("f.md", bad)]++ def test_trailing_space_filename_not_collapsed_to_skip(self):+ # Git emits "+++ b/uv.lock \t\n" for a file literally named "uv.lock "+ # (with a trailing space). The hook must strip only Git's unified-+ # header separator tab and preserve the significant trailing space,+ # so that Path('uv.lock ').name (which keeps the space) is NOT matched+ # by SKIP_BASENAMES and the added email is scanned. (regression:+ # line[4:].strip() collapsed the space, silently failing open.)+ bad = _addr("person", "gmail.com")+ diff = "+++ b/uv.lock \t\n@@ -0,0 +1 @@\n+ " + bad + "\n"+ assert list(mod.iter_added_emails(diff)) == [("uv.lock ", bad)]++ def test_git_c_quoted_py_path_keeps_matmul_suppression(self):+ # a non-ASCII path arrives C-quoted as+ # `+++ "b/caf\\303\\251.py"`; undecoded, the suffix kept the+ # trailing quote and valid matmul code in that file was flagged.+ diff = (+ 'diff --git "a/caf\\303\\251.py" "b/caf\\303\\251.py"\n'+ "new file mode 100644\n"+ "--- /dev/null\n"+ '+++ "b/caf\\303\\251.py"\n'+ "@@ -0,0 +1 @@\n"+ "+result = left@" + "matrix.transpose\n"+ )+ assert list(mod.iter_added_emails(diff)) == []++ def test_git_c_quoted_path_decodes_for_attribution(self):+ # The decoded path must also reach the yield so offenders are+ # attributed (and lock/suffix rules apply) on real filenames.+ bad = _addr("real", "gmail.com")+ diff = (+ 'diff --git "a/caf\\303\\251.txt" "b/caf\\303\\251.txt"\n'+ "--- /dev/null\n"+ '+++ "b/caf\\303\\251.txt"\n'+ "@@ -0,0 +1 @@\n"+ "+contact " + bad + "\n"+ )+ assert list(mod.iter_added_emails(diff)) == [("café.txt", bad)]++ def test_unicode_line_separator_not_split(self):+ # str.splitlines() breaks on U+2028 and would drop the tail; split('\n')+ # keeps the address on its line. (regression)+ bad = _addr("hidden", "gmail.com")+ diff = "+++ b/x\n@@ -0,0 +1 @@\n+lead " + bad+ assert list(mod.iter_added_emails(diff)) == [("x", bad)]++ def test_crlf_line_endings(self):+ bad = _addr("real", "gmail.com")+ diff = "+++ b/x\r\n@@ -0,0 +1 @@\r\n+ " + bad + "\r\n"+ assert list(mod.iter_added_emails(diff)) == [("x", bad)]++ def test_inline_allow_marker_skips_line(self):+ bad = _addr("real", "gmail.com")+ diff = self._diff(+ "docs/x.md", "+ smtp = " + bad + " # email-domains: allow"+ )+ assert list(mod.iter_added_emails(diff)) == []++ def test_allow_marker_is_case_insensitive_same_line_substring(self):+ bad = _addr("real", "gmail.com")+ diff = self._diff("docs/x.md", "+ " + bad + " EMAIL-DOMAINS: ALLOW")+ assert list(mod.iter_added_emails(diff)) == []++ def test_overlong_local_token_is_not_suffix_matched(self):+ overlong = _addr("a" * 65, "gmail.com")+ assert (+ list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + overlong))+ )+ == []+ )++ def test_maximum_length_local_part_is_matched(self):+ maximum = _addr("a" * 64, "gmail.com")+ assert list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + maximum))+ ) == [("docs/x.md", maximum)]++ def test_overlong_domain_label_is_not_suffix_matched(self):+ overlong = _addr("real", "a" * 64 + ".com")+ assert (+ list(+ mod.iter_added_emails(self._diff("docs/x.md", "+ " + overlong))+ )+ == []+ )++ def test_long_unmatched_token_is_bounded(self):+ # The previous unbounded local-part repetition backtracked quadratically.+ diff = self._diff("docs/x.md", "+ " + "a" * 60_000)+ started = perf_counter()+ assert list(mod.iter_added_emails(diff)) == []+ assert perf_counter() - started < 1++ @pytest.mark.parametrize(+ "lockfile", ["yarn.lock", "sub/uv.lock", "Cargo.lock"]+ )+ def test_skips_more_lockfiles(self, lockfile):+ bad = _addr("dep", "gmail.com")+ assert (+ list(mod.iter_added_emails(self._diff(lockfile, "+ " + bad))) == []+ )++ def test_multifile_path_attribution_and_skip_reset(self):+ # A lockfile (skipped) followed by a real file: the skip state must not+ # leak, and the email must be attributed to the correct path. The+ # second file is deliberately NOT Python: a bare `[email protected]` token in+ # code context is matmul (suppressed), which this test does not+ # exercise — and which silently failed it with a missing post-image.+ dep = _addr("dep", "gmail.com")+ bad = _addr("real", "gmail.com")+ diff = (+ "diff --git a/pdm.lock b/pdm.lock\n--- a/pdm.lock\n+++ b/pdm.lock\n"+ "@@ -0,0 +1 @@\n+ " + dep + "\n"+ "diff --git a/src/r.md b/src/r.md\n--- a/src/r.md\n+++ b/src/r.md\n"+ "@@ -0,0 +1 @@\n+ " + bad + "\n"+ )+ assert list(mod.iter_added_emails(diff)) == [("src/r.md", bad)]+++def test_unparseable_hunk_header_line_flags_zero_until_next_header():+ """An unparseable ``@@`` header cannot say where added lines live.++ ``new_lineno_known`` goes False when a hunk header fails to parse, so+ every added line under THAT header reports the ``0`` sentinel line+ (a bare path, never a wrong line number that happens to start+ counting from 0). The next PARSEABLE header resets the flag and+ resumes normal counting from its own new-side start.+ """+ first = _addr("first", "gmail.com")+ second = _addr("second", "gmail.com")+ third = _addr("third", "gmail.com")+ fourth = _addr("fourth", "gmail.com")+ diff = (+ "diff --git a/a.md b/a.md\n"+ "--- a/a.md\n+++ b/a.md\n"+ "@@ garbage @@\n"+ "+first " + first + "\n"+ " ctx\n"+ "+second " + second + "\n"+ "@@ -1,2 +10,3 @@\n"+ "+third " + third + "\n"+ " ctx\n"+ "+fourth " + fourth + "\n"+ )+ assert list(mod.iter_added_findings(diff)) == [+ ("a.md", first, 0),+ ("a.md", second, 0),+ ("a.md", third, 10),+ ("a.md", fourth, 12),+ ]++[email protected](autouse=True)+def no_ci_env(monkeypatch):+ """Isolate staged cases; PR-context cases supply their own event metadata."""+ for k in ("GITHUB_EVENT_NAME", "GITHUB_EVENT_PATH"):+ monkeypatch.delenv(k, raising=False)+++class TestMain:+ def _run(self, monkeypatch, diff, pyproject=""):+ monkeypatch.setattr(mod, "_pr_context", lambda: (diff, pyproject, None))+ return mod.main()++ def test_clean_passes(self, monkeypatch):+ good = (+ "+++ b/tests/x.py\n@@ -0,0 +1 @@\n+ addr = '"+ + _addr("u", "example.com")+ + "'\n"+ )+ assert self._run(monkeypatch, good) == 0++ def test_personal_email_failure_lists_path_without_printing_address(+ self, monkeypatch, capsys+ ):+ bad = _addr("john.doe", "gmail.com")+ diff = (+ "+++ b/docs/readme.md\n@@ -0,0 +1 @@\n+ reach me at " + bad + "\n"+ )+ rc = self._run(monkeypatch, diff)+ err = capsys.readouterr().err+ assert rc == 1+ assert "Email domain check failed" in err+ assert "docs/readme.md" in err+ assert "@users.noreply.github.com" in err+ assert bad not in err # the offending address must never be printed++ def test_personal_email_failure_lists_each_location_once(+ self, monkeypatch, capsys+ ):+ """Repeats on ONE line collapse; distinct lines are listed apart.++ Two DIFFERENT addresses on the same line, not one repeated: a+ single repeated address collapses just as well under a dedup keyed+ on ``(path, email, line)`` as under the intended ``(path, line)``+ key, so that shape cannot catch a regression to the finer-grained+ key. Two distinct addresses on one line only stay collapsed to one+ location under ``(path, line)``.+ """+ first = _addr("john.doe", "gmail.com")+ second = _addr("jane.roe", "gmail.com")+ diff = (+ "+++ b/docs/readme.md\n@@ -0,0 +1,2 @@\n"+ "+ reach me at " + first + " or at " + second + "\n"+ "+ clean line\n"+ )+ assert self._run(monkeypatch, diff) == 1+ err = capsys.readouterr().err+ assert err.count("docs/readme.md") == 1+ assert first not in err+ assert second not in err++ def test_personal_email_failure_reports_each_offending_line(+ self, monkeypatch, capsys+ ):+ """The 1-based post-image line locates a false positive."""+ bad = _addr("john.doe", "gmail.com")+ diff = (+ "+++ b/docs/readme.md\n@@ -10,2 +12,4 @@\n"+ " context\n"+ "-dropped\n"+ "+ reach me at " + bad + "\n"+ " context\n"+ "+ or at " + bad + "\n"+ )+ assert self._run(monkeypatch, diff) == 1+ lines = capsys.readouterr().err.splitlines()+ assert (+ " docs/readme.md:13: adds an email on a non-reserved domain"+ in lines+ )+ assert (+ " docs/readme.md:15: adds an email on a non-reserved domain"+ in lines+ )+ assert bad not in "\n".join(lines)++ def test_personal_email_failure_redacts_email_bearing_path(+ self, monkeypatch, capsys+ ):+ path_email = _addr("owner", "gmail.com")+ bad = _addr("contact", "gmail.com")+ diff = "+++ b/docs/" + path_email + "\n@@ -0,0 +1 @@\n+ " + bad + "\n"+ assert self._run(monkeypatch, diff) == 1+ err = capsys.readouterr().err+ assert "<path containing email>" in err+ assert path_email not in err+ assert bad not in err++ def test_personal_email_failure_redacts_suffixed_email_bearing_path(+ self, monkeypatch, capsys+ ):+ # A path like "docs/[email protected]" contains an email-like+ # token but the strict EMAIL_RE rejects it (suffix boundary), so the+ # previous EMAIL_RE.search(path) predicate leaked the full path.+ # Redaction must be conservative: any "@" in the path triggers it.+ suffix = "-backup"+ path_email = _addr("contact", "gmail.com") + suffix+ bad = _addr("contact", "gmail.com")+ diff = "+++ b/docs/" + path_email + "\n@@ -0,0 +1 @@\n+ " + bad + "\n"+ assert self._run(monkeypatch, diff) == 1+ err = capsys.readouterr().err+ assert "<path containing email>" in err+ assert path_email not in err+ assert bad not in err++ def test_declared_author_in_content_passes(self, monkeypatch):+ addr = _addr("djpetti", "gmail.com")+ diff = "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ djpetti <" + addr + ">\n"+ pyproject = '[project]\nauthors = [{name="d", email="' + addr + '"}]\n'+ assert self._run(monkeypatch, diff, pyproject) == 0++ def test_declared_author_in_doubled_backtick_wrapper_passes(+ self, monkeypatch+ ):+ """Pins the per-wrapper exclusion: each wrapper drops its own char.++ Without dropping the backtick from its own local-part punctuation+ class, doubled backticks (```` ``[email protected]`` ````) read the+ first backtick as delimiter and the second as a local-part+ character, prepending it to the local part — the extracted+ address no longer matches the declared author exactly, and a+ clean doc fails.+ """+ addr = _addr("me", "author.io")+ diff = "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ Maintainer: ``" + addr + "``\n"+ pyproject = '[project]\nauthors = [{name="m", email="' + addr + '"}]\n'+ assert self._run(monkeypatch, diff, pyproject) == 0++ def test_declared_ascii_led_unicode_tld_author_passes(self, monkeypatch):+ # only the ASCII prefix of the declared+ # address was extracted, so the allow-list never matched and+ # declared content failed the check.+ addr = _addr("user", "example.vermögensberater")+ diff = "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ maintainer <" + addr + ">\n"+ pyproject = '[project]\nauthors = [{name="d", email="' + addr + '"}]\n'+ assert self._run(monkeypatch, diff, pyproject) == 0++ def test_declared_unicode_local_author_passes(self, monkeypatch):+ # extraction entered the local part mid-token, so the+ # exact allow-list comparison failed even for the declared author.+ addr = _addr("müller", "wichtig.de")+ diff = "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ maintainer <" + addr + ">\n"+ pyproject = '[project]\nauthors = [{name="d", email="' + addr + '"}]\n'+ assert self._run(monkeypatch, diff, pyproject) == 0++ def test_declared_cjk_local_author_passes(self, monkeypatch):+ # a declared author with a CJK local part+ # could never be matched, so their address always failed.+ addr = _addr("ユーザー", "wichtig.de")+ diff = "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ maintainer <" + addr + ">\n"+ pyproject = '[project]\nauthors = [{name="d", email="' + addr + '"}]\n'+ assert self._run(monkeypatch, diff, pyproject) == 0++ @pytest.mark.parametrize(+ ("declared", "content"),+ [+ (+ _addr("user", "gmail.comрф"),+ _addr("user", "gmail.comрф"),+ ),+ (+ _addr("user", "example.vermo\u0308gensberater"),+ _addr("user", "example.vermo\u0308gensberater"),+ ),+ (+ _addr("user", "名前.テスト"),+ _addr("user", "名前.テスト") + "をご確認ください",+ ),+ ],+ )+ def test_round_five_declared_unicode_author_passes(+ self, monkeypatch, declared, content+ ):+ diff = "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ maintainer <" + content + ">\n"+ pyproject = (+ '[project]\nauthors = [{name="d", email="' + declared + '"}]\n'+ )+ assert self._run(monkeypatch, diff, pyproject) == 0++ def test_idn_combining_mark_and_ascii_led_addresses_fail(self, monkeypatch):+ # both forms are valid IDNA U-labels on non-reserved+ # domains, yet neither was extracted, so the hook exited 0.+ first = _addr("user", "उदाहरण.भारत")+ second = _addr("user", "bücher.aü")+ diff = (+ "+++ b/docs/x.md\n@@ -0,0 +1,2 @@\n+ "+ + first+ + "\n+ "+ + second+ + "\n"+ )+ assert self._run(monkeypatch, diff) == 1++ def test_punycode_tld_address_fails(self, monkeypatch):+ bad = _addr("person", "example.xn--p1ai")+ diff = "+++ b/docs/x.md\n@@ -0,0 +1 @@\n+ " + bad + "\n"+ assert self._run(monkeypatch, diff) == 1++ def test_unicode_domain_address_fails(self, monkeypatch):+ bad = _addr("person", "bücher.de")+ diff = "+++ b/docs/x.md\n@@ -0,0 +1 @@\n+ " + bad + "\n"+ assert self._run(monkeypatch, diff) == 1++ def test_quoted_local_part_address_fails(self, monkeypatch):+ bad = _qaddr("john doe", "gmail.com")+ diff = "+++ b/docs/x.md\n@@ -0,0 +1 @@\n+ " + bad + "\n"+ assert self._run(monkeypatch, diff) == 1++ def test_cjk_glued_reserved_address_passes(self, monkeypatch):+ good = _addr("user", "example.com")+ diff = "+++ b/docs/x.md\n@@ -0,0 +1 @@\n+ 連絡先 " + good + "です\n"+ assert self._run(monkeypatch, diff) == 0++ def test_fails_closed_on_unresolvable_range(self, monkeypatch, capsys):+ def boom():+ raise RuntimeError("could not resolve the PR commit range")++ monkeypatch.setattr(mod, "_pr_context", boom)+ rc = mod.main()+ assert rc == 1+ assert "failing closed" in capsys.readouterr().err++ def test_staged_diff_failure_fails_closed_without_leaking_output(+ self, monkeypatch, no_ci_env, capsys+ ):+ leaked = _addr("secret", "gmail.com")+ monkeypatch.setattr(mod, "_git", lambda *args: (1, leaked))+ rc = mod.main()+ err = capsys.readouterr().err+ assert rc == 1+ assert "staged diff" in err+ assert "exit status 1" in err+ assert "failing closed" in err+ assert leaked not in err++ def test_staged_pyproject_show_failure_fails_closed(+ self, monkeypatch, no_ci_env, capsys+ ):+ leaked = _addr("secret", "gmail.com")++ def fake_git(*args):+ if args[0] == "diff":+ return 0, ""+ if args[0] == "show":+ return 1, leaked+ raise AssertionError(args)++ monkeypatch.setattr(mod, "_git", fake_git)+ assert mod.main() == 1+ err = capsys.readouterr().err+ assert "staged pyproject.toml show" in err+ assert "exit status 1" in err+ assert leaked not in err++ def test_malformed_pyproject_fails_closed_without_leaking_content(+ self, monkeypatch, capsys+ ):+ leaked = _addr("secret", "gmail.com")+ malformed = "[project\nauthors = '" + leaked + "'\n"+ assert self._run(monkeypatch, "", malformed) == 1+ assert leaked not in capsys.readouterr().err++ def test_local_mode_uses_staged_context(self, monkeypatch, no_ci_env):+ # _pr_context returns None off a PR event; main() falls back to staged.+ monkeypatch.setattr(mod, "_pr_context", lambda: None)+ bad = _addr("dev", "gmail.com")+ monkeypatch.setattr(+ mod,+ "_staged_context",+ lambda: (+ "+++ b/a.py\n@@ -0,0 +1 @@\n+ x='" + bad + "'\n",+ "",+ None,+ ),+ )+ assert mod.main() == 1+++class TestPrContext:+ """Fail-closed behaviour of _pr_context on a genuine PR event."""++ def _pr_env(self, monkeypatch, tmp_path, payload_text):+ monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")+ p = tmp_path / "event.json"+ p.write_text(payload_text, encoding="utf-8")+ monkeypatch.setenv("GITHUB_EVENT_PATH", str(p))++ def test_missing_payload_file_fails_closed(self, monkeypatch, tmp_path):+ monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")+ monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "nope.json"))+ with pytest.raises(RuntimeError):+ mod._pr_context()++ def test_bad_json_fails_closed(self, monkeypatch, tmp_path):+ self._pr_env(monkeypatch, tmp_path, "{not json")+ with pytest.raises(RuntimeError):+ mod._pr_context()++ def test_missing_shas_fails_closed(self, monkeypatch, tmp_path):+ self._pr_env(monkeypatch, tmp_path, '{"pull_request": {}}')+ with pytest.raises(RuntimeError):+ mod._pr_context()++ def test_not_pr_event_returns_none(self, monkeypatch, no_ci_env):+ # Off a PR event, a missing payload is simply "not PR CI" -> None.+ assert mod._pr_context() is None++ def test_reads_allowlist_from_base_not_head(self, monkeypatch, tmp_path):+ # A PR that adds a real author on its own line must still be flagged:+ # the allow-list is read from the BASE pyproject, not head.+ addr = _addr("newmaint", "gmail.com")+ self._pr_env(+ monkeypatch,+ tmp_path,+ '{"pull_request": {"base": {"sha": "BASE"}, "head": {"sha": "HEAD"}}}',+ )+ calls = {}++ def fake_git(*args):+ if args[0] == "merge-base":+ return 0, "MB\n"+ if args[0] == "diff":+ return 0, "+++ b/AUTHORS\n@@ -0,0 +1 @@\n+ x <" + addr + ">\n"+ if args[0] == "show":+ calls["show"] = args[1]+ return 0, "[project]\nauthors = []\n" # base declares nothing+ return 0, ""++ monkeypatch.setattr(mod, "_git", fake_git)+ diff, pyproject, head_sha = mod._pr_context()+ assert head_sha == "HEAD" # post-image loader anchor+ assert calls["show"] == "BASE:pyproject.toml" # base, not head+ declared = mod.parse_author_emails(pyproject)+ assert declared == set()+ offenders = [+ p+ for p, e in mod.iter_added_emails(diff)+ if not mod.is_allowed(e, declared)+ ]+ assert offenders == ["AUTHORS"]++ @pytest.mark.parametrize("failed_command", ["diff", "show"])+ def test_git_context_failure_fails_closed_without_leaking_content(+ self, monkeypatch, tmp_path, capsys, failed_command+ ):+ leaked = _addr("secret", "gmail.com")+ self._pr_env(+ monkeypatch,+ tmp_path,+ '{"pull_request": {"base": {"sha": "BASE"}, "head": {"sha": "HEAD"}}}',+ )++ def fake_git(*args):+ if args[0] == "merge-base":+ return 0, "MERGEBASE\n"+ if args[0] == failed_command:+ return 1, leaked+ return 0, "[project]\nauthors = []\n"++ monkeypatch.setattr(mod, "_git", fake_git)+ assert mod.main() == 1+ err = capsys.readouterr().err+ operation = (+ "PR diff"+ if failed_command == "diff"+ else "base pyproject.toml show"+ )+ assert operation in err+ assert "exit status 1" in err+ assert "failing closed" in err+ assert leaked not in err+++class TestResolveMergeBase:+ def test_local_first_no_fetch(self, monkeypatch):+ calls = []++ def local_git(*args):+ calls.append(args)+ return 0, "MERGEBASE\n"++ monkeypatch.setattr(mod, "_git", local_git)+ assert mod._resolve_merge_base("b", "h") == "MERGEBASE"+ assert calls == [("merge-base", "b", "h")]++ def test_raises_when_unresolvable(self, monkeypatch):+ monkeypatch.setattr(mod, "_git", lambda *a: (1, ""))+ monkeypatch.setattr(mod.subprocess, "run", lambda *a, **k: None)+ with pytest.raises(RuntimeError):+ mod._resolve_merge_base("b", "h")++ @pytest.mark.parametrize(+ ("merge_base_results", "expected_fetches"),+ [+ (+ [(1, ""), (0, "MERGEBASE\n")],+ [("fetch", "--quiet", "--depth=1000", "origin", "h", "b")],+ ),+ (+ [(1, ""), (1, ""), (0, "MERGEBASE\n")],+ [+ ("fetch", "--quiet", "--depth=1000", "origin", "h", "b"),+ ("fetch", "--quiet", "--unshallow", "origin"),+ ],+ ),+ ],+ )+ def test_fallback_fetches_use_captured_git_output(+ self, monkeypatch, capsys, merge_base_results, expected_fetches+ ):+ calls = []+ results = iter(merge_base_results)+ leaked = _addr("fetch.output", "gmail.com")++ def fake_git(*args):+ calls.append(args)+ if args[0] == "merge-base":+ return next(results)+ return 1, leaked++ def direct_fetch(*args, **kwargs):+ print(leaked, file=sys.stderr)++ monkeypatch.setattr(mod, "_git", fake_git)+ monkeypatch.setattr(mod.subprocess, "run", direct_fetch)+ assert mod._resolve_merge_base("b", "h") == "MERGEBASE"+ assert all(fetch in calls for fetch in expected_fetches)+ assert leaked not in capsys.readouterr().err+++class TestGitInvocation:+ """The color / non-UTF8 robustness lives in HOW git is invoked; assert the+ params directly so these run in any container (no real ``git`` needed)."""++ def test_diff_forces_textual_builtin_output(self, monkeypatch, tmp_path):+ """Pinned prefixes keep diff headers and post-image lookups consistent.++ Local prefix settings must not change which file supplies string state.+ """+ # Color, external diff drivers, textconv filters, and binary attributes+ # must not hide a newly-added address from either context.+ calls = []++ def fake_git(*args):+ calls.append(args)+ if args[0] == "merge-base":+ return 0, "MERGEBASE\n"+ if args[0] == "show":+ return 0, "[project]\nauthors = []\n"+ return 0, ""++ monkeypatch.setattr(mod, "_git", fake_git)+ mod._staged_context()+ event = tmp_path / "event.json"+ event.write_text(+ '{"pull_request": {"base": {"sha": "BASE"}, "head": {"sha": "HEAD"}}}',+ encoding="utf-8",+ )+ monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")+ monkeypatch.setenv("GITHUB_EVENT_PATH", str(event))+ mod._pr_context()+ flags = (+ "--no-color",+ "--no-ext-diff",+ "--no-textconv",+ "--text",+ "--src-prefix=a/",+ "--dst-prefix=b/",+ )+ assert ("diff", *flags, "--cached") in calls+ assert ("diff", *flags, "MERGEBASE", "HEAD") in calls++ def test_git_decodes_bytes_with_replace_without_newline_translation(+ self, monkeypatch+ ):+ # A non-UTF8 blob must not crash decoding or translate a bare CR.+ captured = {}++ def fake_run(*a, **k):+ captured.update(k)++ class R:+ returncode = 0+ stdout = b"prefix\rbad\xff"++ return R()++ monkeypatch.setattr(mod.subprocess, "run", fake_run)+ assert mod._git("diff") == (0, "prefix\rbad\ufffd")+ assert captured.get("text") is False+ assert "encoding" not in captured+++ "attributes, external_diff",+ [+ ("fixture.txt -diff\n", False),+ ("", True),+ ],+)+def test_real_staged_diff_cannot_hide_disallowed_address(+ tmp_path, monkeypatch, no_ci_env, attributes, external_diff+):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text(+ "[project]\nauthors = []\n", encoding="utf-8"+ )+ (tmp_path / ".gitattributes").write_text(attributes, encoding="utf-8")+ (tmp_path / "fixture.txt").write_text("clean\n", encoding="utf-8")+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")++ if external_diff:+ script = tmp_path / "suppress-diff"+ script.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ script.chmod(0o755)+ _run_git(tmp_path, "config", "diff.external", str(script))++ bad = _addr("real", "gmail.com")+ (tmp_path / "fixture.txt").write_text(+ "contact " + bad + "\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "fixture.txt")+ monkeypatch.chdir(tmp_path)++ assert mod.main() == 1+++def test_real_staged_bare_cr_email_cannot_hide(+ tmp_path, monkeypatch, no_ci_env+):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text(+ "[project]\nauthors = []\n", encoding="utf-8"+ )+ (tmp_path / "fixture.txt").write_text("clean\n", encoding="utf-8")+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")++ bad = _addr("real", "gmail.com")+ (tmp_path / "fixture.txt").write_bytes(b"prefix\r" + bad.encode() + b"\n")+ _run_git(tmp_path, "add", "fixture.txt")+ monkeypatch.chdir(tmp_path)++ assert mod.main() == 1+++def test_unstaged_pyproject_cannot_authorize_staged_email(+ tmp_path, monkeypatch, no_ci_env+):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ pyproject = tmp_path / "pyproject.toml"+ pyproject.write_text("[project]\nauthors = []\n", encoding="utf-8")+ (tmp_path / "fixture.txt").write_text("clean\n", encoding="utf-8")+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")++ bad = _addr("real", "gmail.com")+ (tmp_path / "fixture.txt").write_text(+ "contact " + bad + "\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "fixture.txt")+ pyproject.write_text(+ "[project]\nauthors = [{name = 'Maintainer', email = '" + bad + "'}]\n",+ encoding="utf-8",+ )+ monkeypatch.chdir(tmp_path)++ assert mod.main() == 1+++def test_real_staged_hook_rejects_composed_international_addresses(tmp_path):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text(+ "[project]\nauthors = []\n", encoding="utf-8"+ )+ (tmp_path / "fixture.txt").write_text("clean\n", encoding="utf-8")+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")++ (tmp_path / "fixture.txt").write_text(+ _qaddr("john doe", "bücher.de")+ + "\n"+ + _addr("user", "bücher١.de")+ + "\n",+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "fixture.txt")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_hook_accepts_assets_remotes_and_uri_userinfo(tmp_path):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text(+ "[project]\nauthors = []\n", encoding="utf-8"+ )+ (tmp_path / "fixture.txt").write_text("clean\n", encoding="utf-8")+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")++ lines = [+ '<img src="[email protected]">',+ "Use [email protected].",+ "git clone " + _addr("git", "gitlab.com") + ":org/repo.git",+ "scp file " + _addr("deploy", "server.company.com") + ":/srv/",+ "https://" + _addr("user", "gmail.com") + "/path",+ # A ";" in the password is no longer suppressed userinfo — the+ # line needs the allow marker to stay accepted.+ "https://u:p;" + _addr("ass", "gmail.com") + "/path"+ " email-domains: allow",+ "smtp://user:password@bücher.de/mail",+ ]+ (tmp_path / "fixture.txt").write_text(+ "\n".join(lines) + "\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "fixture.txt")++ assert _run_hook(tmp_path).returncode == 0+++def _staged_repo(tmp_path):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text(+ "[project]\nauthors = []\n", encoding="utf-8"+ )+ (tmp_path / "fixture.txt").write_text("clean\n", encoding="utf-8")+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")+++def _deep_docstring(contact=None):+ """A docstring whose opener sits far above any hunk's context."""+ body = ["contact " + contact] if contact else []+ return (+ "\n".join(['DOC = """'] + ["filler"] * 5 + body + ['"""', "tail = 1"])+ + "\n"+ )+++def test_real_staged_multiline_python_string_address_fails(tmp_path):+ # the docstring body line was read as+ # code, so the matmul-shaped address inside it was suppressed.+ _staged_repo(tmp_path)+ (tmp_path / "calc.py").write_text(+ 'DOC = """\ncontact ' + _addr("user", "gmail.com") + '\n"""\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "calc.py")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_mixed_script_idn_address_fails(tmp_path):+ # `a中.com` is a valid IDNA domain+ # (xn--a-lq6a.com) that the label grammar could not consume.+ _staged_repo(tmp_path)+ (tmp_path / "fixture.txt").write_text(+ "contact " + _addr("user", "a中.com") + "\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "fixture.txt")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_declared_unicode_local_author_passes(tmp_path):+ # truncated extraction `ller@…` never+ # matched the declared full address, so the author was blocked.+ addr = _addr("müller", "wichtig.de")+ _staged_repo(tmp_path)+ (tmp_path / "pyproject.toml").write_text(+ '[project]\nauthors = [{name="d", email="' + addr + '"}]\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "pyproject.toml")+ (tmp_path / "AUTHORS").write_text(+ "maintainer <" + addr + ">\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "AUTHORS")++ assert _run_hook(tmp_path).returncode == 0+++def test_real_staged_dotted_matmul_in_py_file_passes(tmp_path):+ # Exercise the complete staged hook path.+ _staged_repo(tmp_path)+ (tmp_path / "math.py").write_text(+ "result = self.left@" + "matrix.transpose\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "math.py")++ assert _run_hook(tmp_path).returncode == 0+++def test_real_staged_c_quoted_unicode_py_path_passes(tmp_path):+ # Git C-quotes the non-ASCII path in+ # the diff header; the decoded suffix must keep matmul suppression.+ _staged_repo(tmp_path)+ (tmp_path / "café.py").write_text(+ "result = left@" + "matrix.transpose\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "café.py")++ assert _run_hook(tmp_path).returncode == 0+++def test_real_staged_deep_docstring_address_fails(tmp_path):+ # the staged hunk's context+ # cannot reach the opener, so hunk-entry state must come from the+ # staged index blob.+ _staged_repo(tmp_path)+ (tmp_path / "calc.py").write_text(+ "\n".join(['DOC = """'] + ["filler"] * 5 + ['"""', "tail = 1"]) + "\n",+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "calc.py")+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ bad = _addr("user", "gmail.com")+ (tmp_path / "calc.py").write_text(+ "\n".join(+ ['DOC = """']+ + ["filler"] * 5+ + ["contact " + bad, '"""', "tail = 1"],+ )+ + "\n",+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "calc.py")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_disjoint_hunks_matmul_passes(tmp_path):+ # raw-prefixing the+ # docstring in one hunk must not leak string state across the gap+ # into a later hunk's valid matmul line.+ _staged_repo(tmp_path)+ (tmp_path / "calc.py").write_text(+ 'DOC = """\npad\npad\npad\n"""\nCONST = 1\npad\npad\npad\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "calc.py")+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ (tmp_path / "calc.py").write_text(+ 'DOC = r"""\npad\npad\npad\n"""\nCONST = 1\npad\npad\npad'+ "\nresult = left@" + "matrix.transpose\n",+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "calc.py")++ assert _run_hook(tmp_path).returncode == 0+++def test_real_staged_backslash_continued_string_address_fails(tmp_path):+ # Exercise the complete staged hook path.+ _staged_repo(tmp_path)+ (tmp_path / "calc.py").write_text(+ 'DOC = "first\\\nthird"\n', encoding="utf-8"+ )+ _run_git(tmp_path, "add", "calc.py")+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ bad = _addr("user", "gmail.com")+ (tmp_path / "calc.py").write_text(+ 'DOC = "first\\\n' + bad + '\\\nthird"\n', encoding="utf-8"+ )+ _run_git(tmp_path, "add", "calc.py")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_declared_cjk_local_author_passes(tmp_path):+ # the declared author's pure-CJK+ # local part must be matched exactly by the allow-list.+ addr = _addr("ユーザー", "wichtig.de")+ _staged_repo(tmp_path)+ (tmp_path / "pyproject.toml").write_text(+ '[project]\nauthors = [{name="d", email="' + addr + '"}]\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "pyproject.toml")+ (tmp_path / "AUTHORS").write_text(+ "maintainer <" + addr + ">\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "AUTHORS")++ assert _run_hook(tmp_path).returncode == 0+++def test_real_staged_mixed_script_final_label_address_fails(tmp_path):+ # foo.中a is a valid IDNA final+ # label and must be extracted as the whole address.+ _staged_repo(tmp_path)+ (tmp_path / "fixture.txt").write_text(+ "contact " + _addr("user", "foo.中a") + "\n", encoding="utf-8"+ )+ _run_git(tmp_path, "add", "fixture.txt")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_pep701_fstring_address_fails(tmp_path, no_ci_env):+ # PEP 701 same-quote nesting, end to end: parity flipped at the+ # inner quote, the literal text read as code, and the matmul-shaped+ # address inside the f-string was suppressed (the hook exited 0).+ _staged_repo(tmp_path)+ (tmp_path / "app.py").write_text(+ 'd = f"{ {"k": "mail ' + _addr("user", "gmail.com") + '"}["k"] }"\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "app.py")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_multiline_fstring_field_edit_fails(tmp_path, no_ci_env):+ # PEP 701 fail-open, end to end: a replacement field of a+ # single-quoted f-string spans lines, and this edit rewrites the+ # closing line — with the opener sitting above the hunk's context,+ # so the hunk-entry state must be rebuilt from the staged+ # post-image with the f-string (and its open field) still open.+ # The rewritten tail is then literal text, not matmul-suppressed+ # code; at the old head the dropped open-quote state read it as+ # code and suppressed the address (the hook exited 0).+ _staged_repo(tmp_path)+ (tmp_path / "app.py").write_text(+ "# pad one\n# pad two\n# pad three\n"+ 'msg = f"hello {\n a\n b\n c\n d\n} tail"\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "app.py")+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ bad = _addr("user", "gmail.com")+ (tmp_path / "app.py").write_text(+ "# pad one\n# pad two\n# pad three\n"+ 'msg = f"hello {\n a\n b\n c\n d\n} contact ' + bad + '"\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "app.py")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_non_utf8_py_path_deep_docstring_fails(tmp_path, no_ci_env):+ # The filename b"caf\xe9.py" is not valid UTF-8, so git C-quotes it.+ # The C-quoted decode must preserve the original bytes (surrogate+ # escapes) for the `git show :path` post-image lookup to resolve and+ # rebuild the docstring state; a U+FFFD stand-in made the lookup+ # fail and the assumed-code entry state suppressed the address.+ _staged_repo(tmp_path)+ name = "caf\udce9.py"+ (tmp_path / name).write_text(_deep_docstring(), encoding="utf-8")+ _run_git(tmp_path, "add", name)+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ bad = _addr("user", "gmail.com")+ (tmp_path / name).write_text(_deep_docstring(bad), encoding="utf-8")+ _run_git(tmp_path, "add", name)++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_mnemonic_prefix_deep_docstring_fails(tmp_path, no_ci_env):+ # diff.mnemonicPrefix renames the staged-diff header to `+++ i/app.py`;+ # `git show :i/app.py` cannot resolve that path, so the post-image+ # loader fails and the file must fail toward extraction (matmul+ # suppression dropped) instead of assuming the hunk starts in code.+ _staged_repo(tmp_path)+ (tmp_path / "app.py").write_text(_deep_docstring(), encoding="utf-8")+ _run_git(tmp_path, "add", "app.py")+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ bad = _addr("user", "gmail.com")+ (tmp_path / "app.py").write_text(_deep_docstring(bad), encoding="utf-8")+ _run_git(tmp_path, "add", "app.py")+ _run_git(tmp_path, "config", "diff.mnemonicPrefix", "true")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_fstring_field_comment_address_fails(tmp_path, no_ci_env):+ # A comment inside a multi-line replacement field (compile-valid+ # Python 3.12) was processed as field content: the comment's `}`+ # closed the field, its `"` then matched the f-string closer, and+ # the comment tail was classified as a code span where matmul+ # suppression hid the address (the hook exited 0). The comment must+ # instead run to end of line, with the open field carried over.+ _staged_repo(tmp_path)+ (tmp_path / "app.py").write_text(+ 's = f"{1 +\n# } " contact ' + _addr("user", "gmail.com") + '\n2}"\n',+ encoding="utf-8",+ )+ _run_git(tmp_path, "add", "app.py")++ assert _run_hook(tmp_path).returncode == 1+++def test_real_staged_noprefix_b_path_docstring_fails(tmp_path, no_ci_env):+ # With diff.noprefix true, a file genuinely at `b/victim.py` emits+ # `+++ b/victim.py` (its real path); stripping the hardcoded `b/`+ # resolved the ROOT decoy victim.py as the post-image, whose all-code+ # scan rebuilt a code entry state for the docstring hunk and let+ # matmul suppression hide the string-body address (exit 0). The+ # pinned --src-prefix/--dst-prefix flags keep the prefixed form.+ _staged_repo(tmp_path)+ (tmp_path / "victim.py").write_text("X = 1\n", encoding="utf-8")+ (tmp_path / "b").mkdir()+ (tmp_path / "b" / "victim.py").write_text(+ _deep_docstring(), encoding="utf-8"+ )+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "base")+ bad = _addr("user", "gmail.com")+ (tmp_path / "b" / "victim.py").write_text(+ _deep_docstring(bad), encoding="utf-8"+ )+ _run_git(tmp_path, "add", "b/victim.py")+ _run_git(tmp_path, "config", "diff.noprefix", "true")++ assert _run_hook(tmp_path).returncode == 1++[email protected]("prefix", ["f", "F", "fr", "rf", "t", "T", "tr", "rt"])+def test_interpolated_literal_keeps_multiline_field_state(prefix):+ """Literal text after an open replacement field cannot become matmul code."""+ bad = _addr("fixture", "nonreserved.tld")+ source = prefix + '"{\n 1\n} ' + bad + '"\n'+ if prefix.lower() in {"f", "fr", "rf"} or sys.version_info >= (3, 14):+ compile(source, "sample.py", "exec")+ diff = (+ "diff --git a/sample.py b/sample.py\n+++ b/sample.py\n"+ "@@ -0,0 +1,3 @@\n"+ + "\n".join("+" + line for line in source.splitlines())+ + "\n"+ )+ assert list(mod.iter_added_emails(diff, post_image=lambda _: source)) == [+ ("sample.py", bad)+ ]+ code = "tag = " + prefix + '"{1}"; value = left@' + "matrix.transpose\n"+ code_diff = "+++ b/sample.py\n@@ -0,0 +1 @@\n+" + code+ assert list(mod.iter_added_emails(code_diff)) == []+++ "local", ["o'connor", "a!b", "ゆうざあ", "a中", "中a", "!lead", "trail'"]+)[email protected]("wrapper", [("<", ">"), ('"', '"'), ("`", "`")])+def test_explicit_address_preserves_declared_identity(local, wrapper):+ """Delimiters distinguish a complete identity from surrounding prose."""+ email = _addr(local, "nonreserved.tld")+ left, right = wrapper+ diff = (+ "+++ b/contact.md\n@@ -0,0 +1 @@\n+Contact "+ + left+ + right+ + "\n"+ )+ found = list(mod.iter_added_emails(diff))+ assert found == [("contact.md", email)]+ assert mod.is_allowed(found[0][1], {email})+ assert not mod.is_allowed(found[0][1], set())++[email protected]("local", ["o'connor", "a!b", "ゆうざあ"])+def test_bare_local_identity_is_not_truncated(local):+ email = _addr(local, "nonreserved.tld")+ diff = "+++ b/contact.md\n@@ -0,0 +1 @@\n+" + email + "\n"+ assert list(mod.iter_added_emails(diff)) == [("contact.md", email)]+++def test_explicit_mixed_final_label_does_not_become_reserved_prefix():+ email = _addr("user", "example.com中")+ diff = "+++ b/contact.md\n@@ -0,0 +1 @@\n+<" + email + ">\n"+ assert list(mod.iter_added_emails(diff)) == [("contact.md", email)]+ assert not mod.is_allowed(email, set())+ # Outside delimiters, preserve the deliberately conservative prose boundary.+ plain = _addr("user", "example.com")+ prose = "+++ b/contact.md\n@@ -0,0 +1 @@\n+" + plain + "请确认\n"+ assert list(mod.iter_added_emails(prose)) == [("contact.md", plain)]+++def test_delimiters_inside_quoted_local_do_not_create_an_inner_offender():+ inner = _addr("fixture", "nonreserved.tld")+ outer = _qaddr("<" + inner + ">", "example.com")+ diff = "+++ b/contact.md\n@@ -0,0 +1 @@\n+" + outer + "\n"+ assert list(mod.iter_added_emails(diff)) == [("contact.md", outer)]+ assert mod.is_allowed(outer, set())+++def test_mixed_quoted_and_plain_addresses_bound_interval_comparisons(+ monkeypatch,+):+ """Containment work must not compare every plain token with every quote."""+ comparisons = [0]++ class CountedOffset(int):+ def __lt__(self, other):+ comparisons[0] += 1+ return int.__lt__(self, other)++ def __le__(self, other):+ comparisons[0] += 1+ return int.__le__(self, other)++ def __gt__(self, other):+ comparisons[0] += 1+ return int.__gt__(self, other)++ def __ge__(self, other):+ comparisons[0] += 1+ return int.__ge__(self, other)++ class CountedMatch:+ def __init__(self, match):+ self.match = match++ def span(self):+ return tuple(CountedOffset(value) for value in self.match.span())++ def __getattr__(self, name):+ return getattr(self.match, name)++ original = mod.QUOTED_EMAIL_RE++ class CountedPattern:+ def finditer(self, text):+ return (CountedMatch(match) for match in original.finditer(text))++ monkeypatch.setattr(mod, "QUOTED_EMAIL_RE", CountedPattern())+ count = 300+ quoted = _qaddr("quoted", "example.com")+ plain = _addr("plain", "example.com")+ text = " ".join([quoted] * count + [plain] * count)+ diff = "+++ b/contact.md\n@@ -0,0 +1 @@\n+" + text + "\n"+ assert list(mod.iter_added_emails(diff)) == (+ [("contact.md", plain)] * count + [("contact.md", quoted)] * count+ )+ assert comparisons[0] < 30 * count+++ sys.platform == "win32", reason="Colon filenames require a POSIX filesystem"+)+def test_staged_colon_path_uses_its_own_index_blob(tmp_path):+ """A stage-shaped filename must not borrow a code-only decoy's state."""+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text("[project]\nauthors=[]\n")+ before = 'DOC = """\n' + "filler\n" * 10 + 'clean\n"""\n'+ (tmp_path / "0:calc.py").write_text(before)+ (tmp_path / "calc.py").write_text("pass\n" * 20)+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")+ bad = _addr("fixture", "nonreserved.tld")+ (tmp_path / "0:calc.py").write_text(+ before.replace("clean", "contact " + bad)+ )+ _run_git(tmp_path, "add", "--", "0:calc.py")+ result = _run_hook(tmp_path)+ assert result.returncode == 1+ assert "Email domain check failed" in result.stderr+ assert "0:calc.py" in result.stderr+ assert bad not in result.stderr++[email protected]("local", ["o'connor", "a!b", "a中", "ゆうざあ"])+def test_staged_declared_identity_is_accepted_whole(tmp_path, local):+ """The staged author declaration and its delimited use share one identity."""+ _run_git(tmp_path, "init", "--quiet")+ email = _addr(local, "nonreserved.tld")+ (tmp_path / "pyproject.toml").write_text(+ '[project]\nauthors=[{email="' + email + '"}]\n'+ )+ (tmp_path / "contact.md").write_text("Contact <" + email + ">\n")+ _run_git(tmp_path, "add", ".")+ result = _run_hook(tmp_path)+ assert result.returncode == 0, result.stderr+ (tmp_path / "pyproject.toml").write_text("[project]\nauthors=[]\n")+ _run_git(tmp_path, "add", "pyproject.toml")+ result = _run_hook(tmp_path)+ assert result.returncode == 1+ assert "Email domain check failed" in result.stderr+ assert email not in result.stderr++[email protected]("name", ["icon", "a+b", "a%b", "a!b", "can't"])[email protected]("wrapper", ["", '"', "'", "`"])+def test_punctuated_asset_and_remote_contexts_preserve_neighbor_email(+ name, wrapper+):+ bad = _addr("neighbor", "nonreserved.tld")+ for contextual in (+ name + "@2x.png",+ name + "@1.5x.svg",+ name + "@gitlab.com:repo.git",+ ):+ text = (+ "Use " + wrapper + contextual + wrapper + "; Contact <" + bad + ">"+ )+ diff = "+++ b/guide.md\n@@ -0,0 +1 @@\n+" + text + "\n"+ assert list(mod.iter_added_emails(diff)) == [("guide.md", bad)]+++def test_python_matmul_span_lookup_bounds_comparisons(monkeypatch):+ """Alternating literals and operators must not rescan all earlier spans."""+ comparisons = [0]++ class CountedOffset(int):+ def __lt__(self, other):+ comparisons[0] += 1+ return int.__lt__(self, other)++ def __le__(self, other):+ comparisons[0] += 1+ return int.__le__(self, other)++ def __gt__(self, other):+ comparisons[0] += 1+ return int.__gt__(self, other)++ def __ge__(self, other):+ comparisons[0] += 1+ return int.__ge__(self, other)++ original = mod._py_code_spans++ def counted(text, state):+ return [+ (CountedOffset(start), CountedOffset(end))+ for start, end in original(text, state)+ ]++ monkeypatch.setattr(mod, "_py_code_spans", counted)+ count = 300+ bad = _addr("neighbor", "nonreserved.tld")+ text = ('""; left@' + "matrix.transpose; ") * count + " # " + bad+ diff = "+++ b/calc.py\n@@ -0,0 +1 @@\n+" + text + "\n"+ assert list(mod.iter_added_emails(diff)) == [("calc.py", bad)]+ assert comparisons[0] < 30 * count+++ ("path", "escaped"),+ [+ ("with\nnewline.py", r"with\nnewline.py"),+ ("with\ttab.py", r"with\ttab.py"),+ ("with\x1bescape.py", r"with\u001bescape.py"),+ ("with\\slash.py", r"with\\slash.py"),+ ("with\u202edirection.py", r"with\u202edirection.py"),+ ],+)+def test_diagnostic_paths_escape_control_characters(+ monkeypatch, capsys, path, escaped+):+ bad = _addr("fixture", "nonreserved.tld")+ monkeypatch.setattr(+ mod, "_pr_context", lambda: ("", "[project]\nauthors=[]\n", None)+ )+ monkeypatch.setattr(+ mod,+ "iter_added_findings",+ lambda *args, **kwargs: iter([(path, bad, 7)]),+ )+ assert mod.main() == 1+ output = capsys.readouterr().err+ assert (+ " " + escaped + ":7: adds an email on a non-reserved domain"+ in output.splitlines()+ )+ assert path not in output+ assert bad not in output+++def test_staged_python_state_ignores_unstaged_code_decoy(tmp_path):+ _run_git(tmp_path, "init", "--quiet")+ _run_git(tmp_path, "config", "user.name", "Test")+ _run_git(tmp_path, "config", "user.email", "[email protected]")+ (tmp_path / "pyproject.toml").write_text("[project]\nauthors=[]\n")+ before = 'DOC = """\n' + "filler\n" * 10 + 'clean\n"""\n'+ (tmp_path / "calc.py").write_text(before)+ _run_git(tmp_path, "add", ".")+ _run_git(tmp_path, "commit", "--quiet", "-m", "initial")+ bad = _addr("fixture", "review.dev")+ (tmp_path / "calc.py").write_text(before.replace("clean", bad))+ _run_git(tmp_path, "add", "calc.py")+ (tmp_path / "calc.py").write_text(bad + "\n")+ result = _run_hook(tmp_path)+ assert result.returncode == 1+ assert "Email domain check failed" in result.stderr+ assert "calc.py" in result.stderr+ assert bad not in result.stderr