gitstatus.py 2.16 KB
Newer Older
1
#!/usr/bin/env python
2
from __future__ import print_function
3

4
5
# change this symbol to whatever you prefer
prehash = ':'
6

7
import sys
8
9
import re
import subprocess
10
from subprocess import Popen, PIPE
11
12


13
14
15
16
17
18
# `git status --porcelain -b` can collect all information
# branch, remote_branch, untracked, staged, changed, conflicts, ahead, behind
po = Popen(['git', 'status', '--porcelain', '-b'], stdout=PIPE, stderr=PIPE)
stdout, sterr = po.communicate()
if po.returncode != 0:
    sys.exit(0)  # Not a git repository
19

20
# collect git status information
21
untracked, staged, changed, conflicts = [], [], [], []
22
ahead, behind = 0, 0
23
status = [(line[0], line[1], line[2:]) for line in stdout.decode('utf-8').splitlines()]
24
for st in status:
25
    if st[0] == '#' and st[1] == '#':
26
27
28
        if re.search('Initial commit on', st[2]):
            branch = st[2].split(' ')[-1]
        elif len(st[2].strip().split('...')) == 1:
29
            branch = st[2].strip()
30
31
32
            if branch == 'HEAD (no branch)':
                cmd = ['git', 'log', '-1', '--format="%h"']
                branch = subprocess.check_output(cmd).strip().strip('"')
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
        else:
            # current and remote branch info
            branch, rest = st[2].strip().split('...')
            if len(rest.split(' ')) == 1:
                # remote_branch = rest.split(' ')[0]
                pass
            else:
                # ahead or behind
                divergence = ' '.join(rest.split(' ')[1:])
                divergence = divergence.lstrip('[').rstrip(']')
                for div in divergence.split(', '):
                    if 'ahead' in div:
                        ahead = int(div[len('ahead '):].strip())
                    elif 'behind' in div:
                        behind = int(div[len('behind '):].strip())
    elif st[0] == '?' and st[1] == '?':
49
50
51
52
53
54
55
56
        untracked.append(st)
    else:
        if st[1] == 'M':
            changed.append(st)
        if st[0] == 'U':
            conflicts.append(st)
        elif st[0] != ' ':
            staged.append(st)
57

58
out = ' '.join([
59
60
61
62
63
64
65
66
    branch,
    str(ahead),
    str(behind),
    str(len(staged)),
    str(len(conflicts)),
    str(len(changed)),
    str(len(untracked)),
])
67
print(out, end='')