Public repository: timo / mitch

Reader

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

Add --watch to up command

public

Add --watch to up command
Changeset793dd7b39a95d7bb8ebada878ad1b9dba635af37
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parents6ec595eea9dc
Children
Pushlog
by timo via ssh

modified pyproject.toml +2 −1

@@ -12,7 +12,8 @@
1212
     "sqlalchemy (>=2.0.45,<3.0.0)",
1313
     "more-itertools (>=10.8.0,<11.0.0)",
1414
     "typer (>=0.21.1,<0.22.0)",
15
-    "rich (>=14.2.0,<15.0.0)"
15
+    "rich (>=14.2.0,<15.0.0)",
16
+    "watchdog (>=4.0.0,<6.0.0)"
1617
 ]
1718
 
1819
 [project.scripts]

modified src/mitch/cli/deploy.py +116 −5

@@ -1,7 +1,9 @@
11
 from enum import Enum
2
-from typing import Annotated, Iterable
2
+from typing import Annotated, Iterable, Callable
33
 from pathlib import Path
44
 from contextlib import nullcontext
5
+from threading import Event
6
+from time import monotonic, sleep
57
 import os
68
 
79
 from rich.prompt import Confirm
@@ -31,6 +33,88 @@
3133
         )
3234
         raise typer.Exit(1)
3335
     return resolved_database_url
36
+
37
+
38
+def _is_migration_file(path: Path) -> bool:
39
+    name = path.name
40
+    return (
41
+        name.endswith(".up.sql")
42
+        or name.endswith(".down.sql")
43
+        or name.endswith(".config.toml")
44
+    )
45
+
46
+
47
+def _deploy_all_migrations(
48
+    root: Path,
49
+    database_url: str | None,
50
+    if_modified: IfModifiedOption,
51
+) -> None:
52
+    repo = Repository(root)
53
+    migration_ids = [m.id for m in repo.migrations]
54
+    _deploy_migrations(repo, migration_ids, database_url, if_modified)
55
+
56
+
57
+def _watch_migrations(
58
+    root: Path,
59
+    on_change: Callable[[], None],
60
+    keep_going: bool,
61
+    debounce_seconds: float = 0.5,
62
+) -> None:
63
+    try:
64
+        from watchdog.events import FileSystemEventHandler
65
+        from watchdog.observers import Observer
66
+    except ModuleNotFoundError as exc:
67
+        typer.echo("Error: --watch requires the 'watchdog' package.", err=True)
68
+        raise typer.Exit(1) from exc
69
+
70
+    change_event = Event()
71
+    last_change = 0.0
72
+
73
+    def trigger_change() -> None:
74
+        nonlocal last_change
75
+        last_change = monotonic()
76
+        change_event.set()
77
+
78
+    class MigrationWatchHandler(FileSystemEventHandler):
79
+        def on_any_event(self, event) -> None:
80
+            if event.is_directory:
81
+                return
82
+            if _is_migration_file(Path(event.src_path)):
83
+                trigger_change()
84
+                return
85
+            dest_path = getattr(event, "dest_path", None)
86
+            if dest_path and _is_migration_file(Path(dest_path)):
87
+                trigger_change()
88
+
89
+    handler = MigrationWatchHandler()
90
+    observer = Observer()
91
+    observer.schedule(handler, str(root), recursive=True)
92
+    observer.start()
93
+    rich.print("[blue]Watching for migration changes...[/blue]")
94
+
95
+    try:
96
+        while True:
97
+            change_event.wait()
98
+
99
+            while True:
100
+                change_event.clear()
101
+                sleep(debounce_seconds)
102
+                if monotonic() - last_change >= debounce_seconds:
103
+                    break
104
+
105
+            try:
106
+                on_change()
107
+            except typer.Exit:
108
+                raise
109
+            except Exception as exc:
110
+                rich.print(f"[red]Error:[/red] {exc}")
111
+                if not keep_going:
112
+                    raise
113
+    except KeyboardInterrupt:
114
+        pass
115
+    finally:
116
+        observer.stop()
117
+        observer.join()
34118
 
35119
 
