| @@ -1,6 +1,7 @@ |
| 1 | 1 | from collections import defaultdict |
| 2 | 2 | from pathlib import Path |
| 3 | | -from typing import Annotated, Literal, NamedTuple, Protocol |
| 3 | +from typing import Annotated, Literal, NamedTuple, Protocol, Generator |
| 4 | +from dataclasses import dataclass |
| 4 | 5 | import subprocess |
| 5 | 6 | |
| 6 | 7 | import typer |
| @@ -23,150 +24,139 @@ |
| 23 | 24 | target_path: Path | None |
| 24 | 25 | |
| 25 | 26 | |
| 26 | | -class VersionControlManager(Protocol): |
| 27 | | - def _run(self, *args: str) -> str: ... |
| 28 | | - def _fail(self, result: subprocess.CompletedProcess): ... |
| 27 | +@dataclass(frozen=True) |
| 28 | +class Add: |
| 29 | + path: Path |
| 30 | + |
| 31 | +@dataclass(frozen=True) |
| 32 | +class Modified: |
| 33 | + path: Path |
| 34 | + |
| 35 | +@dataclass(frozen=True) |
| 36 | +class Deleted: |
| 37 | + path: Path |
| 38 | + |
| 39 | +@dataclass(frozen=True) |
| 40 | +class TypeChanged: |
| 41 | + path: Path |
| 42 | + |
| 43 | +@dataclass(frozen=True) |
| 44 | +class Renamed: |
| 45 | + old_path: Path |
| 46 | + new_path: Path |
| 47 | + |
| 48 | +@dataclass(frozen=True) |
| 49 | +class Copied: |
| 50 | + old_path: Path |
| 51 | + new_path: Path |
| 52 | + |
| 53 | + |
| 54 | +class VersionControlManagerProtocol(Protocol): |
| 55 | + def can_checkout(self, branch: str, allow_dirty: bool) -> bool: ... |
| 29 | 56 | def is_dirty(self) -> bool: ... |
| 30 | | - def can_checkout(self, branch: str, allow_dirty: bool) -> bool: ... |
| 57 | + def changes(self, branch: str) -> Generator[Add | Modified | Deleted | TypeChanged | Renamed | Copied, None, None]: ... |
| 58 | + def checkout(self, branch: str) -> None: ... |
| 31 | 59 | def stash_changes(self, message: str) -> None: ... |
| 32 | 60 | def restore_changes(self) -> None: ... |
| 33 | 61 | |
| 34 | 62 | |
| 35 | | - |
| 36 | | - |
| 37 | | -def _run_git(root: Path, *args: str) -> str: |
| 38 | | - # Run a git command in the repository and convert git failures into CLI exits. |
| 39 | | - result = subprocess.run( |
| 40 | | - ["git", *args], |
| 41 | | - cwd=root, |
| 42 | | - capture_output=True, |
| 43 | | - text=True, |
| 44 | | - check=False, |
| 45 | | - ) |
| 46 | | - if result.returncode != 0: |
| 47 | | - message = result.stderr.strip() or result.stdout.strip() or "Unknown git error" |
| 48 | | - typer.echo(f"Error: git {' '.join(args)} failed: {message}", err=True) |
| 49 | | - raise typer.Exit(1) |
| 50 | | - return result.stdout |
| 51 | | - |
| 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 | | - |
| 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) |
| 118 | | - entries: list[DiffEntry] = [] |
| 119 | | - |
| 120 | | - for line in diff_output.splitlines(): |
| 121 | | - if not line.strip(): |
| 122 | | - continue |
| 123 | | - |
| 124 | | - parts = line.split("\t") |
| 125 | | - status_token, *paths = parts |
| 126 | | - |
| 127 | | - match (status_token, paths): |
| 128 | | - case ("A", [path]): |
| 129 | | - entries.append(DiffEntry("added", Path(path), Path(path))) |
| 130 | | - case ("M", [path]): |
| 131 | | - entries.append(DiffEntry("modified", Path(path), Path(path))) |
| 132 | | - case ("D", [path]): |
| 133 | | - entries.append(DiffEntry("deleted", Path(path), None)) |
| 134 | | - case ("T", [path]): |
| 135 | | - entries.append(DiffEntry("type_changed", Path(path), Path(path))) |
| 136 | | - case (token, [old_path, new_path]) if token.startswith("R"): |
| 137 | | - # The numeric suffix indicates similarity: higher means less content changed. |
| 138 | | - entries.append(DiffEntry("renamed", Path(old_path), Path(new_path))) |
| 139 | | - case (token, [old_path, new_path]) if token.startswith("C"): |
| 140 | | - # Copy scores use the same similarity convention as rename scores. |
| 141 | | - entries.append(DiffEntry("copied", Path(old_path), Path(new_path))) |
| 142 | | - case _: |
| 143 | | - # Ignore unexpected records to keep checkout robust across git versions. |
| 63 | +class GitManager(VersionControlManagerProtocol): |
| 64 | + def __init__(self, root: Path) -> None: |
| 65 | + self.root = root |
| 66 | + |
| 67 | + def _fail_on_git_error(self, result: subprocess.CompletedProcess) -> None: |
| 68 | + if result.returncode != 0: |
| 69 | + message = result.stderr.strip() or result.stdout.strip() or "Unknown git error" |
| 70 | + typer.echo(f"Error: git command failed: {message}", err=True) |
| 71 | + raise typer.Exit(1) |
| 72 | + return result.stdout |
| 73 | + |
| 74 | + def _run(self, *args: str) -> subprocess.CompletedProcess[str]: |
| 75 | + # Run a git command in the repository and convert git failures into CLI exits. |
| 76 | + result = subprocess.run( |
| 77 | + ["git", *args], |
| 78 | + cwd=self.root, |
| 79 | + capture_output=True, |
| 80 | + text=True, |
| 81 | + check=False, |
| 82 | + ) |
| 83 | + self._fail_on_git_error(result) |
| 84 | + return result |
| 85 | + |
| 86 | + def is_dirty(self) -> bool: |
| 87 | + # Check whether the worktree is dirty by looking for any uncommitted changes, including untracked files. |
| 88 | + result = self._run("status", "--porcelain", "--untracked-files=all") |
| 89 | + return bool(result.stdout.strip()) |
| 90 | + |
| 91 | + def can_checkout(self, branch: str, allow_dirty: bool) -> bool: |
| 92 | + # Validate that the target resolves to a commit before planning any DB changes. |
| 93 | + self._run("rev-parse", "--verify", f"{branch}^{{commit}}") |
| 94 | + |
| 95 | + # Check whether the worktree is dirty before starting destructive DB operations. |
| 96 | + is_dirty = bool(self._run( "status", "--porcelain", "--untracked-files=all" ).stdout.strip()) |
| 97 | + |
| 98 | + if is_dirty and not allow_dirty: |
| 99 | + |
| 100 | + typer.echo( |
| 101 | + "Error: Working tree is not clean. Commit, stash, or discard local changes before checkout.", |
| 102 | + err=True, |
| 103 | + ) |
| 104 | + raise typer.Exit(1) |
| 105 | + |
| 106 | + return not is_dirty or allow_dirty |
| 107 | + |
| 108 | + def changes(self, branch: str) -> Generator[Add | Modified | Deleted | TypeChanged | Renamed | Copied, None, None]: |
| 109 | + # Expected records are tab-separated and look like: |
| 110 | + # - A\tpath |
| 111 | + # - M\tpath |
| 112 | + # - D\tpath |
| 113 | + # - T\tpath |
| 114 | + # - R100\told_path\tnew_path (rename score is git's similarity percentage) |
| 115 | + # - C100\told_path\tnew_path (copy score is git's similarity percentage) |
| 116 | + |
| 117 | + diff_output = self._run("diff", "--name-status", "HEAD", branch, "--", "*.up.sql", "*.config.toml").stdout.strip() |
| 118 | + for line in diff_output.splitlines(): |
| 119 | + if not line.strip(): |
| 144 | 120 | continue |
| 145 | | - |
| 146 | | - return entries |
| 147 | | - |
| 148 | | - |
| 149 | | -def _migration_from_current_entry( |
| 150 | | - repo: Repository, |
| 151 | | - entry: DiffEntry, |
| 152 | | -) -> Migration | None: |
| 153 | | - # Resolve a diff entry to the migration as known on the current branch. |
| 154 | | - if entry.source_path is None: |
| 155 | | - return None |
| 156 | | - |
| 157 | | - current_path = repo.path / entry.source_path |
| 158 | | - try: |
| 159 | | - return repo.by_path(current_path) |
| 160 | | - except MissingMigrationError: |
| 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. |
| 163 | | - if entry.kind == "added" and entry.source_path.name.endswith(".config.toml"): |
| 164 | | - up_path = entry.source_path.with_suffix("").with_suffix(".up.sql") |
| 165 | | - try: |
| 166 | | - return repo.by_path(repo.path / up_path) |
| 167 | | - except MissingMigrationError: |
| 168 | | - return None |
| 169 | | - return None |
| 121 | + |
| 122 | + status_token, *paths = line.split("\t") |
| 123 | + match (status_token, paths): |
| 124 | + case ("A", [path]): |
| 125 | + yield Add(Path(path)) |
| 126 | + case ("M", [path]): |
| 127 | + yield Modified(Path(path)) |
| 128 | + case ("T", [path]): |
| 129 | + # Type changes include mode changes (e.g., file to symlink). |
| 130 | + yield Modified(Path(path)) |
| 131 | + case ("D", [path]): |
| 132 | + yield Deleted(Path(path)) |
| 133 | + case (token, [old_path, new_path]) if token.startswith("R"): |
| 134 | + # The numeric suffix indicates similarity: higher means less content changed. |
| 135 | + yield Renamed(Path(old_path), Path(new_path)) |
| 136 | + case (token, [old_path, new_path]) if token.startswith("C"): |
| 137 | + # Copy scores use the same similarity convention as rename scores. |
| 138 | + yield Copied(Path(old_path), Path(new_path)) |
| 139 | + case _: |
| 140 | + # Ignore unexpected records to keep checkout robust across git versions. |
| 141 | + continue |
| 142 | + |
| 143 | + |
| 144 | + def checkout(self, branch: str) -> None: |
| 145 | + self._run("checkout", branch) |
| 146 | + |
| 147 | + def stash_changes(self, message: str) -> None: |
| 148 | + # Stash local changes after DB reverts so reverts use current on-disk migration files. |
| 149 | + self._run( |
| 150 | + "stash", |
| 151 | + "push", |
| 152 | + "--include-untracked", |
| 153 | + "--message", |
| 154 | + message, |
| 155 | + ) |
| 156 | + |
| 157 | + def restore_changes(self) -> None: |
| 158 | + # Restore local changes after checkout and migration re-application. |
| 159 | + self._run("stash", "pop", "--index") |
| 170 | 160 | |
| 171 | 161 | |
| 172 | 162 | @app.command(name="checkout") |
| @@ -202,110 +192,70 @@ |
| 202 | 192 | ) -> None: |
| 203 | 193 | """Checkout a branch while reverting/deploying migrations as needed.""" |
| 204 | 194 | repo = Repository(root) |
| 205 | | - |
| 195 | + git_manager: VersionControlManagerProtocol = GitManager(repo.path) |
| 196 | + |
| 206 | 197 | # 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. |
| 210 | | - diff_output = _run_git( |
| 211 | | - repo.path, |
| 212 | | - "diff", |
| 213 | | - "--name-status", |
| 214 | | - "HEAD", |
| 215 | | - branch, |
| 216 | | - "--", |
| 217 | | - "*.up.sql", |
| 218 | | - "*.config.toml", |
| 219 | | - ) |
| 220 | | - |
| 198 | + git_manager.can_checkout(branch, allow_dirty) |
| 199 | + should_pop_stash = allow_dirty and git_manager.is_dirty() |
| 200 | + |
| 201 | + # Track where each changed migration will live on the target branch. |
| 202 | + moved_up_scripts: set[Path] = set() |
| 221 | 203 | missing_ids: set[str] = set() |
| 222 | 204 | changed_ids: set[str] = set() |
| 223 | | - # Track where each changed migration will live on the target branch. |
| 224 | | - changed_target_paths_by_migration_id: dict[str, set[Path]] = defaultdict(set) |
| 225 | 205 | |
| 226 | 206 | # Classify migrations affected by the branch switch: |
| 227 | 207 | # - missing_ids: up-script disappears on target branch |
| 228 | 208 | # - changed_ids: up/config content or path differs and should be redeployed |
| 229 | | - for entry in _parse_diff_entries(diff_output): |
| 230 | | - migration = _migration_from_current_entry(repo, entry) |
| 231 | | - if migration is None: |
| 232 | | - continue |
| 233 | | - |
| 234 | | - if ( |
| 235 | | - entry.kind == "deleted" |
| 236 | | - and entry.source_path is not None |
| 237 | | - and entry.source_path.name.endswith(".up.sql") |
| 238 | | - ): |
| 239 | | - missing_ids.add(migration.id) |
| 240 | | - continue |
| 241 | | - |
| 242 | | - changed_ids.add(migration.id) |
| 243 | | - if entry.target_path is not None: |
| 244 | | - changed_target_paths_by_migration_id[migration.id].add(entry.target_path) |
| 209 | + for entry in git_manager.changes(branch): |
| 210 | + match entry: |
| 211 | + case Deleted(path) if path.name.endswith(".up.sql"): |
| 212 | + migration = repo.by_path(repo.path / path) |
| 213 | + missing_ids.add(migration.id) |
| 214 | + case Renamed(old_path, new_path) if old_path.name.endswith(".up.sql") and new_path.name.endswith(".up.sql"): |
| 215 | + migration = repo.by_path(repo.path / old_path) |
| 216 | + missing_ids.add(migration.id) |
| 217 | + moved_up_scripts.add(new_path) |
| 218 | + case Modified(path): |
| 219 | + migration = repo.by_path(repo.path / path) |
| 220 | + changed_ids.add(migration.id) |
| 245 | 221 | |
| 246 | 222 | # Revert all affected migrations (and dependants) before checkout to keep DB consistent. |
| 247 | 223 | ids_to_revert = missing_ids | changed_ids |
| 248 | | - reverted_ids: set[str] = set() |
| 249 | | - # Keep target-branch paths for changed deployed migrations to re-resolve after checkout. |
| 250 | | - changed_deployed_target_paths: set[Path] = set() |
| 251 | | - migrations_to_revert = list(repo.by_ids_with_dependants(ids_to_revert)) |
| 252 | | - |
| 253 | | - if migrations_to_revert: |
| 254 | | - with connection_for(database_url) as connection: |
| 255 | | - runner = Runner(connection) |
| 256 | | - |
| 257 | | - # Capture only deployed migrations; pending ones do not need reapply work. |
| 258 | | - for migration in migrations_to_revert: |
| 259 | | - status = runner.deployment_status(migration) |
| 260 | | - if status not in ("applied", "modified"): |
| 261 | | - continue |
| 262 | | - reverted_ids.add(migration.id) |
| 263 | | - if migration.id in changed_ids: |
| 264 | | - changed_deployed_target_paths |= changed_target_paths_by_migration_id[migration.id] |
| 265 | | - |
| 266 | | - # Execute reverts in dependency-safe order before branch checkout. |
| 267 | | - runner.revert_migrations( |
| 268 | | - migrations_to_revert, |
| 269 | | - before_each=lambda migration, status: rich.print( |
| 270 | | - f"[blue]Reverting:[/blue] Migration '{migration.id}' ({status})" |
| 271 | | - ), |
| 272 | | - ) |
| 224 | + |
| 225 | + # Revert migrations on the current branch before switching branches. |
| 226 | + with connection_for(database_url) as connection: |
| 227 | + runner = Runner(connection) |
| 228 | + runner.revert_migrations( |
| 229 | + repo.by_ids_with_dependencies(ids_to_revert), |
| 230 | + before_each=lambda migration, status: rich.print( |
| 231 | + f"[blue]Reverting:[/blue] Migration '{migration.id}' ({status})" |
| 232 | + ), |
| 233 | + ) |
| 273 | 234 | |
| 274 | 235 | # For dirty worktrees, stash only after DB reverts so reverts reflect current local files. |
| 275 | | - should_pop_stash = allow_dirty and worktree_dirty |
| 276 | 236 | if should_pop_stash: |
| 277 | | - _stash_worktree(repo.path, branch) |
| 237 | + git_manager.stash_changes(f"mitch checkout {branch}") |
| 278 | 238 | |
| 279 | 239 | # Switch working tree to the target branch once pre-checkout DB reverts are complete. |
| 280 | | - _run_git(repo.path, "checkout", branch) |
| 240 | + git_manager.checkout(branch) |
| 281 | 241 | |
| 282 | 242 | # Reload repository state from the target branch and identify migrations to reapply. |
| 283 | 243 | repo_after = Repository(root) |
| 284 | | - reapply_ids = {migration_id for migration_id in reverted_ids if migration_id in repo_after} |
| 285 | | - |
| 286 | | - # Re-resolve changed migrations by their target-side paths (handles renames and moves). |
| 287 | | - for target_relative_path in changed_deployed_target_paths: |
| 288 | | - target_path = repo_after.path / target_relative_path |
| 289 | | - if not target_path.exists(): |
| 290 | | - continue |
| 291 | | - try: |
| 292 | | - migration = repo_after.by_path(target_path) |
| 293 | | - except MissingMigrationError: |
| 294 | | - continue |
| 295 | | - reapply_ids.add(migration.id) |
| 296 | | - |
| 244 | + reapply_migrations = { |
| 245 | + *repo_after.by_ids(changed_ids), |
| 246 | + *repo_after.by_paths(repo_after.path.joinpath(up_script) for up_script in moved_up_scripts), |
| 247 | + } |
| 248 | + |
| 297 | 249 | # Reapply required migrations on the target branch, including dependencies. |
| 298 | | - if reapply_ids: |
| 299 | | - with connection_for(database_url) as connection: |
| 300 | | - runner = Runner(connection) |
| 301 | | - due_migrations = list(repo_after.by_ids_with_dependencies(reapply_ids)) |
| 302 | | - runner.deploy_migrations( |
| 303 | | - due_migrations, |
| 304 | | - before_each=lambda migration, status: rich.print( |
| 305 | | - f"[green]Deploying:[/green] Migration '{migration.id}' ({status})" |
| 306 | | - ), |
| 307 | | - ) |
| 250 | + with connection_for(database_url) as connection: |
| 251 | + runner = Runner(connection) |
| 252 | + runner.deploy_migrations( |
| 253 | + repo_after.with_dependencies(reapply_migrations), |
| 254 | + before_each=lambda migration, status: rich.print( |
| 255 | + f"[green]Deploying:[/green] Migration '{migration.id}' ({status})" |
| 256 | + ), |
| 257 | + ) |
| 308 | 258 | |
| 309 | 259 | # Restore local worktree changes after migration state matches the checked-in target branch. |
| 310 | 260 | if should_pop_stash: |
| 311 | | - _pop_stash(repo.path) |
| 261 | + git_manager.restore_changes() |