husky: git的各种拦截/git hooks

项目中经常用到的一个小工具
更新于: 2024-07-11 07:48:04

安装

# 基础包安装
yarn add husky --dev
npm pkg set scripts.prepare="husky install"
npm run prepare
# 添加命令
npx husky add .husky/post-merge "npm run build"

用法

  • 添加 prepare 任务
  • 添加 pre-commit 的 hook
  • 做一个测试: 提交一条 message
# 添加 prepare 任务
npm pkg set scripts.prepare="husky install"
npm run prepare
# 添加 pre-commit 的hook
npx husky add .husky/pre-commit "npm test"
git add .husky/pre-commit
# 添加一个测试
git commit -m "Keep calm and commit"
# `npm test` will run every time you commit

创建自己的hook

其实这么一行就可以: npx husky add .husky/pre-commit “npm test”

# 添加 pre-commit 的hook
npx husky add .husky/pre-commit "npm test"
git add .husky/pre-commit
# 每次git pull的时候运行命令
npx husky add .husky/post-merge "npm run build"

问题

Linux 下可能出现的问题

其它的hook

git hooks调用时机说明
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 checkoutgit 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-checkoutgit-receive-pack git push做出反应并更新仓库中的引用时,以及当推送试图更新当前被签出的分支且receive.denyCurrentBranch配置被设置为updateInstead 
pre-auto-gcgit gc --auto执行前 
post-rewrite执行git commit --amendgit 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 

cheatsheet

自己工作中的常用场景,利用 husky 完成

场景代码
提交代码的时候,格式化(prettier) 
拉完代码(post merge) 之后运行 build 

添加 cz