使用 towncrier 管理 changelog?
解读
在国内一线互联网与科研型公司,Matplotlib 作为基础依赖,其发版节奏与合规性直接影响下游 10 万+ 项目。面试官问“怎么用 towncrier 管 changelog”,并不是让你背命令,而是考察三条线:
- 是否理解大型开源项目多分支并行协作带来的 changelog 冲突风险;
- 能否把“开发者写一行”→“CI 聚合”→“发布自动生成”做成零人工干预流水线;
- 是否知道国内镜像源(清华、中科大)同步延迟场景下,如何校验 rst 格式与版本号防止发布失败。
答不出“碎片文件命名规则”或“pyproject.toml 配置段”,都会被判定为“只用过小型项目”,直接降档。
知识点
- towncrier 核心原理:每个 PR 只允许在
docs/changes.d/新增一个<issue编号>.<类型>.rst碎片,禁止直接编辑CHANGELOG.rst,从根本上消除冲突。 - Matplotlib 官方类型枚举:
feature、bugfix、doc、api_change、removal、deprecation、development,对应渲染后的小节标题,必须与合并检查脚本.github/workflows/towncrier.yml里的正则保持一致,否则 CI 报错。 - 版本号联动:towncrier 读取
lib/matplotlib/_version.py里的__version__,通过setup.cfg的[tool.towncrier]version = "attr: matplotlib._version.__version__"实现单点定义,避免 release manager 手抖写错。 - 中文合规:国内出版级文档要求中文日期格式“2024年6月”,需在
pyproject.toml自定义date_format = "%Y年%m月%d日",并设置start_string = ".. towncrier release notes start\n"防止 sphinx 中文搜索截断。 - CI 加速技巧:针对国内 GitHub Actions 排队慢,可在
workflow里加if: github.event.pull_request.merged == true判断,只在合并后触发 towncrier build,减少 60% 空跑;同时缓存~/.cache/pip与docs/_build,把 8 min 降到 2 min。 - 发布检查单:
towncrier check --compare-with origin/main确保无遗漏碎片;towncrier build --draft输出 rst 到临时文件,用doc8做 rst 语法校验;- 在清华镜像站拉取最新版本,执行
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib==x.y.z,确认 changelog 已打包进 wheel 的matplotlib-x.y.z.dist-info/entry_points.txt,否则下游 conda-forge 会报警。
答案
在 Matplotlib 仓库根目录,已预置 pyproject.toml 片段:
[tool.towncrier]
package = "matplotlib"
filename = "CHANGELOG.rst"
directory = "doc/changes.d"
version = "attr: matplotlib.version.version"
start_string = ".. towncrier release notes start\n"
title_format = "{name} {version} ({project_date})"
issue_format = "#{issue} <https://github.com/matplotlib/matplotlib/issues/{issue}>"
开发流程如下:
- 每提交一个 PR,在本地新建碎片:
echo "Fixed memory leak in Axes3D.add_collection." > doc/changes.d/12345.bugfix.rst
注意文件名必须匹配正则(\d+).(feature|bugfix|api_change|removal|deprecation|doc|development).rst,否则 pre-commit 钩子拒绝推送。 - PR 合并后,GitHub Actions 自动运行:
towncrier build --yes --version $(python -c "import matplotlib;print(matplotlib.__version__)")
生成的CHANGELOG.rst顶部新增一级标题,例如 Matplotlib 3.9.0 (2024年6月18日),并自动把碎片拼接到对应小节。 - release manager 本地执行最终校验:
towncrier check --compare-with v3.8.0
若无报错,打 tagv3.9.0并推送;tag 触发 cibuildwheel,twine 上传后,国内镜像站 30 min 内同步完成,changelog 随 wheel 一并分发。 - 若发现严重笔误,使用 towncrier 的 orphan 机制:
echo "Revert incorrect attribution." > doc/changes.d/+orfix.bugfix.rst
再次运行towncrier build --yes,即可在下一补丁版本追加修正,无需回滚整个发布。
拓展思考
- 多仓库协同:当 Matplotlib 依赖的子项目(如 matplotlib-cpp)也使用 towncrier 时,可在主仓库 CI 里通过
git submodule foreach towncrier build --draft聚合子项目 changelog,再统一写入顶级发布说明,实现跨 repo 一站式发布。 - 自动化语义化版本:结合 commitizen 与 towncrier,解析碎片类型计数,
feature数量>0 自动升 minor,api_change或removal数量>0 升 major,完全消除人工拍脑袋定版本。 - 国内私有源合规:在头部券商离线环境,需把 towncrier 碎片同步到内部 Gitea,通过 GitLab CI 镜像克隆 + 内网 PyPI 缓存,实现“零外网”发版;此时要把
issue_format改成内网地址,避免生成指向 GitHub 的外部链接,满足证监会信披隔离要求。