如何使用gitpython进行最后一次提交的当前提交的git diff?

时间:2014-02-25 17:34:46

标签: python git gitpython

我正在尝试抓住gitpython模块,

hcommit = repo.head.commit
tdiff = hcommit.diff('HEAD~1')

tdiff = hcommit.diff('HEAD^ HEAD')不起作用!! ('HEAD~ HEAD')。,

也没有

我正在尝试获得差异输出!

5 个答案:

答案 0 :(得分:6)

import git

repo = git.Repo('repo_path')
commits_list = list(repo.iter_commits())

# --- To compare the current HEAD against the bare init commit
a_commit = commits_list[0]
b_commit = commits_list[-1]

a_commit.diff(b_commit)

这将返回提交的diff对象。还有其他方法可以实现这一目标。例如(这是从http://gitpython.readthedocs.io/en/stable/tutorial.html#obtaining-diff-information复制/粘贴):

```

    hcommit = repo.head.commit
    hcommit.diff()                  # diff tree against index
    hcommit.diff('HEAD~1')          # diff tree against previous tree
    hcommit.diff(None)              # diff tree against working tree

    index = repo.index
    index.diff()                    # diff index against itself yielding empty diff
    index.diff(None)                # diff index against working copy
    index.diff('HEAD')              # diff index against current HEAD tree

```

答案 1 :(得分:2)

我想出了如何使用gitPython获取git diff。

import git
repo = git.Repo("path/of/repo/")

# the below gives us all commits
repo.commits()

# take the first and last commit

a_commit = repo.commits()[0]
b_commit = repo.commits()[1]

# now get the diff
repo.diff(a_commit,b_commit)

Voila !!!

答案 2 :(得分:1)

获取diff的内容:

import git
repo = git.Repo("path/of/repo/")

# define a new git object of the desired repo
gitt = repo.git
diff_st = gitt.diff("commitID_A", "commitID_B")

答案 3 :(得分:0)

要获得正确的解决方案(不使用git命令回调),必须使用create_patch选项。

将当前索引与之前的提交进行比较:

diff_as_patch = repo.index.diff(repo.commit('HEAD~1'), create_patch=True)
print(diff_as_patch)

答案 4 :(得分:0)

很抱歉,要挖掘一个旧线程...如果您需要找出更改了哪些文件,则可以使用diff对象的.a_path.b_path属性,具体取决于您将其喂入哪个对象第一。在下面的示例中,我将head commit用作a,所以我看一下a

例如:

# this will compare the most recent commit to the one prior to find out what changed.

from git import repo

repo = git.Repo("path/to/.git directory")
repoDiffs = repo.head.commit.diff('HEAD~1')

for item in repoDiffs:
    print(item.a_path)