gitstatus.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. import subprocess
  7. from subprocess import Popen, PIPE
  8. branch, error = Popen(['git', 'symbolic-ref', 'HEAD'], stdout=PIPE, stderr=PIPE).communicate()
  9. if 'fatal: Not a git repository' in error.decode('utf-8'):
  10. sys.exit(0)
  11. branch = branch.decode("utf-8").strip()[11:]
  12. # Get git status (staged, change, conflicts and untracked)
  13. try:
  14. res = subprocess.check_output(['git', 'status', '--porcelain'])
  15. except subprocess.CalledProcessError:
  16. sys.exit(0)
  17. status = [(st[0], st[1], st[2:]) for st in res.splitlines()]
  18. untracked, staged, changed, conflicts = [], [], [], []
  19. for st in status:
  20. if st[0] == '?' and st[1] == '?':
  21. untracked.append(st)
  22. else:
  23. if st[1] == 'M':
  24. changed.append(st)
  25. if st[0] == 'U':
  26. conflicts.append(st)
  27. elif st[0] != ' ':
  28. staged.append(st)
  29. ahead, behind = 0,0
  30. if not branch: # not on any branch
  31. branch = prehash + Popen(['git','rev-parse','--short','HEAD'], stdout=PIPE).communicate()[0].decode("utf-8")[:-1]
  32. else:
  33. remote_name = Popen(['git','config','branch.%s.remote' % branch], stdout=PIPE).communicate()[0].decode("utf-8").strip()
  34. if remote_name:
  35. merge_name = Popen(['git','config','branch.%s.merge' % branch], stdout=PIPE).communicate()[0].decode("utf-8").strip()
  36. if remote_name == '.': # local
  37. remote_ref = merge_name
  38. else:
  39. remote_ref = 'refs/remotes/%s/%s' % (remote_name, merge_name[11:])
  40. revgit = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % remote_ref],stdout=PIPE, stderr=PIPE)
  41. revlist = revgit.communicate()[0]
  42. if revgit.poll(): # fallback to local
  43. revlist = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % merge_name],stdout=PIPE, stderr=PIPE).communicate()[0]
  44. behead = revlist.decode("utf-8").splitlines()
  45. ahead = len([x for x in behead if x[0]=='>'])
  46. behind = len(behead) - ahead
  47. out = ' '.join([
  48. branch,
  49. str(ahead),
  50. str(behind),
  51. str(len(staged)),
  52. str(len(conflicts)),
  53. str(len(changed)),
  54. str(len(untracked)),
  55. ])
  56. print(out, end='')