gitstatus.py 2.2 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
import subprocess
9
from subprocess import Popen, PIPE
10

11
branch, error = Popen(['git', 'symbolic-ref', 'HEAD'], stdout=PIPE, stderr=PIPE).communicate()
12

13
if 'fatal: Not a git repository' in error.decode('utf-8'):
14
    sys.exit(0)
15

16
branch = branch.decode("utf-8").strip()[11:]
17

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Get git status (staged, change, conflicts and untracked)
try:
    res = subprocess.check_output(['git', 'status', '--porcelain'])
except subprocess.CalledProcessError:
    sys.exit(0)
status = [(st[0], st[1], st[2:]) for st in res.splitlines()]
untracked, staged, changed, conflicts = [], [], [], []
for st in status:
    if st[0] == '?' and st[1] == '?':
        untracked.append(st)
    else:
        if st[1] == 'M':
            changed.append(st)
        if st[0] == 'U':
            conflicts.append(st)
        elif st[0] != ' ':
            staged.append(st)
35

36
ahead, behind = 0,0
37

38
if not branch: # not on any branch
39
    branch = prehash + Popen(['git','rev-parse','--short','HEAD'], stdout=PIPE).communicate()[0].decode("utf-8")[:-1]
40
else:
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    remote_name = Popen(['git','config','branch.%s.remote' % branch], stdout=PIPE).communicate()[0].decode("utf-8").strip()
    if remote_name:
        merge_name = Popen(['git','config','branch.%s.merge' % branch], stdout=PIPE).communicate()[0].decode("utf-8").strip()
        if remote_name == '.': # local
            remote_ref = merge_name
        else:
            remote_ref = 'refs/remotes/%s/%s' % (remote_name, merge_name[11:])
        revgit = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % remote_ref],stdout=PIPE, stderr=PIPE)
        revlist = revgit.communicate()[0]
        if revgit.poll(): # fallback to local
            revlist = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % merge_name],stdout=PIPE, stderr=PIPE).communicate()[0]
        behead = revlist.decode("utf-8").splitlines()
        ahead = len([x for x in behead if x[0]=='>'])
        behind = len(behead) - ahead
55
56

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