-
Notifications
You must be signed in to change notification settings - Fork 4
/
cli.js
executable file
·75 lines (66 loc) · 1.9 KB
/
cli.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
#!/usr/bin/env node
"use strict";
//TODO: glob for source file patterns
//TODO: option to stop on validation error - call xml2json with strict:true
const csdl = require("./xml2json");
const { parseArgs } = require("node:util");
const fs = require("node:fs");
const colors = require("colors/safe");
let unknown = false;
let args;
try {
args = parseArgs({
options: {
help: { type: "boolean", short: "h" },
pretty: { type: "boolean", short: "p" },
target: { type: "string", short: "t" },
},
allowPositionals: true,
});
} catch (e) {
console.error(e.message);
unknown = true;
}
if (unknown || args.positionals.length == 0 || args.values.help) {
console.log(`Usage: odata-csdl-xml2json <options> <source files>
Options:
-h, --help show this info
-p, --pretty pretty-print JSON result
-t, --target target file (only useful with a single source file)`);
} else {
for (var i = 0; i < args.positionals.length; i++) {
convert(args.positionals[i]);
}
}
function convert(source) {
if (!fs.existsSync(source)) {
console.error("Source file not found: " + source);
return;
}
const xml = fs.readFileSync(source);
try {
const messages = [];
const json = csdl.xml2json(xml, { messages });
for (const m of messages) {
console.warn(
`${source}:${m.parser.line}:${m.parser.column}: ${m.message}`
);
}
const target =
args.values.target ||
source.substring(0, source.lastIndexOf(".")) + ".json";
console.log(target);
fs.writeFileSync(
target,
JSON.stringify(json, null, args.values.pretty ? 4 : 0)
);
} catch (e) {
console.error(
colors.red(
`${source}:${e.parser.line}:${e.parser.column}: ${e.message}\nAt: ${e.parser.construct}`
)
);
process.exitCode = 1;
return;
}
}