使用bump2version+pre-commit钩子遇版本无限循环问题求排查
问题描述
我正在使用bump2version Python模块自动递增Python代码库的版本。当pre-commit钩子运行时,version.sh脚本陷入无限循环,init.py文件中的版本号持续递增。请问遗漏了什么配置或步骤?
现有配置文件
.bumpversion.cfg
[bumpversion] current_version = 0.0.0 commit = True message = "Merge the new version" [bumpversion:file:__init__.py]
.pre-commit-config.yaml
repos: - repo : local hooks: - id: VersionIncrement name: VersionIncrement entry: ./version.sh language: script exclude: (.pre-commit-config.yaml)|(.git/)
version.sh
#!/usr/bin/env bash git_branch_name=`git branch --show-current` echo $git_branch_name if [[ $git_branch_name =~ "feature/" ]]; then bump2version --allow-dirty --verbose patch exit 0 elif [[ $git_branch_name == "dev" ]]; then bump2version --allow-dirty --verbose minor exit 0 elif [[ $git_branch_name == "master" ]]; then bump2version --allow-dirty --verbose major exit 0 else echo "branch does not exist" exit 1 fi
问题根源与解决方案
核心问题
无限循环的原因是bump2version的自动提交触发了pre-commit钩子的重复执行:
- 提交代码时,pre-commit钩子启动并运行version.sh
- version.sh调用
bump2version,而配置里commit = True会让bump2version自动提交版本号变更的代码 - 这个新提交又会触发pre-commit钩子,脚本再次运行、版本号再次递增,形成循环
修复步骤
1. 修改.bumpversion.cfg,禁用自动提交
把commit = True改为commit = False,让bump2version只修改文件版本号,不执行提交操作:
[bumpversion] current_version = 0.0.0 commit = False # 此处改为False message = "Merge the new version" [bumpversion:file:__init__.py]
2. 调整pre-commit钩子配置
在钩子中添加pass_filenames: false,因为该钩子是基于分支的全局操作,不需要处理特定文件,避免pre-commit传递不必要的参数:
repos: - repo : local hooks: - id: VersionIncrement name: VersionIncrement entry: ./version.sh language: script exclude: (.pre-commit-config.yaml)|(.git/) pass_filenames: false # 添加该行
3. 移除--allow-dirty参数(可选但推荐)
pre-commit运行时会自动暂存修改,工作区处于干净状态,因此可以去掉version.sh中的--allow-dirty参数,避免在非预期的脏工作区执行版本递增:
# 修改后的version.sh对应部分 if [[ $git_branch_name =~ "feature/" ]]; then bump2version --verbose patch exit 0 elif [[ $git_branch_name == "dev" ]]; then bump2version --verbose minor exit 0 elif [[ $git_branch_name == "master" ]]; then bump2version --verbose major exit 0
修复后的流程
- 执行
git commit时,pre-commit钩子启动 - version.sh检测当前分支,调用bump2version修改__init__.py的版本号
- pre-commit检测到文件变更,提示重新添加并提交这些变更
- 执行
git add __init__.py后再次提交,此时钩子不会再触发版本递增(版本号已为最新,bump2version不会再修改文件)
内容的提问来源于stack exchange,提问作者user2439278
相关产品推荐
相关产品推荐

