From d5ddb3f97f79d886d52cd0aea4caa85b230d1676 Mon Sep 17 00:00:00 2001 From: chenhang Date: Tue, 16 Jun 2026 14:18:25 +0800 Subject: [PATCH] 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. --- .githooks/post-receive | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/.githooks/post-receive b/.githooks/post-receive index 61ef1172..7a7f79bf 100755 --- a/.githooks/post-receive +++ b/.githooks/post-receive @@ -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 -REPO_TOPLEVEL="$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")" +# 关键: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