Elffuss BraidHub

kikocis/auto-code-rover public

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