15

How can I use GitPython to determine whether:

  • My local branch is ahead of the remote (I can safely push)
  • My local branch is behind the remote (I can safely pull)
  • My local branch has diverged from the remote?

To check if the local and remote are the same, I'm doing this:

def local_and_remote_are_at_same_commit(repo, remote):
    local_commit = repo.commit()
    remote_commit = remote.fetch()[0].commit
    return local_commit.hexsha == remote_commit.hexsha
Lorin Hochstein
  • 57,372
  • 31
  • 105
  • 141
  • Possible duplicate of [How to get count of unpublished commit with GitPython?](https://stackoverflow.com/questions/15849640/how-to-get-count-of-unpublished-commit-with-gitpython) – Michael Dec 12 '18 at 15:46

2 Answers2

17

See https://stackoverflow.com/a/15862203/197789

E.g.

commits_behind = repo.iter_commits('master..origin/master')

and

commits_ahead = repo.iter_commits('origin/master..master')

Then you can use something like the following to go from iterator to a count:

count = sum(1 for c in commits_ahead)

(You may want to fetch from the remotes before running iter_commits, eg: repo.remotes.origin.fetch())

This was last checked with GitPython 1.0.2.

Voy
  • 5,286
  • 1
  • 49
  • 59
Von
  • 4,365
  • 2
  • 29
  • 29
  • 1
    With a branch that was 3 commits behind and 1 commit ahead, this gave me a sum of 4 for `len(list(commits_behind))` and `len(list(commits_ahead))` – Waldo Bronchart Apr 15 '21 at 02:03
2

The following worked better for me, which I got from this stackoverflow answer

commits_diff = repo.git.rev_list('--left-right', '--count', f'{branch}...{branch}@{{u}}')
num_ahead, num_behind = commits_diff.split('\t')
print(f'num_commits_ahead: {num_ahead}')
print(f'num_commits_behind: {num_behind}')
Waldo Bronchart
  • 10,152
  • 4
  • 23
  • 29