#!/code/env/gitz-test/bin/python
from gitz import delete
from gitz import git_functions
from gitz import git_root
from gitz.env import ENV
from gitz.program import PROGRAM
from gitz.runner import GIT

SUMMARY = 'Delete one or more branches locally and remotely'

DANGER = 'Deletes remote branches!'

HELP = """
Delete each branch specified together with its remote branch.

By default, branches named `master` and `develop` are protected,
which means they cannot be deleted, and the remote `upstream` is protected,
which means that no branches on that remote can be deleted.

Using the --all/-a flag allows protected branches and remotes
to be deleted.

It's also possible to change which branches or remotes are protected
by setting the environment variable GITZ_PROTECTED_BRANCHES or
GITZ_PROTECTED_REMOTES to a list separated by colons, or to an empty
string to turn off protection entirely.
"""

EXAMPLES = """
git delete foo bar
    Delete the branches foo and bar locally and remotely
"""

_HELP_FORCE = 'Delete all, even protected remotes or branches'


def git_delete():
    args = PROGRAM.args
    branch = git_functions.branch_name()
    branches = git_functions.branches()

    remaining_branches = set(branches).difference(args.target)
    if not remaining_branches:
        PROGRAM.exit('This would delete all the branches')

    if not args.force:
        protected = set(ENV.protected_branches()).intersection(args.target)
        if protected:
            PROGRAM.exit('Protected:', *protected)

    if branch not in remaining_branches:
        git_root.check_clean_workspace()
        for b in ENV.reference_branches():
            if b in remaining_branches:
                GIT.checkout(b, quiet=True)
                break
        else:
            GIT.checkout(min(remaining_branches), quiet=True)

    deleted = delete.delete(args.target)
    if deleted:
        s = '' if deleted == 1 else 'es'
        PROGRAM.message('git-delete: %d branch%s deleted' % (deleted, s))


def add_arguments(parser):
    parser.add_argument('target', nargs='+')
    parser.add_argument('-f', '--force', action='store_true', help=_HELP_FORCE)


if __name__ == '__main__':
    PROGRAM.start()
