| @@ -1,6 +1,6 @@ |
| 1 | 1 | from collections import defaultdict |
| 2 | 2 | from pathlib import Path |
| 3 | | -from typing import Annotated, Literal, NamedTuple |
| 3 | +from typing import Annotated, Literal, NamedTuple, Protocol |
| 4 | 4 | import subprocess |
| 5 | 5 | |
| 6 | 6 | import typer |
| @@ -17,12 +17,25 @@ |
| 17 | 17 | |
| 18 | 18 | |
| 19 | 19 | class DiffEntry(NamedTuple): |
| 20 | + # source_path is the current-branch path; target_path is the post-checkout path. |
| 20 | 21 | kind: Literal["added", "modified", "deleted", "type_changed", "renamed", "copied"] |
| 21 | 22 | source_path: Path | None |
| 22 | 23 | target_path: Path | None |
| 23 | 24 | |
| 24 | 25 | |
| 26 | +class VersionControlManager(Protocol): |
| 27 | + def _run(self, *args: str) -> str: ... |
| 28 | + def _fail(self, result: subprocess.CompletedProcess): ... |
| 29 | + def is_dirty(self) -> bool: ... |
| 30 | + def can_checkout(self, branch: str, allow_dirty: bool) -> bool: ... |
| 31 | + def stash_changes(self, message: str) -> None: ... |
| 32 | + def restore_changes(self) -> None: ... |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + |
| 25 | 37 | def _run_git(root: Path, *args: str) -> str: |
| 38 | + # Run a git command in the repository and convert git failures into CLI exits. |
| 26 | 39 | result = subprocess.run( |
| 27 | 40 | ["git", *args], |
| 28 | 41 | cwd=root, |
| @@ -37,7 +50,71 @@ |
| 37 | 50 | return result.stdout |
| 38 | 51 | |
| 39 | 52 | |
| 53 | +def _ensure_checkout_preconditions(root: Path, branch: str, allow_dirty: bool) -> bool: |
| 54 | + # Validate that the target resolves to a commit before planning any DB changes. |
| 55 | + result = subprocess.run( |
| 56 | + ["git", "rev-parse", "--verify", f"{branch}^{{commit}}"], |
| 57 | + cwd=root, |
| 58 | + capture_output=True, |
| 59 | + text=True, |
| 60 | + check=False, |
| 61 | + ) |
| 62 | + if result.returncode != 0: |
| 63 | + message = result.stderr.strip() or result.stdout.strip() or "Unknown git error" |
| 64 | + typer.echo( |
| 65 | + f"Error: Cannot resolve checkout target '{branch}' to a commit: {message}", |
| 66 | + err=True, |
| 67 | + ) |
| 68 | + raise typer.Exit(1) |
| 69 | + |
| 70 | + # Check whether the worktree is dirty before starting destructive DB operations. |
| 71 | + status = subprocess.run( |
| 72 | + ["git", "status", "--porcelain", "--untracked-files=all"], |
| 73 | + cwd=root, |
| 74 | + capture_output=True, |
| 75 | + text=True, |
| 76 | + check=False, |
| 77 | + ) |
| 78 | + if status.returncode != 0: |
| 79 | + message = status.stderr.strip() or status.stdout.strip() or "Unknown git error" |
| 80 | + typer.echo(f"Error: git status failed: {message}", err=True) |
| 81 | + raise typer.Exit(1) |
| 82 | + is_dirty = bool(status.stdout.strip()) |
| 83 | + if is_dirty and not allow_dirty: |
| 84 | + typer.echo( |
| 85 | + "Error: Working tree is not clean. Commit, stash, or discard local changes before checkout.", |
| 86 | + err=True, |
| 87 | + ) |
| 88 | + raise typer.Exit(1) |
| 89 | + return is_dirty |
| 90 | + |
| 91 | + |
| 92 | +def _stash_worktree(root: Path, branch: str) -> None: |
| 93 | + # Stash local changes after DB reverts so reverts use current on-disk migration files. |
| 94 | + _run_git( |
| 95 | + root, |
| 96 | + "stash", |
| 97 | + "push", |
| 98 | + "--include-untracked", |
| 99 | + "--message", |
| 100 | + f"mitch checkout {branch}", |
| 101 | + ) |
| 102 | + |
| 103 | + |
| 104 | +def _pop_stash(root: Path) -> None: |
| 105 | + # Restore local changes after checkout and migration re-application. |
| 106 | + _run_git(root, "stash", "pop", "--index") |
| 107 | + |
| 108 | + |
| 40 | 109 | def _parse_diff_entries(diff_output: str) -> list[DiffEntry]: |
| 110 | + # Parse `git diff --name-status` output into a structured representation. |
| 111 | + # Expected records are tab-separated and look like: |
| 112 | + # - A\tpath |
| 113 | + # - M\tpath |
| 114 | + # - D\tpath |
| 115 | + # - T\tpath |
| 116 | + # - R100\told_path\tnew_path (rename score is git's similarity percentage) |
| 117 | + # - C100\told_path\tnew_path (copy score is git's similarity percentage) |
| 41 | 118 | entries: list[DiffEntry] = [] |
| 42 | 119 | |
| 43 | 120 | for line in diff_output.splitlines(): |
| @@ -57,10 +134,13 @@ |
| 57 | 134 | case ("T", [path]): |
| 58 | 135 | entries.append(DiffEntry("type_changed", Path(path), Path(path))) |
| 59 | 136 | case (token, [old_path, new_path]) if token.startswith("R"): |
| 137 | + # The numeric suffix indicates similarity: higher means less content changed. |
| 60 | 138 | entries.append(DiffEntry("renamed", Path(old_path), Path(new_path))) |
| 61 | 139 | case (token, [old_path, new_path]) if token.startswith("C"): |
| 140 | + # Copy scores use the same similarity convention as rename scores. |
| 62 | 141 | entries.append(DiffEntry("copied", Path(old_path), Path(new_path))) |
| 63 | 142 | case _: |
| 143 | + # Ignore unexpected records to keep checkout robust across git versions. |
| 64 | 144 | continue |
| 65 | 145 | |
| 66 | 146 | return entries |
| @@ -70,6 +150,7 @@ |
| 70 | 150 | repo: Repository, |
| 71 | 151 | entry: DiffEntry, |
| 72 | 152 | ) -> Migration | None: |
| 153 | + # Resolve a diff entry to the migration as known on the current branch. |
| 73 | 154 | if entry.source_path is None: |
| 74 | 155 | return None |
| 75 | 156 | |
| @@ -77,7 +158,8 @@ |
| 77 | 158 | try: |
| 78 | 159 | return repo.by_path(current_path) |
| 79 | 160 | except MissingMigrationError: |
| 80 | | - # Added config files won't exist on the current branch. Resolve through the paired up-script. |
| 161 | + # Added config files do not exist yet on the current branch. |
| 162 | + # Resolve through the paired up-script path so config-only additions are still tracked. |
| 81 | 163 | if entry.kind == "added" and entry.source_path.name.endswith(".config.toml"): |
| 82 | 164 | up_path = entry.source_path.with_suffix("").with_suffix(".up.sql") |
| 83 | 165 | try: |
| @@ -110,10 +192,21 @@ |
| 110 | 192 | help="Database URL. Can also be set via MITCH_DATABASE_URL or DATABASE_URL environment variable.", |
| 111 | 193 | ), |
| 112 | 194 | ] = None, |
| 195 | + allow_dirty: Annotated[ |
| 196 | + bool, |
| 197 | + typer.Option( |
| 198 | + "--allow-dirty", |
| 199 | + help="Allow local changes by stashing them during checkout and restoring them afterwards.", |
| 200 | + ), |
| 201 | + ] = False, |
| 113 | 202 | ) -> None: |
| 114 | 203 | """Checkout a branch while reverting/deploying migrations as needed.""" |
| 115 | 204 | repo = Repository(root) |
| 116 | 205 | |
| 206 | + # Ensure branch checkout is feasible before touching the database state. |
| 207 | + worktree_dirty = _ensure_checkout_preconditions(repo.path, branch, allow_dirty) |
| 208 | + |
| 209 | + # Diff migration-relevant files between current branch and target branch. |
| 117 | 210 | diff_output = _run_git( |
| 118 | 211 | repo.path, |
| 119 | 212 | "diff", |
| @@ -127,8 +220,12 @@ |
| 127 | 220 | |
| 128 | 221 | missing_ids: set[str] = set() |
| 129 | 222 | changed_ids: set[str] = set() |
| 223 | + # Track where each changed migration will live on the target branch. |
| 130 | 224 | changed_target_paths_by_migration_id: dict[str, set[Path]] = defaultdict(set) |
| 131 | 225 | |
| 226 | + # Classify migrations affected by the branch switch: |
| 227 | + # - missing_ids: up-script disappears on target branch |
| 228 | + # - changed_ids: up/config content or path differs and should be redeployed |
| 132 | 229 | for entry in _parse_diff_entries(diff_output): |
| 133 | 230 | migration = _migration_from_current_entry(repo, entry) |
| 134 | 231 | if migration is None: |
| @@ -146,8 +243,10 @@ |
| 146 | 243 | if entry.target_path is not None: |
| 147 | 244 | changed_target_paths_by_migration_id[migration.id].add(entry.target_path) |
| 148 | 245 | |
| 246 | + # Revert all affected migrations (and dependants) before checkout to keep DB consistent. |
| 149 | 247 | ids_to_revert = missing_ids | changed_ids |
| 150 | 248 | reverted_ids: set[str] = set() |
| 249 | + # Keep target-branch paths for changed deployed migrations to re-resolve after checkout. |
| 151 | 250 | changed_deployed_target_paths: set[Path] = set() |
| 152 | 251 | migrations_to_revert = list(repo.by_ids_with_dependants(ids_to_revert)) |
| 153 | 252 | |
| @@ -155,6 +254,7 @@ |
| 155 | 254 | with connection_for(database_url) as connection: |
| 156 | 255 | runner = Runner(connection) |
| 157 | 256 | |
| 257 | + # Capture only deployed migrations; pending ones do not need reapply work. |
| 158 | 258 | for migration in migrations_to_revert: |
| 159 | 259 | status = runner.deployment_status(migration) |
| 160 | 260 | if status not in ("applied", "modified"): |
| @@ -163,6 +263,7 @@ |
| 163 | 263 | if migration.id in changed_ids: |
| 164 | 264 | changed_deployed_target_paths |= changed_target_paths_by_migration_id[migration.id] |
| 165 | 265 | |
| 266 | + # Execute reverts in dependency-safe order before branch checkout. |
| 166 | 267 | runner.revert_migrations( |
| 167 | 268 | migrations_to_revert, |
| 168 | 269 | before_each=lambda migration, status: rich.print( |
| @@ -170,11 +271,19 @@ |
| 170 | 271 | ), |
| 171 | 272 | ) |
| 172 | 273 | |
| 274 | + # For dirty worktrees, stash only after DB reverts so reverts reflect current local files. |
| 275 | + should_pop_stash = allow_dirty and worktree_dirty |
| 276 | + if should_pop_stash: |
| 277 | + _stash_worktree(repo.path, branch) |
| 278 | + |
| 279 | + # Switch working tree to the target branch once pre-checkout DB reverts are complete. |
| 173 | 280 | _run_git(repo.path, "checkout", branch) |
| 174 | 281 | |
| 282 | + # Reload repository state from the target branch and identify migrations to reapply. |
| 175 | 283 | repo_after = Repository(root) |
| 176 | 284 | reapply_ids = {migration_id for migration_id in reverted_ids if migration_id in repo_after} |
| 177 | 285 | |
| 286 | + # Re-resolve changed migrations by their target-side paths (handles renames and moves). |
| 178 | 287 | for target_relative_path in changed_deployed_target_paths: |
| 179 | 288 | target_path = repo_after.path / target_relative_path |
| 180 | 289 | if not target_path.exists(): |
| @@ -185,6 +294,7 @@ |
| 185 | 294 | continue |
| 186 | 295 | reapply_ids.add(migration.id) |
| 187 | 296 | |
| 297 | + # Reapply required migrations on the target branch, including dependencies. |
| 188 | 298 | if reapply_ids: |
| 189 | 299 | with connection_for(database_url) as connection: |
| 190 | 300 | runner = Runner(connection) |
| @@ -195,3 +305,7 @@ |
| 195 | 305 | f"[green]Deploying:[/green] Migration '{migration.id}' ({status})" |
| 196 | 306 | ), |
| 197 | 307 | ) |
| 308 | + |
| 309 | + # Restore local worktree changes after migration state matches the checked-in target branch. |
| 310 | + if should_pop_stash: |
| 311 | + _pop_stash(repo.path) |