"""Multi-repo SZZ dataset from git alone. Per repo: clone -> labels + features + diff text -> parquet -> delete clone. Label: commit is bug-inducing if a later fix commit's removed lines blame to it (SZZ, ag-szz style w/o refactoring filter). Labelable window: [oldest scanned fix, newest commit - CENSOR_DAYS] (all fixes after the commit were scanned). Usage: python build.py repos.txt [parallel] """ import hashlib, re, subprocess, sys, tempfile, time from collections import defaultdict from multiprocessing import Pool from pathlib import Path import polars as pl FIX = re.compile(r"\b(fix(es|ed)?|bug|bugfix|hotfix|regression|crash|segfault|leak|race|deadlock|overflow)\b", re.I) NOISE = re.compile(r"\b(typo|lint|format|formatting|style|whitespace|docs?|readme|comments?|spelling|ci|build|compile|" r"warnings?|tests?|flaky|chore|revert|merge|bump|deps?|dependenc\w+|upgrade|version)\b", re.I) HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.M) TEST = re.compile(r"(^|/)(tests?|spec|__tests__|testing)(/|$)|[._-](test|spec)\.|_test\.go$", re.I) CAP_FIX_FILES, CAP_FIX_DEL, CAP_TEXT, CENSOR_DAYS, MIN_COMMITS, LABEL_DAYS = 10, 200, 8000, 180, 2000, 365 is_fix = lambda subj: bool(FIX.search(subj)) and not NOISE.search(subj) OUT = Path(__file__).parent / "data" def git(d, *a): return subprocess.run(["git", "-C", d, *a], capture_output=True, text=True, errors="replace", timeout=900).stdout def build(repo: str): out = OUT / (repo.replace("/", "__") + ".parquet") if out.exists(): return f"{repo}: cached" d = tempfile.mkdtemp(); t0 = time.time() try: for attempt in range(2): c = subprocess.run(["git", "clone", "-q", "--bare", f"https://github.com/{repo}", d], capture_output=True, text=True, timeout=1800) if c.returncode == 0: break subprocess.run(["rm", "-rf", d]); time.sleep(30) else: return f"{repo}: CLONE FAILED: {c.stderr.strip()[:200]}" raw = git(d, "log", "--all", "--no-merges", "--format=%x00%H%x01%ae%x01%at%x01%s", "--name-only") commits = [] for rec in raw.split("\x00")[1:]: head, _, files = rec.partition("\n") sha, email, at, subj = head.split("\x01", 3) commits.append((sha, email, int(at), subj, [f for f in files.split("\n") if f])) if len(commits) < MIN_COMMITS: return f"{repo}: skipped ({len(commits)} commits)" commits.sort(key=lambda c: c[2]) fixes = [c for c in commits if is_fix(c[3]) and 0 < len(c[4]) <= CAP_FIX_FILES] inducing = {} # sha -> earliest fix time for sha, _, ft, _, files in fixes: hunks = [] for f in files: if TEST.search(f): continue # fixes to tests don't blame production bugs hunks += [(f, int(m.group(1)), int(m.group(2) or 1)) for m in HUNK.finditer(git(d, "diff", "-U0", f"{sha}^", sha, "--", f))] if not 0 < sum(n for _, _, n in hunks) <= CAP_FIX_DEL: continue # pure additions carry no blame; huge deletions are refactors, not fixes for f, a, n in hunks: if n: blame = git(d, "blame", "--porcelain", "-w", "-L", f"{a},{a + n - 1}", f"{sha}^", "--", f) for l in blame.split("\n"): if re.match(r"^[0-9a-f]{40} ", l): b = l.split()[0]; inducing[b] = min(inducing.get(b, ft), ft) t_lo, t_hi = fixes[0][2], commits[-1][2] - CENSOR_DAYS * 86400 rows, seen = [], defaultdict(lambda: [0, 0, None]) # author -> [n, n_inducing, first_t] for sha, email, at, subj, files in commits: n, p, first = seen[email] labelable = t_lo <= at <= t_hi and bool(files) and not is_fix(subj) y = int(sha in inducing and inducing[sha] - at <= LABEL_DAYS * 86400) if labelable: diff = git(d, "show", "--format=", "-U0", "--no-color", sha) added = [l[1:] for l in diff.split("\n") if l.startswith("+") and not l.startswith("+++")] deleted = sum(1 for l in diff.split("\n") if l.startswith("-") and not l.startswith("---")) rows.append(dict( repo=repo, sha=sha, t=at, author=hashlib.sha1(email.encode()).hexdigest()[:16], subj=subj, nfiles=len(files), la=len(added), ld=deleted, hunks=len(HUNK.findall(diff)), ndirs=len({f.rsplit("/", 1)[0] if "/" in f else "" for f in files}), nexts=len({f.rsplit(".", 1)[-1] if "." in f.rsplit("/", 1)[-1] else "" for f in files}), test_ratio=sum(bool(TEST.search(f)) for f in files) / len(files), a_prior_n=n, a_prior_rate=(p + 1) / (n + 4), a_days=(at - first) / 86400 if first else 0.0, msg_len=len(subj), msg_ref=int(bool(re.search(r"#\d+", subj))), text=(subj + "\n" + " ".join(files) + "\n" + "\n".join(added))[:CAP_TEXT], y=y)) seen[email] = [n + 1, p + y, first or at] if not rows: return f"{repo}: skipped (no labelable commits)" pl.DataFrame(rows).write_parquet(out) ys = sum(r["y"] for r in rows) return f"{repo}: {len(commits)} commits, {len(fixes)} fixes, {len(rows)} labeled, {ys} inducing ({ys / max(len(rows), 1):.1%}), {time.time() - t0:.0f}s" except Exception as e: return f"{repo}: ERROR {e!r}" finally: subprocess.run(["rm", "-rf", d]) if __name__ == "__main__": OUT.mkdir(exist_ok=True) repos = [r.strip() for r in open(sys.argv[1]) if r.strip()] with Pool(int(sys.argv[2]) if len(sys.argv) > 2 else 4) as pool: for msg in pool.imap_unordered(build, repos): print(msg, flush=True)