Skip to content

Instantly share code, notes, and snippets.

@chanux
Created August 11, 2017 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chanux/4cfbfcad73bcab284f94c26cec45c094 to your computer and use it in GitHub Desktop.
Save chanux/4cfbfcad73bcab284f94c26cec45c094 to your computer and use it in GitHub Desktop.
Quick glance in to the state of your git branches
#!/usr/bin/env python
"""
This script implements a git subcommand for viewing git branches with
a summary on how far behind/ahead each branch is compared to current branch.
copy the file to somewhere in the path as git-branches and make it executable
then you can use `git branches` to see summary of unmerged branches
`git brnaches -a` will give a summary of all branches
This is mostly a python port of similar ruby script by @sosedoff
http://sosedoff.com/2014/07/03/cleanup-git-branches.html
"""
from __future__ import print_function
from sys import argv, exit
import os
show_all = True if len(argv) == 2 and argv[1] in ['-a', '--all'] else False
def colorize(num, word):
if 0 <= num <= 5:
return '\x1b[32m{} {}\x1b[0m'.format(num, word)
elif 5 < num <= 15:
return '\x1b[33m{} {}\x1b[0m'.format(num, word)
else:
return '\x1b[31m{} {}\x1b[0m'.format(num, word)
current = os.popen('git rev-parse --abbrev-ref HEAD').read().strip()
_all= [x.replace('*', '').strip() for x in os.popen('git branch --list --no-color').read().strip().split("\n")]
merged = [x.replace('*', '').strip() for x in os.popen('git branch --merged')]
if not show_all:
_all = [b for b in _all if b not in merged]
if len(_all) == 0:
print('Nothing to compare..')
exit()
pad = max(len(s) for s in _all)
for br in _all:
behind = len(os.popen('git rev-list ' + br + '..' + current).read().splitlines())
ahead = len(os.popen('git rev-list ' + current + '..' + br).read().splitlines())
if br is not 'master':
print('{} - {}, {}'.format(br.rjust(pad), colorize(behind, "behind"), colorize(ahead, "ahead")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment