git hooks探索(2)

2015-12-7 sunsmile 专业

 git commit事件相关的hooks
提交工作流程中相关的hooks主要有pre-commit、prepare-commit-msg、commit-msg、post-commit四种,其执行顺序如下所示,将四个脚本文件修改为可执行状态之后,在每个脚本文件中添加一行输出文件名称的代码“echo "this is hook shell script with name: pre-commit"”,在客户端中提交修改的时将会自动显示出调用的脚本文件顺序。

root@d98fb332a1df:~/git/cli/test-client/test# git commit -am "debug 2nd"
this is hook shell script with name: pre-commit 
this is hook shell script with name: prepare-commit-msg 
this is hook shell script with name: commit-msg 
this is hook shell script with name: post-commit 
[master 0da8f9d] debug 2nd
 1 file changed, 2 insertions(+), 1 deletion(-)
root@d98fb332a1df:~/git/cli/test-client/test# 


从上面的实验输出结果可以看出四个脚本文件的调用顺序为:pre-commit, prepare-commit-msg, commit-msg, post-commit。
其中,pre-commit是在最开始执行的hooks,甚至在你填写提交信息之前就已经执行了,它用来检查提交的信息是否存在问题,同样可以用于检查代码中是否存在问题,或者检查代码风格,例如检查函数体之前的注释内容是否完整。如果此脚本最终以非0退出,那么提交过程就会中断。当然可以使用“git commit --no-verify”跳过pre-commit脚本的执行。

prepare-commit-msg脚本是在打开文本编辑器之前,默认消息创建之后被调用执行的。从而能够实现在提交作者看到默认消息之前能够通过prepare-commit-msg修改内容。此钩子含有一些参数:包含提交信息的文件的路径、提交类型以及如果提交是修复性提交则提交的SHA1的校验码;对于一般提交,此钩子是不会起作用的;但是对于自动生成的默认提交信息,例如默认提交信息模板(template commit messages)、分支合并提交信息(merge commit)、squash commits、修复性提交信息(amend commit)

You may use it in conjunction with a commit template to programmatically insert information.


The commit-msg hook takes one parameter, which again is the path to a
temporary file that contains the commit message written by the developer. If
this script exits non-zero, Git aborts the commit process, so you can use it to
validate your project state or commit message before allowing a commit to go
through. In the last section of this chapter, We’ll demonstrate using this hook to
check that your commit message is conformant to a required pattern.
After the entire commit process is completed, the post-commit hook runs.
It doesn’t take any parameters, but you can easily get the last commit by run-
ning git log -1 HEAD . Generally, this script is used for notification or some-
thing similar.

发表评论:

Powered by emlog 京ICP备15044591号-1