Refactored get tag or hash to work as the bash version

master
oGre 10 years ago
parent dd324dcdb2
commit 1170818d04
  1. 68
      gitstatus.py

@ -1,35 +1,32 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 -*- # -*- coding: UTF-8 -*-
"""This module defines a Print function to use with python 2.x or 3.x., so we can use the prompt with older versions of Python too """This module defines a Print function to use with python 2.x or 3.x., so we can use the prompt with older versions of
Python too
It's interface is that of python 3.0's print. See It's interface is that of python 3.0's print. See
http://docs.python.org/3.0/library/functions.html?highlight=print#print http://docs.python.org/3.0/library/functions.html?highlight=print#print
Shamelessly ripped from http://www.daniweb.com/software-development/python/code/217214/a-print-function-for-different-versions-of-python Shamelessly ripped from
http://www.daniweb.com/software-development/python/code/217214/a-print-function-for-different-versions-of-python
""" """
# change those symbols to whatever you prefer # change those symbols to whatever you prefer
symbols = {'ahead of': '↑·', 'behind': '↓·', 'prehash': ':'} symbols = {'ahead of': '↑·', 'behind': '↓·', 'prehash': ':'}
import sys import sys
import re import re
import shlex from subprocess import Popen, PIPE
from subprocess import Popen, PIPE, check_output
__all__ = ["Print"] __all__ = ["Print"]
try: try:
Print = eval("print") # python 3.0 case Print = eval("print") # python 3.0 case
except SyntaxError: except SyntaxError:
D = dict()
try: try:
D = dict()
exec ("from __future__ import print_function\np=print", D) exec ("from __future__ import print_function\np=print", D)
Print = D["p"] # 2.6 case Print = D["p"] # 2.6 case
del D
except SyntaxError: except SyntaxError:
del D
def Print(*args, **kwd): # 2.4, 2.5, define our own Print function def Print(*args, **kwd): # 2.4, 2.5, define our own Print function
fout = kwd.get("file", sys.stdout) fout = kwd.get("file", sys.stdout)
w = fout.write w = fout.write
@ -40,36 +37,31 @@ except SyntaxError:
w(sep) w(sep)
w(str(a)) w(str(a))
w(kwd.get("end", "\n")) w(kwd.get("end", "\n"))
finally:
del D
def get_tagname_or_hash(): def get_tag_or_hash():
"""return tagname if exists else hash""" cmd = Popen(['git', 'describe', '--exact-match'], stdout=PIPE, stderr=PIPE)
cmd = 'git log -1 --format="%h%d"' so, se = cmd.communicate()
output = check_output(shlex.split(cmd)).decode('utf-8').strip() tag = '%s' % so.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: if tag:
return tagname return tag
elif hash_: else:
return hash_ cmd = Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=PIPE, stderr=PIPE)
return None so, se = cmd.communicate()
hash_name = '%s' % so.decode('utf-8').strip()
return symbols['prehash'] + hash_name
def get_stash(): def get_stash():
cmd = Popen(['git', 'rev-parse', '--git-dir'], stdout=PIPE, stderr=PIPE) cmd = Popen(['git', 'rev-parse', '--git-dir'], stdout=PIPE, stderr=PIPE)
so, se = cmd.communicate() so, se = cmd.communicate()
stashFile = '%s%s' % (so.decode('utf-8').rstrip(), '/logs/refs/stash') stash_file = '%s%s' % (so.decode('utf-8').rstrip(), '/logs/refs/stash')
try: try:
with open(stashFile) as f: with open(stash_file) as f:
return sum(1 for _ in f) return sum(1 for _ in f)
except IOError: except IOError:
return 0 return 0
@ -85,7 +77,9 @@ if po.returncode != 0:
# collect git status information # collect git status information
untracked, staged, changed, conflicts = [], [], [], [] untracked, staged, changed, conflicts = [], [], [], []
ahead, behind = 0, 0 num_ahead, num_behind = 0, 0
ahead, behind = '', ''
branch = ''
remote = '' remote = ''
status = [(line[0], line[1], line[2:]) for line in stdout.decode('utf-8').splitlines()] status = [(line[0], line[1], line[2:]) for line in stdout.decode('utf-8').splitlines()]
for st in status: for st in status:
@ -93,7 +87,7 @@ for st in status:
if re.search('Initial commit on', st[2]): if re.search('Initial commit on', st[2]):
branch = st[2].split(' ')[-1] branch = st[2].split(' ')[-1]
elif re.search('no branch', st[2]): # detached status elif re.search('no branch', st[2]): # detached status
branch = get_tagname_or_hash() branch = get_tag_or_hash()
elif len(st[2].strip().split('...')) == 1: elif len(st[2].strip().split('...')) == 1:
branch = st[2].strip() branch = st[2].strip()
else: else:
@ -108,11 +102,15 @@ for st in status:
divergence = divergence.lstrip('[').rstrip(']') divergence = divergence.lstrip('[').rstrip(']')
for div in divergence.split(', '): for div in divergence.split(', '):
if 'ahead' in div: if 'ahead' in div:
ahead = int(div[len('ahead '):].strip()) num_ahead = int(div[len('ahead '):].strip())
remote += '%s%s' % (symbols['ahead of'], ahead) ahead = '%s%s' % (symbols['ahead of'], num_ahead)
elif 'behind' in div: elif 'behind' in div:
behind = int(div[len('behind '):].strip()) num_behind = int(div[len('behind '):].strip())
remote += '%s%s' % (symbols['behind'], behind) behind = '%s%s' % (symbols['behind'], num_behind)
remote = ''.join([
behind,
ahead
])
elif st[0] == '?' and st[1] == '?': elif st[0] == '?' and st[1] == '?':
untracked.append(st) untracked.append(st)
else: else:

Loading…
Cancel
Save