This repository has been archived by the owner on Jun 21, 2019. It is now read-only.
/
cli.js
442 lines (379 loc) · 10.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
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
"use strict";
var cli = require("cli");
var path = require("path");
var shjs = require("shelljs");
var minimatch = require("minimatch");
var JSHINT = require("../stable/jshint.js").JSHINT;
var defReporter = require("../reporters/default").reporter;
var OPTIONS = {
"config": ["config", "Custom configuration file", "string", false ],
"reporter": ["reporter", "Custom reporter", "string", undefined ],
"verbose": ["verbose", "Show message codes"],
"show-non-errors": ["show-non-errors", "Show additional data generated by jshint"],
"extra-ext": ["extra-ext",
"Comma-separated list of file extensions to use (default is .js)", "string", ""],
// 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;
}
/**
* Loads and parses a configuration file.
*
* @param {string} fp a path to the config file
* @returns {object} config object
*/
function loadConfig(fp) {
if (!fp) {
return {};
}
if (!shjs.test("-e", fp)) {
cli.error("Can't find config file: " + fp);
process.exit(1);
}
try {
return JSON.parse(removeComments(shjs.cat(fp)));
} catch (err) {
cli.error("Can't parse config file: " + fp);
process.exit(1);
}
}
/**
* Tries to find a configuration file in either project directory
* or in the home directory. Configuration files are named
* '.jshintrc'.
*
* @param {sting} file path to the file to be linted
* @returns {string} a path to the config file
*/
function findConfig(file) {
var name = ".jshintrc";
var dir = path.dirname(path.resolve(file));
var proj = findFile(name, dir);
var home = path.normalize(path.join(process.env.HOME ||
process.env.HOMEPATH ||
process.env.USERPROFILE, name));
if (proj) {
return proj;
}
if (shjs.test("-e", home)) {
return home;
}
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() {
var file = findFile(".jshintignore");
if (!file) {
return;
}
return shjs.cat(file).split("\n")
.filter(function (line) {
return !!line.trim();
})
.map(function (line) {
return path.resolve(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;
}
});
}
/**
* 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} file a path to a file 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
*/
function lint(file, results, config, data) {
var buffer;
var globals;
var lintData;
config = config || {};
config = JSON.parse(JSON.stringify(config));
try {
buffer = shjs.cat(file);
} catch (err) {
cli.error("Can't open " + file);
process.exit(1);
}
// Remove potential Unicode BOM.
buffer = buffer.replace(/^\uFEFF/, "");
if (config.globals) {
globals = config.globals;
delete config.globals;
}
if (!JSHINT(buffer, config, globals)) {
JSHINT.errors.forEach(function (err) {
if (err) {
results.push({ file: file, error: err });
}
});
}
lintData = JSHINT.data();
if (lintData) {
lintData.file = file;
data.push(lintData);
}
}
var exports = {
/**
* 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
*
* @returns {bool} 'true' if all files passed and 'false' otherwise.
*/
run: function (opts) {
var files = exports.gather(opts);
var results = [];
var data = [];
files.forEach(function (file) {
var config = opts.config || loadConfig(findConfig(file));
lint(file, results, config, data);
});
(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 = 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);
process.exit(1);
}
}
var passed = exports.run({
args: cli.args,
config: config,
reporter: reporter,
ignores: loadIgnores(),
extensions: options["extra-ext"],
verbose: options.verbose
});
// Patch as per https://github.com/visionmedia/mocha/issues/333
// fixes issues with piped output on Windows.
// Root issue is here https://github.com/joyent/node/issues/3584
function exit() { process.exit(passed ? 0 : 2); }
try {
if (exports.getBufferSize()) {
process.stdout.once('drain', exit);
} else {
exit();
}
} catch (err) {
exit();
}
}
};
module.exports = exports;