gulp-eslint-new 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2016 ADAMETRY
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,282 @@
1
+ # gulp-eslint-new · [![npm version][npm badge]][npm URL]
2
+
3
+ > A [gulp](https://gulpjs.com/) plugin to lint code with [ESLint](https://eslint.org/) 8
4
+
5
+ ## Installation
6
+
7
+ [Use](https://docs.npmjs.com/cli/install) [npm](https://docs.npmjs.com/about-npm).
8
+
9
+ ```
10
+ npm install gulp-eslint-new
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```javascript
16
+ const {src, task} = require('gulp');
17
+ const eslint = require('gulp-eslint-new');
18
+
19
+ task('default', () => {
20
+ return src(['scripts/*.js'])
21
+ // eslint() attaches the lint output to the "eslint" property
22
+ // of the file object so it can be used by other modules.
23
+ .pipe(eslint())
24
+ // eslint.format() outputs the lint results to the console.
25
+ // Alternatively use eslint.formatEach() (see Docs).
26
+ .pipe(eslint.format())
27
+ // To have the process exit with an error code (1) on
28
+ // lint error, return the stream and pipe to failAfterError last.
29
+ .pipe(eslint.failAfterError());
30
+ });
31
+ ```
32
+
33
+ Or use the plugin API to do things like:
34
+
35
+ ```javascript
36
+ gulp.src(['**/*.js','!node_modules/**'])
37
+ .pipe(eslint({
38
+ rules: {
39
+ 'my-custom-rule': 1,
40
+ 'strict': 2
41
+ },
42
+ globals: [
43
+ 'jQuery',
44
+ '$'
45
+ ],
46
+ envs: [
47
+ 'browser'
48
+ ]
49
+ }))
50
+ .pipe(eslint.formatEach('compact', process.stderr));
51
+ ```
52
+
53
+ For additional examples, look through the [example directory](https://github.com/fasttime/gulp-eslint-new/tree/master/example).
54
+
55
+ ## API
56
+
57
+ ### `eslint()`
58
+
59
+ *No explicit configuration.* A `.eslintrc` file may be resolved relative to each linted file.
60
+
61
+ ### `eslint(options)`
62
+
63
+ [ESLint constructor options](https://eslint.org/docs/developer-guide/nodejs-api#parameters).
64
+ Additionally, the following options are supported, mostly for backward compatibility with [gulp-eslint](https://github.com/adametry/gulp-eslint).
65
+
66
+ #### `options.rules`
67
+
68
+ Type: `Object`
69
+
70
+ Set [configuration](https://eslint.org/docs/user-guide/configuring/rules#configuring-rules) of [rules](https://eslint.org/docs/rules/).
71
+
72
+ ```javascript
73
+ {
74
+ "rules":{
75
+ "camelcase": 1,
76
+ "comma-dangle": 2,
77
+ "quotes": 0
78
+ }
79
+ }
80
+ ```
81
+
82
+ _Prefer using `options.overrideConfig.rules` instead._
83
+
84
+ #### `options.globals`
85
+
86
+ Type: `Array`
87
+
88
+ Specify [global variables](https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals) to declare.
89
+
90
+ ```javascript
91
+ {
92
+ "globals":[
93
+ "jQuery",
94
+ "$"
95
+ ]
96
+ }
97
+ ```
98
+
99
+ _Prefer using `options.overrideConfig.globals` instead. Note the different format._
100
+
101
+ #### `options.fix`
102
+
103
+ Type: `Boolean`
104
+
105
+ This option instructs ESLint to try to fix as many issues as possible. The fixes are applied to the gulp stream. The fixed content can be saved to file using `gulp.dest` (See [example/fix.js](https://github.com/fasttime/gulp-eslint-new/blob/master/example/fix.js)). Rules that are fixable can be found in ESLint's [rules list](https://eslint.org/docs/rules/).
106
+
107
+ When fixes are applied, a "fixed" property is set to `true` on the fixed file's ESLint result.
108
+
109
+ #### `options.quiet`
110
+
111
+ Type: `Boolean`
112
+
113
+ When `true`, this option will filter warning messages from ESLint results. This mimics the ESLint CLI [`--quiet` option](https://eslint.org/docs/user-guide/command-line-interface#-quiet).
114
+
115
+ Type: `function (message, index, list) { return Boolean(); }`
116
+
117
+ When provided a function, it will be used to filter ESLint result messages, removing any messages that do not return a `true` (or truthy) value.
118
+
119
+ #### `options.envs`
120
+
121
+ Type: `Array`
122
+
123
+ Specify a list of [environments](https://eslint.org/docs/user-guide/configuring/language-options#specifying-environments) to be applied.
124
+
125
+ _Prefer using `options.overrideConfig.env` instead. Note the different option name and format._
126
+
127
+ #### `options.rulePaths`
128
+
129
+ Type: `Array`
130
+
131
+ This option allows you to specify additional directories from which to load rules files. This is useful when you have custom rules that aren't suitable for being bundled with ESLint. This option works much like the ESLint CLI's [`--rulesdir` option](https://eslint.org/docs/user-guide/command-line-interface#-rulesdir).
132
+
133
+ #### `options.configFile`
134
+
135
+ Type: `String`
136
+
137
+ Path to the ESLint rules configuration file. For more information, see the ESLint CLI [`--config` option](https://eslint.org/docs/user-guide/command-line-interface#-c-config) and [Using Configuration Files](https://eslint.org/docs/user-guide/configuring/configuration-files#using-configuration-files).
138
+
139
+ _Prefer using `options.overrideConfig.configFile` instead._
140
+
141
+ #### `options.warnFileIgnored` or `options.warnIgnored`
142
+
143
+ Type: `Boolean`
144
+
145
+ When `true`, add a result warning when ESLint ignores a file. This can be used to file files that are needlessly being loaded by `gulp.src`. For example, since ESLint automatically ignores "node_modules" file paths and gulp.src does not, a gulp task may take seconds longer just reading files from the "node_modules" directory.
146
+
147
+ #### `options.useEslintrc`
148
+
149
+ Type: `Boolean`
150
+
151
+ When `false`, ESLint will not load [.eslintrc files](https://eslint.org/docs/user-guide/configuring/configuration-files#using-configuration-files).
152
+
153
+ ### `eslint(configFilePath)`
154
+
155
+ Param type: `String`
156
+
157
+ Shorthand for defining `options.overrideConfigFile`.
158
+
159
+ ### `eslint.result(action)`
160
+
161
+ Param type: `function (result) {}`
162
+
163
+ Call a function for each ESLint file result. No returned value is expected. If an error is thrown, it will be wrapped in a Gulp PluginError and emitted from the stream.
164
+
165
+ ```javascript
166
+ gulp.src(['**/*.js','!node_modules/**'])
167
+ .pipe(eslint())
168
+ .pipe(eslint.result(result => {
169
+ // Called for each ESLint result.
170
+ console.log(`ESLint result: ${result.filePath}`);
171
+ console.log(`# Messages: ${result.messages.length}`);
172
+ console.log(`# Warnings: ${result.warningCount}`);
173
+ console.log(`# Errors: ${result.errorCount}`);
174
+ }));
175
+ ```
176
+
177
+ Type: `function (result, callback) { callback(error); }`
178
+
179
+ Call an asynchronous function for each ESLint file result. The callback must be called for the stream to finish. If a value is passed to the callback, it will be wrapped in a Gulp PluginError and emitted from the stream.
180
+
181
+
182
+ ### `eslint.results(action)`
183
+
184
+ Param type: `function (results) {}`
185
+
186
+ Call a function once for all ESLint file results before a stream finishes. No returned value is expected. If an error is thrown, it will be wrapped in a Gulp PluginError and emitted from the stream.
187
+
188
+ The results list has a "warningCount" property that is the sum of warnings in all results; likewise, an "errorCount" property is set to the sum of errors in all results.
189
+
190
+ ```javascript
191
+ gulp.src(['**/*.js','!node_modules/**'])
192
+ .pipe(eslint())
193
+ .pipe(eslint.results(results => {
194
+ // Called once for all ESLint results.
195
+ console.log(`Total Results: ${results.length}`);
196
+ console.log(`Total Warnings: ${results.warningCount}`);
197
+ console.log(`Total Errors: ${results.errorCount}`);
198
+ }));
199
+ ```
200
+
201
+ Param type: `function (results, callback) { callback(error); }`
202
+
203
+ Call an asynchronous function once for all ESLint file results before a stream finishes. The callback must be called for the stream to finish. If a value is passed to the callback, it will be wrapped in a Gulp PluginError and emitted from the stream.
204
+
205
+ ### `eslint.failOnError()`
206
+
207
+ Stop a task/stream if an ESLint error has been reported for any file.
208
+
209
+ ```javascript
210
+ // Cause the stream to stop(/fail) before copying an invalid JS file to the output directory
211
+ gulp.src(['**/*.js','!node_modules/**'])
212
+ .pipe(eslint())
213
+ .pipe(eslint.failOnError());
214
+ ```
215
+
216
+ ### `eslint.failAfterError()`
217
+
218
+ Stop a task/stream if an ESLint error has been reported for any file, but wait for all of them to be processed first.
219
+
220
+ ```javascript
221
+ // Cause the stream to stop(/fail) when the stream ends if any ESLint error(s) occurred.
222
+ gulp.src(['**/*.js','!node_modules/**'])
223
+ .pipe(eslint())
224
+ .pipe(eslint.failAfterError());
225
+ ```
226
+
227
+ ### `eslint.format(formatter, output)`
228
+
229
+ Format all linted files once. This should be used in the stream after piping through `eslint`; otherwise, this will find no ESLint results to format.
230
+
231
+ The `formatter` argument may be a `String`, `Function`, or `undefined`. As a `String`, a formatter module by that name or path will be resolved as a module, relative to `process.cwd()`, or as one of the [ESLint-provided formatters](https://github.com/eslint/eslint/tree/master/lib/cli-engine/formatters). If `undefined`, the ESLint “stylish” formatter will be resolved. A `Function` will be called with an `Array` of file linting results to format.
232
+
233
+ ```javascript
234
+ // use the default "stylish" ESLint formatter
235
+ eslint.format()
236
+
237
+ // use the "checkstyle" ESLint formatter
238
+ eslint.format('checkstyle')
239
+
240
+ // use the "eslint-path-formatter" module formatter
241
+ // (@see https://github.com/Bartvds/eslint-path-formatter)
242
+ eslint.format('node_modules/eslint-path-formatter')
243
+ ```
244
+
245
+ The `output` argument may be a `WritableStream`, `Function`, or `undefined`. As a `WritableStream`, the formatter results will be written to the stream. If `undefined`, the formatter results will be written to [gulp’s log](https://github.com/gulpjs/gulp-util#logmsg). A `Function` will be called with the formatter results as the only parameter.
246
+
247
+ ```javascript
248
+ // write to gulp's log (default)
249
+ eslint.format();
250
+
251
+ // write messages to stdout
252
+ eslint.format('junit', process.stdout)
253
+ ```
254
+
255
+ ### `eslint.formatEach(formatter, output)`
256
+
257
+ Format each linted file individually. This should be used in the stream after piping through `eslint`; otherwise, this will find no ESLint results to format.
258
+
259
+ The arguments for `formatEach` are the same as the arguments for `format`.
260
+
261
+
262
+ ## Configuration
263
+
264
+ ESLint may be configured explicity by using any of the supported [configuration options](https://eslint.org/docs/user-guide/configuring/). If the [`useEslintrc` option](#optionsuseEslintrc) is not set to `false`, ESLint will attempt to resolve a file by the name of `.eslintrc` within the same directory as the file to be linted. If not found there, parent directories will be searched until `.eslintrc` is found or the directory root is reached.
265
+
266
+ ## Ignore Files
267
+
268
+ ESLint will ignore files that do not have a `.js` file extension at the point of linting ([some plugins](https://github.com/gulp-community/gulp-coffee) may change file extensions mid-stream). This avoids unintentional linting of non-JavaScript files.
269
+
270
+ ESLint will also detect an `.eslintignore` file at the cwd or a parent directory. See the [ESLint docs](https://eslint.org/docs/user-guide/configuring/ignoring-code#the-eslintignore-file) to learn how to construct this file.
271
+
272
+ ## Extensions
273
+
274
+ ESLint results are attached as an "eslint" property to the vinyl files that pass through a Gulp.js stream pipeline. This is available to streams that follow the initial `eslint` stream. The [eslint.result](#result) and [eslint.results](#results) methods are made available to support extensions and custom handling of ESLint results.
275
+
276
+ #### Gulp-Eslint Extensions:
277
+
278
+ * [gulp-eslint-if-fixed](https://github.com/lukeapage/gulp-eslint-if-fixed)
279
+ * [gulp-eslint-threshold](https://github.com/krmbkt/gulp-eslint-threshold)
280
+
281
+ [npm badge]: https://badge.fury.io/js/gulp-eslint-new.svg
282
+ [npm URL]: https://www.npmjs.com/package/gulp-eslint-new
package/index.js ADDED
@@ -0,0 +1,204 @@
1
+ 'use strict';
2
+
3
+ const PluginError = require('plugin-error');
4
+ const { ESLint } = require('eslint');
5
+ const {
6
+ createIgnoreResult,
7
+ filterResult,
8
+ firstResultMessage,
9
+ handleCallback,
10
+ isErrorMessage,
11
+ migrateOptions,
12
+ resolveFormatter,
13
+ resolveWritable,
14
+ transform,
15
+ tryResultAction,
16
+ writeResults
17
+ } = require('./util');
18
+ const {relative} = require('path');
19
+
20
+ async function lintFile(linter, file, quiet, warnIgnored) {
21
+ if (file.isNull()) {
22
+ return;
23
+ }
24
+
25
+ if (file.isStream()) {
26
+ throw 'gulp-eslint-new doesn\'t support vinyl files with Stream contents.';
27
+ }
28
+
29
+ const filePath = relative(process.cwd(), file.path);
30
+ if (await linter.isPathIgnored(filePath)) {
31
+ // Note:
32
+ // Vinyl files can have an independently defined cwd, but ESLint works relative to `process.cwd()`.
33
+ // (https://github.com/gulpjs/gulp/blob/master/docs/recipes/specifying-a-cwd.md)
34
+ // Also, ESLint doesn't adjust file paths relative to an ancestory .eslintignore path.
35
+ // E.g., If ../.eslintignore has "foo/*.js", ESLint will ignore ./foo/*.js, instead of ../foo/*.js.
36
+ // Eslint rolls this into `ESLint.lintText`. So, gulp-eslint-new must account for this limitation.
37
+
38
+ if (warnIgnored) {
39
+ // Warn that gulp.src is needlessly reading files that ESLint ignores
40
+ file.eslint = createIgnoreResult(file);
41
+ }
42
+ return;
43
+ }
44
+
45
+ const [result] = await linter.lintText(file.contents.toString(), { filePath });
46
+ // Note: Fixes are applied as part of "lintText".
47
+ // Any applied fix messages have been removed from the result.
48
+
49
+ if (quiet) {
50
+ // ignore warnings
51
+ file.eslint = filterResult(result, quiet);
52
+ } else {
53
+ file.eslint = result;
54
+ }
55
+
56
+ // Update the fixed output; otherwise, fixable messages are simply ignored.
57
+ if (file.eslint.hasOwnProperty('output')) {
58
+ file.contents = Buffer.from(file.eslint.output);
59
+ file.eslint.fixed = true;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Append ESLint result to each file
65
+ *
66
+ * @param {(Object|String)} [options] - Configure rules, env, global, and other options for running ESLint
67
+ * @returns {stream} gulp file stream
68
+ */
69
+ function gulpEslint(options) {
70
+ const { eslintOptions, quiet, warnIgnored } = migrateOptions(options);
71
+ const linter = new ESLint(eslintOptions);
72
+
73
+ return transform((file, enc, cb) => {
74
+ lintFile(linter, file, quiet, warnIgnored)
75
+ .then(() => cb(null, file))
76
+ .catch(error => cb(new PluginError('gulp-eslint-new', error)));
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Handle each ESLint result as it passes through the stream.
82
+ *
83
+ * @param {Function} action - A function to handle each ESLint result
84
+ * @returns {stream} gulp file stream
85
+ */
86
+ gulpEslint.result = action => {
87
+ if (typeof action !== 'function') {
88
+ throw new Error('Expected callable argument');
89
+ }
90
+
91
+ return transform((file, enc, done) => {
92
+ if (file.eslint) {
93
+ tryResultAction(action, file.eslint, handleCallback(done, file));
94
+ } else {
95
+ done(null, file);
96
+ }
97
+ });
98
+ };
99
+
100
+ /**
101
+ * Handle all ESLint results at the end of the stream.
102
+ *
103
+ * @param {Function} action - A function to handle all ESLint results
104
+ * @returns {stream} gulp file stream
105
+ */
106
+ gulpEslint.results = function(action) {
107
+ if (typeof action !== 'function') {
108
+ throw new Error('Expected callable argument');
109
+ }
110
+
111
+ const results = [];
112
+ results.errorCount = 0;
113
+ results.warningCount = 0;
114
+
115
+ return transform((file, enc, done) => {
116
+ if (file.eslint) {
117
+ results.push(file.eslint);
118
+ // collect total error/warning count
119
+ results.errorCount += file.eslint.errorCount;
120
+ results.warningCount += file.eslint.warningCount;
121
+ }
122
+ done(null, file);
123
+
124
+ }, done => {
125
+ tryResultAction(action, results, handleCallback(done));
126
+ });
127
+ };
128
+
129
+ /**
130
+ * Fail when an ESLint error is found in ESLint results.
131
+ *
132
+ * @returns {stream} gulp file stream
133
+ */
134
+ gulpEslint.failOnError = () => {
135
+ return gulpEslint.result(result => {
136
+ const error = firstResultMessage(result, isErrorMessage);
137
+ if (!error) {
138
+ return;
139
+ }
140
+
141
+ throw new PluginError('gulp-eslint-new', {
142
+ name: 'ESLintError',
143
+ fileName: result.filePath,
144
+ message: error.message,
145
+ lineNumber: error.line
146
+ });
147
+ });
148
+ };
149
+
150
+ /**
151
+ * Fail when the stream ends if any ESLint error(s) occurred
152
+ *
153
+ * @returns {stream} gulp file stream
154
+ */
155
+ gulpEslint.failAfterError = () => {
156
+ return gulpEslint.results(results => {
157
+ const count = results.errorCount;
158
+ if (!count) {
159
+ return;
160
+ }
161
+
162
+ throw new PluginError('gulp-eslint-new', {
163
+ name: 'ESLintError',
164
+ message: 'Failed with ' + count + (count === 1 ? ' error' : ' errors')
165
+ });
166
+ });
167
+ };
168
+
169
+ /**
170
+ * Format the results of each file individually.
171
+ *
172
+ * @param {(String|Function)} [formatter=stylish] - The name or function for a ESLint result formatter
173
+ * @param {(Function|Stream)} [writable=fancy-log] - A funtion or stream to write the formatted ESLint results.
174
+ * @returns {stream} gulp file stream
175
+ */
176
+ gulpEslint.formatEach = (formatter, writable) => {
177
+ formatter = resolveFormatter(formatter);
178
+ writable = resolveWritable(writable);
179
+
180
+ return gulpEslint.result(result => writeResults([result], formatter, writable));
181
+ };
182
+
183
+ /**
184
+ * Wait until all files have been linted and format all results at once.
185
+ *
186
+ * @param {(String|Function)} [formatter=stylish] - The name or function for a ESLint result formatter
187
+ * @param {(Function|stream)} [writable=fancy-log] - A funtion or stream to write the formatted ESLint results.
188
+ * @returns {stream} gulp file stream
189
+ */
190
+ gulpEslint.format = (formatter, writable) => {
191
+ formatter = resolveFormatter(formatter);
192
+ writable = resolveWritable(writable);
193
+
194
+ return gulpEslint.results(results => {
195
+ // Only format results if files has been lint'd
196
+ if (results.length) {
197
+ writeResults(results, formatter, writable);
198
+ }
199
+ });
200
+ };
201
+
202
+ gulpEslint.PluginError = PluginError;
203
+
204
+ module.exports = gulpEslint;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @author Nicholas C. Zakas
3
+ */
4
+
5
+ 'use strict';
6
+
7
+ //------------------------------------------------------------------------------
8
+ // Requirements
9
+ //------------------------------------------------------------------------------
10
+
11
+ const path = require('path');
12
+
13
+ const { Legacy: { naming, ModuleResolver } } = require('@eslint/eslintrc');
14
+
15
+ /**
16
+ * Returns the formatter representing the given format or null if the `format` is not a string.
17
+ * @param {string} [format] The name of the format to load or the path to a custom formatter.
18
+ * @throws {any} As may be thrown by requiring the formatter.
19
+ * @returns {Function} The formatter function.
20
+ */
21
+ function getFormatter(format) {
22
+
23
+ // default is stylish
24
+ const resolvedFormatName = format == null ? 'stylish' : `${format}`;
25
+
26
+ // replace \ with / for Windows compatibility
27
+ const normalizedFormatName = resolvedFormatName.replace(/\\/gu, '/');
28
+
29
+ const cwd = process.cwd();
30
+ const namespace = naming.getNamespaceFromTerm(normalizedFormatName);
31
+
32
+ let formatterPath;
33
+
34
+ // if there's a slash, then it's a file
35
+ if (!namespace && normalizedFormatName.includes('/')) {
36
+ formatterPath = path.resolve(cwd, normalizedFormatName);
37
+ } else {
38
+ try {
39
+ const npmFormat
40
+ = naming.normalizePackageName(normalizedFormatName, 'eslint-formatter');
41
+
42
+ formatterPath
43
+ = ModuleResolver.resolve(npmFormat, path.join(cwd, '__placeholder__.js'));
44
+ } catch (ex) {
45
+ const baseDir = require.resolve('eslint');
46
+ formatterPath
47
+ = path.resolve(baseDir, '../cli-engine/formatters', normalizedFormatName);
48
+ }
49
+ }
50
+
51
+ try {
52
+ return require(formatterPath);
53
+ } catch (ex) {
54
+ /* c8 ignore start */
55
+ if (format === 'table' || format === 'codeframe') {
56
+ ex.message
57
+ = `The ${format} formatter is no longer part of core ESLint. Install it manually `
58
+ + `with \`npm install -D eslint-formatter-${format}\``;
59
+ /* c8 ignore stop */
60
+ } else {
61
+ ex.message
62
+ = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
63
+ }
64
+ throw ex;
65
+ }
66
+ }
67
+
68
+ module.exports = getFormatter;
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "gulp-eslint-new",
3
+ "version": "0.4.0",
4
+ "description": "A gulp plugin to lint code with ESLint 8",
5
+ "repository": "fasttime/gulp-eslint-new",
6
+ "files": [
7
+ "index.js",
8
+ "legacy-get-formatter.js",
9
+ "util.js"
10
+ ],
11
+ "directories": {
12
+ "example": "example",
13
+ "test": "test"
14
+ },
15
+ "scripts": {
16
+ "build": "npm install && gulp",
17
+ "lint": "eslint .",
18
+ "test": "mocha --check-leaks"
19
+ },
20
+ "keywords": [
21
+ "gulpplugin",
22
+ "eslint",
23
+ "gulp",
24
+ "errors",
25
+ "warnings",
26
+ "check",
27
+ "source",
28
+ "code",
29
+ "formatter",
30
+ "js",
31
+ "javascript",
32
+ "task",
33
+ "lint",
34
+ "plugin"
35
+ ],
36
+ "author": "Adametry",
37
+ "contributors": [
38
+ "Shinnosuke Watanabe <snnskwtnb@gmail.com> (https://github.com/shinnn)"
39
+ ],
40
+ "license": "MIT",
41
+ "dependencies": {
42
+ "eslint": "^8.0.0",
43
+ "fancy-log": "^1.3.3",
44
+ "plugin-error": "^1.0.1"
45
+ },
46
+ "devDependencies": {
47
+ "@babel/core": "^7.15.8",
48
+ "@babel/eslint-parser": "^7.15.8",
49
+ "@shinnn/eslint-config": "^7.0.0",
50
+ "c8": "^7.10.0",
51
+ "eslint-plugin-eslint-comments": "^3.2.0",
52
+ "eslint-plugin-node": "^11.1.0",
53
+ "from2-string": "^1.1.0",
54
+ "gulp": "^4.0.2",
55
+ "mocha": "^9.1.2",
56
+ "vinyl": "^2.2.1"
57
+ }
58
+ }
package/util.js ADDED
@@ -0,0 +1,328 @@
1
+ 'use strict';
2
+
3
+ const {Transform} = require('stream');
4
+ const PluginError = require('plugin-error');
5
+ const fancyLog = require('fancy-log');
6
+ const getFormatter = require('./legacy-get-formatter');
7
+
8
+ /**
9
+ * Convenience method for creating a transform stream in object mode
10
+ *
11
+ * @param {Function} transform - An async function that is called for each stream chunk
12
+ * @param {Function} [flush] - An async function that is called before closing the stream
13
+ * @returns {stream} A transform stream
14
+ */
15
+ exports.transform = function(transform, flush) {
16
+ if (typeof flush === 'function') {
17
+ return new Transform({
18
+ objectMode: true,
19
+ transform,
20
+ flush
21
+ });
22
+ }
23
+
24
+ return new Transform({
25
+ objectMode: true,
26
+ transform
27
+ });
28
+ };
29
+
30
+ /**
31
+ * Mimic the CLIEngine's createIgnoreResult function,
32
+ * only without the ESLint CLI reference.
33
+ *
34
+ * @param {Object} file - file with a "path" property
35
+ * @returns {Object} An ESLint report with an ignore warning
36
+ */
37
+ exports.createIgnoreResult = file => {
38
+ return {
39
+ filePath: file.path,
40
+ messages: [{
41
+ fatal: false,
42
+ severity: 1,
43
+ message: file.path.includes('node_modules/') ?
44
+ 'File ignored because it has a node_modules/** path' :
45
+ 'File ignored because of .eslintignore file'
46
+ }],
47
+ errorCount: 0,
48
+ warningCount: 1
49
+ };
50
+ };
51
+
52
+ /**
53
+ * Convert a string array to a boolean map.
54
+ * @param {string[]|null} keys The keys to assign true.
55
+ * @param {boolean} defaultValue The default value for each property.
56
+ * @param {string} displayName The property name which is used in error message.
57
+ * @returns {Record<string,boolean>} The boolean map.
58
+ */
59
+ function toBooleanMap(keys, defaultValue, displayName) {
60
+ if (keys && !Array.isArray(keys)) {
61
+ throw Error(`${displayName} must be an array.`);
62
+ }
63
+ if (keys && keys.length > 0) {
64
+ return keys.reduce((map, def) => {
65
+ const [key, value] = def.split(':');
66
+
67
+ if (key !== '__proto__') {
68
+ map[key] = value === undefined ? defaultValue : value === 'true';
69
+ }
70
+
71
+ return map;
72
+ }, { });
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Create config helper to merge various config sources
78
+ *
79
+ * @param {Object} options - options to migrate
80
+ * @returns {Object} migrated options
81
+ */
82
+ exports.migrateOptions = function migrateOptions(options = { }) {
83
+ if (typeof options === 'string') {
84
+ // basic config path overload: gulpEslint('path/to/config.json')
85
+ const returnValue = { eslintOptions: { overrideConfigFile: options } };
86
+ return returnValue;
87
+ }
88
+ const {
89
+ overrideConfig: originalOverrideConfig,
90
+ quiet,
91
+ warnFileIgnored,
92
+ warnIgnored: originalWarnIgnored,
93
+ ...eslintOptions
94
+ }
95
+ = options;
96
+ if (originalOverrideConfig != null && typeof originalOverrideConfig !== 'object') {
97
+ throw Error('\'overrideConfig\' must be an object or null.');
98
+ }
99
+ const overrideConfig = eslintOptions.overrideConfig
100
+ = originalOverrideConfig != null ? { ...originalOverrideConfig } : { };
101
+
102
+ function migrateOption(oldName, newName = oldName, convert = value => value) {
103
+ const value = eslintOptions[oldName];
104
+ delete eslintOptions[oldName];
105
+ if (value !== undefined) {
106
+ overrideConfig[newName] = convert(value);
107
+ }
108
+ }
109
+
110
+ {
111
+ const { configFile } = eslintOptions;
112
+ delete eslintOptions.configFile;
113
+ if (configFile !== undefined) {
114
+ eslintOptions.overrideConfigFile = configFile;
115
+ }
116
+ }
117
+ migrateOption('envs', 'env', envs => toBooleanMap(envs, true, 'envs'));
118
+ migrateOption('globals', undefined, globals => toBooleanMap(globals, false, 'globals'));
119
+ migrateOption('ignorePattern', 'ignorePatterns');
120
+ migrateOption('parser');
121
+ migrateOption('parserOptions');
122
+ if (Array.isArray(eslintOptions.plugins)) {
123
+ migrateOption('plugins');
124
+ }
125
+ migrateOption('rules');
126
+ const warnIgnored = warnFileIgnored !== undefined ? warnFileIgnored : originalWarnIgnored;
127
+ const returnValue = { eslintOptions, quiet, warnIgnored };
128
+ return returnValue;
129
+ };
130
+
131
+ /**
132
+ * Ensure that callback errors are wrapped in a gulp PluginError
133
+ *
134
+ * @param {Function} callback - callback to wrap
135
+ * @param {Object} [value=] - A value to pass to the callback
136
+ * @returns {Function} A callback to call(back) the callback
137
+ */
138
+ exports.handleCallback = (callback, value) => {
139
+ return err => {
140
+ if (err != null && !(err instanceof PluginError)) {
141
+ err = new PluginError(err.plugin || 'gulp-eslint-new', err, {
142
+ showStack: (err.showStack !== false)
143
+ });
144
+ }
145
+
146
+ callback(err, value);
147
+ };
148
+ };
149
+
150
+ /**
151
+ * Call sync or async action and handle any thrown or async error
152
+ *
153
+ * @param {Function} action - Result action to call
154
+ * @param {(Object|Array)} result - An ESLint result or result list
155
+ * @param {Function} done - An callback for when the action is complete
156
+ */
157
+ exports.tryResultAction = function(action, result, done) {
158
+ try {
159
+ if (action.length > 1) {
160
+ // async action
161
+ action.call(this, result, done);
162
+ } else {
163
+ // sync action
164
+ action.call(this, result);
165
+ done();
166
+ }
167
+ } catch (error) {
168
+ done(error == null ? new Error('Unknown Error') : error);
169
+ }
170
+ };
171
+
172
+ /**
173
+ * Get first message in an ESLint result to meet a condition
174
+ *
175
+ * @param {Object} result - An ESLint result
176
+ * @param {Function} condition - A condition function that is passed a message and returns a boolean
177
+ * @returns {Object} The first message to pass the condition or null
178
+ */
179
+ exports.firstResultMessage = (result, condition) => {
180
+ if (!result.messages) {
181
+ return null;
182
+ }
183
+
184
+ return result.messages.find(condition);
185
+ };
186
+
187
+ /**
188
+ * Determine if a message is an error
189
+ *
190
+ * @param {Object} message - an ESLint message
191
+ * @returns {Boolean} whether the message is an error message
192
+ */
193
+ function isErrorMessage(message) {
194
+ const level = message.fatal ? 2 : message.severity;
195
+
196
+ if (Array.isArray(level)) {
197
+ return level[0] > 1;
198
+ }
199
+
200
+ return level > 1;
201
+ }
202
+ exports.isErrorMessage = isErrorMessage;
203
+
204
+ /**
205
+ * Increment count if message is an error
206
+ *
207
+ * @param {Number} count - count of errors
208
+ * @param {Object} message - an ESLint message
209
+ * @returns {Number} The number of errors, message included
210
+ */
211
+ function countErrorMessage(count, message) {
212
+ return count + Number(isErrorMessage(message));
213
+ }
214
+
215
+ /**
216
+ * Increment count if message is a warning
217
+ *
218
+ * @param {Number} count - count of warnings
219
+ * @param {Object} message - an ESLint message
220
+ * @returns {Number} The number of warnings, message included
221
+ */
222
+ function countWarningMessage(count, message) {
223
+ return count + Number(message.severity === 1);
224
+ }
225
+
226
+ /**
227
+ * Increment count if message is a fixable error
228
+ *
229
+ * @param {Number} count - count of errors
230
+ * @param {Object} message - an ESLint message
231
+ * @returns {Number} The number of errors, message included
232
+ */
233
+ function countFixableErrorMessage(count, message) {
234
+ return count + Number(isErrorMessage(message) && message.fix !== undefined);
235
+ }
236
+
237
+ /**
238
+ * Increment count if message is a fixable warning
239
+ *
240
+ * @param {Number} count - count of errors
241
+ * @param {Object} message - an ESLint message
242
+ * @returns {Number} The number of errors, message included
243
+ */
244
+ function countFixableWarningMessage(count, message) {
245
+ return count + Number(message.severity === 1 && message.fix !== undefined);
246
+ }
247
+
248
+ /**
249
+ * Filter result messages, update error and warning counts
250
+ *
251
+ * @param {Object} result - an ESLint result
252
+ * @param {Function} [filter=isErrorMessage] - A function that evaluates what messages to keep
253
+ * @returns {Object} A filtered ESLint result
254
+ */
255
+ exports.filterResult = (result, filter) => {
256
+ if (typeof filter !== 'function') {
257
+ filter = isErrorMessage;
258
+ }
259
+ const messages = result.messages.filter(filter, result);
260
+ const newResult = {
261
+ filePath: result.filePath,
262
+ messages: messages,
263
+ errorCount: messages.reduce(countErrorMessage, 0),
264
+ warningCount: messages.reduce(countWarningMessage, 0),
265
+ fixableErrorCount: messages.reduce(countFixableErrorMessage, 0),
266
+ fixableWarningCount: messages.reduce(countFixableWarningMessage, 0)
267
+ };
268
+
269
+ if (result.output !== undefined) {
270
+ newResult.output = result.output;
271
+ } else {
272
+ newResult.source = result.source;
273
+ }
274
+
275
+ return newResult;
276
+ };
277
+
278
+ /**
279
+ * Resolve formatter from unknown type (accepts string or function)
280
+ *
281
+ * @throws TypeError thrown if unable to resolve the formatter type
282
+ * @param {(String|Function)} [formatter=stylish] - A name to resolve as a formatter. If a function is provided, the same function is returned.
283
+ * @returns {Function} An ESLint formatter
284
+ */
285
+ exports.resolveFormatter = (formatter) => {
286
+ // use ESLint to look up formatter references
287
+ if (typeof formatter !== 'function') {
288
+ // load formatter (module, relative to cwd, ESLint formatter)
289
+ formatter = getFormatter(formatter);
290
+ }
291
+
292
+ return formatter;
293
+ };
294
+
295
+ /**
296
+ * Resolve writable
297
+ *
298
+ * @param {(Function|stream)} [writable=fancyLog] - A stream or function to resolve as a format writer
299
+ * @returns {Function} A function that writes formatted messages
300
+ */
301
+ exports.resolveWritable = (writable) => {
302
+ if (!writable) {
303
+ writable = fancyLog;
304
+ } else if (typeof writable.write === 'function') {
305
+ writable = writable.write.bind(writable);
306
+ }
307
+ return writable;
308
+ };
309
+
310
+ /**
311
+ * Write formatter results to writable/output
312
+ *
313
+ * @param {Object[]} results - A list of ESLint results
314
+ * @param {Function} formatter - A function used to format ESLint results
315
+ * @param {Function} writable - A function used to write formatted ESLint results
316
+ */
317
+ exports.writeResults = (results, formatter, writable) => {
318
+ if (!results) {
319
+ results = [];
320
+ }
321
+
322
+ const firstResult = results.find(result => result.config);
323
+
324
+ const message = formatter(results, firstResult ? firstResult.config : {});
325
+ if (writable && message != null && message !== '') {
326
+ writable(message);
327
+ }
328
+ };