我们希望:
当《提交描述信息》不符合 约定式提交规范 的时候,阻止当前的提交,并抛出对应的错误提示
而要实现这个目的,我们就需要先来了解一个概念,叫做 Git hooks(git 钩子 || git 回调方法)
也就是:git 在执行某个事件之前或之后进行一些其他额外的操作.
而我们所期望的 阻止不合规的提交消息,那么就需要使用到 hooks
的钩子函数。
下面是所有的 hooks
,大家可以进行一下参考,其中加粗的是常用到的 hooks
:
Git Hook | 调用时机 | 说明 |
---|---|---|
pre-applypatch | git am 执行前 | |
applypatch-msg | git am 执行前 | |
post-applypatch | git am 执行后 | 不影响git am 的结果 |
pre-commit | git commit 执行前 | 可以用git commit --no-verify 绕过 |
commit-msg | git commit 执行前 | 可以用git commit --no-verify 绕过 |
post-commit | git commit 执行后 | 不影响git commit 的结果 |
pre-merge-commit | git merge 执行前 | 可以用git merge --no-verify 绕过。 |
prepare-commit-msg | git commit 执行后,编辑器打开之前 | |
pre-rebase | git rebase 执行前 | |
post-checkout | git checkout 或git switch 执行后 | 如果不使用--no-checkout 参数,则在git clone 之后也会执行。 |
post-merge | git commit 执行后 | 在执行git pull 时也会被调用 |
pre-push | git push 执行前 | |
pre-receive | git-receive-pack 执行前 | |
update | ||
post-receive | git-receive-pack 执行后 | 不影响git-receive-pack 的结果 |
post-update | 当 git-receive-pack 对 git push 作出反应并更新仓库中的引用时 | |
push-to-checkout | 当``git-receive-pack对 git push做出反应并更新仓库中的引用时,以及当推送试图更新当前被签出的分支且 receive.denyCurrentBranch配置被设置为 updateInstead`时 | |
pre-auto-gc | git gc --auto 执行前 | |
post-rewrite | 执行git commit --amend 或git rebase 时 | |
sendemail-validate | git send-email 执行前 | |
fsmonitor-watchman | 配置core.fsmonitor 被设置为.git/hooks/fsmonitor-watchman 或.git/hooks/fsmonitor-watchmanv2 时 | |
p4-pre-submit | git-p4 submit 执行前 | 可以用git-p4 submit --no-verify 绕过 |
p4-prepare-changelist | git-p4 submit 执行后,编辑器启动前 | 可以用git-p4 submit --no-verify 绕过 |
p4-changelist | git-p4 submit 执行并编辑完changelist message 后 | 可以用git-p4 submit --no-verify 绕过 |
p4-post-changelist | git-p4 submit 执行后 | |
post-index-change | 索引被写入到read-cache.c do_write_locked_index 后 |
PS:详细的 HOOKS介绍
可点击这里查看
整体的 hooks
非常多,当时我们其中用的比较多的其实只有两个:
Git Hook | 调用时机 | 说明 |
---|---|---|
pre-commit | git commit 执行前它不接受任何参数,并且在获取提交日志消息并进行提交之前被调用。脚本 git commit 以非零状态退出会导致命令在创建提交之前中止。 | 可以用git commit --no-verify 绕过 |
commit-msg | git commit 执行前可用于将消息规范化为某种项目标准格式。 还可用于在检查消息文件后拒绝提交。 | 可以用git commit --no-verify 绕过 |
简单来说这两个钩子: |
commit-msg
:可以用来规范化标准格式,并且可以按需指定是否要拒绝本次提交pre-commit
:会在提交前被调用,并且可以按需指定是否要拒绝本次提交。