git hook+ lint-staged控制代码规范

539 阅读1分钟

npm script 应用在git hooks中

团队项目往往是多人协作,如何保证提交代码符合规范,最简单粗暴的就是,不符合规范的代码,限制提交。那我们今天看下如何用git hooks,在提交和推送时候做一些事情。

常用的git hooks

  • pre-commit 在commit之前做一些事情,使用lint-staged检查代码;
  • commit-msg 检查commit时候的message;
  • pre-push 在push之前做一些事情,一般用于运行单元测试;

安装 lint-staged,检查提交代码

npm install lint-staged
// 或
yarn add lint-staged --dev

配置

在package.json中配置

{
    "gitHooks": {
        "pre-commit": "lint-staged",// 检查提交代码
        "pre-push": "npm run test:unit" // 运行单元测试
    },
    "lint-staged": {
        "*.{js,vue}": "eslint"// 使用eslint检查暂存区文件
    },
}

安装yorkie,检查提交信息规范

npm install 安装yorkie
// 或
yarn add 安装yorkie --dev

新增文件

build/verifyCommit.js

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

const chalk = require('chalk')
const msgPath = process.env.GIT_PARAMS
const msg = require('fs').readFileSync(msgPath, 'utf-8').trim()

const releaseRE = /^v\d/
const commitRE = /^(revert: )?(migrate|feat|fix|docs|dx|refactor|perf|test|workflow|build|ci|chore|types|wip|release): .{1,50}/
if (!msg.startsWith('Merge branch')) {
  if (!releaseRE.test(msg) && !commitRE.test(msg)) {
    console.log('message is:', msg)
    console.error(
      `  ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
        'invalid commit message format.'
      )}\n\n` +
        ` rule is ${chalk.green(
          '/^(revert: )?(migrate|feat|fix|docs|dx|refactor|perf|test|workflow|build|ci|chore|types|wip|release): .{1,50}/'
        )} \n` +
        chalk.red(
          '  Proper commit message format is required for automated changelog generation. Examples:\n\n'
        ) +
        `    ${chalk.green("feat: add 'comments' option")}\n` +
        `    ${chalk.green('fix: handle events on blur (close #28)')}\n\n` +
        chalk.red('  See .github/commit-convention.md for more details.\n')
    )
    process.exit(1)
  }
}

packgae.json中配置

{
    "gitHooks": {
        "commit-msg": "node build/verifyCommit.js",
    }
}