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:
JavaScript
x
5
1
def local_and_remote_are_at_same_commit(repo, remote):
2
local_commit = repo.commit()
3
remote_commit = remote.fetch()[0].commit
4
return local_commit.hexsha == remote_commit.hexsha
5
Advertisement
Answer
See https://stackoverflow.com/a/15862203/197789
E.g.
JavaScript
1
2
1
commits_behind = repo.iter_commits('master..origin/master')
2
and
JavaScript
1
2
1
commits_ahead = repo.iter_commits('origin/master..master')
2
Then you can use something like the following to go from iterator to a count:
JavaScript
1
2
1
count = sum(1 for c in commits_ahead)
2
(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.