diff --git a/.githooks/_common.sh b/.githooks/_common.sh index 25365e6a..91ccf385 100644 --- a/.githooks/_common.sh +++ b/.githooks/_common.sh @@ -67,3 +67,64 @@ run_commitlint() { npx --no-install commitlint --edit "${msg_file}" ) } + +resolve_python_cmd() { + # 优先使用 backend 虚拟环境内的 Python,与日常 flask 开发环境一致 + local root_dir="${1}" + local candidates=( + "${root_dir}/backend/.venv/bin/python" + "${root_dir}/backend/.venv/Scripts/python.exe" + "${root_dir}/backend/venv/bin/python" + "${root_dir}/backend/venv/Scripts/python.exe" + ) + local candidate + for candidate in "${candidates[@]}"; do + if [[ -x "${candidate}" ]]; then + echo "${candidate}" + return 0 + fi + done + if command -v python3 >/dev/null 2>&1; then + echo "python3" + return 0 + fi + if command -v python >/dev/null 2>&1; then + echo "python" + return 0 + fi + return 1 +} + +run_migration_heads_check() { + # 调用 scripts/check_migration_heads.py: + # - 校验 Alembic 仅 1 个 head + # - 可选传入本次新增的 migration 路径,校验 down_revision + # 注意:不可被 SKIP_FRONTEND_HOOKS 跳过(见 pre-commit 调用处) + local root_dir="${1}" + local staged_new_migrations="${2:-}" + local python_cmd + local -a check_args=() + + if ! python_cmd="$(resolve_python_cmd "${root_dir}")"; then + echo "[pre-commit] 未找到 Python,无法校验 migration heads。" + echo "[pre-commit] 请先配置 backend 虚拟环境,或确保 python/python3 在 PATH 中。" + return 1 + fi + + echo "[pre-commit] 校验 Alembic migration 链(必须仅 1 个 head)..." + if [[ -n "${staged_new_migrations}" ]]; then + while IFS= read -r migration_file; do + [[ -n "${migration_file}" ]] || continue + check_args+=("${root_dir}/${migration_file}") + done <<< "${staged_new_migrations}" + fi + + if ! "${python_cmd}" "${root_dir}/scripts/check_migration_heads.py" "${check_args[@]}"; then + echo "[pre-commit] migration heads 校验失败,已阻止提交。" + echo "[pre-commit] migration 检查不可通过 SKIP_FRONTEND_HOOKS 跳过;仅可使用 git commit --no-verify" + return 1 + fi + + echo "[pre-commit] migration heads 校验通过。" + return 0 +} diff --git a/.githooks/pre-commit b/.githooks/pre-commit index c5f14568..6b00ace3 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -32,6 +32,15 @@ if [[ "${MODELS_CHANGED}" -eq 1 && "${MIGRATION_CHANGED}" -eq 0 ]]; then exit 1 fi +# migration 链校验:防止多人并行 migration 合并后出现多 head,部署时 db upgrade 失败 +# 实现见 scripts/check_migration_heads.py(离线读文件,无需数据库) +if [[ "${MIGRATION_CHANGED}" -eq 1 ]]; then + STAGED_NEW_MIGRATIONS="$(git diff --cached --name-only --diff-filter=A -- 'backend/migrations/versions/*.py' || true)" + if ! run_migration_heads_check "${ROOT_DIR}" "${STAGED_NEW_MIGRATIONS}"; then + exit 1 + fi +fi + if hook_should_skip; then exit 0 fi diff --git a/Jenkinsfile b/Jenkinsfile index dd602000..a9bdd551 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -76,7 +76,7 @@ def buildDeployNotifyMarkdown(Map opts) { lines << '> **备注**: 远端版本漂移触发部署' } if (env.ROLLBACK_IMAGE_TAG?.trim()) { - lines << "> **备注**: 镜像回滚 → \`${env.ROLLBACK_IMAGE_TAG.trim()}\`(预构建模式,跳过 db upgrade)" + lines << "> **备注**: 镜像回滚 → `${env.ROLLBACK_IMAGE_TAG.trim()}`(预构建模式,跳过 db upgrade)" } if (extraNote) { lines << "> **说明**: ${extraNote}" diff --git a/backend/migrations/versions/5569936e6e0b_merge_migration_heads.py b/backend/migrations/versions/5569936e6e0b_merge_migration_heads.py new file mode 100644 index 00000000..c35a9b01 --- /dev/null +++ b/backend/migrations/versions/5569936e6e0b_merge_migration_heads.py @@ -0,0 +1,24 @@ +"""merge migration heads + +Revision ID: 5569936e6e0b +Revises: e8f9a0b1c2d3, f6f91cb46944 +Create Date: 2026-06-09 10:49:07.242822 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '5569936e6e0b' +down_revision = ('e8f9a0b1c2d3', 'f6f91cb46944') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/docs/GIT_HOOKS.md b/docs/GIT_HOOKS.md index 84f0d671..226e6763 100644 --- a/docs/GIT_HOOKS.md +++ b/docs/GIT_HOOKS.md @@ -14,7 +14,7 @@ | 层级 | 时机 | 谁生效 | 检查内容 | |------|------|--------|----------| -| **pre-commit** | `git commit` | 已安装 Hook 的本机 | models 须带 migration;暂存 `frontend/` 时跑 `vue-tsc` | +| **pre-commit** | `git commit` | 已安装 Hook 的本机 | models 须带 migration;migration 须单 head;暂存 `frontend/` 时跑 `vue-tsc` | | **commit-msg** | `git commit` | 已安装 Hook 的本机 | 提交信息须符合 [COMMIT_CONVENTION](./convention/COMMIT_CONVENTION.md)(commitlint) | | **pre-push** | `git push` | 已安装 Hook 的本机 | 本次推送含 `frontend/` 变更时跑 `npm run build` | | **Jenkins CI** | push 触发流水线 | 全员(不装 Hook 也跑) | `npm ci && npm run build`(`scripts/ci_frontend_build.sh`) | @@ -72,7 +72,7 @@ chmod +x scripts/install_git_hooks.sh ```text [hook-install] Installed Git hooks successfully. -[hook-install] pre-commit: models 变更需带 migration;frontend 暂存时跑 vue-tsc +[hook-install] pre-commit: models 变更需带 migration;migration 须单 head;frontend 暂存时跑 vue-tsc [hook-install] commit-msg: 校验提交信息格式(Conventional Commits) [hook-install] pre-push: 推送含 frontend 变更时跑 npm run build [hook-install] core.hooksPath=.githooks @@ -132,9 +132,12 @@ npm install | 条件 | 行为 | |------|------| | 暂存了 `backend/app/models.py`,但未暂存 `backend/migrations/versions/*.py` | **拒绝 commit** | +| 暂存了 `backend/migrations/versions/*.py` | 运行 `scripts/check_migration_heads.py`:Alembic **必须仅 1 个 head**;新增 migration 的 `down_revision` 须指向已存在的 revision | | 暂存路径含 `frontend/` | 运行 `npx vue-tsc -b`(需已有 `node_modules`) | | 未暂存 `frontend/` | 不跑前端检查 | +多 head 时 hook 会提示执行 `flask --app manage.py db merge heads` 后再提交。 + `SKIP_FRONTEND_HOOKS` **不能**跳过 models/migration 检查,也**不能**跳过 commit-msg 校验。 ### 5.2 commit-msg @@ -243,6 +246,7 @@ git push --no-verify | `package.json` | 根目录 tooling 依赖(commitlint) | | `scripts/install_git_hooks.sh` | 一键安装 | | `scripts/ci_frontend_build.sh` | Jenkins / 本地 CI 同款 build | +| `scripts/check_migration_heads.py` | 离线校验 Alembic 仅 1 个 head(pre-commit 调用) | | `Jenkinsfile` | `Frontend Build (CI)` 阶段 | | `docs/新人环境搭建与配置文档.md` | 新人环境 §4.2 简要说明 | diff --git a/scripts/check_migration_heads.py b/scripts/check_migration_heads.py new file mode 100644 index 00000000..ebe9317d --- /dev/null +++ b/scripts/check_migration_heads.py @@ -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)) diff --git a/scripts/install_git_hooks.sh b/scripts/install_git_hooks.sh index 083f352d..18195d87 100755 --- a/scripts/install_git_hooks.sh +++ b/scripts/install_git_hooks.sh @@ -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)"