@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,386 @@
|
|
|
1
|
+
"""AST-only Alembic revision scanner.
|
|
2
|
+
|
|
3
|
+
Parses migration scripts with the stdlib ``ast`` module. Never imports
|
|
4
|
+
or executes application code. Discovery output matches the GPP/3 result
|
|
5
|
+
shape: resources, unresolved, findings, classificationSignals, scannedPaths.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from gateforge_alembic_detector import PLUGIN_ID, VERSION
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _normalize_path(rel: str) -> str:
|
|
18
|
+
"""Validate and normalize a repo-root-relative path.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
rel (str): A path from the discover request.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
str: Posix repo-root-relative path.
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
ValueError: Absolute paths, empty paths, and ``..`` escapes.
|
|
28
|
+
"""
|
|
29
|
+
path = rel.replace("\\", "/")
|
|
30
|
+
while path.startswith("./"):
|
|
31
|
+
path = path[2:]
|
|
32
|
+
if path == "" or path.startswith("/") or ".." in path.split("/"):
|
|
33
|
+
raise ValueError(f"target must be a repo-root-relative path, got {rel!r}")
|
|
34
|
+
return path
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _loc(relpath: str, node: ast.AST) -> dict[str, Any]:
|
|
38
|
+
"""Build the canonical location triple for an AST node.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
relpath (str): Repo-root-relative source path.
|
|
42
|
+
node (ast.AST): Node that carries the fact.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
dict[str, Any]: ``file``, 1-based ``line``, 0-based ``col``.
|
|
46
|
+
"""
|
|
47
|
+
line = getattr(node, "lineno", 1) or 1
|
|
48
|
+
col = getattr(node, "col_offset", 0) or 0
|
|
49
|
+
return {"file": relpath, "line": int(line), "col": int(col)}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _string_or_list(node: ast.AST) -> str | list[str] | None:
|
|
53
|
+
"""Read a string literal or a list/tuple of strings.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
node (ast.AST): Expression assigned to a revision field.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
str | list[str] | None: The literal, or None when it is not a string.
|
|
60
|
+
"""
|
|
61
|
+
if isinstance(node, ast.Constant):
|
|
62
|
+
if node.value is None:
|
|
63
|
+
return None
|
|
64
|
+
if isinstance(node.value, str):
|
|
65
|
+
return node.value
|
|
66
|
+
return None
|
|
67
|
+
if isinstance(node, (ast.List, ast.Tuple)):
|
|
68
|
+
items: list[str] = []
|
|
69
|
+
for elt in node.elts:
|
|
70
|
+
if not isinstance(elt, ast.Constant) or not isinstance(elt.value, str):
|
|
71
|
+
return None
|
|
72
|
+
items.append(elt.value)
|
|
73
|
+
return items
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _assigned_name(stmt: ast.stmt) -> tuple[str, ast.AST] | None:
|
|
78
|
+
"""Return ``(name, value)`` for a simple module assignment.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
stmt (ast.stmt): A module-level statement.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
tuple[str, ast.AST] | None: Target name and value, or None.
|
|
85
|
+
"""
|
|
86
|
+
if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name):
|
|
87
|
+
return stmt.targets[0].id, stmt.value
|
|
88
|
+
if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and stmt.value is not None:
|
|
89
|
+
return stmt.target.id, stmt.value
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _is_noop(body: list[ast.stmt]) -> bool:
|
|
94
|
+
"""Whether a function body is only pass, ellipsis, or a docstring.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
body (list[ast.stmt]): Function body statements.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
bool: True when the body performs no operation.
|
|
101
|
+
"""
|
|
102
|
+
if not body:
|
|
103
|
+
return True
|
|
104
|
+
for stmt in body:
|
|
105
|
+
if isinstance(stmt, ast.Pass):
|
|
106
|
+
continue
|
|
107
|
+
if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant):
|
|
108
|
+
if stmt.value.value is Ellipsis or isinstance(stmt.value.value, str):
|
|
109
|
+
continue
|
|
110
|
+
return False
|
|
111
|
+
return True
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _finding(code: str, detail: str, locations: list[dict[str, Any]]) -> dict[str, Any]:
|
|
115
|
+
"""One protocol finding.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
code (str): Stable finding code.
|
|
119
|
+
detail (str): Single-cause explanation.
|
|
120
|
+
locations (list[dict[str, Any]]): At least one location.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
dict[str, Any]: Finding without host-owned fields.
|
|
124
|
+
"""
|
|
125
|
+
return {"code": code, "detail": detail, "locations": locations}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def parse_migration_file(file_path: Path, rel_path: str) -> dict[str, Any] | None:
|
|
129
|
+
"""Parse one migration file into revision facts.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
file_path (Path): Absolute path to the file.
|
|
133
|
+
rel_path (str): Repo-root-relative path.
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
dict[str, Any] | None: Facts, a PARSE_ERROR dict, or None when the
|
|
137
|
+
file is not a revision script.
|
|
138
|
+
"""
|
|
139
|
+
try:
|
|
140
|
+
content = file_path.read_text(encoding="utf-8")
|
|
141
|
+
tree = ast.parse(content, filename=rel_path)
|
|
142
|
+
except (OSError, SyntaxError, UnicodeError) as err:
|
|
143
|
+
return {
|
|
144
|
+
"error": "PARSE_ERROR",
|
|
145
|
+
"detail": f"failed to parse migration file {rel_path}: {err}",
|
|
146
|
+
"relPath": rel_path,
|
|
147
|
+
"location": {"file": rel_path, "line": 1, "col": 0},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
revision: str | None = None
|
|
151
|
+
down_revision: str | list[str] | None = None
|
|
152
|
+
revision_node: ast.AST | None = None
|
|
153
|
+
upgrade_fn: ast.FunctionDef | ast.AsyncFunctionDef | None = None
|
|
154
|
+
downgrade_fn: ast.FunctionDef | ast.AsyncFunctionDef | None = None
|
|
155
|
+
|
|
156
|
+
for stmt in tree.body:
|
|
157
|
+
assigned = _assigned_name(stmt)
|
|
158
|
+
if assigned is not None:
|
|
159
|
+
name, value = assigned
|
|
160
|
+
if name == "revision":
|
|
161
|
+
extracted = _string_or_list(value)
|
|
162
|
+
if isinstance(extracted, str) and extracted != "":
|
|
163
|
+
revision = extracted
|
|
164
|
+
revision_node = stmt
|
|
165
|
+
elif name == "down_revision":
|
|
166
|
+
down_revision = _string_or_list(value)
|
|
167
|
+
elif isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
168
|
+
if stmt.name == "upgrade":
|
|
169
|
+
upgrade_fn = stmt
|
|
170
|
+
elif stmt.name == "downgrade":
|
|
171
|
+
downgrade_fn = stmt
|
|
172
|
+
|
|
173
|
+
if revision is None or revision_node is None:
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
down_revs: list[str] = []
|
|
177
|
+
if isinstance(down_revision, str) and down_revision != "":
|
|
178
|
+
down_revs = [down_revision]
|
|
179
|
+
elif isinstance(down_revision, list):
|
|
180
|
+
down_revs = [item for item in down_revision if item != ""]
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
"revision": revision,
|
|
184
|
+
"downRevisions": down_revs,
|
|
185
|
+
"relPath": rel_path,
|
|
186
|
+
"location": _loc(rel_path, revision_node),
|
|
187
|
+
"upgradeNoop": True if upgrade_fn is None else _is_noop(upgrade_fn.body),
|
|
188
|
+
"downgradeNoop": True if downgrade_fn is None else _is_noop(downgrade_fn.body),
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _safe_name(revision: str) -> str | None:
|
|
193
|
+
"""Resource name that does not break plane.name or id:contract grammar.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
revision (str): Alembic revision id.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
str | None: A name without ``.`` or ``:``, or None when unsafe.
|
|
200
|
+
"""
|
|
201
|
+
if revision == "" or "." in revision or ":" in revision:
|
|
202
|
+
return None
|
|
203
|
+
return revision
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def scan(paths: list[str], root: Path | None = None) -> dict[str, Any]:
|
|
207
|
+
"""Scan paths for Alembic revision scripts and lineage findings.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
paths (list[str]): Repo-root-relative files or directories.
|
|
211
|
+
root (Path | None): Scan root. Defaults to the process cwd.
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
dict[str, Any]: GPP/3 discovery outcome. Arrays are sorted.
|
|
215
|
+
"""
|
|
216
|
+
base_root = (root if root is not None else Path.cwd()).resolve()
|
|
217
|
+
resources: list[dict[str, Any]] = []
|
|
218
|
+
findings: list[dict[str, Any]] = []
|
|
219
|
+
unresolved: list[dict[str, Any]] = []
|
|
220
|
+
scanned: list[str] = []
|
|
221
|
+
migration_files: list[tuple[Path, str]] = []
|
|
222
|
+
|
|
223
|
+
for raw_path in paths:
|
|
224
|
+
try:
|
|
225
|
+
rel = _normalize_path(raw_path)
|
|
226
|
+
except ValueError as err:
|
|
227
|
+
findings.append(
|
|
228
|
+
_finding(
|
|
229
|
+
"PARSE_ERROR",
|
|
230
|
+
str(err),
|
|
231
|
+
[{"file": raw_path.replace("\\", "/") or raw_path, "line": 1, "col": 0}],
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
continue
|
|
235
|
+
candidate = (base_root / rel).resolve()
|
|
236
|
+
try:
|
|
237
|
+
candidate.relative_to(base_root)
|
|
238
|
+
except ValueError:
|
|
239
|
+
findings.append(
|
|
240
|
+
_finding(
|
|
241
|
+
"PARSE_ERROR",
|
|
242
|
+
f"target must be a repo-root-relative path, got {raw_path!r}",
|
|
243
|
+
[{"file": rel, "line": 1, "col": 0}],
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
continue
|
|
247
|
+
if candidate.is_file() and candidate.suffix == ".py":
|
|
248
|
+
migration_files.append((candidate, rel))
|
|
249
|
+
elif candidate.is_dir():
|
|
250
|
+
for path in sorted(candidate.rglob("*.py")):
|
|
251
|
+
if path.name.startswith("__"):
|
|
252
|
+
continue
|
|
253
|
+
rel_file = path.resolve().relative_to(base_root).as_posix()
|
|
254
|
+
migration_files.append((path, rel_file))
|
|
255
|
+
|
|
256
|
+
revisions: dict[str, dict[str, Any]] = {}
|
|
257
|
+
for file_path, rel_path in migration_files:
|
|
258
|
+
scanned.append(rel_path)
|
|
259
|
+
facts = parse_migration_file(file_path, rel_path)
|
|
260
|
+
if facts is None:
|
|
261
|
+
continue
|
|
262
|
+
if "error" in facts:
|
|
263
|
+
findings.append(_finding(str(facts["error"]), str(facts["detail"]), [facts["location"]]))
|
|
264
|
+
continue
|
|
265
|
+
rev = str(facts["revision"])
|
|
266
|
+
if rev in revisions:
|
|
267
|
+
findings.append(
|
|
268
|
+
_finding(
|
|
269
|
+
"DUPLICATE_REVISION_ID",
|
|
270
|
+
f"duplicate revision '{rev}' in {rel_path} and {revisions[rev]['relPath']}",
|
|
271
|
+
[facts["location"], revisions[rev]["location"]],
|
|
272
|
+
)
|
|
273
|
+
)
|
|
274
|
+
continue
|
|
275
|
+
revisions[rev] = facts
|
|
276
|
+
|
|
277
|
+
for rev, facts in revisions.items():
|
|
278
|
+
for parent in facts["downRevisions"]:
|
|
279
|
+
if parent not in revisions:
|
|
280
|
+
findings.append(
|
|
281
|
+
_finding(
|
|
282
|
+
"DANGLING_DOWN_REVISION",
|
|
283
|
+
f"migration '{rev}' in {facts['relPath']} references missing parent '{parent}'",
|
|
284
|
+
[facts["location"]],
|
|
285
|
+
)
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
children: dict[str, list[str]] = {rev: [] for rev in revisions}
|
|
289
|
+
for rev, facts in revisions.items():
|
|
290
|
+
for parent in facts["downRevisions"]:
|
|
291
|
+
if parent in children:
|
|
292
|
+
children[parent].append(rev)
|
|
293
|
+
heads = sorted(rev for rev, kids in children.items() if len(kids) == 0)
|
|
294
|
+
if len(heads) > 1:
|
|
295
|
+
named = ", ".join(f"'{head}' ({revisions[head]['relPath']})" for head in heads)
|
|
296
|
+
findings.append(
|
|
297
|
+
_finding(
|
|
298
|
+
"MULTIPLE_MIGRATION_HEADS",
|
|
299
|
+
f"multiple migration heads: {named}",
|
|
300
|
+
[revisions[head]["location"] for head in heads],
|
|
301
|
+
)
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
for rev in sorted(revisions):
|
|
305
|
+
facts = revisions[rev]
|
|
306
|
+
safe = _safe_name(rev)
|
|
307
|
+
if safe is None:
|
|
308
|
+
unresolved.append(
|
|
309
|
+
{
|
|
310
|
+
"code": "UNSAFE_REVISION_ID",
|
|
311
|
+
"detail": f"revision '{rev}' contains '.' or ':' and cannot be a resource name",
|
|
312
|
+
"location": facts["location"],
|
|
313
|
+
}
|
|
314
|
+
)
|
|
315
|
+
continue
|
|
316
|
+
resources.append(
|
|
317
|
+
{
|
|
318
|
+
"schemaVersion": 1,
|
|
319
|
+
"id": f"alembic-migration-{safe}",
|
|
320
|
+
"kind": "alembic.migration",
|
|
321
|
+
"source": facts["relPath"],
|
|
322
|
+
"location": facts["location"],
|
|
323
|
+
"detectorVersion": VERSION,
|
|
324
|
+
"attributes": {
|
|
325
|
+
"resourceName": safe,
|
|
326
|
+
"revision": rev,
|
|
327
|
+
"downRevisions": facts["downRevisions"],
|
|
328
|
+
"isHead": rev in heads,
|
|
329
|
+
"downgradeNoop": facts["downgradeNoop"],
|
|
330
|
+
"upgradeNoop": facts["upgradeNoop"],
|
|
331
|
+
"detectorId": PLUGIN_ID,
|
|
332
|
+
},
|
|
333
|
+
}
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
if revisions:
|
|
337
|
+
head = heads[0] if len(heads) == 1 else None
|
|
338
|
+
source = revisions[heads[0]]["relPath"] if heads else next(iter(revisions.values()))["relPath"]
|
|
339
|
+
location = revisions[heads[0]]["location"] if heads else next(iter(revisions.values()))["location"]
|
|
340
|
+
resources.append(
|
|
341
|
+
{
|
|
342
|
+
"schemaVersion": 1,
|
|
343
|
+
"id": "alembic-chain-default",
|
|
344
|
+
"kind": "alembic.chain",
|
|
345
|
+
"source": source,
|
|
346
|
+
"location": location,
|
|
347
|
+
"detectorVersion": VERSION,
|
|
348
|
+
"attributes": {
|
|
349
|
+
"resourceName": "alembic-chain",
|
|
350
|
+
"heads": heads,
|
|
351
|
+
"head": head,
|
|
352
|
+
"revisionCount": len(revisions),
|
|
353
|
+
"revisions": sorted(revisions),
|
|
354
|
+
"files": sorted(facts["relPath"] for facts in revisions.values()),
|
|
355
|
+
},
|
|
356
|
+
}
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
resources.sort(key=lambda item: (str(item["kind"]), str(item["id"])))
|
|
360
|
+
findings.sort(key=lambda item: (item["code"], item["detail"], item["locations"][0]["file"]))
|
|
361
|
+
unresolved.sort(key=lambda item: (item["code"], item["location"]["file"], item["detail"]))
|
|
362
|
+
return {
|
|
363
|
+
"resources": resources,
|
|
364
|
+
"unresolved": unresolved,
|
|
365
|
+
"findings": findings,
|
|
366
|
+
"classificationSignals": [],
|
|
367
|
+
"scannedPaths": sorted(set(scanned)),
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def main() -> None:
|
|
372
|
+
"""Print one discovery document for a root and repo-relative paths.
|
|
373
|
+
|
|
374
|
+
Returns:
|
|
375
|
+
None: Writes JSON to stdout. ``sys.argv`` is root, then paths.
|
|
376
|
+
"""
|
|
377
|
+
import json
|
|
378
|
+
import sys
|
|
379
|
+
|
|
380
|
+
root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd()
|
|
381
|
+
paths = sys.argv[2:] if len(sys.argv) > 2 else ["."]
|
|
382
|
+
json.dump(scan(paths, root), sys.stdout)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
if __name__ == "__main__":
|
|
386
|
+
main()
|