Buckets:

download
raw
7.98 kB
#!/usr/bin/env python3
"""
Patch Extractor - Extracts patches from git history for benchmark evaluation.
"""
import argparse
import json
import os
import subprocess
from pathlib import Path
from typing import Any
class PatchExtractor:
"""Extracts patches from git history and PRs."""
def __init__(self, repo_path: str | None = None):
self.repo_path = Path(repo_path or os.getcwd())
def get_commit_diff(self, commit_sha: str) -> str:
"""Get diff for a specific commit."""
try:
result = subprocess.run(
["git", "show", commit_sha, "--no-color"],
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=30,
)
return result.stdout if result.returncode == 0 else ""
except Exception:
return ""
def get_commit_files(self, commit_sha: str) -> list[dict[str, Any]]:
"""Get list of files changed in a commit."""
try:
result = subprocess.run(
["git", "show", "--name-status", "--format=", commit_sha],
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
return []
files = []
for line in result.stdout.strip().split("\n"):
if line:
parts = line.split("\t")
if len(parts) >= 2:
files.append(
{
"status": parts[0],
"filename": parts[1],
}
)
return files
except Exception:
return []
def extract_patches_from_log(self, max_count: int = 50, since: str | None = None) -> list[dict[str, Any]]:
"""Extract patches from git log."""
cmd = ["git", "log", f"--max-count={max_count}", "--format=%H|%s|%aI"]
if since:
cmd.extend([f"--since={since}"])
try:
result = subprocess.run(
cmd,
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=60,
)
if result.returncode != 0:
return []
patches = []
for line in result.stdout.strip().split("\n"):
if "|" in line:
parts = line.split("|")
if len(parts) >= 3:
commit_sha = parts[0].strip()
message = parts[1].strip()
date = parts[2].strip()
files = self.get_commit_files(commit_sha)
patches.append(
{
"commit_sha": commit_sha,
"message": message,
"date": date,
"files_changed": files,
}
)
return patches
except Exception as e:
print(f"Error extracting patches: {e}")
return []
def get_patch_for_commit(self, commit_sha: str) -> dict[str, Any]:
"""Get full patch details for a commit."""
diff = self.get_commit_diff(commit_sha)
files = self.get_commit_files(commit_sha)
return {
"commit_sha": commit_sha,
"diff": diff,
"files": files,
"stats": {
"files_changed": len(files),
"lines_added": (
len([line for line in diff.split("\n") if line.startswith("+") and line != "+++ b/"[:1]]) if diff else 0
),
"lines_removed": (
len([line for line in diff.split("\n") if line.startswith("-") and line != "--- a/"[:1]]) if diff else 0
),
},
}
def find_fix_commits(self, keyword: str, max_count: int = 20) -> list[dict[str, Any]]:
"""Find commits related to bug fixes."""
cmd = [
"git",
"log",
"--all",
f"--max-count={max_count}",
"--grep=" + keyword,
"--format=%H|%s|%aI",
]
try:
result = subprocess.run(
cmd,
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
return []
commits = []
for line in result.stdout.strip().split("\n"):
if "|" in line:
parts = line.split("|")
if len(parts) >= 3:
commits.append(
{
"commit_sha": parts[0].strip(),
"message": parts[1].strip(),
"date": parts[2].strip(),
}
)
return commits
except Exception:
return []
def export_patches(self, output_dir: Path, max_patches: int = 50) -> None:
"""Export patches to JSON file."""
output_dir.mkdir(parents=True, exist_ok=True)
patches = self.extract_patches_from_log(max_count=max_patches)
output_file = output_dir / "patches.json"
with open(output_file, "w") as f:
json.dump(patches, f, indent=2, default=str)
print(f"Exported {len(patches)} patches to {output_file}")
def create_benchmark_dataset(self, output_dir: Path) -> None:
"""Create a benchmark-ready dataset from git history."""
output_dir.mkdir(parents=True, exist_ok=True)
fix_keywords = ["fix", "bug", "fixes", "fixed", "patch"]
all_patches = []
for keyword in fix_keywords:
patches = self.find_fix_commits(keyword, max_count=10)
for patch in patches:
patch["keyword"] = keyword
all_patches.append(patch)
unique_patches = {p["commit_sha"]: p for p in all_patches}.values()
dataset = []
for patch in list(unique_patches)[:30]:
details = self.get_patch_for_commit(patch["commit_sha"])
dataset.append(
{
"instance_id": f"zen-ai-{patch['commit_sha'][:8]}",
"commit_sha": patch["commit_sha"],
"issue_description": patch["message"],
"patch": details["diff"],
"files_changed": [f["filename"] for f in details["files"]],
"stats": details["stats"],
}
)
output_file = output_dir / "benchmark_dataset.json"
with open(output_file, "w") as f:
json.dump(dataset, f, indent=2, default=str)
print(f"Created benchmark dataset with {len(dataset)} instances in {output_file}")
def main():
parser = argparse.ArgumentParser(description="Extract patches from git history")
parser.add_argument("--repo", default=".", help="Repository path")
parser.add_argument("--output", default="benchmark/data", help="Output directory")
parser.add_argument("--max-patches", type=int, default=50, help="Max patches to extract")
parser.add_argument(
"--create-dataset",
action="store_true",
help="Create benchmark dataset",
)
args = parser.parse_args()
extractor = PatchExtractor(repo_path=args.repo)
output_dir = Path(args.output)
if args.create_dataset:
extractor.create_benchmark_dataset(output_dir)
else:
extractor.export_patches(output_dir, max_patches=args.max_patches)
print("\nDone!")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
7.98 kB
·
Xet hash:
883ff352973461633437b86cf0a013402bf7cf06c5a34920703d237ce16658ec

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.