-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault-branch.mjs
More file actions
97 lines (84 loc) · 2.41 KB
/
Copy pathdefault-branch.mjs
File metadata and controls
97 lines (84 loc) · 2.41 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
import { promises as fs } from "fs";
const { HOME } = process.env;
const CONFIG_ROOT = `${HOME}/.config/git-tools`;
const CONFIG_PATH = `${CONFIG_ROOT}/default-branch.json`;
async function loadConfig() {
try {
const contents = await fs.readFile(CONFIG_PATH, 'utf-8');
return JSON.parse(contents);
} catch (error) {
if (error.code === 'ENOENT') {
return {};
} else {
throw error;
}
}
}
async function saveConfig(config) {
await fs.mkdir(CONFIG_ROOT, { recursive: true });
await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8');
}
function help() {
console.log("USAGE\n");
console.log("node default-branch.mjs <path> set <branch>");
console.log("node default-branch.mjs <path> [get]");
console.log("node default-branch.mjs <path> rm");
}
function formatRepoPath(path) {
if (path.startsWith(HOME)) {
return "~" + path.slice(HOME.length);
} else {
return path;
}
}
async function getDefaultBranch(config, repoName) {
console.log(config[repoName] || "main");
}
async function setDefaultBranch(config, repoName, branch) {
config[repoName] = branch;
await saveConfig(config);
console.log(`Set default branch for ${formatRepoPath(repoName)} to ${branch}`);
}
async function rmDefaultBranch(config, repoName) {
delete config[repoName];
await saveConfig(config);
console.log(`Removed default branch for ${formatRepoPath(repoName)}`);
}
async function main() {
if (!HOME) {
throw new Error("HOME environment variable is not set");
}
const config = await loadConfig();
const args = process.argv.slice(2);
if (args.length === 3) {
const [repo, command, branch] = args;
if (command !== "set") {
throw new Error("Invalid parameters, only 'set' command accepts 3");
}
await setDefaultBranch(config, repo, branch);
} else if (args.length === 2) {
const [repo, command] = args;
switch (command) {
case "get":
await getDefaultBranch(config, repo);
break;
case "rm":
await rmDefaultBranch(config, repo);
break;
default:
throw new Error(`Invalid command: ${command}`);
}
} else if (args.length === 1) {
await getDefaultBranch(config, args[0]);
} else if (arguments.length === 0) {
help();
} else {
throw new Error(`Invalid parameters: ${args}`)
}
}
try {
await main();
} catch (error) {
console.error(error.message);
process.exit(1);
}