-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
106 lines (83 loc) · 2.67 KB
/
index.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
var path = require( 'path' );
var chalk = require( 'chalk' );
var linter = require( 'eslint' ).linter;
var sander = require( 'sander' );
var promiseMapSeries = require( 'promise-map-series' );
var findup = require( 'findup-sync' );
var sorcery = require( 'sorcery' );
var logSyntaxError = require( 'log-syntax-error' );
var eslintrc = findup( '.eslintrc' );
var defaultOptions;
if ( eslintrc ) {
try {
defaultOptions = JSON.parse( require( 'fs' ).readFileSync( eslintrc ) );
} catch ( err ) {
throw new Error( 'Could not parse .eslintrc file. It must be valid JSON' );
}
}
module.exports = function eslint ( inputdir, options ) {
var log = this.log;
var reportOnly = options.reportOnly;
var reporter = options.reporter || defaultReporter;
delete options.reporter;
delete options.reportOnly;
if ( !Object.keys( options ).length ) {
options = defaultOptions;
}
var reports = [];
return sander.lsr( inputdir ).then( function ( files ) {
return promiseMapSeries( files.filter( isJs ), function ( file ) {
var filename = path.join( inputdir, file );
return sander.readFile( filename )
.then( String )
.then( function ( code ) {
log( 'linting ' + file );
var messages = linter.verify( code, options, filename );
if ( messages.length ) {
reports.push({
filename: filename,
messages: messages.sort( bySeverity )
});
}
});
});
}).then( function () {
if ( reports.length ) {
reporter( reports );
if ( !reportOnly ) {
throw new Error( 'Linting failed' );
}
}
});
};
function isJs ( file ) {
return /\.js$/.test( file );
}
function bySeverity ( a, b ) {
return b.severity - a.severity;
}
function defaultReporter ( reports ) {
reports.forEach( function ( report ) {
var numErrors = report.messages.length;
var chain = sorcery.loadSync( report.filename );
var source = sander.readFileSync( report.filename ).toString();
console.log( '===\n\n%s %s in %s', numErrors, numErrors === 1 ? 'error' : 'errors', report.filename );
report.messages.forEach( function ( message ) {
var block, originalLocation, originalSource;
console.log( '\n---\n' );
console.log( message.message );
block = logSyntaxError( source, message.line, message.column );
console.log( block );
if ( chain ) {
originalLocation = chain.trace( message.line, message.column );
if ( originalLocation ) {
originalSource = sander.readFileSync( originalLocation.source ).toString();
console.log( '\noriginal source: ' + originalLocation.source );
block = logSyntaxError( originalSource, originalLocation.line, originalLocation.column );
console.log( block );
}
}
});
});
console.log( '\n\n' );
}