分类:Git| 发布时间:2014-05-05 23:43:44
钩子主要用于在执行一个Git命令之前或者之后执行特定的脚本
大多数的Git hooks主要分为以下两类:
git clone或者git fetch不会复制hooks
通过在.git/hooks/目录下放置特定脚本(有可执行权限)来实现, 比如要安装一个git commit执行的钩子可以通过添加文件.git/hooks/pre-commit来实现。
$ mkdir hooktest
$ cd hooktest/
$ git init
Initialized empty Git repository in /tmp/hooktest/.git/
$ touch a b c
$ git add a b c
$ git commit -m"added a, b, and c"
[master (root-commit) 0103a5f] added a, b, and c
0 files changed
create mode 100644 a
create mode 100644 b
create mode 100644 c
$ vim .git/hooks/pre-commit
$ cat .git/hooks/pre-commit
#!/bin/bash
echo "Hello, I'm a pre-commit script!" >&2
if git diff --cached | grep '^\+' | grep -q 'broken'; then
echo "ERROR: Can't commit the world 'broken'" >&2
exit 1 # reject
fi
exit 0 # accept
$ ll .git/hooks/pre-commit
-rwxr-xr-x 1 cjl Administ 209 Feb 9 23:02 .git/hooks/pre-commit
$ chmod a+x .git/hooks/pre-commit
$ echo "perfectly fine" > a
$ echo "broken" > b
$ git commit -m"test commit -a" -a
Hello, I'm a pre-commit script!
ERROR: Can't commit the world 'broken'
$ git commit -m"test commit -a" a
Hello, I'm a pre-commit script!
[master 1417a71] test commit -a
1 file changed, 1 insertion(+)
$ git commit -m"test commit -a" b
Hello, I'm a pre-commit script!
ERROR: Can't commit the world 'broken'
可以通过git help hooks查看有哪些可用的钩子