-
-
Notifications
You must be signed in to change notification settings - Fork 374
/
htmlhint
executable file
·393 lines (361 loc) · 10.9 KB
/
htmlhint
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
#!/usr/bin/env node
var program = require('commander');
var fs = require('fs');
var path = require('path');
var stripJsonComments = require('strip-json-comments');
var async = require('async');
var glob = require("glob");
var parseGlob = require('parse-glob');
var request = require('request');
var HTMLHint = require("../index").HTMLHint;
var formatter = require('./formatter');
var pkg = require('../package.json');
require('colors');
function map(val) {
var objMap = {};
val.split(',').forEach(function(item){
var arrItem = item.split(/\s*=\s*/);
objMap[arrItem[0]] = arrItem[1]?arrItem[1]:true;
});
return objMap;
}
program.on('--help', function(){
console.log(' Examples:');
console.log('');
console.log(' htmlhint');
console.log(' htmlhint www');
console.log(' htmlhint www/test.html');
console.log(' htmlhint www/**/*.xhtml');
console.log(' htmlhint www/**/*.{htm,html}');
console.log(' htmlhint http://www.alibaba.com/');
console.log(' cat test.html | htmlhint stdin');
console.log(' htmlhint --list');
console.log(' htmlhint --rules tag-pair,id-class-value=underline test.html');
console.log(' htmlhint --config .htmlhintrc test.html');
console.log(' htmlhint --ignore **/build/**,**/test/**');
console.log(' htmlhint --rulesdir ./rules/');
console.log('');
});
var arrSupportedFormatters = formatter.getSupported();
program
.version(pkg.version)
.usage('<file|folder|pattern|stdin|url ...> [options]')
.option('-l, --list', 'show all of the rules available')
.option('-c, --config <file>', 'custom configuration file')
.option('-r, --rules <ruleid, ruleid=value ...>', 'set all of the rules available', map)
.option('-R, --rulesdir <file|folder>', 'load custom rules from file or folder')
.option('-f, --format <'+arrSupportedFormatters.join('|')+'>', 'output messages as custom format')
.option('-i, --ignore <pattern, pattern ...>', 'add pattern to exclude matches')
.option('--nocolor', 'disable color')
.option('--warn', 'Warn only, exit with 0')
.parse(process.argv);
if(program.list){
listRules();
process.exit(0);
}
var arrTargets = program.args;
if(arrTargets.length === 0){
arrTargets.push('./');
}
// init formatter
formatter.init(HTMLHint, {
'nocolor': program.nocolor
});
var format = program.format || 'default';
if(format){
formatter.setFormat(format);
}
hintTargets(arrTargets, {
rulesdir: program.rulesdir,
ruleset: program.rules,
formatter: formatter,
ignore: program.ignore
});
// list all rules
function listRules(){
var rules = HTMLHint.rules;
var rule;
console.log(' All rules:');
console.log(' ==================================================');
for (var id in rules){
rule = rules[id];
console.log(' %s : %s', rule.id.bold, rule.description);
}
}
function hintTargets(arrTargets, options){
var arrAllMessages = [];
var allFileCount = 0;
var allHintFileCount = 0;
var allHintCount = 0;
var startTime = new Date().getTime();
var formatter = options.formatter;
// load custom rules
var rulesdir = options.rulesdir;
if(rulesdir){
loadCustomRules(rulesdir);
}
// start hint
formatter.emit('start');
var arrTasks = [];
arrTargets.forEach(function(target){
arrTasks.push(function(next){
hintAllFiles(target, options, function(result){
allFileCount += result.targetFileCount;
allHintFileCount += result.targetHintFileCount;
allHintCount += result.targetHintCount;
arrAllMessages = arrAllMessages.concat(result.arrTargetMessages);
next();
});
});
});
async.series(arrTasks, function(){
// end hint
var spendTime = new Date().getTime() - startTime;
formatter.emit('end', {
arrAllMessages: arrAllMessages,
allFileCount: allFileCount,
allHintFileCount: allHintFileCount,
allHintCount: allHintCount,
time: spendTime
});
process.exit(!program.warn && allHintCount > 0 ? 1 : 0);
});
}
// load custom rles
function loadCustomRules(rulesdir){
rulesdir = rulesdir.replace(/\\/g, '/');
if(fs.existsSync(rulesdir)){
if(fs.statSync(rulesdir).isDirectory()){
rulesdir += /\/$/.test(rulesdir)?'':'/';
rulesdir += '**/*.js';
var arrFiles = glob.sync(rulesdir, {
'dot': false,
'nodir': true,
'strict': false,
'silent': true
});
arrFiles.forEach(function(file){
loadRule(file);
});
}
else{
loadRule(rulesdir);
}
}
}
// load rule
function loadRule(filepath){
filepath = path.resolve(filepath);
try{
var module = require(filepath);
module(HTMLHint);
}
catch(e){}
}
// hint all files
function hintAllFiles(target, options, onFinised){
var globInfo = getGlobInfo(target);
globInfo.ignore = options.ignore;
var formatter = options.formatter;
// hint result
var targetFileCount = 0;
var targetHintFileCount = 0;
var targetHintCount = 0;
var arrTargetMessages = [];
// init ruleset
var ruleset = options.ruleset;
if(ruleset === undefined){
ruleset = getConfig(program.config, globInfo.base, formatter);
}
// hint queue
var hintQueue = async.queue(function (filepath, next) {
var startTime = new Date().getTime();
if(filepath === 'stdin'){
hintStdin(ruleset, hintNext);
}
else if(/^https?:\/\//.test(filepath)){
hintUrl(filepath, ruleset, hintNext);
}
else{
var messages = hintFile(filepath, ruleset);
hintNext(messages);
}
function hintNext(messages){
var spendTime = new Date().getTime() - startTime;
var hintCount = messages.length;
if(hintCount > 0){
formatter.emit('file', {
'file': filepath,
'messages': messages,
'time': spendTime
});
arrTargetMessages.push({
'file': filepath,
'messages': messages,
'time': spendTime
});
targetHintFileCount ++;
targetHintCount += hintCount;
}
targetFileCount ++;
setImmediate(next);
}
}, 10);
// start hint
var isWalkDone = false;
var isHintDone = true;
hintQueue.drain = function() {
isHintDone = true;
checkAllHinted();
};
function checkAllHinted(){
if(isWalkDone && isHintDone){
onFinised({
targetFileCount: targetFileCount,
targetHintFileCount: targetHintFileCount,
targetHintCount: targetHintCount,
arrTargetMessages: arrTargetMessages
});
}
}
if(target === 'stdin'){
isWalkDone = true;
hintQueue.push(target);
}
else if(/^https?:\/\//.test(target)){
isWalkDone = true;
hintQueue.push(target);
}
else{
walkPath(globInfo, function(filepath){
isHintDone = false;
hintQueue.push(filepath);
}, function(){
isWalkDone = true;
checkAllHinted();
});
}
}
// split target to base & glob
function getGlobInfo(target){
// fix windows sep
target = target.replace(/\\/g, '/');
var globInfo = parseGlob(target);
var base = path.resolve(globInfo.base);
base += /\/$/.test(base) ? '' : '/';
var pattern = globInfo.glob;
var globPath = globInfo.path;
var defaultGlob = '*.{htm,html}';
if(globInfo.is.glob === true){
// no basename
if(globPath.basename === ''){
pattern += defaultGlob;
}
}
else{
// no basename
if(globPath.basename === ''){
pattern += '**/' + defaultGlob;
}
// detect directory
else if(fs.existsSync(target) && fs.statSync(target).isDirectory()){
base += globPath.basename + '/';
pattern = '**/' + defaultGlob;
}
}
return {
base: base,
pattern: pattern
};
}
// search and load config
function getConfig(configPath, base, formatter){
if(configPath === undefined && fs.existsSync(base)){
// find default config file in parent directory
if(fs.statSync(base).isDirectory() === false){
base = path.dirname(base);
}
while(base){
var tmpConfigFile = path.resolve(base, '.htmlhintrc');
if(fs.existsSync(tmpConfigFile)){
configPath = tmpConfigFile;
break;
}
if (!base) {break;}
base = base.substring(0,base.lastIndexOf(path.sep));
}
}
if(fs.existsSync(configPath)){
var config = fs.readFileSync(configPath, 'utf-8'),
ruleset;
try{
ruleset = JSON.parse(stripJsonComments(config));
formatter.emit('config', {
ruleset: ruleset,
configPath: configPath
});
}
catch(e){}
return ruleset;
}
}
// walk path
function walkPath(globInfo, callback, onFinish) {
var base = globInfo.base;
var pattern = globInfo.pattern;
var ignore = globInfo.ignore;
var arrIgnores = ['**/node_modules/**'];
if(ignore){
ignore.split(',').forEach(function(pattern){
arrIgnores.push(pattern);
});
}
var walk = glob(pattern, {
'cwd': base,
'dot': false,
'ignore': arrIgnores,
'nodir': true,
'strict': false,
'silent': true
},function() {
onFinish();
});
walk.on('match', function(file){
base = base.replace(/^.\//, '');
callback(base + file);
});
}
// hint file
function hintFile(filepath, ruleset){
var content = '';
try{
content = fs.readFileSync(filepath, 'utf-8');
}
catch(e){}
return HTMLHint.verify(content, ruleset);
}
// hint stdin
function hintStdin(ruleset, callback){
process.stdin.setEncoding('utf8');
var buffers = [];
process.stdin.on('data', function(text){
buffers.push(text);
});
process.stdin.on('end', function(){
var content = buffers.join('');
var messages = HTMLHint.verify(content, ruleset);
callback(messages);
});
}
// hint url
function hintUrl(url, ruleset, callback){
request.get(url, function(error, response, body){
if(!error && response.statusCode == 200){
var messages = HTMLHint.verify(body, ruleset);
callback(messages);
}
else{
callback([]);
}
});
}