Debian Codegraph @

misc/branches-tidy

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # FIXME: pretty colors?
4
5 import argparse
6 import collections
7 import re
8 import subprocess
9
10 class Branch:
11 __slots__ = ("local", "repo", "remote", "status")
12
13 def __str__(self):
14 s = self.local
15 if (self.remote is not None):
16 s += " → "
17 if (self.repo == repo_max and self.remote == self.local):
18 s += "•"
19 else:
20 s += "%s/%s" % (self.repo, self.remote)
21 if (self.status is not None):
22 s += " [%s]" % self.status
23 return s
24
25 def delete(name):
26 subprocess.run(["git", "branch", "-qD", name], check=True)
27
28 # globals
29 remote_dangling = set()
30 remote_matched = set()
31 other = set()
32 repos = collections.Counter()
33 repo_max = None
34 delete_ct = 0
35
36 p = argparse.ArgumentParser(
37 description = "List summary of Git branches.",
38 epilog = "Dot (•) indicates branch tracks a remote with same name.")
39 p.add_argument("-d", "--delete",
40 action="store_true",
41 help="delete dangling branches (remote branch missing)")
42 p.add_argument("-r", "--delete-remote",
43 metavar="REMOTE",
44 action="append", default=list(),
45 help="delete branches pointing to REMOTE (can be repeated)")
46 args = p.parse_args()
47
48 cp = subprocess.run(["git", "branch", "--format",
49 "%(refname:short) %(upstream:short) %(upstream:track)"],
50 stdout=subprocess.PIPE, encoding="UTF-8", check=True)
51 for m in re.finditer(r"^(\S+)\s((\S+)/(\S+))?\s(\[(.+)\])?$",
52 cp.stdout, re.MULTILINE):
53 b = Branch()
54 b.local = m[1]
55 b.repo = m[3]
56 b.remote = m[4]
57 b.status = m[6]
58 if (b.remote is None):
59 other.add(b)
60 else:
61 repos[b.repo] += 1
62 if (b.status == "gone"):
63 remote_dangling.add(b)
64 else:
65 remote_matched.add(b)
66
67 assert( len(cp.stdout.splitlines())
68 == len(other) + len(remote_matched) + len(remote_dangling))
69
70 (repo_max, repo_max_ct) = repos.most_common(1)[0]
71 print("found %d repos; most common: %s (%d)"
72 % (len(repos), repo_max, repo_max_ct))
73
74 print("remote dangling (%d):" % len(remote_dangling))
75 for b in remote_dangling:
76 print(" %s" % b, end="")
77 if (args.delete):
78 delete(b.local)
79 delete_ct += 1
80 print(" ☠️", end="")
81 print()
82
83 print("remote (%d):" % len(remote_matched))
84 for b in remote_matched:
85 print(" %s" % b, end="")
86 if (b.repo in args.delete_remote):
87 delete(b.local)
88 delete_ct += 1
89 print(" ☠️", end="")
90 print()
91
92 print("other (%d):" % len(other))
93 for b in other:
94 print(" %s" % b)
95
96 if (delete_ct == 0):
97 print("say “--delete” to delete dangling branches")
98 else:
99 print("deleted %d branches" % delete_ct)