How to use python to check whether there are unstaged/uncommitted change or unpushed commit in a git repo

How to use python to check whether there are unstaged/uncommitted change or unpushed commit in a git repo?

I only know the command line

git status would tell

  • unstaged change
  • uncommitted stage
  • also whether current branch commit behind the remote or not

If I provide a root path such as (“C:/ProgramFiles”) to the function, It will be better if the code could give a list, where each element is the

(path of this repos found under the root path, Unstaged/uncommited changes, Untracked files: , Latest commit is pushed)

Answer

You can use the GitPython package to help.

pip install GitPython

Then this script can give you a starting point:

from git import Repo

repo = Repo('.')

print(f"Unstaged/uncommited changes: {repo.is_dirty()}")
print(f"Untracked files: {len(repo.untracked_files)}")

remote = repo.remote('origin')
remote.fetch()
latest_remote_commit = remote.refs[repo.active_branch.name].commit
latest_local_commit = repo.head.commit

print(f"Latest commit is pushed: {latest_local_commit == latest_remote_commit}")