|
9 | 9 | from functools import cache |
10 | 10 | from io import StringIO |
11 | 11 | from pathlib import Path |
12 | | -from typing import TYPE_CHECKING |
| 12 | +from typing import TYPE_CHECKING, Optional |
13 | 13 |
|
14 | 14 | import git |
15 | 15 | from rich.prompt import Confirm |
16 | 16 | from unidiff import PatchSet |
17 | 17 |
|
18 | 18 | from codeflash.cli_cmds.console import logger |
| 19 | +from codeflash.code_utils.compat import codeflash_cache_dir |
19 | 20 | from codeflash.code_utils.config_consts import N_CANDIDATES |
20 | 21 |
|
21 | 22 | if TYPE_CHECKING: |
@@ -192,3 +193,80 @@ def get_last_commit_author_if_pr_exists(repo: Repo | None = None) -> str | None: |
192 | 193 | return None |
193 | 194 | else: |
194 | 195 | return last_commit.author.name |
| 196 | + |
| 197 | + |
| 198 | +worktree_dirs = codeflash_cache_dir / "worktrees" |
| 199 | +patches_dir = codeflash_cache_dir / "patches" |
| 200 | + |
| 201 | + |
| 202 | +def create_worktree_snapshot_commit(worktree_dir: Path, commit_message: str) -> None: |
| 203 | + repository = git.Repo(worktree_dir, search_parent_directories=True) |
| 204 | + repository.git.commit("-am", commit_message, "--no-verify") |
| 205 | + |
| 206 | + |
| 207 | +def create_detached_worktree(module_root: Path) -> Optional[Path]: |
| 208 | + if not check_running_in_git_repo(module_root): |
| 209 | + logger.warning("Module is not in a git repository. Skipping worktree creation.") |
| 210 | + return None |
| 211 | + git_root = git_root_dir() |
| 212 | + current_time_str = time.strftime("%Y%m%d-%H%M%S") |
| 213 | + worktree_dir = worktree_dirs / f"{git_root.name}-{current_time_str}" |
| 214 | + |
| 215 | + repository = git.Repo(git_root, search_parent_directories=True) |
| 216 | + |
| 217 | + repository.git.worktree("add", "-d", str(worktree_dir)) |
| 218 | + |
| 219 | + # Get uncommitted diff from the original repo |
| 220 | + repository.git.add("-N", ".") # add the index for untracked files to be included in the diff |
| 221 | + uni_diff_text = repository.git.diff(None, "HEAD", ignore_blank_lines=True, ignore_space_at_eol=True) |
| 222 | + |
| 223 | + if not uni_diff_text.strip(): |
| 224 | + logger.info("No uncommitted changes to copy to worktree.") |
| 225 | + return worktree_dir |
| 226 | + |
| 227 | + # Write the diff to a temporary file |
| 228 | + with tempfile.NamedTemporaryFile(mode="w", suffix=".codeflash.patch", delete=False) as tmp_patch_file: |
| 229 | + tmp_patch_file.write(uni_diff_text + "\n") # the new line here is a must otherwise the last hunk won't be valid |
| 230 | + tmp_patch_file.flush() |
| 231 | + |
| 232 | + patch_path = Path(tmp_patch_file.name).resolve() |
| 233 | + |
| 234 | + # Apply the patch inside the worktree |
| 235 | + try: |
| 236 | + subprocess.run( |
| 237 | + ["git", "apply", "--ignore-space-change", "--ignore-whitespace", patch_path], |
| 238 | + cwd=worktree_dir, |
| 239 | + check=True, |
| 240 | + ) |
| 241 | + create_worktree_snapshot_commit(worktree_dir, "Initial Snapshot") |
| 242 | + except subprocess.CalledProcessError as e: |
| 243 | + logger.error(f"Failed to apply patch to worktree: {e}") |
| 244 | + |
| 245 | + return worktree_dir |
| 246 | + |
| 247 | + |
| 248 | +def remove_worktree(worktree_dir: Path) -> None: |
| 249 | + try: |
| 250 | + repository = git.Repo(worktree_dir, search_parent_directories=True) |
| 251 | + repository.git.worktree("remove", "--force", worktree_dir) |
| 252 | + except Exception: |
| 253 | + logger.exception(f"Failed to remove worktree: {worktree_dir}") |
| 254 | + |
| 255 | + |
| 256 | +def create_diff_patch_from_worktree(worktree_dir: Path, files: list[str], fto_name: str) -> Path: |
| 257 | + repository = git.Repo(worktree_dir, search_parent_directories=True) |
| 258 | + uni_diff_text = repository.git.diff(None, "HEAD", *files, ignore_blank_lines=True, ignore_space_at_eol=True) |
| 259 | + |
| 260 | + if not uni_diff_text: |
| 261 | + logger.warning("No changes found in worktree.") |
| 262 | + return None |
| 263 | + |
| 264 | + if not uni_diff_text.endswith("\n"): |
| 265 | + uni_diff_text += "\n" |
| 266 | + |
| 267 | + # write to patches_dir |
| 268 | + patches_dir.mkdir(parents=True, exist_ok=True) |
| 269 | + patch_path = patches_dir / f"{worktree_dir.name}.{fto_name}.patch" |
| 270 | + with patch_path.open("w", encoding="utf8") as f: |
| 271 | + f.write(uni_diff_text) |
| 272 | + return patch_path |
0 commit comments