我想在Python脚本的输出中包含当前的git散列(作为生成该输出的代码的版本号)。

如何在我的Python脚本中访问当前的git哈希?


当前回答

如果您由于某些原因没有可用的Git,但您有Git repo(。),你可以从. Git /fetch/heads/[branch]中获取提交哈希。

例如,我在存储库根运行了下面的Python代码片段来获得提交id:

git_head = '.git\\HEAD'

# Open .git\HEAD file:
with open(git_head, 'r') as git_head_file:
    # Contains e.g. ref: ref/heads/master if on "master"
    git_head_data = str(git_head_file.read())

# Open the correct file in .git\ref\heads\[branch]
git_head_ref = '.git\\%s' % git_head_data.split(' ')[1].replace('/', '\\').strip()

# Get the commit hash ([:7] used to get "--short")
with open(git_head_ref, 'r') as git_head_ref_file:
    commit_id = git_head_ref_file.read().strip()[:7]

其他回答

我遇到了类似于OP的问题,但在我的情况下,我将源代码作为zip文件交付给我的客户端,尽管我知道他们将安装python,但我不能假设他们将安装git。因为OP没有指定他的操作系统,如果他安装了git,我想我可以在这里贡献一下。

为了只获得提交的散列,Naelson Douglas的答案是完美的,但为了获得标记名称,我使用了dulwich python包。这是一个用python简化的git客户端。

在使用pip install dulwich——global-option="——pure"安装包后,可以这样做:

from dulwich import porcelain

def get_git_revision(base_path):
    return porcelain.describe(base_path)

r = get_git_revision("PATH OF YOUR REPOSITORY's ROOT FOLDER")
print(r)

我刚刚在这里的一个存储库中运行了这段代码,它显示了输出v0.1.2-1-gfb41223,类似于git describe返回的结果,这意味着我在标记v0.1.2之后提交了一次,提交的7位哈希值是fb41223。

它有一些限制:目前它没有显示存储库是否脏的选项,它总是显示7位哈希,但不需要安装git,所以可以选择折衷。

编辑:如果pip install命令由于选项——pure(问题在这里解释)而出现错误,请从两个可能的解决方案中选择一个:

首先安装Dulwich包的依赖项: PIP install urllib3 certificate && PIP install Dulwich——global-option="——pure" 安装时没有选择pure: pip Install dulwich。这将在您的系统中安装一些平台相关的文件,但它将提高包的性能。

如果您由于某些原因没有可用的Git,但您有Git repo(。),你可以从. Git /fetch/heads/[branch]中获取提交哈希。

例如,我在存储库根运行了下面的Python代码片段来获得提交id:

git_head = '.git\\HEAD'

# Open .git\HEAD file:
with open(git_head, 'r') as git_head_file:
    # Contains e.g. ref: ref/heads/master if on "master"
    git_head_data = str(git_head_file.read())

# Open the correct file in .git\ref\heads\[branch]
git_head_ref = '.git\\%s' % git_head_data.split(' ')[1].replace('/', '\\').strip()

# Get the commit hash ([:7] used to get "--short")
with open(git_head_ref, 'r') as git_head_ref_file:
    commit_id = git_head_ref_file.read().strip()[:7]

如果你想要比哈希多一点的数据,你可以使用git-log:

import subprocess

def get_git_hash():
    return subprocess.check_output(['git', 'log', '-n', '1', '--pretty=tformat:%H']).strip()

def get_git_short_hash():
    return subprocess.check_output(['git', 'log', '-n', '1', '--pretty=tformat:%h']).strip()

def get_git_short_hash_and_commit_date():
    return subprocess.check_output(['git', 'log', '-n', '1', '--pretty=tformat:%h-%ad', '--date=short']).strip()

关于格式化选项的完整列表-查看git log——help

本文包含该命令,Greg的回答包含subprocess命令。

import subprocess

def get_git_revision_hash() -> str:
    return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip()

def get_git_revision_short_hash() -> str:
    return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip()

运行时

print(get_git_revision_hash())
print(get_git_revision_short_hash())

你得到输出:

fd1cd173fc834f62fa7db3034efc5b8e0f3b43fe
fd1cd17

Numpy在setup.py中有一个漂亮的多平台例程:

import os
import subprocess

# Return the git revision as a string
def git_version():
    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "Unknown"

    return GIT_REVISION