Elffuss BraidHub

kikocis/auto-code-rover public

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