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
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user