python - 安装时将 git hash 嵌入到 python 文件中

标签 python git distutils

如果该模块是使用 ./setup.py install 从 git 存储库安装的,我想将 git 哈希嵌入到 python 模块的版本号中。我怎么做?

我的想法是在 setup.py 中定义一个函数来插入散列并安排在安装程序将模块复制到其 build/lib/ 时调用它目录,但在将其安装到最终目的地之前。那时有什么方法可以挂接到构建过程中吗?

编辑:我知道如何从命令行获取当前版本的哈希值,我想问的是如何让这样的命令在构建/安装期间的正确时间运行。

最佳答案

另一种可能更简单的方法,使用 gitpython , 如 dd/setup.py :

from pkg_resources import parse_version  # part of `setuptools`


def git_version(version):
    """Return version with local version identifier."""
    import git
    repo = git.Repo('.git')
    repo.git.status()
    # assert versions are increasing
    latest_tag = repo.git.describe(
        match='v[0-9]*', tags=True, abbrev=0)
    assert parse_version(latest_tag) <= parse_version(version), (
        latest_tag, version)
    sha = repo.head.commit.hexsha
    if repo.is_dirty():
        return f'{version}.dev0+{sha}.dirty'
    # commit is clean
    # is it release of `version` ?
    try:
        tag = repo.git.describe(
            match='v[0-9]*', exact_match=True,
            tags=True, dirty=True)
    except git.GitCommandError:
        return f'{version}.dev0+{sha}'
    assert tag == f'v{version}', (tag, version)
    return version

也可以引用 https://github.com/tulip-control/tulip-control/pull/145 的讨论

关于python - 安装时将 git hash 嵌入到 python 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17812164/

相关文章:

python - 是否可以将 Black 作为 API 调用?

python - 错误: unbound method Dragon( ) must be called with Enemy instance as first argument (got Player instance instead)

git - 如何处理 Jenkins 上提升的冲突分支

python - 使用 py2exe 创建单文件可执行文件

python - 如何在构建期间生成 python 代码并将它们包含在 python 轮中?

python - 安装扩展模块的混合物。纯 python 模块和带有 distutils 的共享库

python - 如何基于 Pandas 中的两列进行分组?

python - 更改 Python 的默认编码?

git - 我没有 ~/.ssh/config 文件,但多个 GitHub 帐户有效,如何?

git diff 忽略行尾的分号