深入解析git-cliff项目的Keep a Changelog配置模板
什么是git-cliff
git-cliff是一个基于Git提交历史自动生成变更日志(CHANGELOG)的工具。它通过分析Git仓库的提交信息,按照预定义的规则和模板,自动生成结构化的变更日志文档。这种自动化方式极大简化了维护项目变更记录的工作流程。
Keep a Changelog配置模板解析
git-cliff的配置文件使用TOML格式,下面我们详细解析其中的关键配置项。
变更日志头部配置
header = """
# Changelog\n
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n
"""
这部分定义了变更日志的头部内容,包含:
- 标题"Changelog"
- 说明文档用途
- 遵循的规范声明(Keep a Changelog和语义化版本控制)
变更日志主体模板
body = """
{%- macro remote_url() -%}
https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }}
{%- endmacro -%}
{% if version -%}
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else -%}
## [Unreleased]
{% endif -%}
...
"""
主体模板使用Tera模板引擎语法,主要功能包括:
- 定义远程仓库URL的宏
- 根据是否有版本号显示不同标题(已发布版本或未发布变更)
- 格式化版本号(去除开头的"v"前缀)
- 格式化日期显示
变更分组处理
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | upper_first }}
{%- for commit in commits %}
- {{ commit.message | split(pat="\n") | first | upper_first | trim }}\
{% if commit.remote.username %} by @{{ commit.remote.username }}{%- endif -%}
{% if commit.remote.pr_number %} in \
[#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) \
{%- endif -%}
{% endfor %}
{% endfor %}
这部分实现了:
- 按分组(Added/Removed/Fixed等)显示变更
- 每个变更项显示:
- 提交信息的第一行
- 提交者用户名(如果有)
- 关联的Pull Request编号和链接(如果有)
新贡献者识别
{%- if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
## New Contributors
{%- endif -%}
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
* @{{ contributor.username }} made their first contribution
{%- if contributor.pr_number %} in \
[#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \
{%- endif %}
{%- endfor %}\n
这部分专门识别并列出首次为项目做出贡献的开发者,包括:
- 贡献者用户名
- 关联的Pull Request(如果有)
Git提交处理配置
[git]
conventional_commits = true
filter_unconventional = false
commit_preprocessors = [
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "" },
]
commit_parsers = [
{ message = "^[a|A]dd", group = "Added" },
{ message = "^[s|S]upport", group = "Added" },
{ message = "^[r|R]emove", group = "Removed" },
...
]
这部分配置Git提交信息的处理方式:
- 启用常规提交规范解析
- 定义提交信息预处理规则(如移除issue编号)
- 定义提交解析规则,将不同模式的提交信息归类到不同变更组
实际应用建议
- 自定义变更分组:根据项目特点调整
commit_parsers
,添加或修改分组规则 - 本地化处理:可以将模板中的英文内容替换为中文,更适合中文项目
- 扩展功能:可以添加更多模板变量,如影响范围、重要程度等
- 自动化集成:将git-cliff集成到CI/CD流程中,自动更新变更日志
总结
git-cliff的Keep a Changelog配置模板提供了一套完整的自动化变更日志生成方案。通过合理的配置,项目维护者可以:
- 节省手动编写变更日志的时间
- 保持变更记录的一致性和规范性
- 自动识别和感谢新贡献者
- 与项目开发流程无缝集成
理解并合理配置这些模板,将显著提升项目的文档维护效率和质量。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考