#!/usr/bin/env python3
from gitz.git import GIT
from gitz.git import functions
from gitz.git import root
from gitz.program import ARGS
from gitz.program import PROGRAM

SUMMARY = 'Rotate through branches in a Git repository'

HELP = """
Move through the branches in a Git repository in the order
given by the `git branch` command, wrapping around at the end.

If N is a number, ``git-rotate N`` rotates N branches forward,
and ``git-rotate -N`` rotates N branches backward.

``git-rotate`` on its own rotates one branch forward, and
``git-rotate -`` rotates one branch backward.

If N is a string, ``git-rotate <prefix>`` rotates through all branches
starting with that string.

``git-rotate ma`` will rotate through all branches starting with ma


Useful for quickly browsing each branch in a repository one at a time.
"""

EXAMPLES = """
git rotate
git rotate 1
git rotate +
    Rotates to the next branch

git rotate 3
git rotate +3
    Rotates 3 branches ahead

git rotate -1
git rotate -
    Rotates 1 branch backward

git rotate -2
    Rotates 2 branches backward
"""


def git_rot():
    root.check_clean_workspace()

    rotate = ARGS.rotate
    if rotate == '-':
        rotate = -1
    elif rotate == '+':
        rotate = 1

    try:
        rotate = int(rotate)
    except ValueError:
        pass

    branches = functions.branches()
    index = branches.index(functions.branch_name())

    def offset(i):
        return branches[(index + i) % len(branches)]

    if isinstance(rotate, int):
        branch = offset(rotate)

    else:
        for i in range(1, 1 + len(branches)):
            branch = offset(i)
            if branch.startswith(rotate):
                break
        else:
            PROGRAM.exit('No branches starting with', rotate)

    for line in GIT.checkout(branch, merged=True):
        PROGRAM.message(line)


def add_arguments(parser):
    parser.add_argument('rotate', nargs='?', default='1', help=_HELP_ROTATE)


_HELP_ROTATE = """
Number of steps to rotate (positive or negative), or a string prefix
to match.
"""

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