9

diff()在 GitPython 中,我可以通过调用不同提交对象之间的方法来分别迭代树中每个更改的差异信息。如果我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对象。如何获得存储库中的第一个更改?

编辑

一个肮脏的解决方法似乎是直接使用它的 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)

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

4

1 回答 1

3

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

在提交上做 agit show是可行的,但 GitPython 不支持。

另一方面,您可以使用statsGitPython 中的功能来获取某些内容,从而获得所需的信息:

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 的库。这可能是更完整的功能。祝你好运。

于 2018-04-04T10:28:28.157 回答