如何获取Git中当前提交的哈希?


当前回答

主要git repo和子模块的漂亮打印:

echo "Main GIT repo:"
echo $(git show -s --format=%H) '(main)'
echo "Sub-modules:"
git submodule status | awk '{print $1,$2}'

示例输出:

3a032b0992d7786b00a8822bbcbf192326160cf9 (main)
7de695d58f427c0887b094271ba1ae77a439084f sub-module-1
58f427c0887b01ba1ae77a439084947de695d27f sub-module-2
d58f427c0887de6957b09439084f4271ba1ae77a sub-module-3

其他回答

也总是有数字描述。默认情况下,它为您提供--

john@eleanor:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75

要获取缩短的提交哈希,请使用%h格式说明符:

git log --pretty=format:'%h' -n 1

%H表示长提交哈希。此外,可以直接使用-1代替-n 1。

echo“正在打印当前分支的上次提交id#:”;

 git reflog

要将任何扩展对象引用转换为哈希,请使用git-rev-parse:

git rev-parse HEAD

or

git rev-parse --verify HEAD

要检索短哈希:

git rev-parse --short HEAD

要将引用(例如分支和标记)转换为哈希,请使用git show ref和git for each-ref。

我将如何在python中实现(基于@kenorb的bash答案)

def get_git_sha():
    # Which branch are we on?
    branch = open(".git/HEAD", "r").read()

    # Parse output "ref: refs/heads/my_branch" -> my_branch
    branch = branch.strip().split("/")[-1]

    # What's the latest commit in this branch?
    return open(f".git/refs/heads/{branch}").read().strip()