【问题标题】:Get the diff details of first commit in GitPython获取 GitPython 中第一次提交的 diff 详细信息
【发布时间】:2015-11-25 12:33:10
【问题描述】:

在 GitPython 中,我可以通过在不同的提交对象之间调用 diff() 方法来分别迭代树中每个更改的差异信息。如果我使用create_patch=True 关键字参数调用diff(),则会为我可以通过创建的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)

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

【问题讨论】:

  • 与原生 git 不同,GitPython 对第一次提交没有特殊处理。因此,您的解决方案似乎是一个非常可行的解决方案。

标签: python git gitpython


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2020-07-30
    • 2013-03-05
    相关资源
    最近更新 更多