Git钩子脚本失败但脚本在终端运行正常

时间:2014-10-21 08:02:53

标签: git shell githooks

这非常令人困惑。

我有一个在裸存储库上运行的git post-update钩子脚本。它的工作是告诉下游(非裸)git repo自我更新(类似于版本化登台服务器的push-to-deploy脚本)。如果我从终端运行脚本,它工作正常。但是当它在推送后由git运行时,我得到一个错误,即git路径是错误的。

我在Ubuntu 14.04 + git 1.91和Mac git 1.9.3(Apple Git-50)上试过这个

我显然做错了什么但我对git hooks知之甚少,看不到从哪里开始。

以下是脚本:

#!/bin/sh

staging_path="/tmp/git/copy"
staging_repo="$staging_path/.git"
staging_branch=$(git  --git-dir=$staging_repo rev-parse --abbrev-ref HEAD)
upstream_branch=$(git rev-parse --abbrev-ref HEAD)

if [ "$staging_branch" != "master" ] 
then
    echo "Staging site is not on master. Cannot initiate pull."
    exit 0
fi

if [ "$upstream_branch" != "master" ] 
then
    echo "Main repo is not on master -- not sure why that would be. Cannot initiate pull."
    exit 0
fi

git -C $staging_path fetch --all
echo "git status after fetch --all:"
echo $(git -C $staging_path status)
git -C $staging_path reset --hard origin/master
echo ""
echo "git status after reset --hard:"
echo $(git -C $staging_path status)

这是我推动后发生的事情:

$ git push origin master
Counting objects: 5, done.
Writing objects: 100% (3/3), 272 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: fatal: Not a git repository: '.'
remote: git status after fetch --all:
remote: fatal: Not a git repository: '.'
remote: 
remote: fatal: Not a git repository: '.'
remote: 
remote: git status after reset --hard:
remote: fatal: Not a git repository: '.'
remote: 
To /tmp/git/origin/original.git
   8eef13d..96c9847  master -> master

但是当我手动运行时,我看到它正常完成:

$ ./post-update
Fetching origin
remote: Counting objects: 8, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 6 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (6/6), done.
From /tmp/git/origin/original
   4e92291..96c9847  master     -> origin/master
git status after fetch --all:
On branch master Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded. (use "git pull" to update your local branch) nothing to commit, working directory clean
HEAD is now at 96c9847 seven

git status after reset --hard:
On branch master Your branch is up-to-date with 'origin/master'. nothing to commit, working directory clean

修改 我已经注销了shell变量的值,只是为了确保它们给出了我的想法。这些值是:

remote: $staging_path: /tmp/git/copy
remote: $staging_repo: /tmp/git/copy/.git
remote: $staging_branch: master
remote: $upstream_branch: master

1 个答案:

答案 0 :(得分:3)

我总是更喜欢,取消设置GIT_DIRGIT_WORK_TREE环境变量,以便提供git(通过--git-dir--work-tree或{{3我希望在钩子中使用的确切路径。

这些变量可以由Git设置,因为Git事件触发了一个钩子,而不是在shell会话中手动启动相同的钩子。