在 Python 脚本中获取当前的 git hash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14989858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:01:12  来源:igfitidea点击:

Get the current git hash in a Python script

pythongitgit-hash

提问by Victor

I would like to include the current git hash in the output of a Python script (as a the version numberof the code that generated that output).

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

How can I access the current git hash in my Python script?

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

采纳答案by Greg Hewgill

The git describecommand is a good way of creating a human-presentable "version number" of the code. From the examples in the documentation:

git describe命令是创建代码的人类可呈现“版本号”的好方法。从文档中的示例:

With something like git.git current tree, I get:

[torvalds@g5 git]$ git describe parent
v1.0.4-14-g2414721

i.e. the current head of my "parent" branch is based on v1.0.4, but since it has a few commits on top of that, describe has added the number of additional commits ("14") and an abbreviated object name for the commit itself ("2414721") at the end.

使用 git.git current tree 之类的东西,我得到:

[torvalds@g5 git]$ git describe parent
v1.0.4-14-g2414721

即我的“父”分支的当前负责人基于 v1.0.4,但由于它在此之上有一些提交,describe 添加了额外提交的数量(“14”)和提交的缩写对象名称本身(“2414721”)在最后。

From within Python, you can do something like the following:

在 Python 中,您可以执行以下操作:

import subprocess
label = subprocess.check_output(["git", "describe"]).strip()

回答by Yuji 'Tomita' Tomita

This postcontains the command, Greg's answercontains the subprocess command.

这篇文章包含命令,Greg 的答案包含子进程命令。

import subprocess

def get_git_revision_hash():
    return subprocess.check_output(['git', 'rev-parse', 'HEAD'])

def get_git_revision_short_hash():
    return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])

回答by ryanjdillon

numpyhas a nice looking multi-platform routinein its setup.py:

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

回答by kqw

No need to hack around getting data from the gitcommand yourself. GitPythonis a very nice way to do this and a lot of other gitstuff. It even has "best effort" support for Windows.

无需git自己从命令中获取数据。GitPython是一种很好的方式来完成这项工作以及许多其他的git东西。它甚至对 Windows 有“尽力而为”的支持。

After pip install gitpythonyou can do

pip install gitpython你可以做之后

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

回答by kagronick

If subprocess isn't portable and you don't want to install a package to do something this simple you can also do this.

如果子进程不可移植并且您不想安装包来做这么简单的事情,您也可以这样做。

import pathlib

def get_git_revision(base_path):
    git_dir = pathlib.Path(base_path) / '.git'
    with (git_dir / 'HEAD').open('r') as head:
        ref = head.readline().split(' ')[-1].strip()

    with (git_dir / ref).open('r') as git_hash:
        return git_hash.readline().strip()

I've only tested this on my repos but it seems to work pretty consistantly.

我只在我的 repos 上测试过这个,但它似乎工作得非常一致。

回答by AndyP

Here's a more complete version of Greg's answer:

这是Greg 答案的更完整版本:

import subprocess
print(subprocess.check_output(["git", "describe", "--always"]).strip().decode())

Or, if the script is being called from outside the repo:

或者,如果脚本是从 repo 外部调用的:

import subprocess, os
os.chdir(os.path.dirname(__file__))
print(subprocess.check_output(["git", "describe", "--always"]).strip().decode())

回答by am9417

If you don't have git available for some reason, but you have the git repo (.git folder is found), you can fetch the commit hash from .git/fetch/heads/[branch]

如果由于某种原因你没有可用的 git,但你有 git repo(找到 .git 文件夹),你可以从 .git/fetch/heads/[branch] 获取提交哈希

For example, I've used a following quick-and-dirty Python snippet run at the repository root to get the commit id:

例如,我使用了以下在存储库根目录下运行的快速而肮脏的 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]