#!/usr/bin/env python
#coding: utf-8

"""
This module provides utility functions for operate git.
"""

from subprocess import Popen

class GitError(BaseException):
    """
    This Error raises when git command runner has error.
    """

    pass

class GitUtility(object):
    """
    The GitUtility contains utility functions for operate git.
    """

    def __init__(self):

        return

    def run(self, cmd, *args):
        """
        This command is git command runner by subprocess.

        Return output or raise GitError if runner has error.
        """

        if len(args) == 0:
            command = ("git", cmd)

        elif isinstance(args[0], tuple):
            # Avoid duplicate tuple
            # ex. self.rev_parse("--show-toplevel")
            #   ->('git', 'rev-parse', ('--show-toplevel',))
            command = ("git", cmd) + tuple([arg for arg in args[0]])
        else:
            command = ("git", cmd) + args

        proc = Popen(command, stdin=-1,stdout=-1,stderr=-1)

        out, err = proc.communicate()

        if len(err) == 0:
            return out.strip()

        else:
            raise GitError(err.strip())

    def add(self, path):
        """
        Run git add command
        """

        self.run("add", path)

    def commit(self, commit_msg):
        """
        Run git commit
        """

        return self.run("commit", "-m", commit_msg)

    def rev_parse(self, *args):
        """
        Run git rev-parse command
        """
        return self.run("rev-parse", args)

    def get_toplevel(self):
        """
        Return git top level path using git rev-parse
        """

        return self.rev_parse("--show-toplevel")

