当前位置:   article > 正文

巧用 gitHooks 提交前校验代码

java git hooks实践

感谢bigAken投稿

在每一个使用 git 进行版本管理的仓库,都有一个目录 .git/hooks,包含 commit 各个阶段 Hooks 的脚本。这些 Hooks 在 git 操作 commit、push、merge 等得时候,可以做前置或者后置的操作,例如 pre-commit 在 git commit 前可以做代码校验,校验代码的时候使用的ESLint,格式化使用的是 prettier。Git 支持的常用钩子见下表,更多请查看官网Hooks:

Git Hook调用时机调用时机
pre-commitgit commit 执行前可以用 git commit --no-verify 绕过
commit-msggit commit 执行前可以用 git commit --no-verify 绕过
pre-merge-commitgit merge 执行前可以用 git merge --no-verify 绕过
pre-pushgit push 执行前

本文先实践,怎么去写 pre-commit 这个 git hooks,然后介绍 husky,lint-staged,commitlint 的使用

在 git 项目中,.git/hooks下面有很多 hooks 示例如下383a69cd79392d7d12c4ab625f124521.png

这些 git hooks 都是.sample结尾的,如果要启用某个 hooks 用可以去掉.sample结尾

实践

npm init -y初始化一个项目,然后git init,然后npm install eslint --save-dev

新建.gitignore文件

  1. node_modules
  2. # local env files
  3. .env.local
  4. .env.*.local
  5. # Log files
  6. npm-debug.log*
  7. yarn-debug.log*
  8. yarn-error.log*
  9. *-lock.json
  10. *.lock

新建.eslintrc,配置 eslint

  1. {
  2.  "rules": {
  3.   // 要求使用分号
  4.   "semi": ["error""always"],
  5.   // 强制使用一致的反勾号、双引号或单引号
  6.   "quotes": ["error""double"]
  7.  }
  8. }

新建src目录,然后里面新建index.js,禁止使用快捷键格式化

console.log('object')

根目录新建文件夹.customGitHooks然后 git config 'core.hooksPath' .customGitHooks,主要是设置 gitHooks 的存放目录,因为 gitHooks 默认存放目录是.git/hooks,新建pre-commit,写入如下

  1. #!/bin/sh
  2. echo 'start check your code,please wait...'
  3. # git diff 获取更改的内容 可以通过参数--diff-filter 配置条件
  4. npx eslint $(git diff --cached --name-only --diff-filter=ACM -- '*.js')
  5. # 变量$?--->上一个命令的执行状态结果
  6. if [ $? != '0' ];then
  7.   echo "ending and failed,please check your code;"
  8.  exit 1
  9. else
  10.   echo "check pass"
  11. fi

这时候,执行git add .git commit -m 'test'就会发现没有 commit 成功,报错了,如下图27159c3f51a47749ee5427e2c81c845f.png

如果把 index.js 的代码修改如下:

console.log('object')

执行git add .git commit -m 'test'就会发现 eslint 代码检查通过了,能正常提交了,以上实践能很好解释 commit 前怎么检验代码,但是有个缺点就是别人 pull 你的代码要执行git config 'core.hooksPath' .customGitHooks能起作用;下面就介绍 husky,lint-staged,commitlint 的使用

.git 文件夹不会被跟踪并且上传至远程仓库的

Husky

github为了解决.git配置不能提交远程仓库的问题,husky 出来了,husky 在你npm i安装完依赖只有自动执行husky install

安装 npm install husky -D

npm install husky -D

使用

编辑package.jsonscript里添加prepare的值为husky install

  1. "scripts": {
  2.     "prepare":"husky install"
  3.   },

然后执行npm run prepare,做了什么事呢

源码index.ts中,我们看到执行 husky install 实际上就是创建 .husky 目录,复制../husky.sh文件到该目录下,配置了一个.gitignore,设置了core.hooksPath(设置 .husky 目录为 git hooks 目录)

添加一个 hook

.husky目录下创建pre-commit

  1. #!/bin/sh
  2. echo 'start check your code,please wait...'
  3. # git diff 获取更改的内容 可以通过参数--diff-filter 配置条件
  4. npx eslint $(git diff --cached --name-only --diff-filter=ACM -- '*.js')
  5. # 变量$?--->上一个命令的执行状态结果
  6. if [ $? != '0' ];then
  7.   echo "ending and failed,please check your code;"
  8.  exit 1
  9. else
  10.   echo "check pass"
  11. fi

index.js文件内容如下

console.log('object')

然后执行git add .git commit -m 'test'发现代码已经被拦截,没有提交,因为index.js代码不符合规范

遗留问题就是 git hooks 不会编写怎么办,下面 lint-staged 出来了

