# shellcheck shell=bash # 供 pre-commit / pre-push 引用;勿直接执行。 hook_should_skip() { [[ "${SKIP_GIT_HOOKS:-}" == "1" ]] || [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]] } frontend_paths_in() { local file_list="${1:-}" echo "${file_list}" | grep -qE '^frontend/' } ensure_frontend_deps() { local frontend_dir="${1}/frontend" if [[ ! -d "${frontend_dir}/node_modules" ]]; then echo "[git-hook] frontend/node_modules 不存在,请先执行:" echo " cd frontend && npm install" return 1 fi return 0 } run_frontend_typecheck() { local root_dir="${1}" echo "[pre-commit] 检测到 frontend/ 变更,运行 vue-tsc 类型检查..." if ! ensure_frontend_deps "${root_dir}"; then return 1 fi ( cd "${root_dir}/frontend" npx vue-tsc -b --pretty false ) } run_frontend_build() { local root_dir="${1}" echo "[pre-push] 检测到将要推送的提交包含 frontend/ 变更,运行 npm run build..." if ! ensure_frontend_deps "${root_dir}"; then return 1 fi ( cd "${root_dir}/frontend" npm run build ) } ensure_commitlint_deps() { local root_dir="${1}" if [[ ! -d "${root_dir}/node_modules/@commitlint/cli" ]]; then echo "[commit-msg] 根目录 node_modules 不存在,请先执行:" echo " cd ${root_dir}" echo " npm install" echo " 或重新运行: ./scripts/install_git_hooks.sh" return 1 fi return 0 } run_commitlint() { local root_dir="${1}" local msg_file="${2}" if ! ensure_commitlint_deps "${root_dir}"; then return 1 fi ( cd "${root_dir}" 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 }