-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
executable file
·78 lines (67 loc) · 1.94 KB
/
main.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
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env node
const { execFileSync } = require('child_process');
const yargs = require('yargs');
const fuzzy = require('fuzzy');
const inquirer = require('inquirer');
inquirer.registerPrompt(
'autocomplete',
require('inquirer-autocomplete-prompt')
);
(async () => {
const { byCommit } = yargs.argv;
let recentBranches;
if (byCommit) {
recentBranches = execFileSync('git', ['branch', '--sort=-committerdate'], {
encoding: 'utf-8',
})
.trim()
.split('\n')
.map((line) => line.replace(/^[\* ] /, ''));
} else {
const output = execFileSync('git', ['reflog', '--grep-reflog=checkout:'], {
encoding: 'utf-8',
}).trim();
if (!output) {
console.log(
'No recent branches found. This usually means this is a new repo or you haven’t switched branches yet.'
);
process.exit();
}
const lines = output.split('\n');
recentBranches = lines.map(
(line) => line.match(/moving from [^ ]+ to ([^ ]+)$/)[1]
);
}
const currentBranch = execFileSync('git', ['branch', '--show-current'], {
encoding: 'utf-8',
}).trim();
const allBranchesSet = new Set(
execFileSync('git', ['branch'], {
encoding: 'utf-8',
})
.trim()
.split('\n')
.map((line) => line.replace(/^[\* ] /, ''))
);
const uniqueBranchesSet = new Set(recentBranches);
uniqueBranchesSet.delete(currentBranch);
for (const branch of uniqueBranchesSet) {
if (!allBranchesSet.has(branch)) {
uniqueBranchesSet.delete(branch);
}
}
const uniqueBranches = [...uniqueBranchesSet];
const { newBranch } = await inquirer.prompt({
type: 'autocomplete',
message: 'Choose a branch',
name: 'newBranch',
source: (_, input) => {
return Promise.resolve(
input
? fuzzy.filter(input, uniqueBranches).map(({ string }) => string)
: uniqueBranches
);
},
});
execFileSync('git', ['checkout', newBranch]);
})();