lint-staged

配置例子作用:对 Git 暂存区代码文件进行 bash 命令操作等等

npm i lint-staged -D

根目录下新建.lintstagedrc文件

  1. {
  2.   "*.js""eslint"
  3. }

husky目录下的pre-commit修改如下

  1. "$(dirname "$0")/_/husky.sh"
  2. npm run lint

package.json添加script

  1. "scripts": {
  2.   "lint""lint-staged"
  3. }

index.js如下

  1. console.log('object')
  2. console.log('object')

执行git add .git commit -m 'test',可以发现调用了 eslint 去检查代码,检查不通过就退出commit

9697cc36b964058dc6ef8015fcc0b9b6.png

综上,代码检测规范有了,现在也需要规范一下提交规范;

commitlint

github

校验 commit 提交的信息

npm install --save-dev @commitlint/config-conventional @commitlint/cli

使用新建commitlint.config.js

  1. module.exports = {
  2.  extends: ['@commitlint/config-conventional'],
  3.  rules: {
  4.   'type-enum': [2'always', ['build''ci''docs''feat''fix''perf''refactor''style''test''revert''chore']],
  5.   'type-case': [0],
  6.   'type-empty': [0],
  7.   'scope-empty': [0],
  8.   'scope-case': [0],
  9.   'subject-full-stop': [0'never'],
  10.   'subject-case': [0'never'],
  11.   'header-max-length': [0'always'72]
  12.  }
  13. }

配置git hooks,执行下面命令

npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'

commit message 一般分为三个部分 Header,Body 和 Footer

  1. header
  2. <type>(<scope>): <subject>
  3. // 空一行
  4. <body>
  5. // 空一行
  6. <footer>
  7. 其中,Header 是必需的,Body 和 Footer 可以省略

接下来提交的 commit 必须符合下面的格式

注意冒号后面有空格

git commit -m <type>[optional scope]: <description>

常用的 type 类别

  • build:主要目的是修改项目构建系统(例如 glup,webpack,rollup 的配置等)的提交

  • ci:主要目的是修改项目继续集成流程(例如 Travis,Jenkins,GitLab CI,Circle 等)的提交

  • docs:文档更新

  • feat:新增功能

  • fix:bug 修复

  • perf:性能优化

  • refactor:重构代码(既没有新增功能,也没有修复 bug)

  • style:不影响程序逻辑的代码修改(修改空白字符,补全缺失的分号等)

  • test:新增测试用例或是更新现有测试

  • revert:回滚某个更早之前的提交

  • chore:不属于以上类型的其他类型(日常事务)

optional scope:一个可选的修改范围。用于标识此次提交主要涉及到代码中哪个模块。

description:一句话描述此次提交的主要内容,做到言简意赅。

这时候,执行一次测试一下

  1. git add .
  2. git commit -m 'test'

因为该提交的 commit 是不规范的所以提交时失败的 如下图

d12e72ad7d48f8fedf73519715f19275.png

如果把 commit 修改,就会提交成功,因为符合 commit 规范

  1. git add .
  2. git commit -m 'feat: test'
bce325d1f6a1285c27c5f6dab7bf39e6.png

但是问题又来了,每次 commit 都要输入,有点不方便;而且有可能输错 下面就介绍到 commitizen

commitizen

cz-commitlint

生成符合规范的 commit message

本地安装并没有全局安装,当然可以全局安装具体查看官方文档,全局安装可以使用git czcz-commitlint打通 commitizencommitlint配置

npm install --save-dev @commitlint/cz-commitlint commitizen

然后

npx commitizen init cz-conventional-changelog --save-dev --save-exact

package.json添加script

  1. {
  2.  "scripts": {
  3.   "commit""git-cz"
  4.  },
  5.  "config": {
  6.   "commitizen": {
  7.    "path""@commitlint/cz-commitlint"
  8.   }
  9.  }
  10. }

新建commitlint.config.js

  1. module.exports = {
  2.  extends: ['@commitlint/config-conventional']
  3. }

然后执行

git add .
npm run commit

发现为中文提示如下图b2bcf16f14fac2075eb0e8d00030635d.png

再次修改commitlint.config.js

  1. module.exports = {
  2.  extends: ['@commitlint/config-conventional'],
  3.  prompt: {
  4.   questions: {
  5.    type: {
  6.     description: '选择你要提交的类型:',
  7.     enum: {
  8.      feat: {
  9.       description: '新功能',
  10.       title: 'Features',
  11.       emoji: '✨'
  12.      },
  13.      fix: {
  14.       description: '修复相关bug',
  15.       title: 'Bug Fixes',
  16.       emoji: '
    声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/46423
    推荐阅读
    相关标签