forked from timcharper/git-helpers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-cleanup-branches
More file actions
executable file
·501 lines (437 loc) · 13.9 KB
/
git-cleanup-branches
File metadata and controls
executable file
·501 lines (437 loc) · 13.9 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#!/usr/bin/env -S deno run --allow-all
import yargs from "https://deno.land/x/yargs@v17.7.2-deno/deno.ts";
const DEBUG = !!Deno.env.get("DEBUG");
const DRY_RUN = !!Deno.env.get("DRY_RUN");
function tmpNameSync(prefix: string = "tmp"): string {
const uniqueId = crypto.randomUUID();
return `${prefix}-${uniqueId}`;
}
function runCommandSync(command: string, args: string[]): string {
if (DEBUG) {
console.log(`+ ${command} ${args.join(" ")}`);
}
const result = new Deno.Command(command, {
args: args,
}).outputSync();
if (!result.success) {
const stdout = new TextDecoder().decode(result.stdout);
if (stdout) {
console.log(stdout);
}
throw new Error(
`Command failed: ${command} ${args.join(" ")} (exit code: ${result.code})`
);
}
return new TextDecoder().decode(result.stdout);
}
interface ParsedRef {
remote?: string;
ref: string;
branchName: string;
isLocal: boolean;
lastCommitDate: Date;
}
interface BranchesByOrigin {
local: ParsedRef[];
remotes: Record<string, ParsedRef[]>;
}
interface CandidateState {
candidateInstructions(): string;
branchCandidates(): ParsedRef[];
}
function parseRef(ref: string, lastCommitDate: Date): ParsedRef | null {
const remoteMatch = ref.match(/^refs\/remotes\/([^/]+)\/(.+)$/);
const localMatch = ref.match(/^refs\/heads\/(.+)$/);
if (remoteMatch) {
const [, remote, branchName] = remoteMatch;
return {
remote,
ref,
branchName,
isLocal: false,
lastCommitDate,
};
} else if (localMatch) {
const [, branchName] = localMatch;
return {
ref,
branchName,
isLocal: true,
lastCommitDate,
};
}
return null;
}
function groupByOrigin(branches: ParsedRef[]): BranchesByOrigin {
const grouped: BranchesByOrigin = {
local: [],
remotes: {},
};
for (const branch of branches) {
const parsed = parseRef(branch.ref, branch.lastCommitDate);
if (!parsed) {
console.log(`I don't know how to delete ${branch.ref}`);
continue;
}
if (parsed.isLocal) {
grouped.local.push(parsed);
} else if (parsed.remote) {
grouped.remotes[parsed.remote] = grouped.remotes[parsed.remote] || [];
grouped.remotes[parsed.remote].push(parsed);
}
}
return grouped;
}
class BranchNotFound extends Error {}
class ConsiderAll implements CandidateState {
private branches: ParsedRef[];
constructor(branches: ParsedRef[]) {
this.branches = branches;
}
candidateInstructions(): string {
return "# The following is a list of all local and remote branches in your repository";
}
branchCandidates(): ParsedRef[] {
return this.branches;
}
}
function groupByOriginAlphabetically(branches: ParsedRef[]): BranchGroupNode[] {
const byOrigin: Record<string, ParsedRef[]> = {};
for (const branch of branches) {
const origin = branch.isLocal
? "LOCAL BRANCHES"
: branch.remote?.toUpperCase() ?? "UNKNOWN REMOTE";
if (!byOrigin[origin]) byOrigin[origin] = [];
byOrigin[origin].push(branch);
}
return Object.entries(byOrigin).map(([origin, group]) => ({
name: origin,
branches: group.sort((a, b) => a.branchName.localeCompare(b.branchName)),
}));
}
function getLocalRemoteBranchMaps(
branches: ParsedRef[]
): Record<string, string> {
const remoteBranchMaps: Record<string, string> = {};
for (const localBranch of branches) {
if (!localBranch.isLocal) continue;
for (const remoteBranch of branches) {
if (remoteBranch.isLocal) continue;
if (remoteBranch.branchName !== localBranch.branchName) continue;
remoteBranchMaps[localBranch.branchName] = remoteBranch.branchName;
}
}
return remoteBranchMaps;
}
function editBranchList(
allBranches: ParsedRef[],
useStaleGrouping: boolean
): string[] {
const tempFile = tmpNameSync();
const lines = [
"# The following is a list of all local and remote branches in your repository",
"# To delete the branches, delete them from this list, and then save and quit",
];
const groups: BranchGroupNode[] = useStaleGrouping
? groupByRemoteThenStale(allBranches)
: groupByOriginAlphabetically(allBranches);
const remoteBranchMaps = getLocalRemoteBranchMaps(allBranches);
lines.push(...formatBranchGroups(groups, remoteBranchMaps));
Deno.writeTextFileSync(tempFile, lines.join("\n"));
new Deno.Command(Deno.env.get("EDITOR") || "vi", {
args: [tempFile],
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
}).outputSync();
const preserveBranches = Deno.readTextFileSync(tempFile)
.split("\n")
.map((line) => line.replace(/#.+$/, "").replace(/\0/g, "").trim())
.filter((line) => line.length > 0);
Deno.removeSync(tempFile);
// Now, preserveBranches contains ref strings. We need to map these back to ParsedRef objects.
const erroneousBranches = preserveBranches.filter(
(b) => !allBranches.some((c) => c.ref === b)
);
if (erroneousBranches.length > 0) {
console.error(
"Error! unrecognized branches:\n" +
erroneousBranches.map((b) => ` - ${b}`).join("\n")
);
Deno.exit(1);
}
// Return the list of ref strings to preserve (for deletion logic)
return preserveBranches;
}
function deleteBranches(
branchesForDeletion: string[],
refMap: Record<string, ParsedRef>
): void {
if (branchesForDeletion.length === 0) {
console.log("No branches to delete.");
Deno.exit(1);
}
console.log(
"Deleting branches:\n" +
branchesForDeletion.map((b) => ` - ${b}`).join("\n")
);
// are you sure?
let confirmation: string | undefined = undefined;
while (confirmation === undefined || !["y", "n"].includes(confirmation)) {
confirmation = prompt(
"Are you sure you want to delete these branches? [y/N] "
)?.toLocaleLowerCase();
}
if (confirmation === "n") {
console.log("Aborting.");
Deno.exit(0);
}
// Get the ParsedRef objects from the refMap
const parsedBranches = branchesForDeletion
.map((ref) => refMap[ref])
.filter((branch): branch is ParsedRef => branch !== undefined);
if (parsedBranches.length !== branchesForDeletion.length) {
console.log("Warning: Some branches could not be found in the branch map");
}
// Use existing groupByOrigin function
const grouped = groupByOrigin(parsedBranches);
// Delete local branches
if (grouped.local.length > 0) {
const args = ["branch", "-D", ...grouped.local.map((b) => b.branchName)];
if (DRY_RUN) {
console.log(`Would run: git ${args.join(" ")}`);
} else {
runCommandSync("git", args);
}
}
// Delete remote branches
for (const [remote, branches] of Object.entries(grouped.remotes)) {
const args = ["push", remote, ...branches.map((b) => `:${b.branchName}`)];
if (DRY_RUN) {
console.log(`Would run: git ${args.join(" ")}`);
} else {
runCommandSync("git", args);
}
}
}
function fetchAndPrune(): void {
console.log("Fetching and pruning all remotes");
runCommandSync("git", ["fetch", "--all", "--prune"]);
console.log("Done");
}
const GitRefParser = {
parseGitRefLine(line: string): ParsedRef | null {
// Split on first null character
const nullIdx = line.indexOf("\0");
if (nullIdx === -1) return null;
const ref = line.slice(0, nullIdx).replace(/\0/g, "").trim();
const dateStr = line
.slice(nullIdx + 1)
.replace(/\0/g, "")
.trim();
if (!ref || !dateStr) return null;
const lastCommitDate = GitRefParser.parseGitDate(dateStr);
if (!lastCommitDate) return null;
const refInfo = GitRefParser.parseRefString(ref);
if (!refInfo) return null;
return { ...refInfo, ref, lastCommitDate };
},
parseGitDate(dateStr: string): Date | null {
const date = new Date(dateStr);
return isNaN(date.getTime()) ? null : date;
},
parseRefString(
ref: string
): { remote?: string; branchName: string; isLocal: boolean } | null {
const remoteMatch = ref.match(/^refs\/remotes\/([^/]+)\/(.+)$/);
const localMatch = ref.match(/^refs\/heads\/(.+)$/);
if (remoteMatch) {
const [, remote, branchName] = remoteMatch;
return { remote, branchName, isLocal: false };
} else if (localMatch) {
const [, branchName] = localMatch;
return { branchName, isLocal: true };
}
return null;
},
};
function getBranches(): ParsedRef[] {
const output = runCommandSync("git", [
"for-each-ref",
"--format=%(refname)%00%(committerdate:iso8601)",
"refs/heads/",
"refs/remotes/",
]);
if (DEBUG) {
console.log("Raw git for-each-ref output:");
console.log(output);
}
return output
.split("\n")
.filter((line) => line.trim().length > 0)
.map(GitRefParser.parseGitRefLine)
.filter((ref): ref is ParsedRef => ref !== null);
}
function main(args: string[]) {
const argv = yargs(args)
.scriptName("git-cleanup-branches")
.usage("Usage: $0 [options]")
.option("f", {
alias: "fast",
type: "boolean",
description: "Fast cleanup - Skip fetch/prune remotes",
default: false,
})
.option("s", {
alias: "stale",
type: "boolean",
description: "Group branches by staleness",
default: false,
})
.strict()
.parseSync();
const fast = argv.fast;
const stale = argv.stale;
if (!fast) {
fetchAndPrune();
}
const branches = getBranches();
try {
const preserveBranches = editBranchList(branches, stale);
// Create a mapping of ref to ParsedRef for deleteBranches
const refMap: Record<string, ParsedRef> = {};
for (const branch of branches) {
refMap[branch.ref] = branch;
}
const branchesToDelete = branches
.filter((b) => !preserveBranches.includes(b.ref))
.map((b) => b.ref);
deleteBranches(branchesToDelete, refMap);
} catch (e) {
if (e instanceof BranchNotFound) {
console.error(e.message);
Deno.exit(1);
}
console.error(e);
throw e;
}
}
// --- Deno tests for parser ---
if (import.meta.main) {
main(Deno.args);
} else {
// Only run tests if not main script
Deno.test("parseGitRefLine parses valid line", () => {
const line = "refs/heads/feature/foo\x002023-01-01 12:00:00 +0000";
const parsed = GitRefParser.parseGitRefLine(line);
if (!parsed) throw new Error("Should parse");
if (parsed.branchName !== "feature/foo")
throw new Error("Wrong branch name");
if (!parsed.isLocal) throw new Error("Should be local");
if (parsed.lastCommitDate.toISOString() !== "2023-01-01T12:00:00.000Z")
throw new Error("Wrong date");
});
Deno.test("parseGitRefLine returns null for invalid line", () => {
const line = "notaref\x00notadate";
const parsed = GitRefParser.parseGitRefLine(line);
if (parsed !== null) throw new Error("Should not parse");
});
Deno.test("parseRefString parses remote ref", () => {
const ref = "refs/remotes/origin/feature/bar";
const info = GitRefParser.parseRefString(ref);
if (!info) throw new Error("Should parse");
if (info.remote !== "origin") throw new Error("Wrong remote");
if (info.branchName !== "feature/bar") throw new Error("Wrong branch name");
if (info.isLocal) throw new Error("Should not be local");
});
}
interface BranchGroupNode {
name?: string;
children?: BranchGroupNode[];
branches?: ParsedRef[];
}
// Example: group by remote, then by staleness
function groupByRemoteThenStale(branches: ParsedRef[]): BranchGroupNode[] {
const byRemote: Record<string, ParsedRef[]> = {};
for (const branch of branches) {
const remote = branch.remote || "local";
if (!byRemote[remote]) byRemote[remote] = [];
byRemote[remote].push(branch);
}
return Object.entries(byRemote).map(([remote, group]) => ({
name: remote === "local" ? "LOCAL BRANCHES" : remote.toUpperCase(),
children: groupByStaleness(group),
}));
}
function groupByStaleness(branches: ParsedRef[]): BranchGroupNode[] {
const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
const ninetyDaysAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
const oneYearAgo = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
const buckets: { name: string; filter: (b: ParsedRef) => boolean }[] = [
{ name: "Active", filter: (b) => b.lastCommitDate >= thirtyDaysAgo },
{
name: "Older than 30 days",
filter: (b) =>
b.lastCommitDate < thirtyDaysAgo && b.lastCommitDate >= ninetyDaysAgo,
},
{
name: "Older than 90 days",
filter: (b) =>
b.lastCommitDate < ninetyDaysAgo && b.lastCommitDate >= oneYearAgo,
},
{ name: "Older than 1 year", filter: (b) => b.lastCommitDate < oneYearAgo },
];
return buckets
.map((bucket) => {
const bucketBranches = branches.filter(bucket.filter);
return bucketBranches.length > 0
? ({
name: bucket.name as string | undefined,
branches: bucketBranches,
} as BranchGroupNode)
: undefined;
})
.filter((x): x is BranchGroupNode => x !== undefined);
}
function formatBranchGroups(
groups: BranchGroupNode[],
remoteBranchMaps: Record<string, string>,
indent = 0,
isTopLevel = true
): string[] {
const lines: string[] = [];
for (const [i, group] of groups.entries()) {
// Add an empty line above each heading except the very first at the top level
if (group.name && (!isTopLevel || i > 0)) {
lines.push("");
}
if (group.name) {
lines.push(
`${" ".repeat(indent)}${indent === 0 ? "# " : "## "}${group.name}`
);
}
if (group.children) {
lines.push(
...formatBranchGroups(
group.children,
remoteBranchMaps,
indent + 2,
false
)
);
}
if (group.branches) {
for (const branch of group.branches) {
let noRemoteIdentifier: string = "";
if (branch.isLocal) {
if (!remoteBranchMaps[branch.branchName]) {
noRemoteIdentifier = ` # (no remote)`;
}
}
lines.push(`${" ".repeat(indent)}${branch.ref}${noRemoteIdentifier}`);
}
}
}
return lines;
}