Public repository: timo / mitch

Reader

A migration stitcher (therefore mitch) for PostgreSQL, SQLite, MariaDB, and others

Allow to stash changes

public

Allow to stash changes
Changeset2556a8877f11b75d614e41de115a33ac58376f24
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents894282415ec8
Children
Pushlog
by timo via ssh

modified src/mitch/cli/checkout.py +116 −2

@@ -1,6 +1,6 @@
11
 from collections import defaultdict
22
 from pathlib import Path
3
-from typing import Annotated, Literal, NamedTuple
3
+from typing import Annotated, Literal, NamedTuple, Protocol
44
 import subprocess
55
 
66
 import typer
@@ -17,12 +17,25 @@
1717
 
1818
 
1919
 class DiffEntry(NamedTuple):
20
+    # source_path is the current-branch path; target_path is the post-checkout path.
2021
     kind: Literal["added", "modified", "deleted", "type_changed", "renamed", "copied"]
2122
     source_path: Path | None
2223
     target_path: Path | None
2324
 
2425
 
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
+
2537
 def _run_git(root: Path, *args: str) -> str:
38
+    # Run a git command in the repository and convert git failures into CLI exits.
2639
     result = subprocess.run(
2740
         ["git", *args],
2841
         cwd=root,
@@ -37,7 +50,71 @@
3750
     return result.stdout
3851
 
3952
 
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
+
40109
 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)
41118
     entries: list[DiffEntry] = []
42119
 
43120
     for line in diff_output.splitlines():
@@ -57,10 +134,13 @@
57134
             case ("T", [path]):
58135
                 entries.append(DiffEntry("type_changed", Path(path), Path(path)))
59136
             case (token, [old_path, new_path]) if token.startswith("R"):
137
+                # The numeric suffix indicates similarity: higher means less content changed.
60138
                 entries.append(DiffEntry("renamed", Path(old_path), Path(new_path)))
61139
             case (token, [old_path, new_path]) if token.startswith("C"):
140
+                # Copy scores use the same similarity convention as rename scores.
62141
                 entries.append(DiffEntry("copied", Path(old_path), Path(new_path)))
63142
             case _:
143
+                # Ignore unexpected records to keep checkout robust across git versions.
64144
                 continue
65145
 
66146
     return entries
@@ -70,6 +150,7 @@
70150
     repo: Repository,
71151
     entry: DiffEntry,
72152
 ) -> Migration | None:
153
+    # Resolve a diff entry to the migration as known on the current branch.
73154
     if entry.source_path is None:
74155
         return None
75156
 
@@ -77,7 +158,8 @@
77158
     try:
78159
         return repo.by_path(current_path)
79160
     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.
81163
         if entry.kind == "added" and entry.source_path.name.endswith(".config.toml"):
82164
             up_path = entry.source_path.with_suffix("").with_suffix(".up.sql")
83165
             try:
@@ -110,10 +192,21 @@
110192
             help="Database URL. Can also be set via MITCH_DATABASE_URL or DATABASE_URL environment variable.",
111193
         ),
112194
     ] = 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,
113202
 ) -> None:
114203
     """Checkout a branch while reverting/deploying migrations as needed."""
115204
     repo = Repository(root)
