File size: 4,335 Bytes
bf3d2af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Diff patches and regex-dense sources for the structured-output slice.

The requested structured slice is "JSON, YAML, SQL, regular expressions, diff
patches". JSON/YAML/TOML/SQL fall out of the repositories directly; the other
two need explicit work:

* **Diff patches** are real `git log -p` output. The repositories are cloned
  shallow, so history is fetched with `--deepen` first; without that there is
  exactly one commit and no patches at all.
* **Regexes** are not a file type, so instead of inventing them we promote
  genuinely regex-dense real sources (lexers, validators, route matchers) into
  this slice, where they carry real patterns in real context.
"""
from __future__ import annotations

import os
import re
import subprocess

from collect import doc_id
from sources import RAW, REPOS

COMMIT_SEP = "===COMMIT==="

# A slash-delimited literal only counts if it actually contains a regex
# metacharacter, and is not preceded by ':' or a word character. Without those
# guards every `https://host/path` in the corpus reads as a regex and the
# promotion below swallows most of the JavaScript in the repositories.
REGEX_LITERAL = re.compile(
    r"(?<![:\w/])/(?![/*\s])(?:[^/\\\n]|\\.){0,80}?[\\\[\](){}.*+?^$|]"
    r"(?:[^/\\\n]|\\.){0,80}?/[gimsuyd]*(?![\w/])"
    r"|re\.(?:compile|match|search|sub|subn|findall|finditer|fullmatch)\s*\(\s*[rf]?[\"']"
    r"|Regex(?:Builder)?::new\s*\(\s*r?[\"#]"
    r"|std::regex\s+\w+\s*\("
    r"|Pattern\.compile\s*\("
)


def collect_git_diffs(repo_names=None, max_per_repo=45, min_chars=500, max_chars=24000):
    repo_names = repo_names or list(REPOS)
    docs = []
    for repo in repo_names:
        root = os.path.join(RAW, repo)
        if not os.path.isdir(os.path.join(root, ".git")):
            continue
        try:
            res = subprocess.run(
                ["git", "-C", root, "log", "-p", "--unified=3", "--no-color",
                 "--no-merges", "--max-count=140",
                 f"--format={COMMIT_SEP}%n%s%n%n%b"],
                capture_output=True, text=True, timeout=180, errors="replace",
            )
        except (subprocess.SubprocessError, OSError):
            continue
        if res.returncode != 0:
            continue
        lic = REPOS.get(repo, ("", "unknown", ""))[1]
        url = REPOS.get(repo, ("", "", ""))[0]
        got = 0
        for chunk in res.stdout.split(COMMIT_SEP):
            chunk = chunk.strip("\n")
            if got >= max_per_repo:
                break
            if not (min_chars <= len(chunk) <= max_chars):
                continue
            if "diff --git" not in chunk or "Binary files" in chunk:
                continue
            # skip patches that are almost entirely lockfile / generated churn
            if re.search(r"diff --git .*(package-lock\.json|Cargo\.lock|\.min\.)", chunk):
                continue
            docs.append({
                "id": doc_id(chunk),
                "domain": "structured",
                "source": repo,
                "license": lic,
                "url": url,
                "path": f"git-history/{repo}.patch",
                "lang": "diff",
                "text": chunk,
                "origin": "git_diff",
                "split_hint": None,
            })
            got += 1
    return docs


def promote_regex_dense(docs, min_hits=8, min_density=0.02, max_promote=140):
    """Reclassify the most regex-heavy real sources into the structured slice.

    Hard-capped at `max_promote`: a threshold alone is fragile to calibrate,
    and an over-firing detector would turn the structured slice into a dumping
    ground for ordinary JavaScript.
    """
    scored = []
    for d in docs:
        if d.get("origin") != "repo_file" or d["domain"] == "structured":
            continue
        if d["lang"] not in ("javascript", "typescript", "python", "rust", "cpp"):
            continue
        hits = len(REGEX_LITERAL.findall(d["text"]))
        lines = d["text"].count("\n") + 1
        density = hits / lines
        if hits >= min_hits and density >= min_density:
            scored.append((density, hits, d))
    scored.sort(key=lambda t: (-t[0], -t[1], t[2]["id"]))
    for _, _, d in scored[:max_promote]:
        d["domain"] = "structured"
        d["origin"] = "regex_dense"
    return min(len(scored), max_promote)