Instantly share code, notes, and snippets.

Embed
What would you like to do?
GitHub-like commit differences
#!/usr/bin/env python
"""
Checks the commit difference between current branch and target branch
a la GitHub.
Usage:
$ git cdiff upstream/master
This branch is 5 commits ahead, 10 commits behind upstream/master.
Installation:
- Make executable: chmod 755 git-cdiff
- Make accessible in path
"""
import subprocess
import sys
class GitException(Exception):
pass
def commit_diff(target):
cmd = ['git', '--no-pager', 'log', '--oneline', target]
process = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
std_out, std_err = process.communicate()
if std_err:
raise GitException(std_err.strip())
else:
return len(std_out.strip().splitlines())
if __name__ == '__main__':
try:
branch = sys.argv[1]
print("This branch is {} commits ahead, {} commits behind {}".format(
commit_diff('{}..'.format(branch)),
commit_diff('..{}'.format(branch)),
branch))
except IndexError:
print('Target branch name required')
exit(1)
except GitException as e:
print(e.message)
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment