forked from jshint/jshint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
598 lines (504 loc) · 16 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
"use strict";
var _ = require("underscore");
var cli = require("cli");
var path = require("path");
var shjs = require("shelljs");
var minimatch = require("minimatch");
var htmlparser = require("htmlparser2");
var exit = require("exit");
var JSHINT = require("./jshint.js").JSHINT;
var defReporter = require("./reporters/default").reporter;
var OPTIONS = {
"config": ["c", "Custom configuration file", "string", false ],
"reporter": ["reporter", "Custom reporter (<PATH>|jslint|checkstyle)", "string", undefined ],
"exclude": ["exclude",
"Exclude files matching the given filename pattern (same as .jshintignore)", "string", null],
"exclude-path": ["exclude-path", "Pass in a custom jshintignore file path", "string", null],
"verbose": ["verbose", "Show message codes"],
"show-non-errors": ["show-non-errors", "Show additional data generated by jshint"],
"extra-ext": ["e",
"Comma-separated list of file extensions to use (default is .js)", "string", ""],
"extract": [
"extract",
"Extract inline scripts contained in HTML (auto|always|never, default to never)",
"string",
"never"
],
// Deprecated options.
"jslint-reporter": [
"jslint-reporter",
deprecated("Use a jslint compatible reporter", "--reporter=jslint")
],
"checkstyle-reporter": [
"checkstyle-reporter",
deprecated("Use a CheckStyle compatible XML reporter", "--reporter=checkstyle")
]
};
/**
* Returns the same text but with a deprecation notice.
* Useful for options descriptions.
*
* @param {string} text
* @param {string} alt (optional) Alternative command to include in the
* deprecation notice.
*
* @returns {string}
*/
function deprecated(text, alt) {
if (!alt) {
return text + " (DEPRECATED)";
}
return text + " (DEPRECATED, use " + alt + " instead)";
}
/**
* Removes JavaScript comments from a string by replacing
* everything between block comments and everything after
* single-line comments in a non-greedy way.
*
* English version of the regex:
* match '/*'
* then match zero or more instances of any character (incl. \n)
* except for instances of '* /' (without a space, obv.)
* then match '* /' (again, without a space)
*
* @param {string} str a string with potential JavaScript comments.
* @returns {string} a string without JavaScript comments.
*/
function removeComments(str) {
str = str || "";
str = str.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\//g, "");
str = str.replace(/\/\/[^\n\r]*/g, ""); // Everything after '//'
return str;
}
/**
* Tries to find a configuration file in either project directory
* or in the home directory. Configuration files are named
* '.jshintrc'.
*
* @param {string} file path to the file to be linted
* @returns {string} a path to the config file
*/
function findConfig(file) {
var dir = path.dirname(path.resolve(file));
var envs = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var home = path.normalize(path.join(envs, ".jshintrc"));
var proj = findFile(".jshintrc", dir);
if (proj)
return proj;
if (shjs.test("-e", home))
return home;
return null;
}
/**
* Tries to find JSHint configuration within a package.json file
* (if any). It search in the current directory and then goes up
* all the way to the root just like findFile.
*
* @param {string} file path to the file to be linted
* @returns {object} config object
*/
function loadNpmConfig(file) {
var dir = path.dirname(path.resolve(file));
var fp = findFile("package.json", dir);
if (!fp)
return null;
try {
return require(fp).jshintConfig;
} catch (e) {
return null;
}
}
/**
* Tries to import a reporter file and returns its reference.
*
* @param {string} fp a path to the reporter file
* @returns {object} imported module for the reporter or 'null'
* if a module cannot be imported.
*/
function loadReporter(fp) {
try {
return require(fp).reporter;
} catch (err) {
return null;
}
}
// Storage for memoized results from find file
// Should prevent lots of directory traversal &
// lookups when liniting an entire project
var findFileResults = {};
/**
* Searches for a file with a specified name starting with
* 'dir' and going all the way up either until it finds the file
* or hits the root.
*
* @param {string} name filename to search for (e.g. .jshintrc)
* @param {string} dir directory to start search from (default:
* current working directory)
*
* @returns {string} normalized filename
*/
function findFile(name, dir) {
dir = dir || process.cwd();
var filename = path.normalize(path.join(dir, name));
if (findFileResults[filename] !== undefined) {
return findFileResults[filename];
}
var parent = path.resolve(dir, "../");
if (shjs.test("-e", filename)) {
findFileResults[filename] = filename;
return filename;
}
if (dir === parent) {
findFileResults[filename] = null;
return null;
}
return findFile(name, parent);
}
/**
* Loads a list of files that have to be skipped. JSHint assumes that
* the list is located in a file called '.jshintignore'.
*
* @return {array} a list of files to ignore.
*/
function loadIgnores(exclude, excludePath) {
var file = findFile(excludePath || ".jshintignore");
if (!file && !exclude) {
return [];
}
var lines = (file ? shjs.cat(file) : "").split("\n");
lines.unshift(exclude || "");
return lines
.filter(function (line) {
return !!line.trim();
})
.map(function (line) {
if (line[0] === "!")
return "!" + path.resolve(path.dirname(file), line.substr(1).trim());
return path.join(path.dirname(file), line.trim());
});
}
/**
* Checks whether we should ignore a file or not.
*
* @param {string} fp a path to a file
* @param {array} patterns a list of patterns for files to ignore
*
* @return {boolean} 'true' if file should be ignored, 'false' otherwise.
*/
function isIgnored(fp, patterns) {
return patterns.some(function (ip) {
if (minimatch(path.resolve(fp), ip, { nocase: true })) {
return true;
}
if (path.resolve(fp) === ip) {
return true;
}
if (shjs.test("-d", fp) && ip.match(/^[^\/]*\/?$/) &&
fp.match(new RegExp("^" + ip + ".*"))) {
return true;
}
});
}
/**
* Extract JS code from a given source code. The source code my be either HTML
* code or JS code. In the latter case, no extraction will be done unless
* 'always' is given.
*
* @param {string} code a piece of code
* @param {string} when 'always' will extract the JS code, no matter what.
* 'never' won't do anything. 'auto' will check if the code looks like HTML
* before extracting it.
*
* @return {string} the extracted code
*/
function extract(code, when) {
// A JS file won't start with a less-than character, whereas a HTML file
// should always start with that.
if (when !== "always" && (when !== "auto" || !/^\s*</.test(code)))
return code;
var inscript = false;
var index = 0;
var js = [];
var startOffset;
// Test if current tag is a valid <script> tag.
function onopen(name, attrs) {
if (name !== "script")
return;
if (attrs.type && !/text\/javascript/.test(attrs.type.toLowerCase()))
return;
// Mark that we're inside a <script> a tag and push all new lines
// in between the last </script> tag and this <script> tag to preserve
// location information.
inscript = true;
js.push.apply(js, code.slice(index, parser.endIndex).match(/\n\r|\n|\r/g));
startOffset = null;
}
function onclose(name) {
if (name !== "script" || !inscript)
return;
inscript = false;
index = parser.startIndex;
startOffset = null;
}
function ontext(data) {
if (!inscript)
return;
var lines = data.split(/\n\r|\n|\r/);
if (!startOffset) {
lines.some(function (line) {
if (!line) return;
startOffset = /^(\s*)/.exec(line)[1];
return true;
});
}
// check for startOffset again to remove leading white space from first line
if (startOffset) {
lines = lines.map(function (line) {
return line.replace(startOffset, '');
});
data = lines.join('\n');
}
js.push(data); // Collect JavaScript code.
}
var parser = new htmlparser.Parser({ onopentag: onopen, onclosetag: onclose, ontext: ontext });
parser.parseComplete(code);
return js.join("");
}
/**
* Recursively gather all files that need to be linted,
* excluding those that user asked to ignore.
*
* @param {string} fp a path to a file or directory to lint
* @param {array} files a pointer to an array that stores a list of files
* @param {array} ignores a list of patterns for files to ignore
* @param {array} ext a list of non-dot-js extensions to lint
*/
function collect(fp, files, ignores, ext) {
if (ignores && isIgnored(fp, ignores)) {
return;
}
if (!shjs.test("-e", fp)) {
cli.error("Can't open " + fp);
return;
}
if (shjs.test("-d", fp)) {
shjs.ls(fp).forEach(function (item) {
var itempath = path.join(fp, item);
if (shjs.test("-d", itempath) || item.match(ext)) {
collect(itempath, files, ignores, ext);
}
});
return;
}
files.push(fp);
}
/**
* Runs JSHint against provided file and saves the result
*
* @param {string} code code that needs to be linted
* @param {object} results a pointer to an object with results
* @param {object} config an object with JSHint configuration
* @param {object} data a pointer to an object with extra data
* @param {string} file (optional) file name that is being linted
*/
function lint(code, results, config, data, file) {
var globals;
var lintData;
var buffer = [];
config = config || {};
config = JSON.parse(JSON.stringify(config));
if (config.prereq) {
config.prereq.forEach(function (fp) {
fp = path.join(config.dirname, fp);
if (shjs.test("-e", fp))
buffer.push(shjs.cat(fp));
});
delete config.prereq;
}
if (config.globals) {
globals = config.globals;
delete config.globals;
}
delete config.dirname;
buffer.push(code);
buffer = buffer.join("\n");
buffer = buffer.replace(/^\uFEFF/, ""); // Remove potential Unicode BOM.
if (!JSHINT(buffer, config, globals)) {
JSHINT.errors.forEach(function (err) {
if (err) {
results.push({ file: file || "stdin", error: err });
}
});
}
lintData = JSHINT.data();
if (lintData) {
lintData.file = file || "stdin";
data.push(lintData);
}
}
var exports = {
extract: extract,
exit: exit,
/**
* Loads and parses a configuration file.
*
* @param {string} fp a path to the config file
* @returns {object} config object
*/
loadConfig: function (fp) {
if (!fp) {
return {};
}
if (!shjs.test("-e", fp)) {
cli.error("Can't find config file: " + fp);
exports.exit(1);
}
try {
var config = JSON.parse(removeComments(shjs.cat(fp)));
config.dirname = path.dirname(fp);
if (config['extends']) {
_.defaults(config, exports.loadConfig(path.resolve(config.dirname, config['extends'])));
delete config['extends'];
}
return config;
} catch (err) {
cli.error("Can't parse config file: " + fp);
exports.exit(1);
}
},
/**
* Gathers all files that need to be linted
*
* @param {object} post-processed options from 'interpret':
* args - CLI arguments
* ignores - A list of files/dirs to ignore (defaults to .jshintignores)
* extensions - A list of non-dot-js extensions to check
*/
gather: function (opts) {
var files = [];
var reg = new RegExp("\\.(js" +
(!opts.extensions ? "" : "|" +
opts.extensions.replace(/,/g, "|").replace(/[\. ]/g, "")) + ")$");
var ignores = !opts.ignores ? loadIgnores() : opts.ignores.map(function (target) {
return path.resolve(target);
});
opts.args.forEach(function (target) {
collect(target, files, ignores, reg);
});
return files;
},
/**
* Gathers all files that need to be linted, lints them, sends them to
* a reporter and returns the overall result.
*
* @param {object} post-processed options from 'interpret':
* args - CLI arguments
* config - Configuration object
* reporter - Reporter function
* ignores - A list of files/dirs to ignore
* extensions - A list of non-dot-js extensions to check
* @param {function} cb a callback to call when function is finished
* asynchronously.
*
* @returns {bool} 'true' if all files passed, 'false' otherwise and 'null'
* when function will be finished asynchronously.
*/
run: function (opts, cb) {
var files = exports.gather(opts);
var results = [];
var data = [];
if (opts.useStdin) {
cli.withStdin(function (code) {
lint(extract(code, opts.extract), results, opts.config || {}, data);
(opts.reporter || defReporter)(results, data, { verbose: opts.verbose });
cb(results.length === 0);
});
return null;
}
files.forEach(function (file) {
var config = opts.config || loadNpmConfig(file) || exports.loadConfig(findConfig(file));
var code;
try {
code = shjs.cat(file);
} catch (err) {
cli.error("Can't open " + file);
exports.exit(1);
}
lint(extract(code, opts.extract), results, config, data, file);
});
(opts.reporter || defReporter)(results, data, { verbose: opts.verbose });
return results.length === 0;
},
/**
* Helper exposed for testing.
* Used to determine is stdout has any buffered output before exiting the program
*/
getBufferSize: function () {
return process.stdout.bufferSize;
},
/**
* Main entrance function. Parses arguments and calls 'run' when
* its done. This function is called from bin/jshint file.
*
* @param {object} args, arguments in the process.argv format.
*/
interpret: function (args) {
cli.setArgv(args);
cli.options = {};
cli.enable("version", "glob", "help");
cli.setApp(path.resolve(__dirname + "/../package.json"));
var options = cli.parse(OPTIONS);
// Use config file if specified
var config;
if (options.config) {
config = exports.loadConfig(options.config);
}
switch (true) {
// JSLint reporter
case options.reporter === "jslint":
case options["jslint-reporter"]:
options.reporter = "./reporters/jslint_xml.js";
break;
// CheckStyle (XML) reporter
case options.reporter === "checkstyle":
case options["checkstyle-reporter"]:
options.reporter = "./reporters/checkstyle.js";
break;
// Reporter that displays additional JSHint data
case options["show-non-errors"]:
options.reporter = "./reporters/non_error.js";
break;
// Custom reporter
case options.reporter !== undefined:
options.reporter = path.resolve(process.cwd(), options.reporter);
}
var reporter;
if (options.reporter) {
reporter = loadReporter(options.reporter);
if (reporter === null) {
cli.error("Can't load reporter file: " + options.reporter);
exports.exit(1);
}
}
// This is a hack. exports.run is both sync and async function
// because I needed stdin support (and cli.withStdin is async)
// and was too lazy to change tests.
function done(passed) {
/*jshint eqnull:true */
if (passed == null)
return;
exports.exit(passed ? 0 : 2);
}
done(exports.run({
args: cli.args,
config: config,
reporter: reporter,
ignores: loadIgnores(options.exclude, options["exclude-path"]),
extensions: options["extra-ext"],
verbose: options.verbose,
extract: options.extract,
useStdin: {"-": true, "/dev/stdin": true}[args[args.length - 1]]
}, done));
}
};
module.exports = exports;