Elffuss BraidHub

kikocis/auto-code-rover public

d942afa3e83c · 8.5 KiBRawPermalink
1import json
2import os
3import re
4import shutil
5from abc import ABC, abstractmethod
6from os.path import join as pjoin
7from pathlib import Path
8
9import httpx
10
11from app import utils as app_utils
12from app.log import log_and_print
13from app.task import PlainTask, SweTask, Task
14
15
16class RawTask(ABC):
17 @property
18 @abstractmethod
19 def task_id(self) -> str:
20 raise NotImplementedError("abstract base class")
21
22 @abstractmethod
23 def to_task(self) -> Task:
24 raise NotImplementedError("abstract base class")
25
26 @abstractmethod
27 def dump_meta_data(self, output_dir: str) -> None:
28 raise NotImplementedError("abstract base class")
29
30
31class RawSweTask(RawTask):
32 """
33 Encapsulate everything required to run one task.
34 """
35
36 def __init__(self, task_id: str, setup_info: dict, task_info: dict):
37 # a counter str, format "1/150", which means first task out of 150
38 # id from the benchmark
39 self._task_id = task_id
40 # setup_info (Dict): keys: ['repo_path', 'env_name', 'pre_install', 'install','test_cmd']
41 self.setup_info = setup_info
42 # task_info (Dict): keys: ['base_commit', 'hints_text', 'created_at',
43 # 'test_patch', 'repo', 'problem_statement', 'version', 'instance_id',
44 # 'FAIL_TO_PASS', 'PASS_TO_PASS', 'environment_setup_commit']
45 self.task_info = task_info
46
47 @property
48 def task_id(self) -> str:
49 return self._task_id
50
51 def to_task(self) -> SweTask:
52 task_id = self.task_id
53 setup_info = self.setup_info
54 task_info = self.task_info
55 return SweTask(
56 task_id=task_id,
57 problem_statement=task_info["problem_statement"],
58 repo_path=setup_info["repo_path"],
59 env_name=setup_info["env_name"],
60 pre_install_cmds=setup_info["pre_install"],
61 install_cmd=setup_info["install"],
62 # command to run the relevant tests,
63 test_cmd=setup_info["test_cmd"],
64 commit=task_info["base_commit"],
65 repo_name=task_info["repo"],
66 # modifications to the test suite for this task instance,
67 test_patch=task_info["test_patch"],
68 testcases_passing=task_info["PASS_TO_PASS"],
69 testcases_failing=task_info["FAIL_TO_PASS"],
70 )
71
72 def dump_meta_data(self, output_dir: str):
73 meta = {
74 "task_id": self.task_id,
75 "setup_info": self.setup_info,
76 "task_info": self.task_info,
77 }
78 with open(pjoin(output_dir, "meta.json"), "w") as f:
79 json.dump(meta, f, indent=4)
80 with open(pjoin(output_dir, "problem_statement.txt"), "w") as f:
81 f.write(self.task_info["problem_statement"])
82 with open(pjoin(output_dir, "developer_patch.diff"), "w") as f:
83 f.write(self.task_info["patch"])
84
85
86class RawGithubTask(RawTask):
87 """
88 Encapsulate everything required to run ACR on a fresh issue from the internet.
89 """
90
91 def __init__(
92 self,
93 task_id: str,
94 clone_link: str,
95 commit_hash: str,
96 issue_link: str,
97 setup_dir: str,
98 ):
99 self._task_id = task_id
100 self.clone_link = clone_link
101 self.commit_hash = commit_hash
102 self.issue_link = issue_link
103 self.setup_dir = setup_dir
104 self.clone_path = pjoin(self.setup_dir, self.task_id)
105 self.problem_statement, self.created_at = self.fetch_issue()
106 self.clone_repo()
107
108 @property
109 def task_id(self) -> str:
110 return self._task_id
111
112 def clone_repo(self):
113 clone_path = Path(self.clone_path)
114 if os.path.exists(clone_path):
115 log_and_print(
116 f"Path {clone_path} already exists. Removing it to get a fresh clone."
117 )
118 shutil.rmtree(clone_path)
119 app_utils.clone_repo(self.clone_link, str(clone_path.parent), clone_path.name)
120 log_and_print(f"Cloned source code to {clone_path}.")
121
122 def dump_meta_data(self, output_dir: str):
123 meta = {
124 "task_info": {
125 "base_commit": self.commit_hash,
126 "created_at": self.created_at,
127 "problem_statement": self.problem_statement,
128 "instance_id": self.task_id,
129 },
130 "setup_info": {"repo_path": self.clone_path},
131 }
132
133 meta_file = pjoin(output_dir, "meta.json")
134
135 with open(meta_file, "w") as f:
136 json.dump(meta, f, indent=4)
137
138 def fetch_issue(self):
139 if "github.com" not in self.issue_link:
140 raise NotImplementedError("Only GitHub issues are supported for now.")
141
142 retrieved_issue = self.fetch_github_issue(self.issue_link)
143
144 if retrieved_issue is None:
145 raise RuntimeError(
146 f"Failed to retrieve issue information from {self.issue_link}"
147 )
148
149 title, body, created_at = retrieved_issue
150
151 body = self.process_links(body)
152
153 problem_statement = f"{title}\n{body}"
154
155 return problem_statement, created_at
156
157 @classmethod
158 def process_links(cls, body: str):
159 code_pattern = re.compile(
160 r"https://github.com/(.*?)/blob/(.*)/(.*)#L(\d+)-L(\d+)"
161 )
162 replacements = []
163
164 for code_links in code_pattern.finditer(body):
165 print("Found link!")
166 repo_name = code_links.group(1)
167 commit = code_links.group(2)
168 file_path = code_links.group(3)
169 start_line = int(code_links.group(4))
170 end_line = int(code_links.group(5))
171
172 file_contents = httpx.get(
173 f"https://raw.githubusercontent.com/{repo_name}/{commit}/{file_path}"
174 ).text.splitlines()
175 fragment = "\n".join(file_contents[start_line - 1 : end_line])
176
177 replacements.append((code_links.group(0), f"\n```{fragment }```\n"))
178
179 for code_link, replacement in replacements:
180 body = body.replace(code_link, code_link + replacement)
181 return body
182
183 @classmethod
184 def fetch_github_issue(cls, issue_url: str) -> tuple[str, str, str]:
185 """Extract owner, repo, and issue number from the URL"""
186
187 # Example issue URL: https://github.com/owner/repo/issues/123
188
189 _, owner, repo, _, issue_number = issue_url.rsplit("/", 4)
190
191 api_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}"
192 response = httpx.get(api_url)
193
194 if response.status_code != 200:
195 raise RuntimeError(
196 f"Failed to fetch issue information: {response.status_code}"
197 )
198
199 issue_info = response.json()
200
201 title = issue_info["title"]
202 body = issue_info["body"]
203 created_at = issue_info["created_at"]
204
205 return title, body, created_at
206
207 def to_task(self) -> PlainTask:
208 return PlainTask(
209 commit_hash=self.commit_hash,
210 local_path=self.clone_path,
211 problem_statement=self.problem_statement,
212 )
213
214
215class RawLocalTask(RawTask):
216 """
217 Encapsulate everything required to run ACR on a local issue on the disk.
218 """
219
220 def __init__(self, task_id: str, local_repo: str, issue_file: str):
221 self._task_id = task_id
222 self.local_repo = local_repo
223 self.issue_file = issue_file
224 self.commit_hash = self.init_local_repo()
225 self.problem_statement = self.read_issue_from_file()
226
227 @property
228 def task_id(self) -> str:
229 return self._task_id
230
231 def init_local_repo(self):
232 with app_utils.cd(self.local_repo):
233 if not app_utils.is_git_repo():
234 # non git repo - let's make it a git repo first
235 app_utils.initialize_git_repo_and_commit()
236 commit = app_utils.get_current_commit_hash()
237 return commit
238
239 def read_issue_from_file(self) -> str:
240 # ignore encoding errors so at least we can have some issue content
241 issue = Path(self.issue_file).read_text(errors="ignore")
242 return issue
243
244 def dump_meta_data(self, output_dir: str):
245 meta = {
246 "task_info": {
247 "base_commit": self.commit_hash,
248 "problem_statement": self.problem_statement,
249 "instance_id": self.task_id,
250 },
251 "setup_info": {"repo_path": self.local_repo},
252 }
253
254 meta_file = pjoin(output_dir, "meta.json")
255
256 with open(meta_file, "w") as f:
257 json.dump(meta, f, indent=4)
258
259 def to_task(self) -> PlainTask:
260 return PlainTask(
261 commit_hash=self.commit_hash,
262 local_path=self.local_repo,
263 problem_statement=self.problem_statement,
264 )