File size: 8,050 Bytes
065ea6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0190001
 
065ea6f
 
 
 
0190001
 
 
 
 
065ea6f
 
0190001
065ea6f
 
 
0190001
 
065ea6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0190001
065ea6f
 
 
 
 
0190001
 
 
 
065ea6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
"""Export TEBench into a self-contained, SWE-bench-style HuggingFace dataset.

Reads the existing task spine and label table plus the local git repositories,
and materializes one parquet file where every one of the 314 task instances
carries its own ``source_patch`` (V-1 -> V-0.5, the production/non-test delta
already applied for the agent) and ``test_patch`` (V-0.5 -> V0, the developer
ground-truth test changes). Nothing under the existing TEBench tree is modified;
all output lands in this ``hf_release/`` directory.
"""

import argparse
import json
import subprocess
import sys
from pathlib import Path

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

# Repo dir -> canonical upstream GitHub slug (for the ``repo`` field).
REPO_SLUG = {
    "commons-cli": "apache/commons-cli",
    "commons-codec": "apache/commons-codec",
    "commons-collections": "apache/commons-collections",
    "commons-compress": "apache/commons-compress",
    "commons-csv": "apache/commons-csv",
    "commons-lang": "apache/commons-lang",
    "commons-math": "apache/commons-math",
    "gson": "google/gson",
    "jfreechart": "jfree/jfreechart",
    "jsoup": "jhy/jsoup",
}

# new_labels token -> canonical evolution type.
LABEL_MAP = {
    "test_breaking": "breaking",
    "test_stale": "stale",
    "test_missing": "missing",
}

HERE = Path(__file__).resolve().parent
TEBENCH = HERE.parent
TESTUPDATE = TEBENCH.parent


def git(repo: Path, *args: str) -> str:
    """Run a git command in ``repo`` and return stdout.

    Captured as bytes and decoded without newline translation so that CRLF
    line endings in patches (some repos store files with CRLF) are preserved
    verbatim; otherwise the emitted patch would no longer apply to the blob.
    """
    out = subprocess.run(
        ["git", "-C", str(repo), "--no-pager", *args], capture_output=True,
    )
    if out.returncode != 0:
        raise RuntimeError(
            f"git {' '.join(args)} failed in {repo}: {out.stderr.decode('utf-8', 'replace').strip()}")
    return out.stdout.decode("utf-8", "replace")


def is_test_file(path: str) -> bool:
    return "/src/test/" in path or path.startswith("src/test/")


def split_patch(repo: Path, base: str, head: str):
    """Return (source_patch, test_patch, n_src_files, n_test_files)."""
    names = [p for p in git(repo, "diff", "--name-only", base, head).splitlines() if p]
    test_files = [p for p in names if is_test_file(p)]
    src_files = [p for p in names if not is_test_file(p)]

    def diff(files):
        if not files:
            return ""
        # --binary --full-index keep binary hunks and full blob hashes so the
        # patch applies standalone with `git apply` (no repo objects needed).
        return git(repo, "diff", "--no-color", "--no-ext-diff",
                   "--binary", "--full-index", base, head, "--", *files)

    return diff(src_files), diff(test_files), len(src_files), len(test_files)


def to_list(cell) -> list:
    if cell is None or (isinstance(cell, float) and pd.isna(cell)):
        return []
    return [x.strip() for x in str(cell).split("|") if x.strip()]


def load_labels(labels_csv: Path) -> dict:
    """Map (project, short_hash) -> {labels, reasoning, new_test_methods, new_test_files}."""
    df = pd.read_csv(labels_csv, dtype=str).fillna("")
    out = {}
    for _, r in df.iterrows():
        key = (r["project"], r["v_0_commit"])
        labels = [LABEL_MAP[t] for t in to_list(r.get("new_labels")) if t in LABEL_MAP]
        out[key] = {
            "labels": labels,
            "new_test_methods": r.get("new_test_methods", ""),
            "new_test_files": to_list(r.get("new_test_files")),
        }
    return out


