@gate-forge/pack-alembic 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +60 -0
- package/dist/compile.d.ts +168 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +623 -0
- package/dist/compile.js.map +1 -0
- package/dist/detector.d.ts +46 -0
- package/dist/detector.d.ts.map +1 -0
- package/dist/detector.js +77 -0
- package/dist/detector.js.map +1 -0
- package/dist/execute.d.ts +75 -0
- package/dist/execute.d.ts.map +1 -0
- package/dist/execute.js +101 -0
- package/dist/execute.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/lineage.d.ts +6 -0
- package/dist/lineage.d.ts.map +1 -0
- package/dist/lineage.js +6 -0
- package/dist/lineage.js.map +1 -0
- package/dist/merge-safety.d.ts +5 -0
- package/dist/merge-safety.d.ts.map +1 -0
- package/dist/merge-safety.js +5 -0
- package/dist/merge-safety.js.map +1 -0
- package/dist/obligations.d.ts +5 -0
- package/dist/obligations.d.ts.map +1 -0
- package/dist/obligations.js +5 -0
- package/dist/obligations.js.map +1 -0
- package/dist/opt-in.d.ts +21 -0
- package/dist/opt-in.d.ts.map +1 -0
- package/dist/opt-in.js +56 -0
- package/dist/opt-in.js.map +1 -0
- package/dist/preservation.d.ts +5 -0
- package/dist/preservation.d.ts.map +1 -0
- package/dist/preservation.js +5 -0
- package/dist/preservation.js.map +1 -0
- package/dist/roundtrip.d.ts +6 -0
- package/dist/roundtrip.d.ts.map +1 -0
- package/dist/roundtrip.js +6 -0
- package/dist/roundtrip.js.map +1 -0
- package/dist/scratch.d.ts +69 -0
- package/dist/scratch.d.ts.map +1 -0
- package/dist/scratch.js +131 -0
- package/dist/scratch.js.map +1 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +43 -0
- package/python/gateforge_alembic_detector/__init__.py +11 -0
- package/python/gateforge_alembic_detector/__main__.py +45 -0
- package/python/gateforge_alembic_detector/runner.py +430 -0
- package/python/gateforge_alembic_detector/scan.py +386 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
"""Engine-owned Alembic roundtrip runner.
|
|
2
|
+
|
|
3
|
+
Connects only to a database whose name starts with ``gf_tmp_``. The
|
|
4
|
+
project's ``env.py`` is never imported. Schema comparison excludes
|
|
5
|
+
``alembic_version``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import traceback
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
from urllib.parse import urlparse
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
SCRATCH_PREFIX = "gf_tmp_"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _fail(cause: str, detail: str) -> dict[str, Any]:
|
|
24
|
+
"""One failed runner result.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
cause (str): Stable cause code.
|
|
28
|
+
detail (str): Single-cause explanation.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
dict[str, Any]: Result with ``ok`` false.
|
|
32
|
+
"""
|
|
33
|
+
return {"ok": False, "cause": cause, "detail": detail}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _database_name(url: str) -> str | None:
|
|
37
|
+
"""Return the database name from a SQLAlchemy or libpq URL.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
url (str): Database URL.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
str | None: The path database name, or None when absent.
|
|
44
|
+
"""
|
|
45
|
+
parsed = urlparse(url.replace("postgresql+psycopg://", "postgresql://", 1).replace("postgresql+psycopg2://", "postgresql://", 1))
|
|
46
|
+
name = parsed.path.lstrip("/")
|
|
47
|
+
return name or None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _assert_scratch(url: str) -> str | None:
|
|
51
|
+
"""Refuse any URL whose database is not a Gateforge scratch database.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
url (str): Candidate migration URL.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
str | None: An error detail, or None when the name is disposable.
|
|
58
|
+
"""
|
|
59
|
+
name = _database_name(url)
|
|
60
|
+
if name is None or not name.startswith(SCRATCH_PREFIX) or name == SCRATCH_PREFIX:
|
|
61
|
+
return f"refusing database URL whose name is not {SCRATCH_PREFIX}<id>"
|
|
62
|
+
if not name.removeprefix(SCRATCH_PREFIX).isalnum():
|
|
63
|
+
return f"refusing database name '{name}'"
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _driver_url(url: str) -> str:
|
|
68
|
+
"""Rewrite a plain postgres URL to an installed SQLAlchemy driver.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
url (str): ``postgresql://`` URL.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
str: A driver-qualified URL.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
RuntimeError: When neither psycopg nor psycopg2 imports.
|
|
78
|
+
"""
|
|
79
|
+
if url.startswith("postgresql+"):
|
|
80
|
+
return url
|
|
81
|
+
if not url.startswith("postgresql://"):
|
|
82
|
+
raise RuntimeError("scratch URL must be a postgresql URL")
|
|
83
|
+
for driver in ("psycopg", "psycopg2"):
|
|
84
|
+
try:
|
|
85
|
+
__import__(driver)
|
|
86
|
+
except ImportError:
|
|
87
|
+
continue
|
|
88
|
+
return url.replace("postgresql://", f"postgresql+{driver}://", 1)
|
|
89
|
+
raise RuntimeError("no postgres driver installed (need psycopg or psycopg2)")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _metadata(module_name: str, attr_path: str) -> Any:
|
|
93
|
+
"""Import the configured metadata object.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
module_name (str): Importable module name.
|
|
97
|
+
attr_path (str): Dotted attribute path, e.g. ``Base.metadata``.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
Any: SQLAlchemy MetaData.
|
|
101
|
+
"""
|
|
102
|
+
module = importlib.import_module(module_name)
|
|
103
|
+
target: Any = module
|
|
104
|
+
for part in attr_path.split("."):
|
|
105
|
+
target = getattr(target, part)
|
|
106
|
+
return target
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _write_env(directory: Path, models_module: str, metadata_attr: str) -> None:
|
|
110
|
+
"""Write an engine-owned env.py that refuses non-scratch URLs.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
directory (Path): Temporary script location.
|
|
114
|
+
models_module (str): Module that owns the metadata.
|
|
115
|
+
metadata_attr (str): Attribute path on that module.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
None: Writes ``env.py``.
|
|
119
|
+
"""
|
|
120
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
121
|
+
script = f"""
|
|
122
|
+
from alembic import context
|
|
123
|
+
from sqlalchemy import engine_from_config, pool
|
|
124
|
+
|
|
125
|
+
config = context.config
|
|
126
|
+
url = config.get_main_option("sqlalchemy.url") or ""
|
|
127
|
+
name = url.rstrip("/").rsplit("/", 1)[-1].split("?")[0]
|
|
128
|
+
if not name.startswith("{SCRATCH_PREFIX}"):
|
|
129
|
+
raise RuntimeError("refusing non-disposable database")
|
|
130
|
+
import importlib
|
|
131
|
+
module = importlib.import_module({models_module!r})
|
|
132
|
+
target = module
|
|
133
|
+
for part in {metadata_attr!r}.split("."):
|
|
134
|
+
target = getattr(target, part)
|
|
135
|
+
target_metadata = target
|
|
136
|
+
|
|
137
|
+
def run_migrations_offline():
|
|
138
|
+
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
|
|
139
|
+
with context.begin_transaction():
|
|
140
|
+
context.run_migrations()
|
|
141
|
+
|
|
142
|
+
def run_migrations_online():
|
|
143
|
+
connectable = engine_from_config(
|
|
144
|
+
config.get_section(config.config_ini_section) or {{}},
|
|
145
|
+
prefix="sqlalchemy.",
|
|
146
|
+
poolclass=pool.NullPool,
|
|
147
|
+
)
|
|
148
|
+
with connectable.connect() as connection:
|
|
149
|
+
context.configure(connection=connection, target_metadata=target_metadata)
|
|
150
|
+
with context.begin_transaction():
|
|
151
|
+
context.run_migrations()
|
|
152
|
+
|
|
153
|
+
if context.is_offline_mode():
|
|
154
|
+
run_migrations_offline()
|
|
155
|
+
else:
|
|
156
|
+
run_migrations_online()
|
|
157
|
+
"""
|
|
158
|
+
(directory / "env.py").write_text(script, encoding="utf-8")
|
|
159
|
+
(directory / "script.py.mako").write_text("", encoding="utf-8")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _config(scratch_url: str, versions_dir: str, models_module: str, metadata_attr: str, python_path: list[str]) -> Any:
|
|
163
|
+
"""Build an Alembic config that never reads the project's env.py.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
scratch_url (str): Disposable database URL.
|
|
167
|
+
versions_dir (str): Absolute versions directory.
|
|
168
|
+
models_module (str): Metadata module.
|
|
169
|
+
metadata_attr (str): Metadata attribute path.
|
|
170
|
+
python_path (list[str]): Extra import roots.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
Any: Alembic Config.
|
|
174
|
+
"""
|
|
175
|
+
from alembic.config import Config
|
|
176
|
+
import tempfile
|
|
177
|
+
|
|
178
|
+
refused = _assert_scratch(scratch_url)
|
|
179
|
+
if refused is not None:
|
|
180
|
+
raise RuntimeError(refused)
|
|
181
|
+
for entry in python_path:
|
|
182
|
+
if entry not in sys.path:
|
|
183
|
+
sys.path.insert(0, entry)
|
|
184
|
+
script_dir = Path(tempfile.mkdtemp(prefix="gf-alembic-env-"))
|
|
185
|
+
_write_env(script_dir, models_module, metadata_attr)
|
|
186
|
+
ini = script_dir / "alembic.ini"
|
|
187
|
+
driver_url = _driver_url(scratch_url)
|
|
188
|
+
ini.write_text(
|
|
189
|
+
"\n".join(
|
|
190
|
+
[
|
|
191
|
+
"[alembic]",
|
|
192
|
+
f"script_location = {script_dir}",
|
|
193
|
+
f"version_locations = {versions_dir}",
|
|
194
|
+
f"sqlalchemy.url = {driver_url}",
|
|
195
|
+
"",
|
|
196
|
+
]
|
|
197
|
+
),
|
|
198
|
+
encoding="utf-8",
|
|
199
|
+
)
|
|
200
|
+
cfg = Config(str(ini), stdout=sys.stderr)
|
|
201
|
+
cfg.set_main_option("script_location", str(script_dir))
|
|
202
|
+
cfg.set_main_option("version_locations", versions_dir)
|
|
203
|
+
cfg.set_main_option("sqlalchemy.url", driver_url)
|
|
204
|
+
return cfg
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _snapshot(url: str) -> dict[str, Any]:
|
|
208
|
+
"""Capture a deterministic public-schema snapshot.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
url (str): Scratch database URL.
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
dict[str, Any]: Tables, columns, constraints, indexes, enums, sequences.
|
|
215
|
+
"""
|
|
216
|
+
from sqlalchemy import create_engine, text
|
|
217
|
+
|
|
218
|
+
refused = _assert_scratch(url)
|
|
219
|
+
if refused is not None:
|
|
220
|
+
raise RuntimeError(refused)
|
|
221
|
+
engine = create_engine(_driver_url(url))
|
|
222
|
+
queries = {
|
|
223
|
+
"tables": """
|
|
224
|
+
SELECT table_name FROM information_schema.tables
|
|
225
|
+
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
|
|
226
|
+
AND table_name <> 'alembic_version'
|
|
227
|
+
ORDER BY table_name
|
|
228
|
+
""",
|
|
229
|
+
"columns": """
|
|
230
|
+
SELECT table_name, column_name, data_type, udt_name, is_nullable,
|
|
231
|
+
coalesce(column_default, ''), coalesce(character_maximum_length, 0),
|
|
232
|
+
coalesce(numeric_precision, 0)
|
|
233
|
+
FROM information_schema.columns
|
|
234
|
+
WHERE table_schema = 'public' AND table_name <> 'alembic_version'
|
|
235
|
+
ORDER BY table_name, ordinal_position
|
|
236
|
+
""",
|
|
237
|
+
"constraints": """
|
|
238
|
+
SELECT rel.relname, con.conname, con.contype::text, pg_get_constraintdef(con.oid)
|
|
239
|
+
FROM pg_constraint con
|
|
240
|
+
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
241
|
+
JOIN pg_namespace nsp ON nsp.oid = rel.relnamespace
|
|
242
|
+
WHERE nsp.nspname = 'public' AND rel.relname <> 'alembic_version'
|
|
243
|
+
ORDER BY rel.relname, con.conname
|
|
244
|
+
""",
|
|
245
|
+
"indexes": """
|
|
246
|
+
SELECT tablename, indexname, indexdef
|
|
247
|
+
FROM pg_indexes
|
|
248
|
+
WHERE schemaname = 'public' AND tablename <> 'alembic_version'
|
|
249
|
+
ORDER BY tablename, indexname
|
|
250
|
+
""",
|
|
251
|
+
"enums": """
|
|
252
|
+
SELECT t.typname, e.enumlabel
|
|
253
|
+
FROM pg_type t
|
|
254
|
+
JOIN pg_enum e ON e.enumtypid = t.oid
|
|
255
|
+
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
256
|
+
WHERE n.nspname = 'public'
|
|
257
|
+
ORDER BY t.typname, e.enumsortorder
|
|
258
|
+
""",
|
|
259
|
+
"sequences": """
|
|
260
|
+
SELECT sequence_name, data_type, start_value, increment
|
|
261
|
+
FROM information_schema.sequences
|
|
262
|
+
WHERE sequence_schema = 'public'
|
|
263
|
+
ORDER BY sequence_name
|
|
264
|
+
""",
|
|
265
|
+
}
|
|
266
|
+
snapshot: dict[str, Any] = {}
|
|
267
|
+
with engine.connect() as connection:
|
|
268
|
+
for key, sql in queries.items():
|
|
269
|
+
rows = connection.execute(text(sql)).fetchall()
|
|
270
|
+
snapshot[key] = [list(row) for row in rows]
|
|
271
|
+
engine.dispose()
|
|
272
|
+
return snapshot
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _ident(name: str) -> str:
|
|
276
|
+
"""Quote a trusted SQL identifier.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
name (str): Table or column name.
|
|
280
|
+
|
|
281
|
+
Returns:
|
|
282
|
+
str: Quoted identifier.
|
|
283
|
+
|
|
284
|
+
Raises:
|
|
285
|
+
RuntimeError: When the name is not a simple identifier.
|
|
286
|
+
"""
|
|
287
|
+
if not name or not name.replace("_", "a").isalnum() or name[0].isdigit():
|
|
288
|
+
raise RuntimeError(f"refusing SQL identifier '{name}'")
|
|
289
|
+
return '"' + name.replace('"', "") + '"'
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _fingerprints(url: str, tables: list[dict[str, Any]]) -> dict[str, Any]:
|
|
293
|
+
"""Count rows and hash declared columns.
|
|
294
|
+
|
|
295
|
+
Args:
|
|
296
|
+
url (str): Scratch database URL.
|
|
297
|
+
tables (list[dict[str, Any]]): Declared tables and columns.
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
dict[str, Any]: Per-table count and column fingerprints.
|
|
301
|
+
"""
|
|
302
|
+
from sqlalchemy import create_engine, text
|
|
303
|
+
|
|
304
|
+
refused = _assert_scratch(url)
|
|
305
|
+
if refused is not None:
|
|
306
|
+
raise RuntimeError(refused)
|
|
307
|
+
engine = create_engine(_driver_url(url))
|
|
308
|
+
result: dict[str, Any] = {}
|
|
309
|
+
with engine.connect() as connection:
|
|
310
|
+
for table in tables:
|
|
311
|
+
name = str(table["name"])
|
|
312
|
+
columns = list(
|
|
313
|
+
dict.fromkeys(
|
|
314
|
+
[
|
|
315
|
+
*(str(column) for column in table["columns"]),
|
|
316
|
+
*(str(copy["to"]) for copy in table.get("copies", [])),
|
|
317
|
+
]
|
|
318
|
+
)
|
|
319
|
+
)
|
|
320
|
+
count = connection.execute(text(f"SELECT count(*) FROM {_ident(name)}")).scalar_one()
|
|
321
|
+
column_hashes: dict[str, str | None] = {}
|
|
322
|
+
existing = {
|
|
323
|
+
row[0]
|
|
324
|
+
for row in connection.execute(
|
|
325
|
+
text(
|
|
326
|
+
"SELECT column_name FROM information_schema.columns "
|
|
327
|
+
"WHERE table_schema = 'public' AND table_name = :table"
|
|
328
|
+
),
|
|
329
|
+
{"table": name},
|
|
330
|
+
)
|
|
331
|
+
}
|
|
332
|
+
for column in columns:
|
|
333
|
+
if column not in existing:
|
|
334
|
+
column_hashes[column] = None
|
|
335
|
+
continue
|
|
336
|
+
digest = connection.execute(
|
|
337
|
+
text(
|
|
338
|
+
f"SELECT md5(coalesce(string_agg({_ident(column)}::text, ',' ORDER BY {_ident(column)}::text), '')) "
|
|
339
|
+
f"FROM {_ident(name)}"
|
|
340
|
+
)
|
|
341
|
+
).scalar_one()
|
|
342
|
+
column_hashes[column] = str(digest)
|
|
343
|
+
result[name] = {"count": int(count), "columns": column_hashes}
|
|
344
|
+
engine.dispose()
|
|
345
|
+
return result
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def run(payload: dict[str, Any]) -> dict[str, Any]:
|
|
349
|
+
"""Run one engine command against a scratch database.
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
payload (dict[str, Any]): Command document from the TypeScript runner.
|
|
353
|
+
|
|
354
|
+
Returns:
|
|
355
|
+
dict[str, Any]: ``ok`` plus snapshots, fingerprints, or a cause.
|
|
356
|
+
"""
|
|
357
|
+
command_name = str(payload.get("command") or "")
|
|
358
|
+
scratch_url = str(payload.get("scratchUrl") or "")
|
|
359
|
+
refused = _assert_scratch(scratch_url)
|
|
360
|
+
if refused is not None:
|
|
361
|
+
return _fail("MIGRATION_SCRATCH_UNSAFE", refused)
|
|
362
|
+
try:
|
|
363
|
+
if command_name == "snapshot":
|
|
364
|
+
return {"ok": True, "snapshot": _snapshot(scratch_url)}
|
|
365
|
+
if command_name == "fingerprint":
|
|
366
|
+
return {"ok": True, "fingerprints": _fingerprints(scratch_url, list(payload.get("tables") or []))}
|
|
367
|
+
if command_name != "alembic":
|
|
368
|
+
return _fail("MIGRATION_ROUNDTRIP_FAILED", f"unknown runner command '{command_name}'")
|
|
369
|
+
from alembic import command
|
|
370
|
+
|
|
371
|
+
cfg = _config(
|
|
372
|
+
scratch_url,
|
|
373
|
+
str(payload["versionsDir"]),
|
|
374
|
+
str(payload["modelsModule"]),
|
|
375
|
+
str(payload.get("metadataAttr") or "Base.metadata"),
|
|
376
|
+
list(payload.get("pythonPath") or []),
|
|
377
|
+
)
|
|
378
|
+
action = str(payload.get("action") or "")
|
|
379
|
+
if action == "upgrade":
|
|
380
|
+
command.upgrade(cfg, str(payload.get("revision") or "head"))
|
|
381
|
+
elif action == "downgrade":
|
|
382
|
+
command.downgrade(cfg, str(payload.get("revision") or "base"))
|
|
383
|
+
elif action == "check":
|
|
384
|
+
command.check(cfg)
|
|
385
|
+
elif action == "sql":
|
|
386
|
+
from sqlalchemy import create_engine, text
|
|
387
|
+
|
|
388
|
+
engine = create_engine(_driver_url(scratch_url))
|
|
389
|
+
with engine.begin() as connection:
|
|
390
|
+
connection.execute(text(str(payload.get("sql") or "")))
|
|
391
|
+
engine.dispose()
|
|
392
|
+
else:
|
|
393
|
+
return _fail("MIGRATION_ROUNDTRIP_FAILED", f"unknown alembic action '{action}'")
|
|
394
|
+
return {"ok": True}
|
|
395
|
+
except Exception as err: # noqa: BLE001 — runner boundary, mapped to a cause
|
|
396
|
+
text_err = f"{type(err).__name__}: {err}"
|
|
397
|
+
cause = "MIGRATION_ROUNDTRIP_FAILED"
|
|
398
|
+
lowered = text_err.lower()
|
|
399
|
+
if "no postgres driver" in lowered or "refusing" in lowered:
|
|
400
|
+
cause = "MIGRATION_SCRATCH_UNSAFE"
|
|
401
|
+
elif "target database is not up to date" in lowered or "new upgrade operations" in lowered:
|
|
402
|
+
cause = "MIGRATION_DRIFT"
|
|
403
|
+
details = [line.strip() for line in text_err.splitlines() if line.strip()]
|
|
404
|
+
return _fail(cause, (details[0] if details else type(err).__name__)[:500])
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def main() -> int:
|
|
408
|
+
"""Read one JSON command from stdin and write one JSON result.
|
|
409
|
+
|
|
410
|
+
Returns:
|
|
411
|
+
int: Process exit code. Always 0 when a JSON result was written.
|
|
412
|
+
"""
|
|
413
|
+
raw = sys.stdin.read()
|
|
414
|
+
try:
|
|
415
|
+
payload = json.loads(raw)
|
|
416
|
+
except json.JSONDecodeError as err:
|
|
417
|
+
json.dump(_fail("MIGRATION_ROUNDTRIP_FAILED", f"runner payload is not JSON: {err}"), sys.stdout)
|
|
418
|
+
return 0
|
|
419
|
+
if not isinstance(payload, dict):
|
|
420
|
+
json.dump(_fail("MIGRATION_ROUNDTRIP_FAILED", "runner payload must be an object"), sys.stdout)
|
|
421
|
+
return 0
|
|
422
|
+
try:
|
|
423
|
+
json.dump(run(payload), sys.stdout)
|
|
424
|
+
except Exception: # noqa: BLE001 — last-resort boundary
|
|
425
|
+
json.dump(_fail("MIGRATION_ROUNDTRIP_FAILED", traceback.format_exc().splitlines()[-1]), sys.stdout)
|
|
426
|
+
return 0
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
if __name__ == "__main__":
|
|
430
|
+
raise SystemExit(main())
|