-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.ts
81 lines (72 loc) · 2.1 KB
/
cli.ts
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
import { parse } from "https://deno.land/std@0.100.0/flags/mod.ts";
import { json2yaml } from "./mod.ts";
import { VERSION } from "./version.ts";
function printVersion(): void {
console.log(`json2yaml ${VERSION}`);
}
function printHelp(): void {
printVersion();
console.log("Converts a JSON string to a (pretty) YAML string 🦕");
console.log();
console.log("Docs: https://deno.land/x/json2yaml");
console.log("Bugs: https://github.com/rikilele/json2yaml/issues");
console.log();
console.log("USAGE:");
console.log(
" deno run --allow-read https://deno.land/x/json2yaml/cli.ts [OPTIONS] -- FILE",
);
console.log();
console.log("OPTIONS:");
console.log(" -h, --help Print help information");
console.log(" -v, --version Print version information");
console.log(
" -s, --spaces <n> Set number of spaces > 1 used for indents",
);
console.log();
console.log("FILE:");
console.log(" A path to a file containing a valid JSON string");
}
function executeConversion(filePath: string, numSpaces: number) {
try {
const decoder = new TextDecoder("utf-8");
const fileContents = Deno.readFileSync(filePath);
const jsonString = decoder.decode(fileContents);
const yamlString = json2yaml(jsonString, numSpaces);
const encoder = new TextEncoder();
const outputContent = encoder.encode(yamlString);
Deno.stdout.writeSync(outputContent);
Deno.exit(0);
} catch (e) {
console.log(`Failed to convert file ${filePath}`);
console.log(e);
Deno.exit(1);
}
}
function cli() {
const parsedArgs = parse(Deno.args, {
"--": true,
alias: {
h: ["help"],
v: ["version"],
s: ["spaces"],
},
});
if (parsedArgs.help) {
printHelp();
Deno.exit(0);
}
if (parsedArgs.version) {
printVersion();
Deno.exit(0);
}
if (parsedArgs["--"].length === 0) {
printHelp();
Deno.exit(0);
}
const filePath = parsedArgs["--"][0];
const numSpaces = isNaN(parsedArgs.s) || parsedArgs.s < 2 ? 2 : parsedArgs.s;
executeConversion(filePath, numSpaces);
}
if (import.meta.main) {
cli();
}