fix(githooks): cd to worktree root before running build

When git invokes post-receive, cwd is GIT_DIR (not worktree root).
`git rev-parse --show-toplevel` refuses to run from a bare context,
so the script would silently cd into .git/. Use `--absolute-git-dir`
and its parent to find the worktree reliably.

Also: receive.denyCurrentBranch=false means push does NOT auto-update
the worktree, so the hook must do `git reset --hard HEAD` to sync
the source the build will use.
This commit is contained in:
2026-06-16 14:18:25 +08:00
parent fa5678ffdf
commit d5ddb3f97f
+11 -1
View File
@@ -1,15 +1,25 @@
#!/bin/sh
# Post-receive hook: push 后自动 build + start
#
echo "DEBUG: PWD=$PWD GIT_DIR=$GIT_DIR GIT_WORK_TREE=$GIT_WORK_TREE HOME=$HOME USER=$USER" >&2
# 重要:git 调钩子时 cwd=GIT_DIR(不是工作树根),所以必须先把 cwd
# 切到工作树根,下面的所有路径(env-example/、logs/、pnpm)才正确。
# pnpm 环境变量
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
# 关键:git 调钩子时 cwd=GIT_DIR,且`git rev-parse --show-toplevel`会拒返回。
# 用 `git rev-parse --absolute-git-dir` 拿到绝对 git-dir 路径,
# 其父目录就是工作树根。
GIT_DIR_ABS="$(git rev-parse --absolute-git-dir 2>/dev/null)"
if [ -n "$GIT_DIR_ABS" ] && [ -d "$GIT_DIR_ABS" ]; then
REPO_TOPLEVEL="$(cd "$GIT_DIR_ABS/.." && pwd)"
else
REPO_TOPLEVEL="$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")"
fi
cd "$REPO_TOPLEVEL" || { echo "FATAL: cannot cd to $REPO_TOPLEVEL" >&2; exit 1; }
echo "=== REPO_TOPLEVEL=$REPO_TOPLEVEL (GIT_DIR=$GIT_DIR_ABS) ===" >&2
# ============================================================
# 0. sync_worktree —— 将**工**作**树**同步到**新** push 的 HEAD