7

规范你的commit msg

 2 years ago
source link: https://segmentfault.com/a/1190000040922831
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

TL;DR:

👉 commitizen 使用

👉 commitlint 使用

👉 可以直接抄走的配置

👉 git cz 的原理

可参考的代码库

规范 commit msg 的意义

规范化、格式化的 commit message 可以让我们更好的追踪需求的演进、回滚时能够快速的找到提交、最次也能让我们的仓库显的更专业。

团队如何规范 commit msg呢,靠宣讲、靠文档?当然得靠工具生成和约束。前端圈轮子那么多,这种工具不在话下。

  • commitizen 问答式生成 commit msg 格式化
  • commitlint 校验卡控 commit msg 规范化

commitizen

commitizen: simple commit conventions for internet citizens.

commitizen/cz-cli 借助它提供的 git cz 命令替代 git commit 命令,生成符合规范的 commit message。

commitizen 默认的提交规范是 angular 团队强规定的,若想自定义我们还需配合 Adapter(适配器)此处我们用cz-customizable。下面我们直接来介绍项目级配置。

进行 commitizen 配置

执行 npm install -D commitizennpm install -D cz-customizable命令

然后在 package.json文件中 scripts 和 config 字段进行配置

{
  "scripts": {
    "commit": "cz"
  },
  "config": {
    "commitizen": {
      "path": "./node_modules/cz-customizable"
    },
    "cz-customizable": {
      "config": ".cz-configrc.js"
    }
  }
}

添加 .cz-configrc.js文件,可参考 cz-demo

在项目的根目录下执行 npm run commit试试吧

后续t npm run commit 替换 git commit

commitlint

如何保证组内成员都使用npm run commit命令呢?当然是用工具。

这里我们用 commitlint,作用和 eslint 类似。利用 git hooks 拦截不符合规范的 commit msg。

npm install --save-dev @commitlint/{config-conventional,cli}

npm install yorkie --save-dev

添加 .commitlint.config.js 文件

扩展开源配置,然后再添加部分个性化 rules
参考配置

如果你和我一样对 Applicable always|never: never inverts the rule.很迷惑请阅读链接

配置 git hooks

为了拦截不规范的 commit msg,需要利用 git hooks 的 commit-msg 自动执行 commitlint

"gitHooks": {
  "commit-msg": "commitlint -e $GIT_PARAMS"
}

乱输入一个 commit msg 试试,发现非常神奇。卡控生效了

按照以上步骤就可以规范你们团队的 commit msg了。

总结一下:

step 1: 安装依赖

npm install -D commitizen cz-customizable
npm install -D @commitlint/{config-conventional,cli}
npm install -D yorkie 

step 2: 添加配置文件

自定义格式的commitizen配置文件 .cz-configrc.js ,校验规范的 .commitlint.config.js 文件

step 2: 配置 package.json

{
  "scripts": {
    "commit": "cz"
  },
  "config": {
    "commitizen": {
      "path": "./node_modules/cz-customizable"
    },
    "cz-customizable": {
      "config": ".cz-configrc.js"
    }
  },
  "gitHooks": {
    "commit-msg": "commitlint -e $GIT_PARAMS"
  }
}

git cz 的原理

如果你是全局按照的 commitizen,你还能用 git cz命令代替 npm run commit

git cz 是什么玩意? git 的命令,还 commitizen 的命令。2脸懵逼 ???

通过查阅资料 git cz 是 commitizen 利用 git 的文件命名规范生成的自定义 git 命令。cz-cli/issues

Git遵循命名约定git-<subcmd>自动解析PATH中可执行文件中的子命令。 这些子命令可以用git <subcmd>执行。

我们看下 commitizen 仓库 package.json 的 bin 字段。真香大白了,就是 git 的自定义命令

 "bin": {
    "cz": "./bin/git-cz",
    "git-cz": "./bin/git-cz",
    "commitizen": "./bin/commitizen"
  },

参考这个 demo 仓库将你的代码库武装起来吧

原文地址


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK