GitPython Library

Documentation

GitPython is a python library used to interact with Git repositories

How To’s

Get List of Commits

from git import Repo

repo = Repo('repo-directory')
commit_list = list(repo.iter_commits('branch', max_count=10))
for commit in commit_list:
    print('----')
    print(commit.hexsha)
    print(commit.authored_datetime)
    print(commit.summary)
    print(commit.author)
    print(commit.message)

(GitPython 3.1.18)

Get List of Staged Files

from git import Repo
git_repo = Repo('repo_directory')
staged_files [ item.a_path for item in git_repo.index.diff(git_repo.head.commit) ]

(GitPython 3.1.18)

Get Diff as String

from git import Repo
git_repo = Repo('repo_directory')
diff = git_repo.git.diff(git_repo.head.commit.tree)
print(diff)

(GitPython 3.1.18)