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

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


10
11
12
def get_tagname_or_hash():
    """return tagname if exists else hash"""
    # get hash
13
    hash_cmd = ['git', 'rev-parse', '--short', 'HEAD']
14
    hash_ = check_output(hash_cmd).decode('utf-8').strip()
15

16
    # get tagname
17
    tags_cmd = ['git', 'for-each-ref', '--points-at=HEAD', '--count=2', '--sort=-version:refname', '--format=%(refname:short)', 'refs/tags']
18
    tags = check_output(tags_cmd).decode('utf-8').split()
19

20
21
    if tags:
        return tags[0] + ('+' if len(tags) > 1 else '')
22
23
24
25
    elif hash_:
        return hash_
    return None

26
27
28
29
30
31
32
33
34
35
36
37
# Re-use method from https://github.com/magicmonty/bash-git-prompt to get stashs count
def get_stash():
    cmd = Popen(['git', 'rev-parse', '--git-dir'], stdout=PIPE, stderr=PIPE)
    so, se = cmd.communicate()
    stash_file = '%s%s' % (so.decode('utf-8').rstrip(), '/logs/refs/stash')

    try:
        with open(stash_file) as f:
            return sum(1 for _ in f)
    except IOError:
        return 0

38

Marc Cornellà's avatar
Marc Cornellà committed
39
# `git status --porcelain --branch` can collect all information
40
# branch, remote_branch, untracked, staged, changed, conflicts, ahead, behind
41
po = Popen(['git', 'status', '--porcelain', '--branch'], env=dict(os.environ, LANG="C"), stdout=PIPE, stderr=PIPE)
42
43
44
stdout, sterr = po.communicate()
if po.returncode != 0:
    sys.exit(0)  # Not a git repository
45

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

83
84
85
86
87
88
stashed = get_stash()
if not changed and not staged and not conflicts and not untracked and not stashed:
    clean = 1
else:
    clean = 0

89
out = ' '.join([
90
91
92
93
94
95
96
    branch,
    str(ahead),
    str(behind),
    str(len(staged)),
    str(len(conflicts)),
    str(len(changed)),
    str(len(untracked)),
97
98
    str(stashed),
    str(clean)
99
])
100
print(out, end='')