#!/usr/bin/env python3 """apply-diagnose.py -- why does a queue patch refuse to apply to the served base? `apply-check.py` reported 13 rows where `git apply --check` fails both forward and in reverse. A refusal is only useful with a cause, and there are three candidates that are cheap to separate: line endings the patch and the base disagree about CRLF/LF, and the patch applies once the base is normalised (#1357's premise, which review 159 called an artifact of the author's unpinned fetch path -- so a hit here is a statement about the CARRIER, not about the text being wrong) whitespace the patch applies with `--ignore-whitespace` base moved neither fixes it: the diff really is against a different text Read-only. Writes apply-diagnose.json and prints one line per refusing row with the cause it found. """ import hashlib import json import os import shutil import subprocess import sys import tempfile import urllib.error import urllib.request BASE = "https://solveathome.org/projects/twin-primes" TOK = os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token") ROOT = os.path.dirname(os.path.abspath(__file__)) def get(path, token=None): headers = {"Accept": "*/*", "User-Agent": "sahreq/1.0"} if token: headers["Authorization"] = "Bearer " + token try: with urllib.request.urlopen(urllib.request.Request(BASE + path, headers=headers), timeout=120) as r: return r.status, r.read() except urllib.error.HTTPError as e: return e.code, e.read() def attempt(base_bytes, rel_path, patch_text, extra=(), newline=None): tmp = tempfile.mkdtemp(prefix="sah-diag-") try: data = base_bytes if newline is None else base_bytes.replace(b"\r\n", b"\n") \ if newline == "lf" else base_bytes.replace(b"\n", b"\r\n") target = os.path.join(tmp, rel_path.replace("/", os.sep)) os.makedirs(os.path.dirname(target), exist_ok=True) with open(target, "wb") as fh: fh.write(data) pf = os.path.join(tmp, "_p.diff") with open(pf, "w", encoding="utf-8", newline="\n") as fh: fh.write(patch_text) p = subprocess.run(["git", "apply", "-p1", "--check", *extra, pf], cwd=tmp, capture_output=True, text=True) return p.returncode == 0, (p.stderr or "").strip()[:160], hashlib.sha256(data).hexdigest() finally: shutil.rmtree(tmp, ignore_errors=True) def main(): tok = open(TOK, encoding="utf-8").read().strip() chk = json.load(open(os.path.join(ROOT, "apply-check.json"), encoding="utf-8")) refusing = [r for r in chk["rows"] if r["applies"] is False and r["already_applied"] is False] out = [] for r in refusing: code, rr = get("/return/%d" % r["return"], tok) patch = (json.loads(rr).get("patch") or "") if code == 200 else "" bcode, base = get("/docs/" + r["path"], tok) if not patch or bcode != 200: out.append({"return": r["return"], "path": r["path"], "cause": "unavailable", "detail": "patch %s docs %s" % (code, bcode)}) continue base_crlf = base.count(b"\r\n") base_lf = base.count(b"\n") plain, plain_err, _ = attempt(base, r["path"], patch) ws, ws_err, _ = attempt(base, r["path"], patch, extra=("--ignore-whitespace",)) to_lf, lf_err, lf_sha = attempt(base, r["path"], patch, newline="lf") to_crlf, crlf_err, _ = attempt(base, r["path"], patch, newline="crlf") cause = ("applies_plain" if plain else "whitespace" if ws else "line_endings" if (to_lf or to_crlf) else "base_moved") out.append({"return": r["return"], "path": r["path"], "cause": cause, "base_crlf_pairs": base_crlf, "base_newlines": base_lf, "applies_plain": plain, "applies_ignore_whitespace": ws, "applies_after_lf": to_lf, "applies_after_crlf": to_crlf, "sha_after_lf_normalisation": lf_sha, "err": plain_err or ws_err or lf_err or crlf_err}) res = {"job": "2829-continuation", "route": 114, "tool": "apply-diagnose.py/1.0", "n_refusing": len(refusing), "rows": out, "causes": {c: sum(1 for r in out if r["cause"] == c) for c in sorted({r["cause"] for r in out})}} json.dump(res, open(os.path.join(ROOT, "apply-diagnose.json"), "w", encoding="utf-8", newline="\n"), indent=1, ensure_ascii=False, sort_keys=True) print(json.dumps({"n_refusing": len(refusing), "causes": res["causes"]}, indent=1)) for r in out: print("%-4s %-48s %-14s crlf=%s plain=%s ws=%s lf=%s" % ( r["return"], r["path"][:48], r["cause"], r.get("base_crlf_pairs"), r.get("applies_plain"), r.get("applies_ignore_whitespace"), r.get("applies_after_lf"))) return 0 if __name__ == "__main__": sys.exit(main())