import re
import subprocess

def get_git_status():
    has_pending_commits = True
    has_untracked_files = False
    origin_position = ""
    output = subprocess.Popen(['git', 'status', '--ignore-submodules'],
            stdout=subprocess.PIPE).communicate()[0]
    for line in output.split('\n'):
        origin_status = re.findall(
                r"Your branch is (ahead|behind).*?(\d+) comm", line)
        if origin_status:
            origin_position = " %d" % int(origin_status[0][1])
            if origin_status[0][0] == 'behind':
                origin_position += u'\u21E3'
            if origin_status[0][0] == 'ahead':
                origin_position += u'\u21E1'

        if line.find('nothing to commit') >= 0:
            has_pending_commits = False
        if line.find('Untracked files') >= 0:
            has_untracked_files = True
    return has_pending_commits, has_untracked_files, origin_position


def add_git_segment():
    #cmd = "git branch 2> /dev/null | grep -e '\\*'"
    p1 = subprocess.Popen(['git', 'branch', '--no-color'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p2 = subprocess.Popen(['grep', '-e', '\\*'], stdin=p1.stdout, stdout=subprocess.PIPE)
    output = p2.communicate()[0].strip()
    if not output:
        return

    branch = output.rstrip()[2:]
    has_pending_commits, has_untracked_files, origin_position = get_git_status()
    branch += origin_position
    if has_untracked_files:
        branch += ' +'

    bg = Color.REPO_CLEAN_BG
    fg = Color.REPO_CLEAN_FG
    if has_pending_commits:
        bg = Color.REPO_DIRTY_BG
        fg = Color.REPO_DIRTY_FG

    powerline.append(' %s ' % branch, fg, bg)

try:
    add_git_segment()
except OSError:
    pass
except subprocess.CalledProcessError:
    pass

@@ -204,16 +204,34 @@
 ules'%5D,%0A
+                  
         
@@ -347,20 +347,16 @@
 indall(%0A
-    
         
@@ -963,62 +963,101 @@
    #
-cmd = %22git branch 2%3E /dev/null %7C grep -e '%5C%5C*'%22
+ See http://git-blame.blogspot.com/2013/06/checking-current-branch-programatically.html
 %0A    p
-1
  = s
@@ -1085,28 +1085,34 @@
 ', '
-branch', '--no-color
+symbolic-ref', '-q', 'HEAD
 '%5D, 
@@ -1167,109 +1167,20 @@
     
-p2 = subprocess.Popen(%5B'grep', '-e', '%5C%5C*'%5D, stdin=p1.stdout, stdout=subprocess.PIPE)%0A    output
+out, err
  = p
-2
 .com
@@ -1193,27 +1193,17 @@
 te()
-%5B0%5D.strip()
+%0A
 %0A    if 
 not 
@@ -1202,18 +1202,31 @@
  if 
-not output
+'Not a git repo' in err
 :%0A  
@@ -1247,36 +1247,107 @@
     
-branch = output.rstrip()%5B2:%5D
+if out:%0A        branch = out%5Blen('refs/heads/'):%5D.rstrip()%0A    else:%0A        branch = '(Detached)'%0A
 %0A   

Make git segment faster