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

如何为Python包注入最新Git提交哈希值?

为Python包自动注入Git提交哈希(基于Poetry)

核心方案

通过Poetry的构建脚本机制,在安装/构建阶段自动执行脚本获取当前Git提交短哈希,写入包内的版本文件,无需手动配置钩子或额外操作。

步骤实现

1. 创建构建脚本

在项目根目录新建build.py,用于获取Git哈希并生成版本文件:

import subprocess
from pathlib import Path

def get_git_short_hash():
    try:
        # 获取当前Git仓库的短哈希
        result = subprocess.run(
            ["git", "rev-parse", "--short", "HEAD"],
            capture_output=True,
            text=True,
            check=True,
            cwd=Path(__file__).parent
        )
        return result.stdout.strip()
    except (subprocess.CalledProcessError, FileNotFoundError):
        # 无Git环境或非Git仓库时返回默认值
        return "unknown"

def write_git_hash_to_version():
    # 指向你的包目录和版本文件
    package_dir = Path(__file__).parent / "my_package"  # 替换为实际包名
    version_file = package_dir / "version.py"
    
    # 写入哈希到版本文件
    with open(version_file, "w") as f:
        f.write(f'__git_hash__ = "{get_git_short_hash()}"\n')

if __name__ == "__main__":
    write_git_hash_to_version()

2. 配置包的导入逻辑

在你的包的__init__.py中导入哈希变量,方便外部调用:

# my_package/__init__.py
from .version import __git_hash__

# 保留原有包初始化内容...

3. 配置Poetry构建钩子

修改pyproject.toml,指定Poetry在构建前执行上述脚本:

[tool.poetry]
name = "my_package"
# 其他基础配置(版本、作者等)保持不变

[tool.poetry.build]
# 指定构建前置脚本
script = "build.py"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

4. 忽略动态生成的版本文件

在.gitignore中添加版本文件,避免提交动态生成的内容:

# .gitignore
my_package/version.py

场景验证

本地安装场景

  1. 克隆Git仓库后,执行pip install .或poetry install
  2. 启动Python交互环境验证:
import my_package as mp
print(mp.__git_hash__)  # 输出当前Git提交的短哈希,如770f67ec492d
  1. 提交代码后,重新执行pip install .,哈希会自动更新为最新提交值。

PyPI发布场景

  1. 执行poetry publish --build,Poetry会先运行build.py注入当前哈希,再构建包并发布到PyPI
  2. 用户通过pip install my_package安装后,执行上述验证代码,会显示发布时的Git提交哈希。

特殊情况处理

  • 若用户从PyPI安装包,包内已包含发布时生成的哈希,无需依赖Git环境
  • 若本地环境无Git或非Git仓库,哈希会显示为unknown

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:43:08