-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
65 lines (51 loc) · 1.81 KB
/
cli.ts
File metadata and controls
65 lines (51 loc) · 1.81 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
import { encode } from "@toon-format/toon";
import { Command } from "commander";
import stringify from "safe-stable-stringify";
const program = new Command();
let helpText = "";
const getHelp = () => helpText;
program
.name("nova")
.description("Nova CLI")
.option("-j, --json", "Output results as JSON")
.option("-t, --toon", "Output results as TOON")
.exitOverride()
.configureOutput({
writeOut: (str) => {
helpText += str;
},
writeErr: (str) => {
helpText += str;
},
});
const argvWantsJson = () =>
process.argv.includes("--json") || process.argv.includes("-j");
const argvWantsToon = () =>
process.argv.includes("--toon") || process.argv.includes("-t");
const wantsJsonOutput = () => Boolean(program.opts().json) || argvWantsJson();
const wantsToonOutput = () => Boolean(program.opts().toon) || argvWantsToon();
const formatOutput = (payload: object) => {
if (wantsJsonOutput()) return stringify(payload) + "\n";
if (wantsToonOutput()) return encode(payload) + "\n";
throw new Error("invalid call");
};
const printOk = (result: object, humanReadable?: string) => {
if (wantsJsonOutput() || wantsToonOutput()) {
const payload = { status: "ok", result };
process.stdout.write(formatOutput(payload));
return;
}
console.log(humanReadable === undefined ? result : humanReadable);
};
const logExit = (message: string | object, humanReadable?: string) => {
process.exitCode = 1;
if (wantsJsonOutput() || wantsToonOutput()) {
const error = typeof message === "string" ? { message } : message;
const payload = { status: "error", error: { ...error, exitCode: 1 } };
process.stdout.write(formatOutput(payload));
return;
}
console.error(humanReadable === undefined ? message : humanReadable);
};
export default program;
export { getHelp, logExit, printOk };