Search code examples
pythongitgitpython

git diff hexsha:directorypath/file


Given that hexsha, directory and file are known, how can I get the diff between 2 specific files, for example the following will return the diff between 2 revisions:

irepo.git.diff("93ba8ae12f79e7f90e5ec5217e44ce28624a66d8..d144da4b5f0dff89b918bc88629cb7902150d77c")

But, how can I produce the diff of <directory>/<file> included in both revisions above?


Solution

  • You can use GitPython's built-in diff facilities to do that.

    import git
    r = git.Repo(path_to_repo)
    diff_index = r.commit(lhs_hexsha).diff(rhs_hexsha, create_patch=True)
    # find all modified paths you are interested in
    for diff_info in diff_index.iter_change_type('M'):
        if diff_info.a_blob.path == my_path:
            print(str(diff_info))
    

    Follow the links for more information on diffing objects, the diff() call, the returned DiffIndex object, or the Diff objects contained therein.

    The a_blob referenced in the example is a Blob object, which provides read-access to the compared file at the commit at lhs_hexsha. There is a b_blob too which represents the state of the file at the commit at rhs_hexsha.