how to do a git diff of current commit with last commit using gitpython?

Ciasto piekarz picture Ciasto piekarz · Feb 25, 2014 · Viewed 7k times · Source

I am trying o grasp gitpython module,

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

but tdiff = hcommit.diff('HEAD^ HEAD') doesn't work !! neither does ('HEAD~ HEAD').,

I am trying to get the diff output !

Answer

Jon Sonesen picture Jon Sonesen · Sep 22, 2015
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)

This will return a diff object for the commits. There are other ways to achieve this as well. For example (this is copy/pasted from 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

```