gitstatus.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. # change this symbol to whatever you prefer
  4. prehash = ':'
  5. import sys
  6. from subprocess import Popen, PIPE
  7. # `git status --porcelain -b` can collect all information
  8. # branch, remote_branch, untracked, staged, changed, conflicts, ahead, behind
  9. po = Popen(['git', 'status', '--porcelain', '-b'], stdout=PIPE, stderr=PIPE)
  10. stdout, sterr = po.communicate()
  11. if po.returncode != 0:
  12. sys.exit(0) # Not a git repository
  13. # collect git status information
  14. untracked, staged, changed, conflicts = [], [], [], []
  15. ahead, behind = 0, 0
  16. status = [(line[0], line[1], line[2:]) for line in stdout.splitlines()]
  17. for st in status:
  18. if st[0] == '#' and st[1] == '#':
  19. if len(st[2].strip().split('...')) == 1:
  20. branch = st[2].strip()
  21. else:
  22. # current and remote branch info
  23. branch, rest = st[2].strip().split('...')
  24. if len(rest.split(' ')) == 1:
  25. # remote_branch = rest.split(' ')[0]
  26. pass
  27. else:
  28. # ahead or behind
  29. divergence = ' '.join(rest.split(' ')[1:])
  30. divergence = divergence.lstrip('[').rstrip(']')
  31. for div in divergence.split(', '):
  32. if 'ahead' in div:
  33. ahead = int(div[len('ahead '):].strip())
  34. elif 'behind' in div:
  35. behind = int(div[len('behind '):].strip())
  36. elif st[0] == '?' and st[1] == '?':
  37. untracked.append(st)
  38. else:
  39. if st[1] == 'M':
  40. changed.append(st)
  41. if st[0] == 'U':
  42. conflicts.append(st)
  43. elif st[0] != ' ':
  44. staged.append(st)
  45. out = ' '.join([
  46. branch,
  47. str(ahead),
  48. str(behind),
  49. str(len(staged)),
  50. str(len(conflicts)),
  51. str(len(changed)),
  52. str(len(untracked)),
  53. ])
  54. print(out, end='')