创建一个在工作目录时失败的`git pre-recieve hook`并不干净

时间:2016-03-31 10:55:24

标签: git githooks

场合

我的本​​地系统上有一个git存储库的副本,以及远程服务器上的第二个(非裸机)。由于环境的限制,我不得不在两者上使用Git 1.8。

在服务器上,[receive] denyCurrentBranch = ignore中有.git/configgit reset --hard中有.git/hooks/post-receive。这允许我模仿denyCurrentBranch = updateInstead行为。

我试图添加一个pre-receive挂钩,当我没有一个干净的头时会失败。

尝试

在服务器上,如果我运行git status,我有以下内容:

[server test_app]$ git status
# On branch master
nothing to commit, working directory clean

我原本计划在钩子中添加git status,像这样(伪bash):

((git status | grep "On branch master" | wc -l) == 1) && ((git status | grep "nothing to commit, working directory clean" | wc -l) == 1) && (exit 0)
exit 1

为了测试这是否可行,我在钩子中尝试了以下内容

git status
exit 1

结果

当我尝试推动时,我得到以下内容:

Pushing to ssh://.../test_app
remote: # On branch master[K
remote: # Changes not staged for commit:[K
remote: #   (use "git add/rm <file>..." to update what will be committed)[K
remote: #   (use "git checkout -- <file>..." to discard changes in working directory)[K
remote: #[K
remote: #   deleted:    bin/README[K
remote: #[K
remote: # Untracked files:[K
remote: #   (use "git add <file>..." to include in what will be committed)[K
remote: #[K
remote: #   COMMIT_EDITMSG[K
remote: #   HEAD[K
remote: #   ORIG_HEAD[K
remote: #   config[K
remote: #   description[K
remote: #   hooks/[K
remote: #   index[K
remote: #   info/[K
remote: #   logs/[K
remote: #   objects/[K
remote: #   refs/[K
remote: no changes added to commit (use "git add" and/or "git commit -a")[K
remote: I will fail[K
To ssh://.../test_app
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ssh://.../test_app'

结论

我认为这意味着我误解了预接收挂钩中状态git的含义。在我的预接收(或其他)钩子中,如果工作目录不干净,我应该怎么防止更新?

1 个答案:

答案 0 :(得分:0)

感谢http://longair.net/blog/2011/04/09/missing-git-hooks-documentation/reset hard on git push,我发现pre-receive将工作目录和GIT_DIR环境变量设置为.git /文件夹。

因此以下就足够了

git --git-dir=. --work-tree=$PWD/.. status

任何有兴趣的人的整个钩子:

#!/bin/bash

data=`git --git-dir=. --work-tree=$PWD/.. status`
val=`echo $data | grep "working directory clean" | wc -l`

if [ $val -eq 1 ]
then
  echo "All good"
  exit 0
else
  echo "I will fail"
  echo $data
  exit 1
fi