Elffuss BraidHub

kikocis/auto-code-rover public

main · 9.7 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 | None,
96 issue_link: str,
97 setup_dir: str,
98 use_comments: bool = False,
99 ):
100 self._task_id = task_id
101 self.clone_link = clone_link
102 # if commit_hash is None, assume using the HEAD of default branch
103 self.commit_hash = commit_hash
104 self.issue_link = issue_link
105 self.setup_dir = setup_dir
106 self.use_comments = use_comments
107 self.clone_path = pjoin(self.setup_dir, self.task_id)
108 self.problem_statement, self.created_at = self.fetch_issue()
109 self.clone_repo()
110
111 @property
112 def task_id(self) -> str:
113 return self._task_id
114
115 def clone_repo(self):
116 clone_path = Path(self.clone_path)
117 if os.path.exists(clone_path):
118 log_and_print(
119 f"Path {clone_path} already exists. Removing it to get a fresh clone."
120 )
121 shutil.rmtree(clone_path)
122 app_utils.clone_repo(self.clone_link, str(clone_path.parent), clone_path.name)
123 log_and_print(f"Cloned source code to {clone_path}.")
124 if self.commit_hash is None:
125 # let's get the current commit hash
126 with app_utils.cd(clone_path):
127 self.commit_hash = app_utils.get_current_commit_hash()
128
129 def dump_meta_data(self, output_dir: str):
130 meta = {
131 "task_info": {
132 "base_commit": self.commit_hash,
133 "created_at": self.created_at,
134 "problem_statement": self.problem_statement,
135 "instance_id": self.task_id,
136 },
137 "setup_info": {"repo_path": self.clone_path},
138 }
139
140 meta_file = pjoin(output_dir, "meta.json")
141
142 with open(meta_file, "w") as f:
143 json.dump(meta, f, indent=4)
144
145 def fetch_issue(self):
146 if "github.com" not in self.issue_link:
147 raise NotImplementedError("Only GitHub issues are supported for now.")
148
149 retrieved_issue = self.fetch_github_issue(self.issue_link, self.use_comments)
150
151 if retrieved_issue is None:
152 raise RuntimeError(
153 f"Failed to retrieve issue information from {self.issue_link}"
154 )
155
156 title, body, created_at = retrieved_issue
157
158 body = self.process_links(body)
159
160 problem_statement = f"{title}\n{body}"
161
162 return problem_statement, created_at
163
164 @classmethod
165 def process_links(cls, body: str):
166 code_pattern = re.compile(
167 r"https://github.com/(.*?)/blob/(.*)/(.*)#L(\d+)-L(\d+)"
168 )
169 replacements = []
170
171 for code_links in code_pattern.finditer(body):
172 repo_name = code_links.group(1)
173 commit = code_links.group(2)
174 file_path = code_links.group(3)
175 start_line = int(code_links.group(4))
176 end_line = int(code_links.group(5))
177
178 file_contents = httpx.get(
179 f"https://raw.githubusercontent.com/{repo_name}/{commit}/{file_path}"
180 ).text.splitlines()
181 fragment = "\n".join(file_contents[start_line - 1 : end_line])
182
183 replacements.append((code_links.group(0), f"\n```{fragment }```\n"))
184
185 for code_link, replacement in replacements:
186 body = body.replace(code_link, code_link + replacement)
187 return body
188
189 @classmethod
190 def fetch_github_issue(
191 cls, issue_url: str, use_comments: bool = False
192 ) -> tuple[str, str, str]:
193 """Extract owner, repo, and issue number from the URL"""
194
195 # Example issue URL: https://github.com/owner/repo/issues/123
196
197 _, owner, repo, _, issue_number = issue_url.rsplit("/", 4)
198
199 api_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}"
200 comments_url = f"https://api.github.com/repos/{owner}/{repo}/issues/{issue_number}/comments"
201
202 issue_response = httpx.get(api_url)
203
204 if issue_response.status_code != 200:
205 raise RuntimeError(
206 f"Failed to fetch issue information: {issue_response.status_code}"
207 )
208
209 issue_info = issue_response.json()
210
211 title = issue_info["title"]
212 body = issue_info["body"]
213
214 if use_comments:
215 comments_response = httpx.get(comments_url)
216 if comments_response.status_code != 200:
217 raise RuntimeError(
218 f"Failed to fetch comments information: {comments_response.status_code}"
219 )
220
221 comments_info = comments_response.json()
222 for comment in comments_info:
223 if (
224 "user" not in comment
225 or comment["user"]["type"] == "Bot"
226 or comment["user"]["login"] == "acr-bot"
227 ):
228 continue
229
230 body += (
231 f"\nUser: {comment['user']['login']}\nComment: {comment['body']}"
232 )
233
234 created_at = issue_info["created_at"]
235
236 return title, body, created_at
237
238 def to_task(self) -> PlainTask:
239 return PlainTask(
240 commit_hash=self.commit_hash,
241 local_path=self.clone_path,
242 problem_statement=self.problem_statement,
243 )
244
245
246class RawLocalTask(RawTask):
247 """
248 Encapsulate everything required to run ACR on a local issue on the disk.
249 """
250
251 def __init__(self, task_id: str, local_repo: str, issue_file: str):
252 self._task_id = task_id
253 self.local_repo = local_repo
254 self.issue_file = issue_file
255 self.commit_hash = self.init_local_repo()
256 self.problem_statement = self.read_issue_from_file()
257
258 @property
259 def task_id(self) -> str:
260 return self._task_id
261
262 def init_local_repo(self):
263 with app_utils.cd(self.local_repo):
264 if not app_utils.is_git_repo():
265 # non git repo - let's make it a git repo first
266 app_utils.initialize_git_repo_and_commit()
267 commit = app_utils.get_current_commit_hash()
268 return commit
269
270 def read_issue_from_file(self) -> str:
271 # ignore encoding errors so at least we can have some issue content
272 issue = Path(self.issue_file).read_text(errors="ignore")
273 return issue
274
275 def dump_meta_data(self, output_dir: str):
276 meta = {
277 "task_info": {
278 "base_commit": self.commit_hash,
279 "problem_statement": self.problem_statement,
280 "instance_id": self.task_id,
281 },
282 "setup_info": {"repo_path": self.local_repo},
283 }
284
285 meta_file = pjoin(output_dir, "meta.json")
286
287 with open(meta_file, "w") as f:
288 json.dump(meta, f, indent=4)
289
290 def to_task(self) -> PlainTask:
291 return PlainTask(
292 commit_hash=self.commit_hash,
293 local_path=self.local_repo,
294 problem_statement=self.problem_statement,
295 )