| 1 | import ast |
| 2 | import contextlib |
| 3 | import glob |
| 4 | import os |
| 5 | import subprocess |
| 6 | from os.path import dirname as pdirname |
| 7 | from os.path import join as pjoin |
| 8 | from pathlib import Path |
| 9 | from subprocess import CalledProcessError |
| 10 | |
| 11 | from app.log import log_and_print |
| 12 | |
| 13 | |
| 14 | @contextlib.contextmanager |
| 15 | def 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 | |
| 29 | def 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 | |
| 43 | def 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 | |
| 51 | def 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 | |
| 63 | def 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 | |
| 73 | def 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 | |
| 84 | def 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 | |
| 99 | def 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 | |
| 115 | def 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 | |
| 127 | def 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, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL |
| 160 | ) |
| 161 | run_command( |
| 162 | submodule_init_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL |
| 163 | ) |
| 164 | |
| 165 | |
| 166 | def run_script_in_conda( |
| 167 | args: list[str], env_name: str, **kwargs |
| 168 | ) -> subprocess.CompletedProcess: |
| 169 | """ |
| 170 | Run a python command in a given conda environment. |
| 171 | """ |
| 172 | cmd = ["conda", "run", "-n", env_name, "python", *args] |
| 173 | return subprocess.run(cmd, **kwargs) |
| 174 | |
| 175 | |
| 176 | def run_string_cmd_in_conda( |
| 177 | command: str, env_name: str, **kwargs |
| 178 | ) -> subprocess.CompletedProcess: |
| 179 | """ |
| 180 | Run a complete command in a given conda environment, where the command is a string. |
| 181 | |
| 182 | This is useful when the command to be run contains &&, etc. |
| 183 | |
| 184 | NOTE: use `conda activate` instead of `conda run` in this verison, so that we can |
| 185 | run commands that contain `&&`, etc. |
| 186 | """ |
| 187 | conda_bin_path = os.getenv("CONDA_EXE") # for calling conda |
| 188 | if conda_bin_path is None: |
| 189 | raise RuntimeError("Env variable CONDA_EXE is not set") |
| 190 | conda_root_dir = pdirname(pdirname(conda_bin_path)) |
| 191 | conda_script_path = pjoin(conda_root_dir, "etc", "profile.d", "conda.sh") |
| 192 | conda_cmd = f"source {conda_script_path} ; conda activate {env_name} ; {command} ; conda deactivate" |
| 193 | log_and_print(f"Running command: {conda_cmd}") |
| 194 | return subprocess.run(conda_cmd, shell=True, **kwargs) |
| 195 | |
| 196 | |
| 197 | def create_dir_if_not_exists(dir_path: str): |
| 198 | """ |
| 199 | Create a directory if it does not exist. |
| 200 | Args: |
| 201 | dir_path (str): Path to the directory. |
| 202 | """ |
| 203 | if not os.path.exists(dir_path): |
| 204 | os.makedirs(dir_path) |
| 205 | |
| 206 | |
| 207 | def to_relative_path(file_path: str, project_root: str) -> str: |
| 208 | """Convert an absolute path to a path relative to the project root. |
| 209 | |
| 210 | Args: |
| 211 | - file_path (str): The absolute path. |
| 212 | - project_root (str): Absolute path of the project root dir. |
| 213 | |
| 214 | Returns: |
| 215 | The relative path. |
| 216 | """ |
| 217 | if Path(file_path).is_absolute(): |
| 218 | return str(Path(file_path).relative_to(project_root)) |
| 219 | else: |
| 220 | return file_path |
| 221 | |
| 222 | |
| 223 | def to_absolute_path(file_path: str, project_root: str) -> str: |
| 224 | """Convert a relative path to an absolute path. |
| 225 | |
| 226 | Args: |
| 227 | - file_path (str): The relative path. |
| 228 | - project_root (str): Absolute path of a root dir. |
| 229 | """ |
| 230 | return pjoin(project_root, file_path) |
| 231 | |
| 232 | |
| 233 | def find_file(directory, filename) -> str | None: |
| 234 | """ |
| 235 | Find a file in a directory. filename can be short name, relative path to the |
| 236 | directory, or an incomplete relative path to the directory. |
| 237 | Returns: |
| 238 | - the relative path to the file if found; None otherwise. |
| 239 | """ |
| 240 | |
| 241 | # Helper method one |
| 242 | def find_file_exact_relative(directory, filename) -> str | None: |
| 243 | if os.path.isfile(os.path.join(directory, filename)): |
| 244 | return filename |
| 245 | return None |
| 246 | |
| 247 | # Helper method two |
| 248 | def find_file_shortname(directory, filename) -> str | None: |
| 249 | for root, dirs, files in os.walk(directory): |
| 250 | for file in files: |
| 251 | if file == filename: |
| 252 | return os.path.relpath(os.path.join(root, file), directory) |
| 253 | return None |
| 254 | |
| 255 | # if the filename is exactly the relative path. |
| 256 | found = find_file_exact_relative(directory, filename) |
| 257 | if found is not None: |
| 258 | return found |
| 259 | |
| 260 | # if the filename is a short name without any directory |
| 261 | found = find_file_shortname(directory, filename) |
| 262 | if found is not None: |
| 263 | return found |
| 264 | |
| 265 | # if the filename has some directory, but is not a relative path to |
| 266 | # the directory |
| 267 | parts = filename.split(os.path.sep) |
| 268 | shortname = parts[-1] |
| 269 | found = find_file_shortname(directory, shortname) |
| 270 | if found is None: |
| 271 | # really cannot find this file |
| 272 | return None |
| 273 | # can find this shortname, but we also need to check whether the intermediate |
| 274 | # directories match |
| 275 | if filename in found: |
| 276 | return found |
| 277 | else: |
| 278 | return None |
| 279 | |
| 280 | |
| 281 | def parse_function_invocation( |
| 282 | invocation_str: str, |
| 283 | ) -> tuple[str, list[str]]: |
| 284 | try: |
| 285 | tree = ast.parse(invocation_str) |
| 286 | expr = tree.body[0] |
| 287 | assert isinstance(expr, ast.Expr) |
| 288 | call = expr.value |
| 289 | assert isinstance(call, ast.Call) |
| 290 | func = call.func |
| 291 | assert isinstance(func, ast.Name) |
| 292 | function_name = func.id |
| 293 | raw_arguments = [ast.unparse(arg) for arg in call.args] |
| 294 | # clean up spaces or quotes, just in case |
| 295 | arguments = [arg.strip().strip("'").strip('"') for arg in raw_arguments] |
| 296 | |
| 297 | try: |
| 298 | new_arguments = [ast.literal_eval(x) for x in raw_arguments] |
| 299 | if new_arguments != arguments: |
| 300 | log_and_print( |
| 301 | f"Refactored invocation argument parsing gives different result on " |
| 302 | f"{invocation_str!r}: old result is {arguments!r}, new result " |
| 303 | f" is {new_arguments!r}" |
| 304 | ) |
| 305 | except Exception as e: |
| 306 | log_and_print( |
| 307 | f"Refactored invocation argument parsing failed on {invocation_str!r}: {e!s}" |
| 308 | ) |
| 309 | except Exception as e: |
| 310 | raise ValueError(f"Invalid function invocation: {invocation_str}") from e |
| 311 | |
| 312 | return function_name, arguments |