fix(githooks): use git rev-parse --absolute-git-dir for repo root

The $0-based dirname trick didn't work because git invokes
hooks with just the basename (e.g., 'post-receive'), not the
absolute path. Use 'git rev-parse --absolute-git-dir' instead,
which works even when CWD is inside .git/.
This commit is contained in:
2026-06-15 13:07:16 +08:00
parent d3e134d247
commit 3b1ab0fc1b
+9 -14
View File
@@ -19,21 +19,16 @@
# 3) **验**证 PATH —— 写日**志**确认 pnpm 可**用****不**可用则 build **必**失**败** # 3) **验**证 PATH —— 写日**志**确认 pnpm 可**用****不**可用则 build **必**失**败**
# ---- 前置:切到 repo 顶 + 加 pnpm 到 PATH ---- # ---- 前置:切到 repo 顶 + 加 pnpm 到 PATH ----
# 重要:不能**用** `git rev-parse --show-toplevel` 获**** repo **** # 重要:git-receive-pack 调 hook 时 CWD ****能是 `.git/` 内****
# —— git-receive-pack 调 hook 时 CWD ****能是 `.git/` 内**部** # `git rev-parse --show-toplevel` 会****错 `must be run in a work tree`。
# 这种情况下 `--show-toplevel` **报**错 `must be run in a work tree`。 # 解**法****用** `git rev-parse --absolute-git-dir` **取**得**绝**对 .git **路**径,
# ************据 hook ****身路径推**** repo **** # 然后 dirname **得**到 repo ****层。****两个调****在 .git/ 内****也都********。
SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo "")" GIT_DIR_ABS="$(git rev-parse --absolute-git-dir 2>/dev/null || true)"
if [ -z "$SCRIPT_DIR" ]; then if [ -n "$GIT_DIR_ABS" ] && [ "$GIT_DIR_ABS" != ".git" ]; then
# 兜底:**用** git rev-parse(如**果**可**用** REPO_TOPLEVEL="$(cd "$GIT_DIR_ABS/.." && pwd)"
REPO_TOPLEVEL="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [ -z "$REPO_TOPLEVEL" ]; then
# **最**后**兜**底:**直**接**用** PWD
REPO_TOPLEVEL="$PWD"
fi
else else
# .githooks/post-receive 的****目录********目录 = repo **** # 兜底:**用** PWD **非** bare repo 默****************下)
REPO_TOPLEVEL="$(cd "$SCRIPT_DIR/.." && pwd)" REPO_TOPLEVEL="$PWD"
fi 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; }