fix(githooks): derive repo top from $0 path (not --show-toplevel)

git-receive-pack may invoke hook with CWD inside .git/,
where 'git rev-parse --show-toplevel' errors with
'must be run in a work tree'. Use $(dirname $0) instead.
This commit is contained in:
2026-06-15 11:51:49 +08:00
parent 558b3a32af
commit b7e048ed87
+16 -1
View File
@@ -19,7 +19,22 @@
# 3) **验**证 PATH —— 写日**志**确认 pnpm 可**用****不**可用则 build **必**失**败** # 3) **验**证 PATH —— 写日**志**确认 pnpm 可**用****不**可用则 build **必**失**败**
# ---- 前置:切到 repo 顶 + 加 pnpm 到 PATH ---- # ---- 前置:切到 repo 顶 + 加 pnpm 到 PATH ----
REPO_TOPLEVEL="$(git rev-parse --show-toplevel)" # 重要:不能**用** `git rev-parse --show-toplevel` 获**取** repo **顶**层
# —— git-receive-pack 调 hook 时 CWD **可**能是 `.git/` 内**部**
# 这种情况下 `--show-toplevel` **报**错 `must be run in a work tree`。
# 解**法****直**接**根**据 hook **本**身路径推**算** repo **顶**层。
SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo "")"
if [ -z "$SCRIPT_DIR" ]; then
# 兜底:**用** git rev-parse(如**果**可**用**
REPO_TOPLEVEL="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [ -z "$REPO_TOPLEVEL" ]; then
# **最**后**兜**底:**直**接**用** PWD
REPO_TOPLEVEL="$PWD"
fi
else
# .githooks/post-receive 的**父**目录**的****父**目录 = repo **顶**
REPO_TOPLEVEL="$(cd "$SCRIPT_DIR/.." && pwd)"
fi
cd "$REPO_TOPLEVEL" || { echo "FATAL: cannot cd to $REPO_TOPLEVEL" >&2; exit 1; } cd "$REPO_TOPLEVEL" || { echo "FATAL: cannot cd to $REPO_TOPLEVEL" >&2; exit 1; }
# 加**载** nvm**非**交互 shell **不**自动 source .bashrc # 加**载** nvm**非**交互 shell **不**自动 source .bashrc