This repository has been archived by the owner on Apr 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
executable file
·459 lines (385 loc) · 14.3 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
#!/usr/bin/env node
/*!
CSSLint
Copyright (c) 2013 Nicole Sullivan and Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Build: v0.10.0 15-August-2013 01:07:22 *//*
* Encapsulates all of the CLI functionality. The api argument simply
* provides environment-specific functionality.
*/
/*global CSSLint*/
function cli(api){
var globalOptions = {
"help" : { "format" : "", "description" : "Displays this information."},
"format" : { "format" : "<format>", "description" : "Indicate which format to use for output."},
"list-rules" : { "format" : "", "description" : "Outputs all of the rules available."},
"quiet" : { "format" : "", "description" : "Only output when errors are present."},
"errors" : { "format" : "<rule[,rule]+>", "description" : "Indicate which rules to include as errors."},
"warnings" : { "format" : "<rule[,rule]+>", "description" : "Indicate which rules to include as warnings."},
"ignore" : { "format" : "<rule[,rule]+>", "description" : "Indicate which rules to ignore completely."},
"exclude-list": { "format" : "<file|dir[,file|dir]+>", "description" : "Indicate which files/directories to exclude from being linted."},
"version" : { "format" : "", "description" : "Outputs the current version number."}
};
//-------------------------------------------------------------------------
// Helper functions
//-------------------------------------------------------------------------
/**
* Returns an array of messages for a particular type.
* @param messages {Array} Array of CSS Lint messages.
* @param type {String} The type of message to filter on.
* @return {Array} An array of matching messages.
*/
function pluckByType(messages, type){
return messages.filter(function(message) {
return message.type === type;
});
}
/**
* Returns a ruleset object based on the CLI options.
* @param options {Object} The CLI options.
* @return {Object} A ruleset object.
*/
function gatherRules(options, ruleset){
var warnings = options.rules || options.warnings,
errors = options.errors;
if (warnings){
ruleset = ruleset || {};
warnings.split(",").forEach(function(value){
ruleset[value] = 1;
});
}
if (errors){
ruleset = ruleset || {};
errors.split(",").forEach(function(value){
ruleset[value] = 2;
});
}
return ruleset;
}
/**
* Filters out rules using the ignore command line option.
* @param options {Object} the CLI options
* @return {Object} A ruleset object.
*/
function filterRules(options) {
var ignore = options.ignore,
ruleset = null;
if (ignore) {
ruleset = CSSLint.getRuleset();
ignore.split(",").forEach(function(value){
ruleset[value] = 0;
});
}
return ruleset;
}
/**
* Filters out files using the exclude-list command line option.
* @param files {Array} the list of files to check for exclusions
* @param options {Object} the CLI options
* @return {Array} A list of files
*/
function filterFiles(files, options) {
var excludeList = options["exclude-list"],
excludeFiles = [],
filesToLint = files.map(api.getFullPath),
fullPath;
if (excludeList) {
// Build up the exclude list, expanding any directory exclusions that were passed in
excludeList.split(",").forEach(function(value){
if (api.isDirectory(value)) {
excludeFiles = excludeFiles.concat(api.getFiles(value));
} else {
excludeFiles.push(value);
}
});
// Remove the excluded files from the list of files to lint
excludeFiles.forEach(function(value){
fullPath = api.getFullPath(value);
if (filesToLint.indexOf(fullPath) > -1) {
filesToLint.splice(filesToLint.indexOf(fullPath),1);
}
});
}
return filesToLint;
}
/**
* Outputs all available rules to the CLI.
* @return {void}
*/
function printRules(){
api.print("");
var rules = CSSLint.getRules();
rules.forEach(function(rule){
api.print(rule.id + "\n " + rule.desc + "\n");
});
}
/**
* Given a file name and options, run verification and print formatted output.
* @param {String} relativeFilePath absolute file location
* @param {Object} options for processing
* @return {Number} exit code
*/
function processFile(input, relativeFilePath, options) {
var ruleset = filterRules(options),
result = CSSLint.verify(input, gatherRules(options, ruleset)),
formatter = CSSLint.getFormatter(options.format || "text"),
messages = result.messages || [],
output,
exitCode = 0;
if (!input) {
if (formatter.readError) {
api.print(formatter.readError(relativeFilePath, "Could not read file data. Is the file empty?"));
} else {
api.print("csslint: Could not read file data in " + relativeFilePath + ". Is the file empty?");
}
exitCode = 1;
} else {
//var relativeFilePath = getRelativePath(api.getWorkingDirectory(), fullFilePath);
options.fullPath = api.getFullPath(relativeFilePath);
output = formatter.formatResults(result, relativeFilePath, options);
if (output){
api.print(output);
}
if (messages.length > 0 && pluckByType(messages, "error").length > 0) {
exitCode = 1;
}
}
return exitCode;
}
/**
* Outputs the help screen to the CLI.
* @return {void}
*/
function outputHelp(){
var lenToPad = 40,
toPrint = '',
formatString = '';
api.print([
"\nUsage: csslint-rhino.js [options]* [file|dir]*",
" ",
"Global Options"
].join("\n"));
for (var optionName in globalOptions) {
if (globalOptions.hasOwnProperty(optionName)) {
// Print the option name and the format if present
toPrint += " --" + optionName;
if (globalOptions[optionName].format !== "") {
formatString = '=' + globalOptions[optionName].format;
toPrint += formatString;
} else {
formatString = '';
}
// Pad out with the appropriate number of spaces
toPrint += new Array(lenToPad - (optionName.length + formatString.length)).join(' ');
// Print the description
toPrint += globalOptions[optionName].description + "\n";
}
}
api.print(toPrint);
}
/**
* Given an Array of filenames, print wrapping output and process them.
* @param files {Array} filenames list
* @param options {Object} options object
* @return {Number} exit code
*/
function processFiles(fileArray, options){
var exitCode = 0,
formatId = options.format || "text",
formatter,
files = filterFiles(fileArray,options),
output;
if (!files.length) {
api.print("csslint: No files specified.");
exitCode = 1;
} else {
if (!CSSLint.hasFormat(formatId)){
api.print("csslint: Unknown format '" + formatId + "'. Cannot proceed.");
exitCode = 1;
} else {
formatter = CSSLint.getFormatter(formatId);
output = formatter.startFormat();
if (output){
api.print(output);
}
return files.reduce(function(promise, file){
return promise.then(function() {
return api.readFile(file)
}).then(function(contents){
if (exitCode === 0) {
return processFile(contents, file,options).then(function(code){
exitCode = code
})
} else {
return processFile(contents, file,options);
}
})
}, Promise.resolve()).then(function(){
output = formatter.endFormat();
if (output){
api.print(output);
}
return exitCode
})
}
}
}
function processArguments(args, options) {
var arg = args.shift(),
argName,
parts,
files = [];
while(arg){
if (arg.indexOf("--") === 0){
argName = arg.substring(2);
if (argName.indexOf("=") > -1){
parts = argName.split("=");
options[parts[0]] = parts[1];
} else {
options[argName] = true;
}
} else {
//see if it's a directory or a file
if (api.isDirectory(arg)){
files = files.concat(api.getFiles(arg));
} else {
files.push(arg);
}
}
arg = args.shift();
}
options.files = files;
return options;
}
function validateOptions(options) {
for (var option_key in options) {
if (!globalOptions.hasOwnProperty(option_key) && option_key !== 'files') {
api.print(option_key + ' is not a valid option. Exiting...');
outputHelp();
api.quit(0);
}
}
}
function readConfigFile(options) {
var data = api.readFile(api.getFullPath(".csslintrc"));
if (data) {
options = processArguments(data.split(/[\s\n\r]+/m), options);
}
return options;
}
//-----------------------------------------------------------------------------
// Process command line
//-----------------------------------------------------------------------------
var args = api.args,
argCount = args.length,
options = {};
// first look for config file .csslintrc
options = readConfigFile(options);
// Command line arguments override config file
options = processArguments(args, options);
if (options.help || argCount === 0){
outputHelp();
api.quit(0);
}
// Validate options
validateOptions(options);
if (options.version){
api.print("v" + CSSLint.version);
api.quit(0);
}
if (options["list-rules"]){
printRules();
api.quit(0);
}
Promise.resolve(processFiles(options.files,options)).then(function(exitCode){
api.quit(exitCode);
});
}
/*
* CSSLint Node.js Command Line Interface
*/
/*jshint node:true*/
/*global cli*/
var fs = require("fs"),
path = require("path"),
CSSLint = require("./lib/csslint-node").CSSLint;
cli({
args: process.argv.slice(2),
print: function(message){
fs.writeSync(1, message + "\n");
},
quit: function(code){
process.exit(code || 0);
},
isDirectory: function(name){
try {
return fs.statSync(name).isDirectory();
} catch (ex) {
return false;
}
},
getFiles: function(dir){
var files = [];
try {
fs.statSync(dir);
} catch (ex){
return [];
}
function traverse(dir, stack){
stack.push(dir);
fs.readdirSync(stack.join("/")).forEach(function(file){
var path = stack.concat([file]).join("/"),
stat = fs.statSync(path);
if (file[0] == ".") {
return;
} else if (stat.isFile() && /\.css$/.test(file)){
files.push(path);
} else if (stat.isDirectory()){
traverse(file, stack);
}
});
stack.pop();
}
traverse(dir, []);
return files;
},
getWorkingDirectory: function() {
return process.cwd();
},
getFullPath: function(filename){
return path.resolve(process.cwd(), filename);
},
readFile: function(filename){
if(path.basename(filename) === '-'){
return new Promise(function(resolve, reject) {
var data = []
process.stdin.on('data', function(chunk){
data.push(chunk.toString())
})
process.stdin.on('end', function(){
resolve(data.join(''))
})
})
}
try {
return fs.readFileSync(filename, "utf-8");
} catch (ex) {
return "";
}
}
});