Elffuss BraidHub

kikocis/auto-code-rover public

0f4e2e4e2ecb · 10.5 KiBRawPermalink
1import ast
2import contextlib
3import glob
4import os
5import subprocess
6from os.path import dirname as pdirname
7from os.path import join as pjoin
8from pathlib import Path
9from subprocess import CalledProcessError
10
11from app.log import log_and_print
12
13
14@contextlib.contextmanager
15def cd(newdir):
16 """
17 Context manager for changing the current working directory
18 :param newdir: path to the new directory
19 :return: None
20 """
21 prevdir = os.getcwd()
22 os.chdir(os.path.expanduser(newdir))
23 try:
24 yield
25 finally:
26 os.chdir(prevdir)
27
28
29def run_command(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
30 """
31 Run a command in the shell.
32 Args:
33 - cmd: command to run
34 """
35 try:
36 cp = subprocess.run(cmd, check=True, **kwargs)
37 except subprocess.CalledProcessError as e:
38 log_and_print(f"Error running command: {cmd}, {e}")
39 raise e
40 return cp
41
42
43def is_git_repo() -> bool:
44 """
45 Check if the current directory is a git repo.
46 """
47 git_dir = ".git"
48 return os.path.isdir(git_dir)
49
50
51def initialize_git_repo_and_commit(logger=None):
52 """
53 Initialize the current directory as a git repository and make an initial commit.
54 """
55 init_cmd = ["git", "init"]
56 add_all_cmd = ["git", "add", "."]
57 commit_cmd = ["git", "commit", "-m", "Temp commit made by ACR."]
58 run_command(init_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
59 run_command(add_all_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
60 run_command(commit_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
61
62
63def get_current_commit_hash() -> str:
64 command = ["git", "rev-parse", "HEAD"]
65 cp = subprocess.run(command, text=True, capture_output=True)
66 try:
67 cp.check_returncode()
68 return cp.stdout.strip()
69 except CalledProcessError as e:
70 raise RuntimeError(f"Failed to get SHA-1 of HEAD: {cp.stderr}") from e
71
72
73def repo_commit_current_changes():
74 """
75 Commit the current active changes so that it's safer to do git reset later on.
76 Use case: for storing the changes made in pre_install and test_patch in a commit.
77 """
78 add_all_cmd = ["git", "add", "."]
79 commit_cmd = ["git", "commit", "-m", "Temporary commit for storing changes"]
80 run_command(add_all_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
81 run_command(commit_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
82
83
84def clone_repo(clone_link: str, dest_dir: str, cloned_name: str):
85 """
86 Clone a repo to dest_dir.
87
88 Returns:
89 - path to the newly cloned directory.
90 """
91 clone_cmd = ["git", "clone", clone_link, cloned_name]
92 create_dir_if_not_exists(dest_dir)
93 with cd(dest_dir):
94 run_command(clone_cmd)
95 cloned_dir = pjoin(dest_dir, cloned_name)
96 return cloned_dir
97
98
99def clone_repo_and_checkout(
100 clone_link: str, commit_hash: str, dest_dir: str, cloned_name: str
101):
102 """
103 Clone a repo to dest_dir, and checkout to commit `commit_hash`.
104
105 Returns:
106 - path to the newly cloned directory.
107 """
108 cloned_dir = clone_repo(clone_link, dest_dir, cloned_name)
109 checkout_cmd = ["git", "checkout", commit_hash]
110 with cd(cloned_dir):
111 run_command(checkout_cmd)
112 return cloned_dir
113
114
115def repo_clean_changes() -> None:
116 """
117 Reset repo to HEAD. Basically clean active changes and untracked files on top of HEAD.
118
119 A lightweight version of `repo_reset_and_clean_checkout`. This is also used in different scenarios.
120 """
121 reset_cmd = ["git", "reset", "--hard"]
122 clean_cmd = ["git", "clean", "-fd"]
123 run_command(reset_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
124 run_command(clean_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
125
126
127def repo_reset_and_clean_checkout(commit_hash: str) -> None:
128 """
129 Run commands to reset repo to the original commit state.
130 Cleans both the uncommited changes and the untracked files, and submodule changes.
131 Assumption: The current directory is the git repository.
132 """
133 # NOTE: do these before `git reset`. This is because some of the removed files below
134 # may actually be in version control. So even if we deleted such files here, they
135 # will be brought back by `git reset`.
136 # Clean files that might be in .gitignore, but could have been created by previous runs
137 if os.path.exists(".coverage"):
138 os.remove(".coverage")
139 if os.path.exists("tests/.coveragerc"):
140 os.remove("tests/.coveragerc")
141 other_cov_files = glob.glob(".coverage.TSS.*", recursive=True)
142 for f in other_cov_files:
143 os.remove(f)
144
145 reset_cmd = ["git", "reset", "--hard", commit_hash]
146 clean_cmd = ["git", "clean", "-fd"]
147 checkout_cmd = ["git", "checkout", commit_hash]
148 run_command(reset_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
149 run_command(clean_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
150 # need to checkout before submodule init. Otherwise submodule may init to another version
151 run_command(checkout_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
152
153 # this is a fail-safe combo to reset any changes to the submodule: first unbind all submodules
154 # and then make a fresh checkout of them.
155 # Reference: https://stackoverflow.com/questions/10906554/how-do-i-revert-my-changes-to-a-git-submodule
156 submodule_unbind_cmd = ["git", "submodule", "deinit", "-f", "."]
157 submodule_init_cmd = ["git", "submodule", "update", "--init"]
158 run_command(
159 submodule_unbind_cmd,
160 stdout=subprocess.DEVNULL,
161 stderr=subprocess.DEVNULL,
162 )
163 run_command(
164 submodule_init_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
165 )
166
167
168def run_script_in_conda(
169 args: list[str], env_name: str, **kwargs
170) -> subprocess.CompletedProcess:
171 """
172 Run a python command in a given conda environment.
173 """
174 cmd = ["conda", "run", "-n", env_name, "python", *args]
175 return subprocess.run(cmd, **kwargs)
176
177
178def run_string_cmd_in_conda(
179 command: str, env_name: str, **kwargs
180) -> subprocess.CompletedProcess:
181 """
182 Run a complete command in a given conda environment, where the command is a string.
183
184 This is useful when the command to be run contains &&, etc.
185
186 NOTE: use `conda activate` instead of `conda run` in this verison, so that we can
187 run commands that contain `&&`, etc.
188 """
189 conda_bin_path = os.getenv("CONDA_EXE") # for calling conda
190 if conda_bin_path is None:
191 raise RuntimeError("Env variable CONDA_EXE is not set")
192 conda_root_dir = pdirname(pdirname(conda_bin_path))
193 conda_script_path = pjoin(conda_root_dir, "etc", "profile.d", "conda.sh")
194 conda_cmd = f"source {conda_script_path} ; conda activate {env_name} ; {command} ; conda deactivate"
195 log_and_print(f"Running command: {conda_cmd}")
196 return subprocess.run(conda_cmd, shell=True, **kwargs)
197
198
199def create_dir_if_not_exists(dir_path: str):
200 """
201 Create a directory if it does not exist.
202 Args:
203 dir_path (str): Path to the directory.
204 """
205 if not os.path.exists(dir_path):
206 os.makedirs(dir_path)
207
208
209def to_relative_path(file_path: str, project_root: str) -> str:
210 """Convert an absolute path to a path relative to the project root.
211
212 Args:
213 - file_path (str): The absolute path.
214 - project_root (str): Absolute path of the project root dir.
215
216 Returns:
217 The relative path.
218 """
219 if Path(file_path).is_absolute():
220 return str(Path(file_path).relative_to(project_root))
221 else:
222 return file_path
223
224
225def to_absolute_path(file_path: str, project_root: str) -> str:
226 """Convert a relative path to an absolute path.
227
228 Args:
229 - file_path (str): The relative path.
230 - project_root (str): Absolute path of a root dir.
231 """
232 return pjoin(project_root, file_path)
233
234
235def find_file(directory, filename) -> str | None:
236 """
237 Find a file in a directory. filename can be short name, relative path to the
238 directory, or an incomplete relative path to the directory.
239 Returns:
240 - the relative path to the file if found; None otherwise.
241 """
242
243 # Helper method one
244 def find_file_exact_relative(directory, filename) -> str | None:
245 if os.path.isfile(os.path.join(directory, filename)):
246 return filename
247 return None
248
249 # Helper method two
250 def find_file_shortname(directory, filename) -> str | None:
251 for root, dirs, files in os.walk(directory):
252 for file in files:
253 if file == filename:
254 return os.path.relpath(os.path.join(root, file), directory)
255 return None
256
257 # if the filename is exactly the relative path.
258 found = find_file_exact_relative(directory, filename)
259 if found is not None:
260 return found
261
262 # if the filename is a short name without any directory
263 found = find_file_shortname(directory, filename)
264 if found is not None:
265 return found
266
267 # if the filename has some directory, but is not a relative path to
268 # the directory
269 parts = filename.split(os.path.sep)
270 shortname = parts[-1]
271 found = find_file_shortname(directory, shortname)
272 if found is None:
273 # really cannot find this file
274 return None
275 # can find this shortname, but we also need to check whether the intermediate
276 # directories match
277 if filename in found:
278 return found
279 else:
280 return None
281
282
283def parse_function_invocation(
284 invocation_str: str,
285) -> tuple[str, list[str]]:
286 try:
287 tree = ast.parse(invocation_str)
288 expr = tree.body[0]
289 assert isinstance(expr, ast.Expr)
290 call = expr.value
291 assert isinstance(call, ast.Call)
292 func = call.func
293 assert isinstance(func, ast.Name)
294 function_name = func.id
295 raw_arguments = [ast.unparse(arg) for arg in call.args]
296 # clean up spaces or quotes, just in case
297 arguments = [arg.strip().strip("'").strip('"') for arg in raw_arguments]
298
299 try:
300 new_arguments = [ast.literal_eval(x) for x in raw_arguments]
301 if new_arguments != arguments:
302 log_and_print(
303 f"Refactored invocation argument parsing gives different result on "
304 f"{invocation_str!r}: old result is {arguments!r}, new result "
305 f" is {new_arguments!r}",
306 )
307 except Exception as e:
308 log_and_print(
309 f"Refactored invocation argument parsing failed on {invocation_str!r}: {e!s}",
310 )
311 except Exception as e:
312 raise ValueError(f"Invalid function invocation: {invocation_str}") from e
313
314 return function_name, arguments