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

4
import sys
5
import re
6
import shlex
Marc Cornellà's avatar
Marc Cornellà committed
7
from subprocess import Popen, PIPE, check_output
8
9


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def get_tagname_or_hash():
    """return tagname if exists else hash"""
    cmd = 'git log -1 --format="%h%d"'
    output = check_output(shlex.split(cmd)).decode('utf-8').strip()
    hash_, tagname = None, None
    # get hash
    m = re.search('\(.*\)$', output)
    if m:
        hash_ = output[:m.start()-1]
    # get tagname
    m = re.search('tag: .*[,\)]', output)
    if m:
        tagname = 'tags/' + output[m.start()+len('tag: '): m.end()-1]

    if tagname:
        return tagname
    elif hash_:
        return hash_
    return None


Marc Cornellà's avatar
Marc Cornellà committed
31
# `git status --porcelain --branch` can collect all information
32
# branch, remote_branch, untracked, staged, changed, conflicts, ahead, behind
Marc Cornellà's avatar
Marc Cornellà committed
33
po = Popen(['git', 'status', '--porcelain', '--branch'], stdout=PIPE, stderr=PIPE)
34
35
36
stdout, sterr = po.communicate()
if po.returncode != 0:
    sys.exit(0)  # Not a git repository
37

38
# collect git status information
39
untracked, staged, changed, conflicts = [], [], [], []
40
ahead, behind = 0, 0
41
status = [(line[0], line[1], line[2:]) for line in stdout.decode('utf-8').splitlines()]
42
for st in status:
43
    if st[0] == '#' and st[1] == '#':
44
45
        if re.search('Initial commit on', st[2]):
            branch = st[2].split(' ')[-1]
46
47
        elif re.search('no branch', st[2]):  # detached status
            branch = get_tagname_or_hash()
48
        elif len(st[2].strip().split('...')) == 1:
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
            branch = st[2].strip()
        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] == '?':
66
67
68
69
70
71
72
73
        untracked.append(st)
    else:
        if st[1] == 'M':
            changed.append(st)
        if st[0] == 'U':
            conflicts.append(st)
        elif st[0] != ' ':
            staged.append(st)
74

75
out = ' '.join([
76
77
78
79
80
81
82
83
    branch,
    str(ahead),
    str(behind),
    str(len(staged)),
    str(len(conflicts)),
    str(len(changed)),
    str(len(untracked)),
])
84
print(out, end='')