Datasets:
Download scripts/prepare_workspace.py from CrossSWE/CrossSWE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.28 kB
-
https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/scripts/prepare_workspace.py
- Command line
-
hf download hf://datasets/CrossSWE/CrossSWE-Bench/scripts/prepare_workspace.py
-
curl -L -o prepare_workspace.py https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/scripts/prepare_workspace.py
9.28 kB
| """Export base source snapshots into independent agent Git repositories.""" | |
| import argparse | |
| import io | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import shutil | |
| import subprocess | |
| import tarfile | |
| import tempfile | |
| from common import ROOT, contained, load_task, run | |
| from statement_text import read_problem_statement | |
| from fetch_sources import fetch | |
| from source_construction import object_id | |
| def extract_tar(archive, target, bindings=None, workspace_root=None): | |
| """Extract Git archive regular files and contained symlinks on Python 3.10+.""" | |
| target = Path(target).resolve() | |
| bindings = bindings or {} | |
| workspace_root = Path(workspace_root or target).resolve() | |
| link_targets = {} | |
| with tarfile.open(fileobj=io.BytesIO(archive) if isinstance(archive, bytes) else archive) as stream: | |
| members = stream.getmembers() | |
| names = set() | |
| links = set() | |
| for member in members: | |
| name = PurePosixPath(member.name) | |
| if name.is_absolute() or ".." in name.parts or ".git" in name.parts or not name.parts: | |
| raise ValueError(f"Unsafe archive path: {member.name}") | |
| if str(name) in names: | |
| raise ValueError(f"Duplicate archive member: {member.name}") | |
| names.add(str(name)) | |
| if not (member.isdir() or member.isfile() or member.issym()): | |
| raise ValueError(f"Unsupported archive member: {member.name}") | |
| path = contained(target, str(name)) | |
| if member.issym(): | |
| binding = bindings.get(str(name)) | |
| linkname = member.linkname | |
| scope = target | |
| if binding: | |
| if linkname != binding["original_target"] or object_id("blob", linkname.encode()) != binding["expected_blob"]: | |
| raise ValueError(f"Declared source binding differs: {member.name}") | |
| linkname = binding["replacement"] | |
| scope = workspace_root | |
| link = PurePosixPath(linkname) | |
| if link.is_absolute() or not linkname: | |
| raise ValueError(f"Unsafe symlink: {member.name}") | |
| destination = (path.parent / linkname).resolve() | |
| if not destination.is_relative_to(scope) or ".git" in destination.relative_to(scope).parts: | |
| raise ValueError(f"Symlink escapes snapshot: {member.name}") | |
| link_targets[str(name)] = linkname | |
| links.add(name) | |
| if set(bindings) - set(link_targets): | |
| raise ValueError("Declared cross-repository binding is missing from the source tree") | |
| # No archive entry may traverse a symlink, even one contained in target. | |
| for member in members: | |
| if any(parent in links for parent in PurePosixPath(member.name).parents): | |
| raise ValueError(f"Archive traverses symlink: {member.name}") | |
| for member in members: | |
| path = contained(target, member.name) | |
| if member.isdir(): | |
| path.mkdir(parents=True, exist_ok=True) | |
| elif member.isfile(): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with stream.extractfile(member) as source, path.open("xb") as dest: | |
| shutil.copyfileobj(source, dest) | |
| path.chmod(member.mode & 0o777) | |
| for member in members: | |
| if member.issym(): | |
| path = contained(target, member.name) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| os.symlink(link_targets[str(PurePosixPath(member.name))], path) | |
| def extract_snapshot(cache, revision, target, bindings=None, workspace_root=None): | |
| # Materialize exact tracked blobs: Git archive can omit export-ignore files | |
| # or rewrite export-subst content, which would change a pinned snapshot. | |
| tree = subprocess.check_output(["git", "-C", str(cache), "ls-tree", "-rz", "--full-tree", revision]) | |
| entries = [entry.split(b"\t", 1) for entry in tree.split(b"\0") if entry] | |
| if any(meta.startswith(b"160000 ") for meta, _ in entries): | |
| raise ValueError("This source tree has submodules; explicit submodule materialization is required") | |
| with tempfile.TemporaryFile() as archive: | |
| process = subprocess.Popen(["git", "-C", str(cache), "cat-file", "--batch"], | |
| stdin=subprocess.PIPE, stdout=subprocess.PIPE) | |
| try: | |
| with tarfile.open(fileobj=archive, mode="w") as stream: | |
| for meta, name in entries: | |
| mode, kind, oid = meta.split(b" ") | |
| if kind != b"blob" or mode not in (b"100644", b"100755", b"120000"): | |
| raise ValueError(f"Unsupported Git tree entry: {name!r}") | |
| process.stdin.write(oid + b"\n") | |
| process.stdin.flush() | |
| header = process.stdout.readline().split() | |
| if len(header) != 3 or header[:2] != [oid, b"blob"]: | |
| raise ValueError(f"Invalid Git object response: {header!r}") | |
| size = int(header[2]) | |
| info = tarfile.TarInfo(os.fsdecode(name)) | |
| info.mode = int(mode, 8) & 0o777 | |
| if mode == b"120000": | |
| info.type = tarfile.SYMTYPE | |
| info.linkname = os.fsdecode(process.stdout.read(size)) | |
| stream.addfile(info) | |
| else: | |
| info.size = size | |
| stream.addfile(info, process.stdout) | |
| if process.stdout.read(1) != b"\n": | |
| raise ValueError("Truncated Git object response") | |
| process.stdin.close() | |
| if process.wait() != 0: | |
| raise ValueError("Git object export failed") | |
| archive.seek(0) | |
| extract_tar(archive, target, bindings, workspace_root) | |
| finally: | |
| if process.poll() is None: | |
| process.terminate() | |
| process.wait() | |
| process.stdout.close() | |
| def prepare(task, cache_root, output): | |
| output = Path(output).resolve() | |
| if output.exists(): | |
| raise ValueError(f"Output already exists: {output}") | |
| cache_root = Path(cache_root).resolve() | |
| if cache_root.is_relative_to(output) or output.is_relative_to(cache_root): | |
| raise ValueError("Source object cache must remain outside the agent workspace") | |
| if output.is_relative_to(ROOT) or ROOT.is_relative_to(output): | |
| raise ValueError("Agent workspace must remain outside the benchmark release") | |
| targets = [contained(output, r["workspace_path"]) for r in task["repositories"]] | |
| for i, target in enumerate(targets): | |
| if target == output or target.name == "problem_statement.md": | |
| raise ValueError("Invalid repository workspace path") | |
| if any(target.is_relative_to(other) or other.is_relative_to(target) for other in targets[:i]): | |
| raise ValueError("Repository workspace paths overlap") | |
| by_key = {repo["key"]: (repo, target) for repo, target in zip(task["repositories"], targets)} | |
| repository_bindings = {} | |
| for repo, target in zip(task["repositories"], targets): | |
| bindings = {} | |
| for link in repo.get("source_policy", {}).get("workspace_links", []): | |
| provider_key = link["target_repository"] | |
| if provider_key not in by_key or provider_key == repo["key"]: | |
| raise ValueError("Source binding requires a declared, distinct provider repository") | |
| provider, provider_path = by_key[provider_key] | |
| if link["original_target"] != provider["container_path"]: | |
| raise ValueError("Source binding does not refer to its declared provider repository") | |
| link_path = contained(target, link["path"]) | |
| bindings[link["path"]] = {**link, "replacement": os.path.relpath(provider_path, link_path.parent)} | |
| repository_bindings[repo["key"]] = bindings | |
| statement = read_problem_statement(task) | |
| caches = fetch(task, cache_root) | |
| output.mkdir(parents=True) | |
| for repo, target in zip(task["repositories"], targets): | |
| target.mkdir(parents=True) | |
| extract_snapshot(caches[repo["key"]], repo["base_commit"], target, repository_bindings[repo["key"]], output) | |
| run("git", "init", "-b", "main", str(target)) | |
| run("git", "-C", str(target), "add", "--force", "--all") | |
| run("git", "-C", str(target), "-c", "user.name=CrossSWE", "-c", "user.email=base@crossswe.invalid", | |
| "-c", "core.hooksPath=/dev/null", "commit", "--allow-empty", "-m", "Pinned base source snapshot") | |
| (output / "problem_statement.md").write_text(statement, encoding="utf-8") | |
| print(output) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--instance-id", required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--source-cache", type=Path) | |
| args = parser.parse_args() | |
| task = load_task(args.instance_id) | |
| cache = args.source_cache or ROOT / ".cache" / "source-repos" / task["instance_id"] | |
| prepare(task, cache, args.output_dir) | |
| if __name__ == "__main__": | |
| main() | |