-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcli.js
103 lines (93 loc) · 2.5 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env node
(function() {
var colors = require('colors');
var cssparser = require('./cssparser.js');
var nomnom = require('nomnom');
var fs = require('fs');
var path = require('path');
var version = require('../package.json').version;
var opts = require("nomnom")
.script('cssparser')
.option('file', {
flag: true,
position: 0,
help: 'CSS document file'
})
.option('outfile', {
abbr: 'o',
metavar: 'FILE',
help: 'Filename or base name of the generated JSON'
})
.option('indent', {
abbr: 'i',
default: 4,
help: 'indentation(string or number)'
})
.option('type', {
abbr: 't',
default: 'simple',
choices: ['simple', 'deep', 'atomic'],
metavar: 'TYPE',
help: 'The type of JSON to generate (simple, deep, atomic)'
})
.option('console', {
abbr: 'c',
flag: true,
help: 'Display JSON to console only. this option will ignore output-file options.'
})
.option('beautify-delimiter', {
abbr: 'b',
flag: true,
help: 'Beautify delimiters such as comma and whitespaces for simple & deep type.'
})
.option('version', {
abbr: 'v',
flag: true,
help: 'print version and exit',
callback: function() {
return version;
}
})
.parse();
function toJSON(raw, type, indent, beautifyDelimiter) {
var parser = new cssparser.Parser();
var ast = parser.parse(raw)
if (beautifyDelimiter) {
ast.setOptions({
commaDelimiter: ', ',
whitespaceDelimiter: ' '
})
}
return JSON.stringify(ast.toJSON(type), null, indent);
}
if (opts.file) {
try {
var raw = fs.readFileSync(path.normalize(opts.file), 'utf8');
} catch (e) {
console.error(e.toString().red + '\n' + e.stack.red);
return;
}
var name = path.basename((opts.outfile || opts.file)).replace(/\..*$/g, '');
var type = opts.type;
var indent = opts.indent;
var beautifyDelimiter = opts['beautify-delimiter'];
try {
var json = toJSON(raw, type, indent, beautifyDelimiter);
} catch (e) {
var output = e.message
if ('stack' in e) {
output += '\n' + e.stack
}
if ('hash' in e) {
output += '\n' + JSON.stringify(e[e.hash], null, '\t')
}
console.error(output.red);
return;
}
if (opts.console) {
console.log(json);
} else {
fs.writeFileSync(opts.outfile || (name + '.json'), json);
}
}
})();