#!/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.

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()

    if ARGS.steps == '-':
        steps = -1
    elif ARGS.steps == '+':
        steps = 1
    else:
        try:
            steps = int(ARGS.steps)
        except ValueError:
            PROGRAM.exit('steps must be an integer, not', ARGS.steps)

    branches = functions.branches()
    pos = branches.index(functions.branch_name()) + steps
    branch = branches[pos % len(branches)]

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


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


_HELP_STEPS = 'Number of steps to rotate (positive or negative)'

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