Public repository: timo / mitch

Reader

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

Cleanup for checkout.py

public

Cleanup for checkout.py
Changeset5c96730c9b63d2119b8e5f41a4bdd811af6f9475
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents9b8402aad90e
Children
Pushlog
by timo via ssh

modified src/mitch/cli/checkout.py +13 −33

@@ -158,21 +158,6 @@
158158
     def restore_changes(self) -> None:
159159
         # Restore local changes after checkout and migration re-application.
160160
         self._run("stash", "pop", "--index")
161
-
162
-
163
-def _migration_up_path(path: Path) -> Path | None:
164
-    if path.name.endswith(".up.sql"):
165
-        return path
166
-    if path.name.endswith(".config.toml"):
167
-        stem = path.name.removesuffix(".config.toml")
168
-        return path.with_name(f"{stem}.up.sql")
169
-    return None
170
-
171
-
172
-def _resolve_repo_path(path: Path, repo_root: Path) -> Path:
173
-    if path.is_absolute():
174
-        return path.resolve()
175
-    return (repo_root / path).resolve()
176161
 
177162
 
178163
 @contextmanager
@@ -257,41 +242,37 @@
257242
     for entry in git_manager.changes(branch):
258243
         match entry:
259244
             case Deleted(path) if path.suffix == '.sql':
260
-                up_deleted.add(repo.by_path(_resolve_repo_path(path, repo_root)))
245
+                up_deleted.add(repo.by_path(path))
261246
             case Deleted(path) if path.suffix == '.toml':
262
-                config_deleted.add(repo.by_path(_resolve_repo_path(path, repo_root)))
247
+                config_deleted.add(repo.by_path(path))
263248
             case Modified(path) if path.suffix == '.sql':
264
-                up_modified.add(repo.by_path(_resolve_repo_path(path, repo_root)))
249
+                up_modified.add(repo.by_path(path))
265250
             case Modified(path) if path.suffix == '.toml':
266
-                config_modified.add(repo.by_path(_resolve_repo_path(path, repo_root)))
251
+                config_modified.add(repo.by_path(path))
267252
             case Renamed(old_path, new_path) if old_path.suffix == '.sql' and new_path.suffix == '.sql':
268
-                old_abs = _resolve_repo_path(old_path, repo_root)
269
-                new_abs = _resolve_repo_path(new_path, repo_root)
270
-                up_deleted.add(repo.by_path(old_abs))
271
-                moved_paths[old_abs] = new_abs
272
-                redeploy_by_path.add(new_abs)
253
+                up_deleted.add(repo.by_path(old_path))
254
+                moved_paths[repo.path / old_path] = repo.path / new_path
255
+                redeploy_by_path.add(repo.path / new_path)
273256
             case Renamed(old_path, new_path) if old_path.suffix == '.toml' and new_path.suffix == '.toml':
274
-                old_abs = _resolve_repo_path(old_path, repo_root)
275
-                new_abs = _resolve_repo_path(new_path, repo_root)
276
-                config_deleted.add(repo.by_path(old_abs))
277
-                moved_paths[old_abs] = new_abs
257
+                config_deleted.add(repo.by_path(old_path))
258
+                moved_paths[repo.path / old_path] = repo.path / new_path
278259
                 # Redeploys should not be triggered here, but by the up script path above.
279260
             # FIXME: Added migrations should only be applied if requested. 
280261
             # For now, we assume all adds are intended to be applied, basically matching the behavior of `mitch up` on new files.
281262
             # But maybe, we should be closer to a `mitch pick` and only apply what the user explicitly wanted to add.
282263
             case Add(path) if path.suffix == '.sql':
283
-                new_paths.add(_resolve_repo_path(path, repo_root))
264
+                new_paths.add(repo.path / path)
284265
             case Add(path) if path.suffix == '.toml':
285266
                 try:
286267
                     # Maybe, we already have a migration with an up script, but no config yet.
287268
                     # If so, we want to make sure to reapply that migration after checkout since the new config may introduce new dependencies or change IDs.
288
-                    config_added.add(repo.by_path(_resolve_repo_path(path.with_suffix('').with_suffix('.up.sql'), repo_root)))
269
+                    config_added.add(repo.by_path(path.with_suffix('').with_suffix('.up.sql')))
289270
                 except MissingMigrationError:
