获取GitPython中第一次提交的差异细节

时间:2015-11-25 12:33:10

标签: python git gitpython

在GitPython中,我可以通过调用不同提交对象之间的diff()方法,分别迭代树中每个更改的diff信息。如果我使用diff()关键字参数调用create_patch=True,则会为我可以通过创建的diff对象访问的每个更改(添加,删除,重命名)创建一个补丁字符串,并进行剖析变化。

但是,我没有父母可以与第一次提交进行比较。

import git
from git.compat import defenc
repo = git.Repo("path_to_my_repo")

commits = list(repo.iter_commits('master'))
commits.reverse()

for i in commits:

    if not i.parents:
        # First commit, don't know what to do
        continue
    else:
        # Has a parent
        diff = i.diff(i.parents[0], create_patch=True)

    for k in diff:
        try:
            # Get the patch message
            msg = k.diff.decode(defenc)
            print(msg)
        except UnicodeDecodeError:
            continue

您可以使用方法

diff = repo.git.diff_tree(i.hexsha, '--', root=True)

但是这会使用给定的参数调用整个树上的git diff,返回一个字符串,我无法单独获取每个文件的信息。

也许,有一种方法可以创建某种类型的root对象。如何在存储库中获得第一个更改?

修改

通过直接使用its hash

,一个肮脏的解决方法似乎与空树进行比较
EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"

....

    if not i.parents:
        diff = i.diff(EMPTY_TREE_SHA, create_patch=True, **diffArgs)
    else:
        diff = i.diff(i.parents[0], create_patch=True, **diffArgs)

但这似乎不是一个真正的解决方案。其他答案仍然受到欢迎。

1 个答案:

答案 0 :(得分:2)

简短的回答是你不能。 GitPython似乎不支持这种方法。

在提交时可以做git show,但是GitPython不支持。

另一方面,您可以使用GitPython中的stats功能来获取可以获取所需信息的内容:

import git

repo = git.Repo(".")

commits = list(repo.iter_commits('master'))
commits.reverse()
print(commits[0])
print(commits[0].stats.total)
print(commits[0].stats.files)

这可能会解决您的问题。如果这不能解决您的问题,您可能最好不要尝试使用基于libgit2的pygit2 - VSTS,Bitbucket和GitHub用于在其后端处理Git的库。这可能更完整。祝你好运。