git-hooks

291 阅读2分钟

通常使用git hooks来防止一些不规范的代码被提交到仓库中,简单的列举一些常见的hooks钩子:

Git Hook调用时机说明
pre-applypatchgit am执行前
applypatch-msggit am执行前
post-applypatchgit am执行后不影响git am的结果
pre-commitgit commit执行前可以用git commit --no-verify绕过
commit-msggit commit执行前可以用git commit --no-verify绕过
post-commitgit commit执行后不影响git commit的结果
pre-merge-commitgit merge执行前可以用git merge --no-verify绕过。
prepare-commit-msggit commit执行后,编辑器打开之前
pre-rebasegit rebase执行前
post-checkoutgit checkout或git switch执行后如果不使用--no-checkout参数,则在git clone之后也会执行。
post-mergegit commit执行后在执行git pull时也会被调用
pre-pushgit push执行前
pre-receivegit-receive-pack执行前
update
post-receivegit-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-gcgit gc --auto执行前
post-rewrite执行git commit --amend或git rebase时
sendemail-validategit send-email执行前
fsmonitor-watchman配置core.fsmonitor被设置为.git/hooks/fsmonitor-watchman或.git/hooks/fsmonitor-watchmanv2时
p4-pre-submitgit-p4 submit执行前可以用git-p4 submit --no-verify绕过
p4-prepare-changelistgit-p4 submit执行后,编辑器启动前可以用git-p4 submit --no-verify绕过
p4-changelistgit-p4 submit执行并编辑完changelist message后可以用git-p4 submit --no-verify绕过
p4-post-changelistgit-p4 submit执行后
post-index-change索引被写入到read-cache.c do_write_locked_index后

详细的 hooks 的介绍,可点击这里查看

最常用的其实就是上面表格中标粗的pre-commit和commit-msg:

  1. commit-msg:可以用来规范化标准格式,并且可以按需指定是否要拒绝本次提交
  2. pre-commit:会在提交前被调用,并且可以按需指定是否要拒绝本次提交