Skip to main content
 首页 » 编程设计

python之如何使用 gitpython 对当前提交与上次提交进行 git diff

2025年05月04日11softidea

我正在尝试掌握 gitpython 模块,

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

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

也没有

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

请您参考如下方法:

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) 

这将为提交返回一个差异对象。还有其他方法可以实现这一点。例如(这是从 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 

```