changelog的自动生成
# 背景
想根据 git 每次提交的 commit,做 changlog 的自动生成,大多数开源库都是这个思路做的。比较流行的工具是:standard-version (opens new window)、release-it (opens new window)。
# standard-version
最基本的使用方法安装文档来就行。前提是 commit 的规范需要按照Conventional Commits (opens new window)。一般来说使用了git cz管理规范就可以了。
# git cz (opens new window)
推荐开发使用,可以很好并且直观的看到 git 的 commit 信息。
安装方式:
npm install -g commitizen cz-conventional-changelog
echo '{ "path": "cz-conventional-changelog" }' > ~/.czrc
2
3
使用方式:
git cz
当然 commit 的格式可以按照需求定制。一般使用cz-customizable (opens new window)
# 当 cz-customizable 碰到 standard-version
如果定制了 commit,又需要定制 changelog.md 的输出格式。就需要稍微花点时间看 standard-version 的源码。
最简单的定制
查看源码 默认可以定制的配置 (opens new window) 不然发现。只需要在
package.json下加入以下字段{ "standard-version": { "skip": { "bump": true, "commit": true, "tag": true }, "header": "### 更新日志\n\n" } }1
2
3
4
5
6
7
8
9
10就可以定制 changelog 的 header,或者跳过 commit 阶段。
定制 changelog 的格式
如果需要定制 changlog 的格式,比如去掉 commit 的 hash,修改匹配 commit 的正则等需求。这个时候,就需要定制
conventional-changelog的preset。源码 (opens new window)中可以发现,standard-version 底层使用了
conventional-changelog去处理 commit 的。默认的情况 (opens new window)下使用了conventional-changelog-conventionalcommits去处理 commit。这个时候。我们只需按照
conventional-changelog-conventionalcommits的规范,去自定义我们想要的模板功能就好了。- 项目根目录下添加
.versionrc.jsmodule.exports = { preset: require.resolve("./my-conventionalcommits"), };1
2
3 - copy 一份
conventional-changelog-conventionalcommits修改templates/commit.hbs。这个模板控制着 changelog 里的 commit 的格式,按照需求更改即可。 - 修改
writer-opts.js。这里控制着 commit 的匹配类型 - 修改
parser-opts.js。这里控制着 commit 的匹配正则
- 项目根目录下添加