gitstatus.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import sys
  4. import re
  5. import shlex
  6. from subprocess import Popen, PIPE, check_output
  7. def get_tagname_or_hash():
  8. """return tagname if exists else hash"""
  9. cmd = 'git log -1 --format="%h%d"'
  10. output = check_output(shlex.split(cmd)).decode('utf-8').strip()
  11. hash_, tagname = None, None
  12. # get hash
  13. m = re.search('\(.*\)$', output)
  14. if m:
  15. hash_ = output[:m.start()-1]
  16. # get tagname
  17. m = re.search('tag: .*[,\)]', output)
  18. if m:
  19. tagname = 'tags/' + output[m.start()+len('tag: '): m.end()-1]
  20. if tagname:
  21. return tagname
  22. elif hash_:
  23. return hash_
  24. return None
  25. # `git status --porcelain --branch` can collect all information
  26. # branch, remote_branch, untracked, staged, changed, conflicts, ahead, behind
  27. po = Popen(['git', 'status', '--porcelain', '--branch'], stdout=PIPE, stderr=PIPE)
  28. stdout, sterr = po.communicate()
  29. if po.returncode != 0:
  30. sys.exit(0) # Not a git repository
  31. # collect git status information
  32. untracked, staged, changed, conflicts = [], [], [], []
  33. ahead, behind = 0, 0
  34. status = [(line[0], line[1], line[2:]) for line in stdout.decode('utf-8').splitlines()]
  35. for st in status:
  36. if st[0] == '#' and st[1] == '#':
  37. if re.search('Initial commit on', st[2]):
  38. branch = st[2].split(' ')[-1]
  39. elif re.search('no branch', st[2]): # detached status
  40. branch = get_tagname_or_hash()
  41. elif len(st[2].strip().split('...')) == 1:
  42. branch = st[2].strip()
  43. else:
  44. # current and remote branch info
  45. branch, rest = st[2].strip().split('...')
  46. if len(rest.split(' ')) == 1:
  47. # remote_branch = rest.split(' ')[0]
  48. pass
  49. else:
  50. # ahead or behind
  51. divergence = ' '.join(rest.split(' ')[1:])
  52. divergence = divergence.lstrip('[').rstrip(']')
  53. for div in divergence.split(', '):
  54. if 'ahead' in div:
  55. ahead = int(div[len('ahead '):].strip())
  56. elif 'behind' in div:
  57. behind = int(div[len('behind '):].strip())
  58. elif st[0] == '?' and st[1] == '?':
  59. untracked.append(st)
  60. else:
  61. if st[1] == 'M':
  62. changed.append(st)
  63. if st[0] == 'U':
  64. conflicts.append(st)
  65. elif st[0] != ' ':
  66. staged.append(st)
  67. out = ' '.join([
  68. branch,
  69. str(ahead),
  70. str(behind),
  71. str(len(staged)),
  72. str(len(conflicts)),
  73. str(len(changed)),
  74. str(len(untracked)),
  75. ])
  76. print(out, end='')