build(migration): pre-commit拦截migration 多head问题
This commit is contained in:
1 parent
4fa5ab4929
commit
ac67b07107
5 files changed
+263
-3
No files matched your search
@@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Alembic migration 图校验(离线,不连数据库)。
|
||||
|
||||
作用
|
||||
----
|
||||
在 git pre-commit 或 CI 中,扫描 backend/migrations/versions/*.py,
|
||||
确认 Flask-Migrate / Alembic 迁移链处于可部署状态,避免部署时
|
||||
``flask db upgrade`` 因多 head 报错(Multiple head revisions)。
|
||||
|
||||
典型失败场景
|
||||
------------
|
||||
- 两人从同一父 revision 各建一条 migration,合并后未 ``db merge heads``
|
||||
- 新 migration 的 down_revision 写错或指向不存在的 revision
|
||||
|
||||
校验规则
|
||||
--------
|
||||
1. 全仓库 migration 图必须恰好 **1 个 head**(链顶 revision)
|
||||
2. 每个文件的 down_revision 必须能在 versions/ 中找到
|
||||
3. 若命令行传入「本次新增的 migration 文件路径」,额外要求:
|
||||
down_revision 非空,且父 revision 已存在
|
||||
|
||||
用法
|
||||
----
|
||||
::
|
||||
|
||||
# 检查整个仓库(本地或 CI)
|
||||
python scripts/check_migration_heads.py
|
||||
|
||||
# pre-commit:额外传入本次 git add 的新 migration 绝对路径
|
||||
python scripts/check_migration_heads.py /path/to/new_migration.py
|
||||
|
||||
退出码:0 通过,1 失败(stderr 会打印 merge 修复指引)。
|
||||
|
||||
调用方:.githooks/pre-commit → .githooks/_common.sh::run_migration_heads_check
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
VERSIONS_DIR = ROOT / "backend" / "migrations" / "versions"
|
||||
|
||||
|
||||
def _parse_down_revision(raw: str) -> list[str]:
|
||||
"""解析 migration 文件中的 down_revision 赋值(支持 None / 单值 / 元组 merge)。"""
|
||||
raw = raw.strip()
|
||||
if raw in {"None", "null"}:
|
||||
return []
|
||||
if raw.startswith("("):
|
||||
return re.findall(r"""['"]([^'"]+)['"]""", raw)
|
||||
value = raw.strip().strip("'\"")
|
||||
return [value] if value else []
|
||||
|
||||
|
||||
def _load_migration(path: Path) -> tuple[str, list[str]] | None:
|
||||
"""从 migration 源码读取 revision 与 down_revision 列表;无 revision 则返回 None。"""
|
||||
text = path.read_text(encoding="utf-8")
|
||||
revision_match = re.search(r"""^revision\s*=\s*['"]([^'"]+)['"]""", text, re.M)
|
||||
down_match = re.search(r"^down_revision\s*=\s*(.+)$", text, re.M)
|
||||
if not revision_match:
|
||||
return None
|
||||
revision = revision_match.group(1)
|
||||
down_raw = down_match.group(1).strip() if down_match else "None"
|
||||
return revision, _parse_down_revision(down_raw)
|
||||
|
||||
|
||||
def _collect_graph() -> tuple[dict[str, Path], set[str]]:
|
||||
"""
|
||||
遍历 versions/ 构建 revision → 文件 映射,并收集所有被引用的父 revision。
|
||||
|
||||
head 定义:出现在 revisions 中、但从未被任何 down_revision 引用的 revision。
|
||||
"""
|
||||
revisions: dict[str, Path] = {}
|
||||
down_revisions: set[str] = set()
|
||||
duplicates: list[str] = []
|
||||
|
||||
if not VERSIONS_DIR.is_dir():
|
||||
print(f"[migration-check] Missing migrations directory: {VERSIONS_DIR}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
for path in sorted(VERSIONS_DIR.glob("*.py")):
|
||||
parsed = _load_migration(path)
|
||||
if parsed is None:
|
||||
continue
|
||||
revision, downs = parsed
|
||||
if revision in revisions:
|
||||
duplicates.append(revision)
|
||||
revisions[revision] = path
|
||||
down_revisions.update(downs)
|
||||
|
||||
if duplicates:
|
||||
print("[migration-check] Duplicate migration revision id(s):", ", ".join(sorted(set(duplicates))), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
return revisions, down_revisions
|
||||
|
||||
|
||||
def _validate_down_revisions(revisions: dict[str, Path]) -> bool:
|
||||
"""确保每条 migration 的 down_revision 都指向 versions/ 内已存在的 revision。"""
|
||||
ok = True
|
||||
for revision, path in revisions.items():
|
||||
parsed = _load_migration(path)
|
||||
if parsed is None:
|
||||
continue
|
||||
_, downs = parsed
|
||||
for parent in downs:
|
||||
if parent not in revisions:
|
||||
ok = False
|
||||
print(
|
||||
f"[migration-check] {path.name}: down_revision '{parent}' not found in versions/",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return ok
|
||||
|
||||
|
||||
def _validate_new_migrations(new_paths: list[Path], revisions: dict[str, Path]) -> bool:
|
||||
"""
|
||||
针对本次 commit 新增的 migration 做更严格校验。
|
||||
|
||||
新文件必须显式挂在现有链上(down_revision 非空且父节点存在),
|
||||
防止误提交孤立或接错的 migration。
|
||||
"""
|
||||
ok = True
|
||||
for path in new_paths:
|
||||
if not path.is_file():
|
||||
continue
|
||||
parsed = _load_migration(path)
|
||||
if parsed is None:
|
||||
ok = False
|
||||
print(f"[migration-check] {path.name}: missing revision id", file=sys.stderr)
|
||||
continue
|
||||
_, downs = parsed
|
||||
if not downs:
|
||||
ok = False
|
||||
print(f"[migration-check] {path.name}: down_revision is required for new migrations", file=sys.stderr)
|
||||
continue
|
||||
for parent in downs:
|
||||
if parent not in revisions:
|
||||
ok = False
|
||||
print(
|
||||
f"[migration-check] {path.name}: down_revision '{parent}' does not reference an existing migration",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return ok
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
# argv[1:] 为 pre-commit 传入的、本次新增的 migration 绝对路径(可为空)
|
||||
new_files = [Path(p) for p in argv[1:] if p.strip()]
|
||||
|
||||
revisions, down_revisions = _collect_graph()
|
||||
if not revisions:
|
||||
print("[migration-check] No migration revisions found.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if not _validate_down_revisions(revisions):
|
||||
return 1
|
||||
|
||||
if new_files:
|
||||
if not _validate_new_migrations(new_files, revisions):
|
||||
return 1
|
||||
|
||||
# head = 没有被任何 down_revision 指向的 revision;正常仓库应只有一个
|
||||
heads = sorted(revision for revision in revisions if revision not in down_revisions)
|
||||
if len(heads) == 1:
|
||||
print(f"[migration-check] OK: single head {heads[0]}")
|
||||
return 0
|
||||
|
||||
print("[migration-check] Alembic migration graph must have exactly one head.", file=sys.stderr)
|
||||
print(f"[migration-check] Found {len(heads)} head(s):", file=sys.stderr)
|
||||
for head in heads:
|
||||
print(f" - {head} ({revisions[head].name})", file=sys.stderr)
|
||||
print("[migration-check] Fix before commit:", file=sys.stderr)
|
||||
print(" cd backend", file=sys.stderr)
|
||||
print(" flask --app manage.py db merge heads -m \"merge migration heads\"", file=sys.stderr)
|
||||
print(" flask --app manage.py db upgrade", file=sys.stderr)
|
||||
print(" git add backend/migrations/versions/*.py", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv))
|
||||
@@ -38,7 +38,7 @@ if [[ -f "${ROOT_DIR}/package.json" ]]; then
|
||||
fi
|
||||
|
||||
echo "[hook-install] Installed Git hooks successfully."
|
||||
echo "[hook-install] pre-commit: models 变更需带 migration;frontend 暂存时跑 vue-tsc"
|
||||
echo "[hook-install] pre-commit: models 变更需带 migration;migration 须单 head;frontend 暂存时跑 vue-tsc"
|
||||
echo "[hook-install] commit-msg: 校验提交信息格式(Conventional Commits)"
|
||||
echo "[hook-install] pre-push: 推送含 frontend 变更时跑 npm run build"
|
||||
echo "[hook-install] core.hooksPath=$(git -C "${ROOT_DIR}" config --get core.hooksPath)"
|
||||
|
||||
Reference in new issue
Block a user