#!/usr/bin/python

import docopt
from whelk import Shell
import sys

usage = """git delete-merged-branches
Delete merged branches, either remote or locally

Usage:
    git delete-merged-branches [--noop] [--remote=REMOTE] [<branch>]
"""

# Make sure we exit when a git command fails
def check(cmd, sp, res):
    if not res:
        if res.stderr:
            sys.stderr.write(res.stderr)
        sys.exit(res.returncode)
shell = Shell(exit_callback=check)

def main():
    sys.argv.insert(1, 'delete-merged-branches')
    opts = docopt.docopt(usage)
    shell.git('rev-parse')

    dest = opts['<branch>'] or 'HEAD'
    dest = shell.git('rev-parse', '--symbolic-full-name', dest).stdout.strip()
    dest_sha = shell.git('rev-parse', dest).stdout.strip()
    base = 'refs/heads'
    if opts['--remote']:
        base = 'refs/remotes/%s' % opts['--remote']
        # Make sure we're up to date with what the remote actually has
        shell.git('fetch', opts['--remote'])
    refs = shell.git('for-each-ref', '--merged', dest, base).stdout.splitlines()
    refs = [ref.split(None, 2) for ref in refs]

    to_delete = []
    for oid, reftype, refname in refs:
        if oid == dest_sha or refname == dest:
            # As a precaution, don't delete branches that point to the current commit
            continue
        if opts['--noop']:
            print("Would delete %s" % refname)
        elif opts['--remote']:
            ref = refname.replace('refs/remotes/%s/' % opts['--remote'], 'refs/heads/')
            to_delete.append(ref)
        else:
            branch = refname.replace('refs/heads/', '')
            to_delete.append(branch)

    if to_delete and not opts['--noop']:
        kwargs = {'redirect': False}
        if opts['--remote']:
            shell.git('push', opts['--remote'], '--delete', *to_delete, **kwargs)
        else:
            shell.git('branch', '-d', *to_delete, **kwargs)

if __name__ == '__main__':
    main()
