在git-python中通过hexsha获取Commit对象

问题描述 投票:0回答:3

我正在尝试查找在两个特定提交之间已签入的提交内容。

在 git 中我会做

git rev-list --ancestry-path <older_commit_sha>..<newer_commit_sha>

在 git-python 中,由于看起来没有直接的方法,我只好通过

repo.git.execute()
调用确切的命令。 输出是一串提交 ID(十六进制 SHA)。

现在,git-python 有没有办法从

Commit
给出的十六进制 SHA 开始创建一个有效的
execute()
对象?

python git gitpython
3个回答
1
投票

我在 git-python 中没有找到通过 sha 获取特定提交对象的函数。 所以我只能想到迭代所有提交来获取它:

def get_commit_by_sha(repo, sha):
    for c in r.iter_commits():
        if c.hexsha == last_one:
            return c
    return None

至于比较两次提交具体提交之间的差异。

diff
方法很好用,简单的用法:

old_commit.diff(new_comit.hexsha)

结果是一个

git.diff.DiffIndex
对象,参考https://gitpython.readthedocs.io/en/stable/reference.html#git.diff.DiffIndex


1
投票

有点晚了(差不多晚了 6 年),但我不知何故找到了如何做到这一点。

commits = list(repo.iter_commits("{}..{}".format(begin_sha, end_sha), "", ancestry_path=True))

这将返回 (

begin_sha
,
end_sha
] 内的提交对象列表(启用
--ancestry-path
)。我怀疑
kwargs
参数列表末尾的
iter_commits
应该被重定向到
git rev-list
,所以我只是尝试一下是否可以指定切换选项,而不是像
--after
这样的值选项。

我责怪缺乏适当的参考手册,不得不通过反复试验来解决这个问题。 :(


0
投票

经过多次探索,鉴于这个问题没有引起太多关注,我求助于使用

.execute()
。 具体来说:

commits = repo.git.execute(['git', 'rev-list', '--ancestry-path',
                            '%s..%s' % (oldCommit.hexsha, newCommit.hexsha)]).split()

commits
str
的列表。

当然,

oldCommit
newCommit
git.Commit
对象。

© www.soinside.com 2019 - 2024. All rights reserved.