import os
from subprocess import Popen, PIPE
import re

from path import path


class GitError(Exception):
    pass


class GitUtil(object):
    def __init__(self, root_path='.'):
        self.root_path = path(root_path)
        if root_path is None:
            dir_node = path(os.getcwd())
            while not dir_node.dirs('.git') and dir_node:
                dir_node = dir_node.parent
            if not dir_node:
                raise GitError('No git root found.')
            self.root_path = dir_node
        assert(self.root_path.dirs('.git'))


    def command(self, x):
        try:
            x.__iter__
        except:
            x = re.split(r'\s+', x)
        cwd = os.getcwd()

        os.chdir(self.root_path)
        cmd = ['git'] + x
        stdout, stderr = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE).communicate()
        os.chdir(cwd)

        if stderr:
            raise GitError('Error executing git %s' % x)
        return stdout.strip()


    def describe(self):
        return self.command('describe')


    def summary(self, color=False):
        if color:
            format_ = '''--pretty=format:%Cred%h%Creset - %s %Cgreen(%cr)%Creset'''
        else:
            format_ = '''--pretty=format:%h - %s (%cr)'''
        return self.command(['''log''', '''--graph''', format_,
                    '''--abbrev-commit''', '''--date=relative'''])


    def rev_parse(self, ref='HEAD'):
        return self.command(['rev-parse', ref])


    def show(self, ref='HEAD', color=False, extra_args=None):
        extra_args = [extra_args, []][extra_args is None]
        args = ['show', ref]
        if color:
            args += ['--color']
        return self.command(args + extra_args)

@@ -37,17 +37,49 @@
 en, PIPE
+, check_call, CalledProcessError
 %0A
-
 import r
@@ -538,16 +538,41 @@
 ir_node%0A
+        self._git = None%0A
         
@@ -605,24 +605,754 @@
 ('.git'))%0A%0A%0A
+    @property%0A    def git(self):%0A        if self._git:%0A            return self._git%0A%0A        cmds = %5B'git'%5D%0A        if os.name == 'nt':%0A            exceptions = (WindowsError,)%0A            cmds += %5B'git.cmd'%5D%0A        else:%0A            exceptions = (OSError,)%0A%0A        valid_cmd = False%0A        for cmd in cmds:%0A            try:%0A                check_call(%5Bcmd%5D, stdout=PIPE, stderr=PIPE)%0A            except exceptions:%0A                # The command was not found, try the next one%0A                pass%0A            except CalledProcessError:%0A                valid_cmd = True%0A                break%0A        if not valid_cmd:%0A            raise GitError, 'No valid git command found'%0A        self._git = cmd%0A        return self._git%0A%0A%0A
     def comm
@@ -1528,21 +1528,24 @@
  cmd = %5B
-'
+self.
 git
-'
 %5D + x%0A  

Modify git_util to check for git.cmd on Windows