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

如何配置setuptools_scm使其始终生成时间戳与Git哈希值

如何让setuptools_scm始终返回Git哈希和时间戳

方法1:自定义版本生成规则

通过get_version()的version_scheme和local_scheme参数自定义输出格式,强制所有仓库状态下都包含哈希和时间戳:

from setuptools_scm import get_version
from setuptools_scm.version import guess_next_dev_version, get_local_node_and_date

def custom_version(version):
    # 针对无版本距离且干净的tag状态,直接拼接tag、哈希和日期
    if version.exact:
        return f"{version.tag}+g{version.node}.d{version.date.strftime('%Y%m%d')}"
    # 其他状态沿用默认的预发布版本规则
    return guess_next_dev_version(version)

my_version = get_version(
    version_scheme=custom_version,
    local_scheme=get_local_node_and_date
)

get_local_node_and_date是setuptools_scm内置函数,会生成g{短哈希}.d{YYYYMMDD}格式的后缀,不管仓库是否有未提交修改。

方法2:直接提取原始SCM元数据

如果需要完全自定义版本格式,可跳过版本字符串生成,直接获取底层仓库元数据:

from setuptools_scm import get_config, parse_scm

config = get_config()
scm_info = parse_scm(config=config)

# 提取所需核心信息
git_short_hash = scm_info.node
git_full_hash = scm_info.full_node  # 完整Git哈希
commit_date = scm_info.date.strftime('%Y%m%d')
latest_tag = scm_info.tag or "untagged"
is_repo_clean = not scm_info.dirty

# 自行构建自定义版本
custom_version = f"{latest_tag}+{git_short_hash}.{commit_date}"

全局配置(可选)

如果想在项目全局生效,可在pyproject.toml中添加配置,替代代码传参:

[tool.setuptools_scm]
version_scheme = "your.module.custom_version"
local_scheme = "setuptools_scm.version.get_local_node_and_date"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:12:51