-
Notifications
You must be signed in to change notification settings - Fork 11
/
fmt2json.js
executable file
·59 lines (54 loc) · 1.87 KB
/
fmt2json.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
#!/usr/bin/env node
const fn = require('funclib');
const program = require('commander');
const { prompt } = require('enquirer');
const package = require('../package.json');
const fmt2json = require('../fmt2json');
program.version(package.version)
.option('-v, --version', 'output the version number')
.option('-i, --indent <indent>', 'Indnet number.')
.option('-q, --qtMark <qtMark>', `Quotation mark, one of ['""', "''", '"', "'"]`, '""')
.option('-e, --escape', 'Escape format result.')
.option('-u, --unescape', 'Unescape source before format.')
.option('-s, --strict', 'Strict mode.')
.option('-r, --resultOnly', 'Result only, not return the format info.')
.parse(process.argv);
const { indent, qtMark, strict, unescape, resultOnly } = program;
const options = {};
if (indent && indent.match(/^([1-9])$/)) {
options.indent = +indent;
}
if(['""', "''", '"', "'"].includes(qtMark)) {
const qtArr = qtMark.split();
if (qtMark.length === 2) {
options.keyQtMark = qtArr[0];
options.valQtMark = qtArr[1];
} else {
options.keyQtMark = '';
options.valQtMark = qtArr[0];
}
} else {
throw new Error(`qtMark mast one of ['""', "''", '"', "'"], for key and value, single mark means no key mark just for value.`);
}
if (strict) options.strict = true;
if (unescape) options.unescape = true;
if (resultOnly) options.resultOnly = true;
prompt({
type: 'input',
name: 'source',
message: 'Input a string to foramt:'
}).then(({ source }) => {
if (resultOnly) {
fmt2json(source, options).then(result => {
console.log(fn.chalk(result, 'cyan'));
});
} else {
fmt2json(source, options).then(res => {
fn.log('', { title: `format-to-json(${package.version})`, pre: true });
console.log(fn.chalk(res.result, 'cyan'));
console.log(fn.array(66, '-').join(''));
console.log(res.status);
fn.log('', { end: true });
});
}
});