1515from collections .abc import Iterator
1616from contextlib import contextmanager
1717from pathlib import Path
18+ from typing import cast
1819
20+ from alembic import command
1921from alembic .config import Config
2022
2123import agent_control_server
22- from alembic import command
2324
2425
25- @contextmanager
26- def _bundled_config () -> Iterator [Config ]:
26+ def _bundled_config () -> Config :
2727 pkg_dir = Path (agent_control_server .__file__ ).parent
2828 ini_path = pkg_dir / "_alembic.ini"
2929 alembic_dir = pkg_dir / "_alembic"
@@ -33,13 +33,27 @@ def _bundled_config() -> Iterator[Config]:
3333 f"{ ini_path } and { alembic_dir } . The installed wheel is missing "
3434 "migration assets."
3535 )
36+ cfg = Config (str (ini_path ))
37+ cfg .set_main_option ("script_location" , str (alembic_dir ).replace ("%" , "%%" ))
38+ return cfg
39+
40+
41+ @contextmanager
42+ def _runtime_bundled_config () -> Iterator [Config ]:
43+ cfg = _bundled_config ()
44+ if not isinstance (cfg , Config ):
45+ yield cast (Config , cfg )
46+ return
47+
48+ bundled_script_location = cfg .get_main_option ("script_location" )
49+ if bundled_script_location is None :
50+ raise RuntimeError ("Bundled Alembic script_location is not configured." )
51+
3652 with tempfile .TemporaryDirectory (prefix = "agent-control-alembic-" ) as tmp :
3753 script_location = Path (tmp ) / "_alembic"
38- shutil .copytree (alembic_dir , script_location )
54+ shutil .copytree (bundled_script_location , script_location )
3955 for injected_init in (script_location / "versions" ).rglob ("__init__.py" ):
4056 injected_init .unlink ()
41-
42- cfg = Config (str (ini_path ))
4357 cfg .set_main_option ("script_location" , str (script_location ).replace ("%" , "%%" ))
4458 yield cfg
4559
@@ -89,7 +103,7 @@ def main(argv: list[str] | None = None) -> int:
89103 _configure_logging ()
90104
91105 try :
92- with _bundled_config () as cfg :
106+ with _runtime_bundled_config () as cfg :
93107 if parsed .command == "upgrade" :
94108 command .upgrade (cfg , parsed .revision , sql = parsed .sql )
95109 elif parsed .command == "downgrade" :
0 commit comments