116205
 
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.
117210
     diff_output = _run_git(
118211
         repo.path,
119212
         "diff",
@@ -127,8 +220,12 @@
127220
 
128221
     missing_ids: set[str] = set()
129222
     changed_ids: set[str] = set()
223
+    # Track where each changed migration will live on the target branch.
130224
     changed_target_paths_by_migration_id: dict[str, set[Path]] = defaultdict(set)
131225
 
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
132229
     for entry in _parse_diff_entries(diff_output):
133230
         migration = _migration_from_current_entry(repo, entry)
134231
         if migration is None:
@@ -146,8 +243,10 @@
146243
         if entry.target_path is not None:
147244
             changed_target_paths_by_migration_id[migration.id].add(entry.target_path)
148245
 
246
+    # Revert all affected migrations (and dependants) before checkout to keep DB consistent.
149247
     ids_to_revert = missing_ids | changed_ids
150248
     reverted_ids: set[str] = set()
249
+    # Keep target-branch paths for changed deployed migrations to re-resolve after checkout.
151250
     changed_deployed_target_paths: set[Path] = set()
152251
     migrations_to_revert = list(repo.by_ids_with_dependants(ids_to_revert))
153252
 
@@ -155,6 +254,7 @@
155254
         with connection_for(database_url) as connection:
156255
             runner = Runner(connection)
157256
 
257
+            # Capture only deployed migrations; pending ones do not need reapply work.
158258
             for migration in migrations_to_revert:
159259
                 status = runner.deployment_status(migration)
160260
                 if status not in ("applied", "modified"):
@@ -163,6 +263,7 @@
163263
                 if migration.id in changed_ids:
164264
                     changed_deployed_target_paths |= changed_target_paths_by_migration_id[migration.id]
165265
 
266
+            # Execute reverts in dependency-safe order before branch checkout.
166267
             runner.revert_migrations(
167268
                 migrations_to_revert,
168269
                 before_each=lambda migration, status: rich.print(
@@ -170,11 +271,19 @@
170271
                 ),
171272
             )
172273
 
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.
173280
     _run_git(repo.path, "checkout", branch)
174281
 
282
+    # Reload repository state from the target branch and identify migrations to reapply.
175283
     repo_after = Repository(root)
176284
     reapply_ids = {migration_id for migration_id in reverted_ids if migration_id in repo_after}
177285
 
286
+    # Re-resolve changed migrations by their target-side paths (handles renames and moves).
178287
     for target_relative_path in changed_deployed_target_paths:
179288
         target_path = repo_after.path / target_relative_path
180289
         if not target_path.exists():
@@ -185,6 +294,7 @@
185294
             continue
186295
         reapply_ids.add(migration.id)
187296
 
297
+    # Reapply required migrations on the target branch, including dependencies.
188298
     if reapply_ids:
189299
         with connection_for(database_url) as connection:
190300
             runner = Runner(connection)
@@ -195,3 +305,7 @@
195305
                     f"[green]Deploying:[/green] Migration '{migration.id}' ({status})"
196306
                 ),
197307
             )
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)

modified tests/test_cli.py +158 −0

@@ -577,3 +577,161 @@
577577
         ).fetchall()
578578
 
579579
     assert [row[0] for row in rows] == ["001-renamed"]
