-
Notifications
You must be signed in to change notification settings - Fork 31
/
cli.ts
74 lines (65 loc) · 1.46 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
#!/usr/bin/env node
import Fs from "fs";
import Path from "path";
import meow from "meow";
import getStdin from "get-stdin";
import type { Parent } from "unist";
import { toD3Force, parse, toDot } from "./index";
const cli = meow(
`
Usage
$ parse-gedcom <input>
Options
--type, -s Output type (json, d3.json, dot)
Examples
$ parse-gedcom input.ged output.json
`,
{
flags: {
type: {
type: "string",
alias: "t",
},
},
}
);
const EXTENSION_TO_TYPE = {
".json": "json",
".d3.json": "force",
".dot": "dot",
};
type ExtKey = keyof typeof EXTENSION_TO_TYPE;
function getOutputFromType(type: string, parsed: Parent) {
switch (type) {
case "json": {
return JSON.stringify(parsed, null, 2);
}
case "d3.json": {
return JSON.stringify(toD3Force(parsed), null, 2);
}
case "dot": {
return toDot(parsed);
}
}
return '';
}
(async () => {
const [infile, outfile] = cli.input;
const inputStr = infile ? Fs.readFileSync(infile, "utf8") : await getStdin();
const parsed = parse(inputStr);
let type = "json";
if (cli.flags.type) {
type = cli.flags.type;
} else if (outfile) {
const ext = Path.extname(outfile);
if (ext in EXTENSION_TO_TYPE) {
type = EXTENSION_TO_TYPE[ext as ExtKey];
}
}
const output = getOutputFromType(type, parsed);
if (outfile) {
Fs.writeFileSync(outfile, output, "utf8");
} else {
process.stdout.write(output);
}
})();