-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
80 lines (71 loc) · 2.21 KB
/
index.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
79
80
#!/usr/bin/env node
import { exec } from "child_process";
import inquirer from 'inquirer';
import inquirerPrompt from 'inquirer-autocomplete-prompt';
inquirer.registerPrompt("autocomplete", inquirerPrompt);
const showHelp = process.argv.includes("-h");
const includeOrigin = process.argv.includes("-l") ? "" : " -a";
const fetchFirst = process.argv.includes("-f");
if (showHelp) {
console.log(`
Command: gitcheckout [-l] [-f]
Select a branch using the keyboard arrows, hit Enter, and watch the magic as it happens.
The current checked out branch is the default selection.
-l: include only local branches in branches list
-f: fetch before listing branches (quietly skips if failed)
`)
process.exit(0);
}
function execute(cmd, pipe = true) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout) => {
if (err) {
return reject(err);
}
resolve(stdout);
});
});
}
(async function run() {
if (fetchFirst) {
await execute(`git fetch`).catch(() => {
console.log("Couldn't fetch. Fetch manually before to display new remote branches");
return;
});
}
const gitBranchOut = await execute(`git branch --sort=-committerdate${includeOrigin}`, false);
let checkedOutBranch = 0;
let branches = gitBranchOut
// removed output whitespace
.trim()
// deal with windows
.replace(/\r/, "")
// split to rows - each one is a branch
.split("\n")
// removed the checked out branch indicator '*', origin/ if branch -a was executed and trim whitespace
.map((n, i) => {
if (n.match(/^\s*\*/)) {
checkedOutBranch = i;
}
return n.replace(/^\s*\*|^\s*remotes\/origin\//g, "").trim()
});
// dedup (if local was or is checked out and origins are included)
branches = [...new Set(branches)];
const { branch } = await inquirer.prompt([
{
type: "autocomplete",
message: "Select branch to checkout:",
name: "branch",
source: (answersSoFar, input) => {
return Promise.resolve(!input ? branches : branches.filter(n => n.includes(input)));
},
pageSize: 10,
default: checkedOutBranch,
}
]);
await execute(`git checkout ${branch}`);
})()
.catch((e) => {
console.log(e.message || e);
process.exit(1);
});