# Field names follow the paper's version notation (V-1 / V0). V-0.5 is not a
# commit: it is V-1 with source_patch applied.
SCHEMA = pa.schema([
    ("instance_id", pa.string()),
    ("project", pa.string()),
    ("repo", pa.string()),
    ("v_minus_1_commit", pa.string()),   # V-1: parent state, before the change
    ("v0_commit", pa.string()),          # V0: full commit incl. GT test changes
    ("v0_date", pa.string()),
    ("v0_message", pa.string()),
    ("labels", pa.list_(pa.string())),   # breaking / stale / missing
    ("changed_test_methods", pa.list_(pa.string())),
    ("new_test_files", pa.list_(pa.string())),
    ("new_test_methods", pa.string()),   # JSON map {TestClass: [methods]}
    ("num_changed_files", pa.int64()),
    ("src_changed_lines", pa.int64()),
    ("test_changed_lines", pa.int64()),
    ("source_patch", pa.string()),       # V-1 -> V-0.5 (non-test; the system input)
    ("test_patch", pa.string()),         # V-0.5 -> V0  (gold test changes)
])


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--spine", type=Path,
                    default=TEBENCH / "data" / "filtered_commits_step2_full.csv")
    ap.add_argument("--labels", type=Path,
                    default=TESTUPDATE / "classification_results_v2.csv")
    ap.add_argument("--repos", type=Path,
                    default=TESTUPDATE / "TUDataset" / "defects4j-projects")
    ap.add_argument("--out", type=Path, default=HERE / "data" / "test.parquet")
    args = ap.parse_args()

    spine = pd.read_excel(args.spine, engine="openpyxl")
    labels = load_labels(args.labels)
    print(f"spine rows={len(spine)}  label rows={len(labels)}")

    records, errors, missing_labels = [], [], 0
    for i, row in enumerate(spine.itertuples(index=False), 1):
        project = row.Project
        short = str(row.CommitID)
        full = str(row.FullHash)
        repo = args.repos / project
        try:
            base = git(repo, "rev-parse", "--verify", f"{full}^").strip()
            msg = git(repo, "log", "-1", "--format=%B", full).strip()
            src_patch, test_patch, n_src, n_test = split_patch(repo, base, full)
        except Exception as e:  # noqa: BLE001
            errors.append(f"{project}/{short}: {e}")
            continue

        lab = labels.get((project, short))
        if lab is None:
            missing_labels += 1
            lab = {"labels": [], "new_test_methods": "", "new_test_files": []}

        records.append({
            "instance_id": f"{project}__{short}",
            "project": project,
            "repo": REPO_SLUG.get(project, project),
            "v_minus_1_commit": base,
            "v0_commit": full,
            "v0_date": str(row.Date),
            "v0_message": msg,
            "labels": lab["labels"],
            "changed_test_methods": to_list(row.ChangedTestMethods),
            "new_test_files": lab["new_test_files"],
            "new_test_methods": lab["new_test_methods"],
            "num_changed_files": int(row.ChangedFiles),
            "src_changed_lines": int(row.SrcChangedLines),
            "test_changed_lines": int(row.TestChangedLines),
            "source_patch": src_patch,
            "test_patch": test_patch,
        })
        if i % 50 == 0:
            print(f"  ...{i}/{len(spine)}")

    args.out.parent.mkdir(parents=True, exist_ok=True)
    table = pa.Table.from_pylist(records, schema=SCHEMA)
    pq.write_table(table, args.out)

    # ---- validation summary ----
    b = sum("breaking" in r["labels"] for r in records)
    s = sum("stale" in r["labels"] for r in records)
    m = sum("missing" in r["labels"] for r in records)
    empty_src = sum(not r["source_patch"] for r in records)
    empty_test = sum(not r["test_patch"] for r in records)
    print("\n==== summary ====")
    print(f"instances written : {len(records)}")
    print(f"errors            : {len(errors)}")
    print(f"missing labels    : {missing_labels}")
    print(f"labels  B/S/M     : {b}/{s}/{m}   (paper: 172/207/199)")
    print(f"empty source_patch: {empty_src}")
    print(f"empty test_patch  : {empty_test}")
    print(f"written to        : {args.out}")
    if errors:
        print("\nfirst errors:")
        for e in errors[:10]:
            print("  ", e)


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