290271
                     pass
291272
             case Copied(_, new_path) if new_path.suffix == '.sql':
292273
                 # Copies are treated as additions on the target branch, 
293274
                 # but we don't need to track them here since they don't cause reverts on the source branch.
294
-                new_paths.add(_resolve_repo_path(new_path, repo_root))
275
+                new_paths.add(repo.path / new_path)
295276
     
296277
     # Revert migrations on the current branch before switching branches.
297278
     with connection_for(database_url) as connection:
@@ -305,8 +286,7 @@
305286
         
306287
         for migration in reverted:
307288
             if not migration in up_deleted:
308
-                old_path = _resolve_repo_path(migration.up_script, repo_root)
309
-                redeploy_by_path.add(moved_paths.get(old_path, old_path))
289
+                redeploy_by_path.add(moved_paths.get(migration.up_script, migration.up_script))
310290
 
311291
 
312292
     # For dirty worktrees, stash only after DB reverts so reverts reflect current local files.

modified src/mitch/repository.py +17 −36

@@ -41,7 +41,18 @@
4141
                 dependencies={ *config.get('dependencies', []) }
4242
             )
4343
             self.migrations.append(migration)
44
-        self.migrations_by_id = WeakValueDictionary({m.id: m for m in self.migrations})
44
+
45
+        # Index migrations by ID
46
+        self.migrations_by_id: WeakValueDictionary[str, Migration] = WeakValueDictionary({m.id: m for m in self.migrations})
47
+        
48
+        # Index migrations by path
49
+        self.migrations_by_path: WeakValueDictionary[Path, Migration] = WeakValueDictionary()
50
+        for migration in self.migrations:
51
+            self.migrations_by_path[migration.up_script] = migration
52
+            if migration.down_script is not None:
53
+                self.migrations_by_path[migration.down_script] = migration
54
+            if migration.config_file is not None:
55
+                self.migrations_by_path[migration.config_file] = migration
4556
 
4657
         # Check for duplicate IDs
4758
         if len(self.migrations_by_id) != len(self.migrations):
@@ -139,43 +150,13 @@
139150
         else:
140151
             migration_path = (self.path / migration_path).resolve()
141152
         
142
-        for migration in self.migrations:
143
-            if migration_path in (migration.up_script, migration.down_script, migration.config_file):
144
-                return migration
145
-        
146
-        raise MissingMigrationError(f"No migration found for path: {migration_path}")
153
+        try:
154
+            return self.migrations_by_path[migration_path]
155
+        except KeyError:
156
+            raise MissingMigrationError(f"No migration found for path: {migration_path}")
147157
 
148158
     def by_paths(self, migration_paths: Iterable[Path | str]) -> Iterable[Migration]:
149
-        # FIXME: This is heavy and should be moved to _load_migrations
150
-        path_to_migration: dict[Path, Migration] = {}
151
-        for migration in self.migrations:
152
-            path_to_migration[migration.up_script] = migration
153
-            if migration.down_script is not None:
154
-                path_to_migration[migration.down_script] = migration
155
-            if migration.config_file is not None:
156
-                path_to_migration[migration.config_file] = migration
157
-
158
-        selected: list[Migration] = []
159
-        selected_ids: set[str] = set()
160
-        missing_paths: list[Path] = []
161
-
162
-        for path in migration_paths:
163
-            resolved = Path(path).resolve()
164
-            migration = path_to_migration.get(resolved)
165
-            if migration is None:
166
-                missing_paths.append(resolved)
167
-                continue
168
-            if migration.id not in selected_ids:
169
-                selected_ids.add(migration.id)
170
-                selected.append(migration)
171
-
172
-        if missing_paths:
173
-            if len(missing_paths) == 1:
174
-                raise MissingMigrationError(f"No migration found for path: {missing_paths[0]}")
175
-            joined = ", ".join(str(path) for path in missing_paths)
176
-            raise MissingMigrationError(f"No migration found for paths: {joined}")
177
-
178
-        yield from selected
159
+        return (self.by_path(path) for path in migration_paths)
179160
 
180161
     def watch_for_changes(self):
181162
         from .watcher import wait_for_changes