-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgit-cleanup.js
66 lines (60 loc) · 2.03 KB
/
git-cleanup.js
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
import { exec } from 'node:child_process';
const rxGone = /:\sgone\]/;
const rxInUse = /^\*\s/;
const rxBranch = /^\s+([^\s]+)/;
async function pruneAsync() {
console.log('> Pruning branches');
return new Promise((resolve, reject) => {
exec('git remote prune origin', (error, stdout, stderr) => {
if (stderr || error) {
reject('Error when pruning branches.');
} else if (stdout) {
resolve();
}
});
});
}
/**
* @returns {Promise<string[]>}
*/
async function getBranchesNoLongerOnOriginAsync() {
console.log('> Getting branches no longer on origin');
return new Promise((resolve, reject) => {
exec('git branch -vv', (error, stdout, stderr) => {
if (stderr || error) {
reject('Error when getting branches.');
} else if (stdout) {
const lines = stdout.replace('\r', '').split('\n')
.filter((line) => rxGone.test(line))
.filter((line) => !rxInUse.test(line))
.filter((line) => rxBranch.test(line));
resolve(lines.map((line) => rxBranch.exec(line)[1]));
}
});
});
}
/**
* @param {string[]} arrayOfBranches
*/
async function deleteBranchesAsync(arrayOfBranches) {
console.log('> Removing branches no longer on origin');
if (arrayOfBranches.length > 0) {
arrayOfBranches.forEach((branchName) => {
exec(`git branch -d "${branchName}"`, (error, stdout, stderr) => {
if (stderr || error) {
console.error(` - Error when deleting branch: ${branchName}`, stderr);
} else if (stdout) {
console.log(` - Deleted: ${branchName}`);
}
});
});
} else {
console.log('> No branches to remove');
}
}
async function runAsync() {
await pruneAsync();
const branches = await getBranchesNoLongerOnOriginAsync();
await deleteBranchesAsync(branches);
}
runAsync();