git-branchp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python3
  2. # vim: set noet sw=4 ts=4:
  3. import subprocess
  4. import sys
  5. def main():
  6. delete = len(sys.argv) == 2 and sys.argv[1] == '-d'
  7. remotes = all_remotes()
  8. to_delete = []
  9. print('will delete:')
  10. for local, remote in iter_locals():
  11. if remote not in remotes:
  12. to_delete.append(local)
  13. sys.stdout.buffer.write(b'\t' + local)
  14. print()
  15. if delete and len(to_delete) > 0:
  16. subprocess.run([b'git', b'branch', b'-D'] + to_delete, check=True)
  17. def all_remotes():
  18. refs = subprocess.run(['git', 'for-each-ref', '--format=%(refname:short)', 'refs/remotes'],
  19. capture_output=True, check=True)
  20. return frozenset(refs.stdout.rstrip(b'\n').split(b'\n'))
  21. def iter_locals():
  22. refs = subprocess.run(['git', 'for-each-ref', '--format=%(refname:short) %(upstream)', 'refs/heads'],
  23. capture_output=True, check=True)
  24. for line in refs.stdout.split(b'\n'):
  25. if not line:
  26. continue
  27. local, remote = line.split(b' ', 1)
  28. if not remote:
  29. continue
  30. assert remote.startswith(b'refs/remotes/')
  31. remote = remote.removeprefix(b'refs/remotes/')
  32. yield local, remote
  33. if __name__ == '__main__':
  34. main()