husky: git的各种拦截/git hooks
项目中经常用到的一个小工具
安装
# 基础包安装
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 下可能出现的问题
- 部分
centos系统里无法正常工作(原因不明zgmw-server) - 可能原因: https://github.com/typicode/husky/issues/1241
其它的hook
| git hooks | 调用时机 | 说明 |
|---|---|---|
| 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后 |
cheatsheet
自己工作中的常用场景,利用 husky 完成
| 场景 | 代码 |
|---|---|
| 提交代码的时候,格式化(prettier) | |
| 拉完代码(post merge) 之后运行 build |
添加 cz
lint-staged
- https://dev.to/samueldjones/run-a-typescript-type-check-in-your-pre-commit-hook-using-lint-staged-husky-30id
- https://github.com/lint-staged/lint-staged/issues/825
- https://stackoverflow.com/questions/74947483/running-tsc-in-expo-project-with-husky-via-lint-staged-keeps-generating-js-files
bash -c tsc --noEmit