File size: 11,656 Bytes
41e2b8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""Download repository snapshots for MM-IssueLoc Bench at each PR base_commit.

For every entry in `commit_cache.json`, this script fetches a source-code
tarball at the exact `base_commit` via the GitHub REST API and extracts it
into `repos/<dir_name>/`. No `.git` history is retained.

Requirements
------------
- Python 3.10+ (stdlib only — no external packages).
- A GitHub personal access token with `public_repo` scope is strongly
  recommended: the anonymous rate limit is 60 req/hour, vs 5000/hour with
  a token. Pass it via `--token` or set `GITHUB_TOKEN` / `GH_TOKEN`.
  Generate one at https://github.com/settings/tokens (no extra permissions
  needed for public repositories).

Example
-------
    export GITHUB_TOKEN=ghp_xxx
    python3 scripts/download_repos.py                     # ~10 min w/ token
    python3 scripts/download_repos.py --workers 8
    python3 scripts/download_repos.py --only 5            # dry-run small slice
    python3 scripts/download_repos.py --retry-failed      # retry failures

Resumability
------------
Already-extracted directories are skipped by default. Partial downloads
use a `<dir>.tmp` staging directory that is renamed atomically on success,
so a Ctrl+C never leaves a half-extracted repo under `repos/`.

Disk / bandwidth
----------------
Full download is ~5–20 GB across 653 repos; size is dominated by a few
large upstream projects. Individual tarballs are streamed in memory
(typical peak RSS < 500 MB) and extracted immediately.
"""

from __future__ import annotations

import argparse
import concurrent.futures as cf
import json
import os
import shutil
import sys
import tarfile
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path

API_ROOT = "https://api.github.com"
UA = "mm-issueloc-bench-downloader/1.0"


# ---------------------------------------------------------------------------
# Types
# ---------------------------------------------------------------------------

@dataclass
class Job:
    instance_id: str
    repo: str          # "owner/name"
    sha: str           # full commit SHA
    dir_name: str      # target directory name

    @property
    def owner(self) -> str:
        return self.repo.split("/", 1)[0]

    @property
    def name(self) -> str:
        return self.repo.split("/", 1)[1]


@dataclass
class Result:
    job: Job
    ok: bool
    files: int = 0
    error: str = ""


# ---------------------------------------------------------------------------
# GitHub API
# ---------------------------------------------------------------------------

def _request(url: str, token: str | None, timeout: int = 180) -> bytes:
    """GET a URL, returning the raw body. Follows redirects (tarball → codeload)."""
    headers = {"Accept": "application/vnd.github+json", "User-Agent": UA}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.read()


def fetch_tarball(job: Job, token: str | None, max_retries: int = 5) -> bytes:
    """Fetch the repo as a gzipped tarball at the target commit.

    Retries on 403 rate-limit and transient network errors with exponential backoff.
    """
    url = f"{API_ROOT}/repos/{job.repo}/tarball/{job.sha}"
    last_err: Exception | None = None
    for attempt in range(max_retries):
        try:
            return _request(url, token)
        except urllib.error.HTTPError as e:
            body = e.read().decode("utf-8", errors="replace") if hasattr(e, "read") else ""
            if e.code == 403 and ("rate limit" in body.lower() or "secondary" in body.lower()):
                wait = min(60 * (2 ** attempt), 900)
                print(f"    rate limited ({e.code}); sleeping {wait}s (attempt {attempt + 1}/{max_retries})",
                      file=sys.stderr, flush=True)
                time.sleep(wait)
                last_err = e
                continue
            # 404 / 451 / 410 etc — repo is gone, don't retry
            raise RuntimeError(f"HTTP {e.code} — {body[:200]}") from e
        except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
            wait = 2 ** attempt
            print(f"    network error ({e}); retrying in {wait}s", file=sys.stderr, flush=True)
            time.sleep(wait)
            last_err = e
    raise RuntimeError(f"exhausted retries: {last_err}")


# ---------------------------------------------------------------------------
# Extraction
# ---------------------------------------------------------------------------

_TAR_KW = {"filter": "data"} if sys.version_info >= (3, 12) else {}


def extract_tarball(data: bytes, dest: Path) -> int:
    """Extract into dest/, stripping the GitHub tarball's top-level dir.

    GitHub tarballs have a top-level directory like `owner-name-shortsha/`;
    we strip it so that dest/ holds the repo contents directly.
    """
    dest.mkdir(parents=True, exist_ok=True)
    n = 0
    with tarfile.open(fileobj=BytesIO(data), mode="r:gz") as tf:
        members = tf.getmembers()
        if not members:
            return 0
        root = members[0].name.split("/", 1)[0] + "/"
        for m in members:
            if not m.name.startswith(root):
                continue
            m.name = m.name[len(root):]
            if not m.name:
                continue
            try:
                tf.extract(m, path=dest, **_TAR_KW)
                n += 1
            except Exception as e:
                # Skip problematic members (broken symlinks, etc.) but keep going
                print(f"    skipped member {m.name!r}: {e}", file=sys.stderr)
    return n


# ---------------------------------------------------------------------------
# Per-job driver
# ---------------------------------------------------------------------------

def run_one(job: Job, out_dir: Path, token: str | None) -> Result:
    dest = out_dir / job.dir_name
    tmp = dest.with_suffix(".tmp")
    if tmp.exists():
        shutil.rmtree(tmp)
    try:
        data = fetch_tarball(job, token)
        n = extract_tarball(data, tmp)
        tmp.rename(dest)
        return Result(job, ok=True, files=n)
    except Exception as e:
        if tmp.exists():
            shutil.rmtree(tmp, ignore_errors=True)
        return Result(job, ok=False, error=str(e))


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def _load_jobs(cache_path: Path, out_dir: Path, *, skip_existing: bool) -> tuple[list[Job], int]:
    cache: dict[str, dict] = json.loads(cache_path.read_text())
    jobs: list[Job] = []
    skipped = 0
    for iid, entry in cache.items():
        job = Job(
            instance_id=iid,
            repo=entry["repo"],
            sha=entry["sha"],
            dir_name=entry["dir_name"],
        )
        dest = out_dir / job.dir_name
        if skip_existing and dest.exists() and any(dest.iterdir()):
            skipped += 1
            continue
        jobs.append(job)
    return jobs, skipped


def _load_failed(failures_path: Path, out_dir: Path) -> list[Job]:
    records = json.loads(failures_path.read_text())
    return [
        Job(instance_id=r["instance_id"], repo=r["repo"], sha=r["sha"], dir_name=r["dir_name"])
        for r in records
    ]


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--output-dir", type=Path, default=Path("repos"),
                    help="Directory to place `<dir_name>/` snapshots into (default: repos)")
    ap.add_argument("--cache-file", type=Path, default=Path("commit_cache.json"),
                    help="Path to commit_cache.json (default: ./commit_cache.json)")
    ap.add_argument("--workers", type=int, default=4,
                    help="Parallel download workers (default: 4)")
    ap.add_argument("--only", type=int, default=0,
                    help="Download only the first N jobs (for testing)")
    ap.add_argument("--token", default=os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN"),
                    help="GitHub token; falls back to $GITHUB_TOKEN / $GH_TOKEN")
    ap.add_argument("--no-skip-existing", action="store_true",
                    help="Re-download even if the target directory already exists")
    ap.add_argument("--retry-failed", action="store_true",
                    help="Retry entries from download_failures.json instead of the full cache")
    args = ap.parse_args()

    if not args.cache_file.exists():
        print(f"error: {args.cache_file} not found — run from the dataset root.", file=sys.stderr)
        return 2
    if not args.token:
        print("WARNING: no token provided. Unauthenticated rate limit is 60 req/hour.\n"
              "         Set GITHUB_TOKEN or pass --token for a 5000/hour limit.",
              file=sys.stderr)

    args.output_dir.mkdir(parents=True, exist_ok=True)
    failures_path = args.output_dir.parent / "download_failures.json"

    if args.retry_failed:
        if not failures_path.exists():
            print(f"error: no {failures_path} — nothing to retry.", file=sys.stderr)
            return 2
        jobs = _load_failed(failures_path, args.output_dir)
        skipped = 0
        print(f"Retrying {len(jobs)} previously failed entries from {failures_path}")
    else:
        jobs, skipped = _load_jobs(
            args.cache_file, args.output_dir, skip_existing=not args.no_skip_existing,
        )
        if args.only:
            jobs = jobs[: args.only]

    if not jobs:
        print(f"Nothing to do — {skipped} already present in {args.output_dir}/.")
        return 0

    print(f"Downloading {len(jobs)} repos into {args.output_dir}/ ({skipped} already present) "
          f"with {args.workers} workers.")

    failures: list[Result] = []
    start = time.time()
    with cf.ThreadPoolExecutor(max_workers=args.workers) as ex:
        futures = {ex.submit(run_one, j, args.output_dir, args.token): j for j in jobs}
        try:
            for i, fut in enumerate(cf.as_completed(futures), 1):
                res = fut.result()
                tag = "ok " if res.ok else "FAIL"
                short_sha = res.job.sha[:12]
                extra = f"{res.files:>5} files" if res.ok else res.error[:80]
                print(f"  [{i:>4}/{len(jobs)}] {tag}  {res.job.repo:<55s} @ {short_sha}  {extra}",
                      flush=True)
                if not res.ok:
                    failures.append(res)
        except KeyboardInterrupt:
            print("\nInterrupted — waiting for in-flight downloads to finish cleanly...",
                  file=sys.stderr)
            ex.shutdown(cancel_futures=True)
            return 130

    elapsed = time.time() - start
    n_ok = len(jobs) - len(failures)
    print(f"\n{n_ok}/{len(jobs)} repos fetched in {elapsed:.0f}s.")

    if failures:
        failures_path.write_text(json.dumps(
            [
                {
                    "instance_id": r.job.instance_id,
                    "repo": r.job.repo,
                    "sha": r.job.sha,
                    "dir_name": r.job.dir_name,
                    "error": r.error,
                }
                for r in failures
            ],
            indent=2,
        ))
        print(f"{len(failures)} failures logged to {failures_path}\n"
              f"Retry with:  python3 scripts/download_repos.py --retry-failed", file=sys.stderr)
        return 1
    return 0


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