#!/usr/bin/env python

import os
import sys
from pprint import pprint
from collections import OrderedDict

cwd = os.getcwd()

skips = (
    'On branch',
    'HEAD detached',
    'Your branch is up-to-date',
    'nothing to commit, working directory clean',
)
fetches = (
    'Your branch is ahead',
    'Your branch is behind',
)

def check(dir):
    os.chdir(dir)
    status = check_status()
    if status is None:
        return
    if status.startswith(fetches):
        #os.system('git fetch --quiet')
        status = check_status()
        if status is None:
            return
    return status

def check_status():
    status = None
    for line in os.popen('git status').readlines():
        status = line.strip()
        if status and not status.startswith(skips):
            return status.strip('.,:')
    return None

endcolors = '\033[0m'
termcolors = {
    'blue':     '\033[94m',
    'yellow':   '\033[93m',
    'green':    '\033[92m',
    'end':      '\033[0m',
}

def colored(str, color):
    if sys.stdout.isatty():
        return termcolors[color] + str + endcolors
    return str

def tprint(str):
    if sys.stdout.isatty():
        print(str),

def run():
    prev = 'Finding gits... '
    tprint(prev)
    sys.stdout.flush()
    raws = os.popen('find . -name .git').readlines()
    dirs = sorted(raws)
    stats = OrderedDict()
    for dir in dirs:
        dir = cwd + '/' + dir[2:-6]
        tprint('\r')
        tprint(dir.ljust(len(prev)))
        prev = dir
        status = check(dir)
        if status:
            stats[dir] = status
    tprint('\r')
    max = 1
    for dir in stats:
        if len(dir)>max:
            max = len(dir)
    for dir in stats:
        print("{dir} - {status}".format(status=colored(stats[dir], 'yellow'), dir=dir.ljust(max)))

run()
