-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgit_prompt.py
executable file
·99 lines (78 loc) · 2.02 KB
/
git_prompt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3
"""
git-prompt
Ole Martin Bjorndalen
https://github.com/olemb/git-prompt
License: MIT
"""
#
# To use just add $(git-prompt.py) to PS1, for example.
#
# PS1='\u@\h:\w $(git-prompt.py)$ '
#
import os
def get_status():
return list(os.popen('git status --porcelain=v2 --branch 2>/dev/null'))
def parse_status(lines):
oid = ''
head = ''
status = {
'ahead': False,
'behind': False,
'untracked': False,
'conflict': False,
'changed': False,
}
for line in lines:
char = line[:1]
if char == '#':
_, name, *args = line.split()
if name == 'branch.oid':
oid = args[0]
elif name == 'branch.head':
head = args[0]
elif name == 'branch.ab':
status['ahead'] = args[0] != '+0'
status['behind'] = args[1] != '-0'
elif char == '?':
status['untracked'] = True
elif char == 'u':
status['conflict'] = True
elif char.isdigit():
status['changed'] = True
if oid == '(initial)':
branch = ':initial'
elif head == '(detached)':
branch = ':' + oid[:6]
else:
branch = head
return branch, status
def format_status(branch, status):
green = '92'
yellow = '93'
red = '31'
flags = ''
color = green
if status['changed']:
flags += '*'
color = yellow
if status['untracked']:
flags += '?'
color = yellow
if status['conflict']:
flags += '!'
color = red
if status['ahead'] and status['behind']:
flags += '↕'
elif status['ahead']:
flags += '↑'
elif status['behind']:
flags += '↓'
if flags != '':
flags = ' ' + flags
return f'\033[{color}m[{branch}{flags}]\033[0m'
if __name__ == '__main__':
lines = get_status()
if lines != []:
branch, status = parse_status(lines)
print(format_status(branch, status), end='')