Git钩子Script之客户端`pre-push`

有个童鞋说,老是会忘记当前分支和误推了master,有没有办法防止这种低级错误。好吧,发生这种事,其实是那个repo没有设置服务器钩子脚本,来防止客户端的推送操作(我们用的不是gitlab,没有那种功能,暂时是人为终端控制)。%>_<%,我们要实现童鞋想要的功能,需要使用到 git hook scripts,git hook scripts又分为客户端和服务器端两种:

client side

  • pre-commit
  • prepare-commit-msg
  • commit-msg
  • post-commit
  • post-merge
  • pre-push
    ...

server side

  • pre-receive
  • update
  • post-receive

博客后面的链接【1】可以了解所有的script,这里需要的是叫做pre-push的script。

pre-push

首先,我们把工作目录切到git repo的根目录,然后编写.git/hooks/pre-push文件:

vim .git/hooks/pre-push

文件内容如下:

#!/bin/bash
# Prevents force-pushing to master.
# Based on: https://gist.github.com/pixelhandler/5718585
# Install:
# cd path/to/git/repo
# curl -fL -o .git/hooks/pre-push https://gist.githubusercontent.com/stefansundin/d465f1e331fc5c632088/raw/pre-push
# chmod +x .git/hooks/pre-push

BRANCH=`git rev-parse --abbrev-ref HEAD`
PUSH_COMMAND=`ps -ocommand= -p $PPID`

if [[ "$BRANCH" == "master" && "$PUSH_COMMAND" =~ push|force|delete|-f ]]; then
echo "Prevented force-push to $BRANCH. This is a very dangerous command."
echo "If you really want to do this, use --no-verify to bypass this pre-push hook."
exit 1
fi

exit 0

这段script也很容易理解。

执行结果:

$ chmod u+x .git/hooks/pre-push
$ git push
Prevented force-push to master. This is a very dangerous command.
If you really want to do this, use --no-verify to bypass this pre-push hook.
error: failed to push some refs to 'git@git.xxx.net:user/repo.git'

如上,如果执行git push,我们的echo提示出现了,说明script起作用了。
如果我们想跳过pre-push钩子,可以使用--no-verify参数。
或者把.git/hooks/pre-push改个名字。

参考


【1】https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
【2】https://gist.github.com/stefansundin/d465f1e331fc5c632088

#