gitstatus.py 2.6 KB

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