四时宝库

程序员的知识宝库

通过 husky 来规范 git 的提交流程

相信大家在开发过程中,常常会遇到这种场景:当你接手一个项目(或者结对开发时),欢快地打开 gitlab,突然!看到 commit message 都是 “添加了一些小功能”、“优化了很多内容” 或者每次都是重复的提交信息时,心态直接炸裂[炸弹][炸弹][炸弹]。此时,除了心里默默叹一声 “你礼貌吗” 外,我们能够做些什么来改善这种情况呢?

试想如果我们能够接入到代码从 pull 到 push 的各个阶段内,那么我们也拥有了管理 git 流程的能力。Githooks 为此而生,它提供了一系列“生命周期钩子”来让我们方便地管理 git 流程,接下来我们以如何结合 husky 来规范化 commit message 为例进行说明。

第一步,在项目内引入 husky,这里为大家介绍简要步骤:

# 1. 引入 husky

yarn add husky --dev


# 2. 启用 git hooks

yarn husky install


# 3. 更新 package.json,添加脚本

{

	"postinstall": "husky install"

}

完成以上步骤之后:

  1. 再执行 npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"' 来添加 commit-message 的脚本文件到 `.husky/commit-msg.sh` 内;
  2. 编辑文件,添加相应脚本,当提交 commit 时会触发该脚本;


获取 commit message?

在 commit-msg.sh 内,通过读取 $1 传参可以获取提交信息的保存路径,之后通过读取该路径的文件信息,获取提交信息,通常保存在 ./.git/COMMIT_EDITMSG


如何编写验证脚本?

我们需要:

1. 获取提交信息;

2. 开发正则验证;

3. 验证不通过时,输出提示信息;

这里提供一个通用的脚本:

// verfiyCommit.js
// Invoked on the commit-msg git hook by yorkie.

const chalk = require('chalk')

// to get commit message from file

const msgPath = require('path').resolve('./.git/COMMIT_EDITMSG')

const msg = require('fs')

  .readFileSync(msgPath, 'utf-8')

  .trim()

const commitRE = /^(revert: )?(feat|improve|fix|docs|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release|dep)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {

  console.log()

  console.error(

    '  ' +

      chalk.bgRed.white(' ERROR ') +

      ' ' +

      chalk.red('invalid commit message format.') +

      '\n\n' +

      chalk.red(

        'Proper commit message format is required for automated changelog generation. Examples:\n\n',

      ) +

      '    \n    ' +

      chalk.green("\uD83D\uDCA5 feat(compiler): add 'comments' option") +

      '\n    ' +

      chalk.green("\ud83c\udf0a improve(compiler): make some improvements") +

      '\n    ' +

      chalk.green('\uD83D\uDC1B fix(compiler): fix some bug') +

      '\n    ' +

      chalk.green('\uD83D\uDCDD docs(compiler): add some docs') +

      '\n    ' +

      chalk.green('\uD83C\uDF37 UI(compiler): better styles') +

      '\n    ' +

      chalk.green('\uD83C\uDFF0 chore(compiler): Made some changes to the scaffolding') +

      '\n    ' +

      chalk.green(

        '\uD83C\uDF10 locale(compiler): Made a small contribution to internationalization',

      ) +

      '\n\n' +

      chalk.red('Normalized is required and having fun in coding~\n'),

  )

  process.exit(1)

}

当验证不通过时,会展示如下效果:



后话:一份规范的 commit message 不仅能够帮助我们:1. 方便地生成 changelog,2. 同时能够在 review 或者排查问题时提供便利,如果你还在忍受一些杂乱不堪的 commit message,不妨试试通过技术手段对其“感化”!

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接