36120
 def _deploy_migrations(
@@ -129,9 +213,36 @@
129213
 def up(
130214
     root: Annotated[Path, typer.Option("--repository", "-r", help="Repository directory.", default_factory=lambda: Path.cwd(), dir_okay=True, file_okay=False, exists=True)],
131215
     database_url: Annotated[str | None, typer.Option("--database", "-d", help="Database connection URL.")] = None,
132
-    if_modified: Annotated[IfModifiedOption, typer.Option("--if-modified", "-m", help="Action to take if a migration has been modified since its last deployment.", case_sensitive=False, show_choices=True)] = IfModifiedOption.PROMPT,
216
+    if_modified: Annotated[
217
+        IfModifiedOption | None,
218
+        typer.Option(
219
+            "--if-modified",
220
+            "-m",
221
+            help="Action to take if a migration has been modified since its last deployment.",
222
+            case_sensitive=False,
223
+            show_choices=True,
224
+            show_default=False,
225
+        ),
226
+    ] = None,
227
+    watch: Annotated[
228
+        bool,
229
+        typer.Option("--watch", help="Watch the repository and re-run deployments on changes."),
230
+    ] = False,
231
+    watch_keep_going: Annotated[
232
+        bool,
233
+        typer.Option("--watch-keep-going", help="Keep watching even if a deployment fails."),
234
+    ] = False,
133235
 ) -> None:
134236
     """Deploy all migrations in the repository."""
135
-    repo = Repository(root)
136
-    migration_ids = [m.id for m in repo.migrations]
137
-    _deploy_migrations(repo, migration_ids, database_url, if_modified)
237
+    resolved_if_modified = (
238
+        if_modified
239
+        if if_modified is not None
240
+        else (IfModifiedOption.REDEPLOY if watch else IfModifiedOption.PROMPT)
241
+    )
242
+    _deploy_all_migrations(root, database_url, resolved_if_modified)
243
+    if watch:
244
+        _watch_migrations(
245
+            root,
246
+            on_change=lambda: _deploy_all_migrations(root, database_url, resolved_if_modified),
247
+            keep_going=watch_keep_going,
248
+        )

modified tests/test_cli.py +53 −0

@@ -5,6 +5,7 @@
55
 from typer.testing import CliRunner
66
 
77
 from mitch.cli import app
8
+from mitch.cli import deploy as deploy_module
89
 
910
 runner = CliRunner()
1011
 
@@ -14,6 +15,14 @@
1415
 
1516
     assert result.exit_code == 0
1617
     assert "Deploy the specified migrations." in result.output
18
+
19
+
20
+def test_up_help_includes_watch_options():
21
+    result = runner.invoke(app, ["up", "--help"])
22
+
23
+    assert result.exit_code == 0
24
+    assert "--watch" in result.output
25
+    assert "--watch-keep-going" in result.output
1726
 
1827
 
1928
 def test_deploy_applies_migration_to_sqlite(tmp_path):
@@ -109,6 +118,50 @@
109118
     assert not (tmp_path / "001-init.config.toml").exists()
110119
 
111120
 
121
+def test_up_watch_applies_new_migration(tmp_path, monkeypatch):
122
+    repo_path = tmp_path / "migrations"
123
+    repo_path.mkdir()
124
+    (repo_path / "001-init.up.sql").write_text(
125
+        "CREATE TABLE some_table (id int);",
126
+        encoding="utf-8",
127
+    )
128
+
129
+    db_path = tmp_path / "test.db"
130
+    database_url = f"sqlite:///{db_path}"
131
+
132
+    def fake_watch(root, on_change, keep_going, debounce_seconds=0.5):
133
+        (repo_path / "002-add.up.sql").write_text(
134
+            "ALTER TABLE some_table ADD COLUMN extra int;",
135
+            encoding="utf-8",
136
+        )
137
+        on_change()
138
+
139
+    monkeypatch.setattr(deploy_module, "_watch_migrations", fake_watch)
140
+
141
+    result = runner.invoke(
142
+        app,
143
+        [
144
+            "up",
145
+            "--watch",
146
+            "--repository",
147
+            str(repo_path),
148
+            "--database",
149
+            database_url,
150
+            "--if-modified",
151
+            "ignore",
152
+        ],
153
+    )
154
+
155
+    assert result.exit_code == 0
156
+
157
+    with sqlite3.connect(db_path) as connection:
158
+        rows = connection.execute(
159
+            "SELECT id FROM mitch_migrations ORDER BY id",
160
+        ).fetchall()
161
+
162
+    assert [row[0] for row in rows] == ["001-init", "002-add"]
163
+
164
+
112165
 def test_up_applies_all_migrations_to_sqlite(tmp_path):
113166
     db_path = tmp_path / "test.db"
114167
     database_url = f"sqlite:///{db_path}"