580
+
581
+
582
+def test_checkout_refuses_dirty_worktree_before_db_reverts(tmp_path):
583
+    repo_path = tmp_path / "repo"
584
+    repo_path.mkdir()
585
+    _init_git_repo(repo_path)
586
+    base_branch = _run_git(repo_path, "branch", "--show-current")
587
+
588
+    (repo_path / "README.md").write_text("base\n", encoding="utf-8")
589
+    (repo_path / "001-init.up.sql").write_text(
590
+        "CREATE TABLE table_one (id int);",
591
+        encoding="utf-8",
592
+    )
593
+    (repo_path / "001-init.down.sql").write_text(
594
+        "DROP TABLE table_one;",
595
+        encoding="utf-8",
596
+    )
597
+    _run_git(repo_path, "add", ".")
598
+    _run_git(repo_path, "commit", "-m", "base")
599
+
600
+    db_path = tmp_path / "test.db"
601
+    database_url = f"sqlite:///{db_path}"
602
+
603
+    up_result = runner.invoke(
604
+        app,
605
+        [
606
+            "up",
607
+            "--repository",
608
+            str(repo_path),
609
+            "--database",
610
+            database_url,
611
+            "--if-modified",
612
+            "ignore",
613
+        ],
614
+    )
615
+    assert up_result.exit_code == 0
616
+
617
+    _run_git(repo_path, "checkout", "-b", "target")
618
+    _run_git(repo_path, "rm", "001-init.up.sql", "001-init.down.sql")
619
+    _run_git(repo_path, "commit", "-m", "remove migration")
620
+    _run_git(repo_path, "checkout", base_branch)
621
+
622
+    # Dirty tracked file to force checkout refusal before any DB operations.
623
+    (repo_path / "README.md").write_text("dirty\n", encoding="utf-8")
624
+
625
+    checkout_result = runner.invoke(
626
+        app,
627
+        [
628
+            "checkout",
629
+            "target",
630
+            "--repository",
631
+            str(repo_path),
632
+            "--database",
633
+            database_url,
634
+        ],
635
+    )
636
+    assert checkout_result.exit_code == 1
637
+    assert "Working tree is not clean" in checkout_result.output
638
+
639
+    branch = _run_git(repo_path, "branch", "--show-current")
640
+    assert branch == base_branch
641
+
642
+    with sqlite3.connect(db_path) as connection:
643
+        rows = connection.execute(
644
+            "SELECT id FROM mitch_migrations ORDER BY id",
645
+        ).fetchall()
646
+        table = connection.execute(
647
+            "SELECT name FROM sqlite_schema WHERE type='table' AND name='table_one'",
648
+        ).fetchone()
649
+
650
+    assert [row[0] for row in rows] == ["001-init"]
651
+    assert table is not None
652
+
653
+
654
+def test_checkout_allow_dirty_reverts_using_local_migration_files(tmp_path):
655
+    repo_path = tmp_path / "repo"
656
+    repo_path.mkdir()
657
+    _init_git_repo(repo_path)
658
+    base_branch = _run_git(repo_path, "branch", "--show-current")
659
+
660
+    (repo_path / "001-init.up.sql").write_text(
661
+        "CREATE TABLE table_one (id int);",
662
+        encoding="utf-8",
663
+    )
664
+    (repo_path / "001-init.down.sql").write_text(
665
+        "DROP TABLE table_one;",
666
+        encoding="utf-8",
667
+    )
668
+    _run_git(repo_path, "add", ".")
669
+    _run_git(repo_path, "commit", "-m", "base migration")
670
+
671
+    db_path = tmp_path / "test.db"
672
+    database_url = f"sqlite:///{db_path}"
673
+
674
+    up_result = runner.invoke(
675
+        app,
676
+        [
677
+            "up",
678
+            "--repository",
679
+            str(repo_path),
680
+            "--database",
681
+            database_url,
682
+            "--if-modified",
683
+            "ignore",
684
+        ],
685
+    )
686
+    assert up_result.exit_code == 0
687
+
688
+    _run_git(repo_path, "checkout", "-b", "target")
689
+    (repo_path / "001-init.up.sql").write_text(
690
+        "CREATE TABLE table_one (id int, name text);",
691
+        encoding="utf-8",
692
+    )
693
+    _run_git(repo_path, "add", ".")
694
+    _run_git(repo_path, "commit", "-m", "changed migration on target")
695
+    _run_git(repo_path, "checkout", base_branch)
696
+
697
+    # Dirty local down-script change should be used for the pre-checkout revert.
698
+    (repo_path / "001-init.down.sql").write_text(
699
+        "DROP TABLE table_one;\nCREATE TABLE dirty_marker (id int);",
700
+        encoding="utf-8",
701
+    )
702
+
703
+    checkout_result = runner.invoke(
704
+        app,
705
+        [
706
+            "checkout",
707
+            "target",
708
+            "--repository",
709
+            str(repo_path),
710
+            "--database",
711
+            database_url,
712
+            "--allow-dirty",
713
+        ],
714
+    )
715
+    assert checkout_result.exit_code == 0
716
+
717
+    branch = _run_git(repo_path, "branch", "--show-current")
718
+    assert branch == "target"
719
+
720
+    # Stash pop restored local dirty change on top of target branch.
721
+    down_script = (repo_path / "001-init.down.sql").read_text(encoding="utf-8")
722
+    assert "dirty_marker" in down_script
723
+
724
+    with sqlite3.connect(db_path) as connection:
725
+        applied_ids = connection.execute(
726
+            "SELECT id FROM mitch_migrations ORDER BY id",
727
+        ).fetchall()
728
+        table_columns = connection.execute(
729
+            "PRAGMA table_info(table_one)",
730
+        ).fetchall()
731
+        marker_table = connection.execute(
732
+            "SELECT name FROM sqlite_schema WHERE type='table' AND name='dirty_marker'",
733
+        ).fetchone()
734
+
735
+    assert [row[0] for row in applied_ids] == ["001-init"]
736
+    assert any(column[1] == "name" for column in table_columns)
737
+    assert marker_table is not None