File size: 4,635 Bytes
c4c44be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/env python3
"""Validate that every file under data/ contains real diff content.

A file is valid when, for each `=== <url> ===` section (or for the whole
body if there is no separator), the section contains `diff --git ` at
column 0 OR starts with `From <sha40> Mon Sep 17 00:00:00 2001`.

Invalid files and the reason are written to .logs/invalid_diffs.tsv and
printed as a summary on stdout.

Usage:
    python validate_diffs.py [DATA_DIR]

If DATA_DIR is omitted, defaults to ./data next to this script.
"""

from __future__ import annotations

import pathlib
import re
import sys
from collections import Counter


SCRIPT_DIR = pathlib.Path(__file__).resolve().parent
DEFAULT_DATA_DIR = SCRIPT_DIR / "data"
LOG_DIR = SCRIPT_DIR / ".logs"

_DIFF_GIT_RE = re.compile(rb"^diff --git ", re.M)
_GIT_FORMAT_PATCH_RE = re.compile(rb"^From [0-9a-f]{40} Mon Sep ")
_SECTION_SEP_RE = re.compile(rb"^=== (.+?) ===$", re.M)
_HTML_HINT_RE = re.compile(rb"<(?:html|head|body|!doctype)\b", re.I)


def looks_like_diff(body: bytes) -> bool:
    if not body:
        return False
    if _DIFF_GIT_RE.search(body):
        return True
    return bool(_GIT_FORMAT_PATCH_RE.match(body.split(b"\n", 1)[0]))


def classify_bad(body: bytes) -> str:
    """Return a short reason describing why `body` is not a diff."""
    if not body:
        return "empty file"
    stripped = body.strip()
    if not stripped:
        return "whitespace only"
    head = body[:4096]
    if _HTML_HINT_RE.search(head):
        title = re.search(rb"<title[^>]*>(.*?)</title>", head, re.I | re.S)
        if title:
            t = title.group(1).strip().decode("utf-8", "replace")[:120]
            return f"HTML page (title: {t!r})"
        return "HTML page"
    if head.lstrip().startswith((b"{", b"[")):
        return "JSON payload (likely API error)"
    if b"Not Found" in head or b"404" in head[:200]:
        return "looks like 404 / not-found text"
    if b"Rate limit" in head or b"rate limit" in head:
        return "rate-limit message"
    try:
        text_preview = head.decode("utf-8")
    except UnicodeDecodeError:
        return f"binary / non-utf8 content ({len(body)} B)"
    snippet = " ".join(text_preview.split())[:120]
    return f"no `diff --git` and no git-format-patch header; starts with: {snippet!r}"


def validate_file(path: pathlib.Path) -> list[str]:
    """Return a list of reasons why `path` is invalid (empty list = OK)."""
    try:
        body = path.read_bytes()
    except OSError as e:
        return [f"unreadable: {e}"]

    if not body:
        return ["empty file"]

    sep_matches = list(_SECTION_SEP_RE.finditer(body))
    if not sep_matches:
        if looks_like_diff(body):
            return []
        return [classify_bad(body)]

    reasons: list[str] = []
    for i, m in enumerate(sep_matches):
        url = m.group(1).decode("utf-8", "replace")
        start = m.end() + 1  # skip newline after separator
        end = sep_matches[i + 1].start() if i + 1 < len(sep_matches) else len(body)
        section = body[start:end]
        if not looks_like_diff(section):
            reasons.append(f"section {i + 1} ({url}): {classify_bad(section)}")
    return reasons


def main() -> int:
    data_dir = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_DATA_DIR
    if not data_dir.is_dir():
        print(f"error: {data_dir} is not a directory", file=sys.stderr)
        return 2

    LOG_DIR.mkdir(parents=True, exist_ok=True)
    log_path = LOG_DIR / "invalid_diffs.tsv"

    files = sorted(p for p in data_dir.rglob("*") if p.is_file())
    print(f"[scan] {len(files)} file(s) under {data_dir}", file=sys.stderr)

    invalid = 0
    reason_counts: Counter[str] = Counter()
    with open(log_path, "w", encoding="utf-8") as log:
        log.write("path\treason\n")
        for path in files:
            reasons = validate_file(path)
            if not reasons:
                continue
            invalid += 1
            rel = path.relative_to(data_dir)
            for r in reasons:
                # bucket the reason for the summary (keep the prefix)
                head = r.split(":", 1)[0].split(";", 1)[0][:80]
                reason_counts[head] += 1
                log.write(f"{rel}\t{r}\n")

    ok = len(files) - invalid
    print(f"[done] ok={ok}  invalid={invalid}  log={log_path}", file=sys.stderr)
    if reason_counts:
        print("[summary] top reasons:", file=sys.stderr)
        for reason, n in reason_counts.most_common(10):
            print(f"  {n:>6}  {reason}", file=sys.stderr)
    return 1 if invalid else 0


if __name__ == "__main__":
    sys.exit(main())