You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于SCM的Python Pip版本自动递增及develop分支版本适配问题

适配分支策略的setuptools_scm版本配置方案

核心思路

利用setuptools_scm的自定义版本钩子功能,通过分支名称检测实现不同分支的版本生成规则:

  • feature分支:基于最近标签递增minor版本,附加.devN后缀
  • fix分支:基于最近标签递增patch版本,附加.devN后缀
  • develop分支:直接使用合并后对应的正式版本标签,无dev后缀

具体实现步骤

1. 编写自定义版本处理脚本

在项目源码目录(如src/hello_python/)下创建_scm_version.py,写入以下逻辑:

from setuptools_scm.version import guess_next_version, get_local_node_and_date

def custom_version_scheme(version):
    # 获取当前分支名称
    branch = getattr(version, 'branch', '')
    
    if branch.startswith('feature/'):
        # feature分支:递增minor版本
        return guess_next_version(version, increment='minor')
    elif branch.startswith('fix/'):
        # fix分支:递增patch版本
        return guess_next_version(version, increment='patch')
    elif branch == 'develop':
        # develop分支:直接使用最近的正式标签版本
        return version.tag or version.closest_tag
    # 其他分支沿用默认逻辑
    return guess_next_version(version)

def custom_local_scheme(version):
    branch = getattr(version, 'branch', '')
    
    if branch == 'develop':
        # develop分支不添加dev后缀
        return ''
    # feature/fix分支保留devN格式后缀
    return get_local_node_and_date(version)

2. 修改pyproject.toml配置

更新[tool.setuptools_scm]部分,指定自定义的版本处理函数:

[build-system]
requires = ["setuptools_scm"]
build-backend = "setuptools.build_meta"

[project]
...
dynamic = ["version"]

[tool.setuptools_scm]
writeIn = "src/hello_python/_version.py"
# 指向自定义的版本规则函数
version_scheme = "src.hello_python._scm_version.custom_version_scheme"
local_scheme = "src.hello_python._scm_version.custom_local_scheme"

3. 配合Git标签完成版本闭环

  • 当feature/fix分支合并到develop后,在develop分支上打对应的正式版本标签(如v0.1.0对应feature分支合并,v0.0.1对应fix分支合并)
  • 打标签命令示例:git tag -a v0.1.0 -m "Release version 0.1.0",然后推送标签:git push origin v0.1.0

验证效果

  • feature分支:基于最近标签v0.0.0,生成版本如0.1.0.devXXXX
  • fix分支:基于最近标签v0.0.0,生成版本如0.0.1.devXXXX
  • develop分支:打标签v0.1.0后,生成版本为0.1.0(无dev后缀)

内容的提问来源于stack exchange,提问作者Matthias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:55:16