Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import subprocess
  4. import sys
  5.  
  6. # Helper wrapper class around common git commands
  7. class Git:
  8. # Run single git command
  9. @staticmethod
  10. def git(cmd, args=[]):
  11. try:
  12. return subprocess.check_output(["git", cmd] + args)
  13. except:
  14. return None
  15.  
  16. @staticmethod
  17. def branches():
  18. return [line.strip() for line in Git.git("branch").splitlines()]
  19.  
  20. @staticmethod
  21. def current_branch():
  22. return next(b[2:] for b in Git.branches() if b.startswith("* "))
  23.  
  24. def colorprint(text, color, bold):
  25. attr = []
  26. if not sys.stdout.isatty():
  27. print text
  28. return
  29. elif color == "red":
  30. attr.append('31')
  31. elif color == "cyan":
  32. attr.append('36')
  33. else: # Green
  34. attr.append('32')
  35.  
  36. if bold:
  37. attr.append('1')
  38.  
  39. print '\x1b[%sm%s\x1b[0m' % (';'.join(attr), text)
  40.  
  41. def visit(branch, indent, all_branches, upstreams, current_branch):
  42. if branch == current_branch:
  43. colorprint("%s%s *" % (indent, branch), 'cyan', True)
  44. elif upstreams[branch] == None:
  45. colorprint("%s%s" % (indent, branch), 'red', True)
  46. else:
  47. colorprint("%s%s" % (indent, branch), 'green', False)
  48.  
  49. for child in [b for b in all_branches if upstreams[b] == branch]:
  50. visit(child, indent + " ", all_branches, upstreams, current_branch)
  51.  
  52. def main():
  53. verbose_branches = [line.strip() for line in Git.git("branch", ["-vv"]).splitlines()]
  54.  
  55. upstreams = {}
  56.  
  57. all_branches = set()
  58.  
  59. for verbose_branch in verbose_branches:
  60. verbose_branch_info = verbose_branch.split()
  61.  
  62. name_idx = 1 if verbose_branch_info[0] == "*" else 0
  63.  
  64. branch = verbose_branch_info[name_idx]
  65. upstream = verbose_branch_info[name_idx+2][1:-1]
  66.  
  67. all_branches.add(branch)
  68. all_branches.add(upstream)
  69.  
  70. # Create upstream mappings
  71. upstreams[branch] = upstream
  72. if upstream not in upstreams:
  73. upstreams[upstream] = None
  74.  
  75. current_branch = Git.current_branch()
  76.  
  77. rootlist = [branch for branch in all_branches if upstreams[branch] == None]
  78. for root in rootlist:
  79. visit(root, "", all_branches, upstreams, current_branch)
  80.  
  81. if __name__ == "__main__":
  82. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement