forked from beautifier/js-beautify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
executable file
·378 lines (334 loc) · 11 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/usr/bin/env node
var debug = process.env.DEBUG_JSBEAUTIFY || process.env.JSBEAUTIFY_DEBUG
? function () { console.error.apply(console, arguments); }
: function () {};
var fs = require('fs'),
cc = require('config-chain'),
beautify = require('./index'),
nopt = require('nopt'),
path = require('path'),
knownOpts = {
// Beautifier
"indent_size": Number,
"indent_char": String,
"indent_level": Number,
"indent_with_tabs": Boolean,
"preserve_newlines": Boolean,
"max_preserve_newlines": Number,
"jslint_happy": Boolean,
"brace_style": ["collapse", "expand", "end-expand", "expand-strict"],
"break_chained_methods": Boolean,
"keep_array_indentation": Boolean,
"unescape_strings": Boolean,
"wrap_line_length": Number,
// HTML-only
"max_char": Number,
"unformatted": [String, Array],
"indent_scripts": ["keep", "separate", "normal"],
// CLI
"version": Boolean,
"help": Boolean,
"files": [path, Array],
"outfile": path,
"replace": Boolean,
"quiet": Boolean,
"type": ["js", "css", "html"],
"config": path
},
// dasherizeShorthands provides { "indent-size": ["--indent_size"] }
// translation, allowing more convenient dashes in CLI arguments
shortHands = dasherizeShorthands({
// Beautifier
"s": ["--indent_size"],
"c": ["--indent_char"],
"l": ["--indent_level"],
"t": ["--indent_with_tabs"],
"p": ["--preserve_newlines"],
"m": ["--max_preserve_newlines"],
"j": ["--jslint_happy"],
"b": ["--brace_style"],
"B": ["--break_chained_methods"],
"k": ["--keep_array_indentation"],
"x": ["--unescape_strings"],
"w": ["--wrap_line_length"],
// HTML-only
"W": ["--max_char"],
"U": ["--unformatted"],
"S": ["--indent_scripts"],
// non-dasherized hybrid shortcuts
"good-stuff": [
"--keep_array_indentation",
"--keep_function_indentation",
"--jslint_happy"
],
"js" : ["--type", "js"],
"css" : ["--type", "css"],
"html": ["--type", "html"],
// CLI
"v": ["--version"],
"h": ["--help"],
"f": ["--files"],
"o": ["--outfile"],
"r": ["--replace"],
"q": ["--quiet"]
// no shorthand for "config"
});
// var cli = require('js-beautify/cli'); cli.interpret();
var interpret = exports.interpret = function (argv, slice) {
var parsed = nopt(knownOpts, shortHands, argv, slice);
if (parsed.version) {
console.log(require('./package.json').version);
process.exit(0);
}
else if (parsed.help) {
usage();
process.exit(0);
}
var cfg = cc(
parsed,
cleanOptions(cc.env('jsbeautify_'), knownOpts),
parsed.config,
cc.find('.jsbeautifyrc'),
__dirname + '/config/defaults.json'
).snapshot;
try {
// Verify arguments
checkType(cfg);
checkFiles(cfg);
checkIndent(cfg);
debug(cfg);
// Process files synchronously to avoid EMFILE error
cfg.files.forEach(processInputSync, { cfg: cfg });
}
catch (ex) {
debug(cfg);
// usage(ex);
console.error(ex);
console.error('Run `' + getScriptName() + ' -h` for help.');
process.exit(1);
}
};
// interpret args immediately when called as executable
if (require.main === module) {
interpret();
}
function usage(err) {
var scriptName = getScriptName();
var msg = [
scriptName + '@' + require('./package.json').version,
'',
'CLI Options:',
' -f, --file Input file(s) (Pass \'-\' for stdin)',
' -r, --replace Write output in-place, replacing input',
' -o, --outfile Write output to file (default stdout)',
' --config Path to config file',
' --type [js|css|html] ["js"]',
' -q, --quiet Suppress logging to stdout',
' -h, --help Show this help',
' -v, --version Show the version',
'',
'Beautifier Options:',
' -s, --indent-size Indentation size [4]',
' -c, --indent-char Indentation character [" "]'
];
switch (scriptName.split('-').shift()) {
case "js":
msg.push(' -l, --indent-level Initial indentation level [0]');
msg.push(' -t, --indent-with-tabs Indent with tabs, overrides -s and -c');
msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)');
msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]');
msg.push(' -j, --jslint-happy Enable jslint-stricter mode');
msg.push(' -b, --brace-style [collapse|expand|end-expand|expand-strict] ["collapse"]');
msg.push(' -B, --break-chained-methods Break chained method calls across subsequent lines');
msg.push(' -k, --keep-array-indentation Preserve array indentation');
msg.push(' -x, --unescape-strings Decode printable characters encoded in xNN notation');
msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]');
msg.push(' --good-stuff Warm the cockles of Crockford\'s heart');
break;
case "html":
msg.push(' -b, --brace-style [collapse|expand|end-expand] ["collapse"]');
msg.push(' -S, --indent-scripts [keep|separate|normal] ["normal"]');
msg.push(' -W, --max-char Maximum characters per line (0 disables) [250]');
msg.push(' -U, --unformatted List of tags (defaults to inline) that should not be reformatted');
break;
}
if (err) {
msg.push(err);
msg.push('');
console.error(msg.join('\n'));
} else {
console.log(msg.join('\n'));
}
}
// main iterator, {cfg} passed as thisArg of forEach call
function processInputSync(filepath) {
var data = '',
config = this.cfg,
outfile = config.outfile,
input;
// -o passed with no value overwrites
if (outfile === true || config.replace) {
outfile = filepath;
}
if (filepath === '-') {
input = process.stdin;
input.resume();
input.setEncoding('utf8');
input.on('data', function (chunk) {
data += chunk;
});
input.on('end', function () {
makePretty(data, config, outfile, writePretty);
});
}
else {
data = fs.readFileSync(filepath, 'utf8');
makePretty(data, config, outfile, writePretty);
}
}
function makePretty(code, config, outfile, callback) {
try {
var fileType = getOutputType(outfile, config.type);
var pretty = beautify[fileType](code, config);
// ensure newline at end of beautified output
pretty += '\n';
callback(null, pretty, outfile, config);
}
catch (ex) {
callback(ex);
}
}
function writePretty(err, pretty, outfile, config) {
if (err) {
console.error(err);
process.exit(1);
}
if (outfile) {
try {
fs.writeFileSync(outfile, pretty, 'utf8');
logToStdout('beautified ' + path.relative(process.cwd(), outfile), config);
}
catch (ex) {
onOutputError(ex);
}
}
else {
process.stdout.write(pretty);
}
}
// workaround the fact that nopt.clean doesn't return the object passed in :P
function cleanOptions(data, types) {
nopt.clean(data, types);
return data;
}
// error handler for output stream that swallows errors silently,
// allowing the loop to continue over unwritable files.
function onOutputError(err) {
if (err.code === 'EACCES') {
console.error(err.path + " is not writable. Skipping!");
}
else {
console.error(err);
process.exit(0);
}
}
// turn "--foo_bar" into "foo-bar"
function dasherizeFlag(str) {
return str.replace(/^\-+/, '').replace(/_/g, '-');
}
// translate weird python underscored keys into dashed argv,
// avoiding single character aliases.
function dasherizeShorthands(hash) {
// operate in-place
Object.keys(hash).forEach(function (key) {
// each key value is an array
var val = hash[key][0];
// only dasherize one-character shorthands
if (key.length === 1 && val.indexOf('_') > -1) {
hash[dasherizeFlag(val)] = val;
}
});
return hash;
}
function getOutputType(outfile, configType) {
if (outfile && /\.(js|css|html)$/.test(outfile)) {
return outfile.split('.').pop();
}
return configType;
}
function getScriptName() {
return path.basename(process.argv[1]);
}
function checkType(parsed) {
var scriptType = getScriptName().split('-').shift();
debug("executable type:", scriptType);
var parsedType = parsed.type;
debug("parsed type:", parsedType);
if (!parsedType) {
debug("type defaulted:", scriptType);
parsed.type = scriptType;
}
}
function checkIndent(parsed) {
if (parsed["indent_with_tabs"]) {
parsed["indent_size"] = 1;
parsed["indent_char"] = "\t";
}
return parsed;
}
function checkFiles(parsed) {
var argv = parsed.argv;
if (!parsed.files) {
parsed.files = [];
}
else {
if (argv.cooked.indexOf('-') > -1) {
// strip stdin path eagerly added by nopt in '-f -' case
parsed.files.some(removeDashedPath);
}
}
if (argv.remain.length) {
// assume any remaining args are files
argv.remain.forEach(function (f) {
parsed.files.push(path.resolve(f));
});
}
if ('string' === typeof parsed.outfile && !parsed.files.length) {
// use outfile as input when no other files passed in args
parsed.files.push(parsed.outfile);
// operation is now an implicit overwrite
parsed.replace = true;
}
if (argv.original.indexOf('-') > -1) {
// ensure '-' without '-f' still consumes stdin
parsed.files.push('-');
}
if (!parsed.files.length) {
throw 'Must define at least one file.';
}
debug('files.length ' + parsed.files.length);
parsed.files.forEach(testFilePath);
return parsed;
}
function removeDashedPath(filepath, i, arr) {
var found = filepath.lastIndexOf('-') === (filepath.length - 1);
if (found) {
arr.splice(i, 1);
}
return found;
}
function testFilePath(filepath) {
try {
if (filepath !== "-") {
fs.statSync(filepath);
}
}
catch (err) {
throw 'Unable to open path "' + filepath + '"';
}
}
function logToStdout(str, config) {
if (typeof config.quiet === "undefined" || !config.quiet) {
console.log(str);
}
}