-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-clean-branches
executable file
·210 lines (153 loc) · 5.67 KB
/
git-clean-branches
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
import argparse
import os
import re
import sys
from subprocess import CalledProcessError, run, PIPE
from tempfile import NamedTemporaryFile
class Branch:
def __init__(self, branch, origins):
pat = r"^(\*?)\s*(.*?)\s+([0-9a-f]{7,9}) (?:\[((?:%s).*?)(: gone)?])?(.*?)" % "|".join(origins)
m = re.match(pat, branch)
remote = m.group(2).strip().startswith("remotes")
if remote:
self.local = None
self.remote = re.sub(r"remotes/", "", m.group(2).strip()) if m.group(2) else None
self.name = self.remote
self.tracking = False
else:
self.local = m.group(2).strip()
self.name = self.local
self.remote = m.group(4).strip() if m.group(4) else None
self.tracking = not bool(m.group(5))
self.current = bool(m.group(1))
self.commit = m.group(3).strip()
self.message = m.group(6).strip()
self.original = branch
def __str__(self):
return "Local: %s; Remote: %s; Commit: %s, Current: %s; Tracking: %s\n%s" % (self.local, self.remote, self.commit, self.current, self.tracking, self.message)
def git(*args):
try:
cmd = ["git"]
for a in args:
cmd.append(a)
print(" ".join(cmd))
result = run(cmd, check=True, stdout=PIPE).stdout
except CalledProcessError as e:
result = e.output
print(result)
return None
return [t.strip() for t in result.decode().split("\n") if t.strip()]
def all_branches(*flags):
origins = git("remote")
args = ["branch", "--all", "-vv"] + list(*flags)
return [Branch(b, origins) for b in git(*args) if not "-> origin" in b]
def local_branches(*flags):
return [b for b in all_branches(flags) if b.local]
def remote_branches(*flags):
return [b for b in all_branches(flags) if b.remote and not b.local]
def review(message, branches):
if not branches:
return branches
temp_filehandle = NamedTemporaryFile(suffix=".txt", delete=False)
temp_file = temp_filehandle.name
temp_filehandle.write(b"")
temp_filehandle.close()
with open(temp_file, "w") as fh:
for m in message:
print("# %s" % m, file=fh)
for b in branches:
print("# %s" % b.original, file=fh)
print(b.name, file=fh)
print("", file=fh)
editor = os.environ.get('EDITOR')
run([editor, temp_file])
with open(temp_file) as fh:
out = [line.strip() for line in fh if line.strip() and not line.strip().startswith("#")]
os.remove(temp_file)
return out
def remove_local_with_missing_remote():
local = local_branches()
with_missing_remote = [b for b in local if not b.tracking]
to_remove = review(
[
"These branches are following remote branches that no longer exist.",
"Remove any branches you wish to keep from the list."
],
with_missing_remote
)
for b in to_remove:
print("Deleting %s" % b)
git("branch", "-D", b)
def remove_local_without_remote():
local = local_branches()
without_remote = [b for b in local if not b.remote]
to_remove = review(
[
"The following branches have no remote and will be deleted.",
"Remove any branches you wish to keep from the list."
],
without_remote
)
for b in to_remove:
print("Deleting %s" % b)
git("branch", "-D", b)
def remove_merged_remotes():
all_merged = remote_branches("--merged", "origin/master")
remote_merged = [b for b in all_merged if not b.name == "origin/master"]
to_remove = review(
[
"The following remote branches have been merged into master and will be deleted.",
"Please review and remove any that you do NOT want to delete:"
],
remote_merged
)
refs_by_origin = {}
for branch in to_remove:
origin, ref = branch.split("/")
if not origin in refs_by_origin:
refs_by_origin[origin] = []
refs_by_origin[origin].append(ref)
for origin in refs_by_origin.keys():
cmd = ["push", origin, "--delete"] + refs_by_origin[origin]
print("Deleting: %s" % ", ".join(to_remove))
git(*cmd)
def initialize():
head = git("rev-parse", "--abbrev-ref", "HEAD")[0]
if head == 'HEAD':
head = git("rev-parse", "HEAD")[0]
print("Current Head: %s" % head)
git("checkout", "master")
git("fetch")
return head
def reset(commit):
if commit:
git("checkout", commit)
def options():
parser = argparse.ArgumentParser(description="Interactive delete of branches that should be safe to remove")
parser.add_argument("-l", "--local", action='store_true', help="Remove local branches with missing or no remote", default=False)
parser.add_argument("-m", "--merged", action='store_true', help="Remove merged branches from local and remote", default=False)
parser.add_argument("-a", "--all", action='store_true', help="Remove all safe to delete branches", default=False)
try:
import argcomplete
argcomplete.autocomplete(parser)
except:
pass
out = parser.parse_args()
if out.all:
out.local = True
out.merged = True
if not out.local and not out.merged:
parser.print_help()
sys.exit(0)
return out
if __name__ == "__main__":
opts = options()
current_commit = initialize()
if opts.merged:
remove_merged_remotes()
if opts.local:
remove_local_with_missing_remote()
remove_local_without_remote()
reset(current_commit)