-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
219 lines (178 loc) · 7.02 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
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
/* eslint global-require: 0, consistent-return: 0 */
const Filter = require('broccoli-persistent-filter');
const CLIEngine = require('eslint').CLIEngine;
const md5Hex = require('md5-hex');
const stringify = require('json-stable-stringify');
const path = require('path');
const escapeStringRegexp = require('escape-string-regexp');
const BUILD_DIR_REGEXP = new RegExp('(' + escapeStringRegexp(path.sep) + ')?build(' + escapeStringRegexp(path.sep) + ')?$');
const IGNORED_FILE_MESSAGE_REGEXP = /(?:File ignored by default\.)|(?:File ignored because of a matching ignore pattern\.)/;
/**
* Calculates the severity of a eslint.linter.verify result
* @param {Array} result Eslint verify result array
* @returns {Number} If the returned number is greater than 0 the result contains errors.
*/
function getResultSeverity(resultMessages = []) {
// count all errors
return resultMessages.reduce((totalSeverity, message) => {
if (message.fatal) {
return totalSeverity + 1;
}
if (message.severity === 2) {
return totalSeverity + 1;
}
return totalSeverity;
}, 0);
}
/**
* Ignores messages that are about ignored files as they are intended
* but we are processing a file at a time
*
* @param {Array} errors result errors
* @returns {Array} filtered errors
*/
function filterIgnoredFileMessages(errors) {
return errors.filter((error) => !IGNORED_FILE_MESSAGE_REGEXP.test(error.message));
}
/**
* Filters all ignored file messages from result object
* @param {Object} result result errors
* @returns {Object} filtered results
*/
function filterAllIgnoredFileMessages(result) {
const resultOutput = result;
resultOutput.results.forEach((resultItem) => {
resultItem.messages = filterIgnoredFileMessages(resultItem.messages);
});
return resultOutput;
}
function isString(x) {
return toString.call(x) === '[object String]';
}
function resolveInputDirectory(inputNode) {
if (typeof inputNode === 'string') {
return inputNode;
}
// eslint-disable-next-line no-underscore-dangle
const nodeInfo = inputNode.__broccoliGetInfo__();
if (nodeInfo.nodeType === 'source') {
return nodeInfo.sourceDirectory;
}
if (nodeInfo.inputNodes.length > 1) {
// eslint-disable-next-line max-len
throw new Error('EslintValidationFilter can only handle one:* broccoli nodes, but part of the given input pipeline is a many:* node. (broccoli-merge-trees is an example of a many:* node) Please perform many:* operations after linting.');
}
return resolveInputDirectory(nodeInfo.inputNodes[0]);
}
/**
* Uses the content of each file in a given node and runs eslint validation on it.
* @param {Object} inputNode Node from broccoli.makeTree
* @param {{config: String, rulesdir: String, format: String}} options Filter options
* @returns {EslintValidationFilter} Filter obconfig @constructor
*/
function EslintValidationFilter(inputNode, options = {}) {
if (!(this instanceof EslintValidationFilter)) {
return new EslintValidationFilter(inputNode, options);
}
this.internalOptions = options;
const eslintOptions = options.options || {};
// default ignore:true option
if (typeof eslintOptions.ignore === 'undefined') {
eslintOptions.ignore = true;
}
// default is to persist filter output
if (typeof this.internalOptions.persist === 'undefined') {
this.internalOptions.persist = true;
}
// call base class constructor
Filter.call(this, inputNode, this.internalOptions);
// set formatter
if (typeof this.internalOptions.format === 'function') {
this.formatter = this.internalOptions.format;
} else {
// eslint-disable-next-line global-require
this.formatter = require(this.internalOptions.format || 'eslint/lib/formatters/stylish');
}
this.console = options.console || console;
this.cli = new CLIEngine(eslintOptions);
this.eslintrc = resolveInputDirectory(inputNode);
if (isString(this.internalOptions.testGenerator)) {
const testGenerators = require('./test-generators');
this.testGenerator = testGenerators[this.internalOptions.testGenerator];
if (!this.testGenerator) {
throw new Error(`Could not find '${this.internalOptions.testGenerator}' test generator.`);
}
} else {
this.testGenerator = this.internalOptions.testGenerator;
}
if (this.testGenerator) {
this.targetExtension = 'lint-test.js';
}
}
module.exports = EslintValidationFilter;
EslintValidationFilter.prototype = Object.create(Filter.prototype);
EslintValidationFilter.prototype.constructor = EslintValidationFilter;
EslintValidationFilter.prototype.extensions = ['js'];
EslintValidationFilter.prototype.targetExtension = 'js';
EslintValidationFilter.prototype.baseDir = function baseDir() {
return __dirname.replace(BUILD_DIR_REGEXP, '');
};
EslintValidationFilter.prototype.cacheKeyProcessString = function cacheKeyProcessString(content, relativePath) {
function functionStringifier(key, value) {
if (typeof value === 'function') {
return value.toString();
}
return value;
}
return md5Hex([
content,
relativePath,
stringify(this.internalOptions, {replacer: functionStringifier}),
stringify(this.cli.getConfigForFile(path.join(this.eslintrc, relativePath)))
]);
};
EslintValidationFilter.prototype.processString = function processString(content, relativePath) {
// verify file content
const configPath = path.join(this.eslintrc, relativePath);
const report = this.cli.executeOnText(content, configPath);
const filteredReport = filterAllIgnoredFileMessages(report);
const toCache = { report, output: content };
if (this.testGenerator && Array.isArray(filteredReport.results)) {
const result = filteredReport.results[0] || {};
const messages = result.messages || [];
toCache.output = this.testGenerator(relativePath, messages, result);
}
return toCache;
};
/**
* Post-process the filtered output, calculating the result severity from the report
* if the option to `throwOnError` has been set
*
* @param {Object} results A results object returned from `processString` containing
* the following properties:
* report {Object}: The report returned from this.cli.executeOnText()
* output {string}: The original file content passed to `processString` -- or the
* result of executing the a provided `testGenerator` function on the `report`
*
* @returns {Object} An object with an `.output` property, which will be
* used as the emitted file contents
*/
EslintValidationFilter.prototype.postProcess = function postProcess({ report, output } /* , relativePath */) {
// if verification has result
if (report.results.length && report.results[0].messages.length) {
// log formatter output
const results = this.formatter(report.results);
if (results) {
this.console.log(results);
}
if ('throwOnError' in this.internalOptions && this.internalOptions.throwOnError === true) {
if (getResultSeverity(report.results[0].messages) > 0) {
// throw error if severe messages exist
throw new Error('rules violation with `error` severity level');
}
}
}
return {
output
};
};