Actualizacion maquina principal
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / cli-engine / file-enumerator.js
1 /**
2  * @fileoverview `FileEnumerator` class.
3  *
4  * `FileEnumerator` class has two responsibilities:
5  *
6  * 1. Find target files by processing glob patterns.
7  * 2. Tie each target file and appropriate configuration.
8  *
9  * It provies a method:
10  *
11  * - `iterateFiles(patterns)`
12  *     Iterate files which are matched by given patterns together with the
13  *     corresponded configuration. This is for `CLIEngine#executeOnFiles()`.
14  *     While iterating files, it loads the configuration file of each directory
15  *     before iterate files on the directory, so we can use the configuration
16  *     files to determine target files.
17  *
18  * @example
19  * const enumerator = new FileEnumerator();
20  * const linter = new Linter();
21  *
22  * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) {
23  *     const code = fs.readFileSync(filePath, "utf8");
24  *     const messages = linter.verify(code, config, filePath);
25  *
26  *     console.log(messages);
27  * }
28  *
29  * @author Toru Nagashima <https://github.com/mysticatea>
30  */
31 "use strict";
32
33 //------------------------------------------------------------------------------
34 // Requirements
35 //------------------------------------------------------------------------------
36
37 const fs = require("fs");
38 const path = require("path");
39 const getGlobParent = require("glob-parent");
40 const isGlob = require("is-glob");
41 const { escapeRegExp } = require("lodash");
42 const { Minimatch } = require("minimatch");
43 const { IgnorePattern } = require("./config-array");
44 const { CascadingConfigArrayFactory } = require("./cascading-config-array-factory");
45 const debug = require("debug")("eslint:file-enumerator");
46
47 //------------------------------------------------------------------------------
48 // Helpers
49 //------------------------------------------------------------------------------
50
51 const minimatchOpts = { dot: true, matchBase: true };
52 const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u;
53 const NONE = 0;
54 const IGNORED_SILENTLY = 1;
55 const IGNORED = 2;
56
57 // For VSCode intellisense
58 /** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
59
60 /**
61  * @typedef {Object} FileEnumeratorOptions
62  * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays.
63  * @property {string} [cwd] The base directory to start lookup.
64  * @property {string[]} [extensions] The extensions to match files for directory patterns.
65  * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
66  * @property {boolean} [ignore] The flag to check ignored files.
67  * @property {string[]} [rulePaths] The value of `--rulesdir` option.
68  */
69
70 /**
71  * @typedef {Object} FileAndConfig
72  * @property {string} filePath The path to a target file.
73  * @property {ConfigArray} config The config entries of that file.
74  * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified.
75  */
76
77 /**
78  * @typedef {Object} FileEntry
79  * @property {string} filePath The path to a target file.
80  * @property {ConfigArray} config The config entries of that file.
81  * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag.
82  * - `NONE` means the file is a target file.
83  * - `IGNORED_SILENTLY` means the file should be ignored silently.
84  * - `IGNORED` means the file should be ignored and warned because it was directly specified.
85  */
86
87 /**
88  * @typedef {Object} FileEnumeratorInternalSlots
89  * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays.
90  * @property {string} cwd The base directory to start lookup.
91  * @property {RegExp} extensionRegExp The RegExp to test if a string ends with specific file extensions.
92  * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
93  * @property {boolean} ignoreFlag The flag to check ignored files.
94  * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files.
95  */
96
97 /** @type {WeakMap<FileEnumerator, FileEnumeratorInternalSlots>} */
98 const internalSlotsMap = new WeakMap();
99
100 /**
101  * Check if a string is a glob pattern or not.
102  * @param {string} pattern A glob pattern.
103  * @returns {boolean} `true` if the string is a glob pattern.
104  */
105 function isGlobPattern(pattern) {
106     return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern);
107 }
108
109 /**
110  * Get stats of a given path.
111  * @param {string} filePath The path to target file.
112  * @returns {fs.Stats|null} The stats.
113  * @private
114  */
115 function statSafeSync(filePath) {
116     try {
117         return fs.statSync(filePath);
118     } catch (error) {
119         /* istanbul ignore next */
120         if (error.code !== "ENOENT") {
121             throw error;
122         }
123         return null;
124     }
125 }
126
127 /**
128  * Get filenames in a given path to a directory.
129  * @param {string} directoryPath The path to target directory.
130  * @returns {string[]} The filenames.
131  * @private
132  */
133 function readdirSafeSync(directoryPath) {
134     try {
135         return fs.readdirSync(directoryPath);
136     } catch (error) {
137         /* istanbul ignore next */
138         if (error.code !== "ENOENT") {
139             throw error;
140         }
141         return [];
142     }
143 }
144
145 /**
146  * The error type when no files match a glob.
147  */
148 class NoFilesFoundError extends Error {
149
150     // eslint-disable-next-line jsdoc/require-description
151     /**
152      * @param {string} pattern The glob pattern which was not found.
153      * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled.
154      */
155     constructor(pattern, globDisabled) {
156         super(`No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`);
157         this.messageTemplate = "file-not-found";
158         this.messageData = { pattern, globDisabled };
159     }
160 }
161
162 /**
163  * The error type when there are files matched by a glob, but all of them have been ignored.
164  */
165 class AllFilesIgnoredError extends Error {
166
167     // eslint-disable-next-line jsdoc/require-description
168     /**
169      * @param {string} pattern The glob pattern which was not found.
170      */
171     constructor(pattern) {
172         super(`All files matched by '${pattern}' are ignored.`);
173         this.messageTemplate = "all-files-ignored";
174         this.messageData = { pattern };
175     }
176 }
177
178 /**
179  * This class provides the functionality that enumerates every file which is
180  * matched by given glob patterns and that configuration.
181  */
182 class FileEnumerator {
183
184     /**
185      * Initialize this enumerator.
186      * @param {FileEnumeratorOptions} options The options.
187      */
188     constructor({
189         cwd = process.cwd(),
190         configArrayFactory = new CascadingConfigArrayFactory({ cwd }),
191         extensions = [".js"],
192         globInputPaths = true,
193         errorOnUnmatchedPattern = true,
194         ignore = true
195     } = {}) {
196         internalSlotsMap.set(this, {
197             configArrayFactory,
198             cwd,
199             defaultIgnores: IgnorePattern.createDefaultIgnore(cwd),
200             extensionRegExp: new RegExp(
201                 `.\\.(?:${extensions
202                     .map(ext => escapeRegExp(
203                         ext.startsWith(".")
204                             ? ext.slice(1)
205                             : ext
206                     ))
207                     .join("|")
208                 })$`,
209                 "u"
210             ),
211             globInputPaths,
212             errorOnUnmatchedPattern,
213             ignoreFlag: ignore
214         });
215     }
216
217     /**
218      * The `RegExp` object that tests if a file path has the allowed file extensions.
219      * @type {RegExp}
220      */
221     get extensionRegExp() {
222         return internalSlotsMap.get(this).extensionRegExp;
223     }
224
225     /**
226      * Iterate files which are matched by given glob patterns.
227      * @param {string|string[]} patternOrPatterns The glob patterns to iterate files.
228      * @returns {IterableIterator<FileAndConfig>} The found files.
229      */
230     *iterateFiles(patternOrPatterns) {
231         const { globInputPaths, errorOnUnmatchedPattern } = internalSlotsMap.get(this);
232         const patterns = Array.isArray(patternOrPatterns)
233             ? patternOrPatterns
234             : [patternOrPatterns];
235
236         debug("Start to iterate files: %o", patterns);
237
238         // The set of paths to remove duplicate.
239         const set = new Set();
240
241         for (const pattern of patterns) {
242             let foundRegardlessOfIgnored = false;
243             let found = false;
244
245             // Skip empty string.
246             if (!pattern) {
247                 continue;
248             }
249
250             // Iterate files of this pttern.
251             for (const { config, filePath, flag } of this._iterateFiles(pattern)) {
252                 foundRegardlessOfIgnored = true;
253                 if (flag === IGNORED_SILENTLY) {
254                     continue;
255                 }
256                 found = true;
257
258                 // Remove duplicate paths while yielding paths.
259                 if (!set.has(filePath)) {
260                     set.add(filePath);
261                     yield {
262                         config,
263                         filePath,
264                         ignored: flag === IGNORED
265                     };
266                 }
267             }
268
269             // Raise an error if any files were not found.
270             if (errorOnUnmatchedPattern) {
271                 if (!foundRegardlessOfIgnored) {
272                     throw new NoFilesFoundError(
273                         pattern,
274                         !globInputPaths && isGlob(pattern)
275                     );
276                 }
277                 if (!found) {
278                     throw new AllFilesIgnoredError(pattern);
279                 }
280             }
281         }
282
283         debug(`Complete iterating files: ${JSON.stringify(patterns)}`);
284     }
285
286     /**
287      * Iterate files which are matched by a given glob pattern.
288      * @param {string} pattern The glob pattern to iterate files.
289      * @returns {IterableIterator<FileEntry>} The found files.
290      */
291     _iterateFiles(pattern) {
292         const { cwd, globInputPaths } = internalSlotsMap.get(this);
293         const absolutePath = path.resolve(cwd, pattern);
294         const isDot = dotfilesPattern.test(pattern);
295         const stat = statSafeSync(absolutePath);
296
297         if (stat && stat.isDirectory()) {
298             return this._iterateFilesWithDirectory(absolutePath, isDot);
299         }
300         if (stat && stat.isFile()) {
301             return this._iterateFilesWithFile(absolutePath);
302         }
303         if (globInputPaths && isGlobPattern(pattern)) {
304             return this._iterateFilesWithGlob(absolutePath, isDot);
305         }
306
307         return [];
308     }
309
310     /**
311      * Iterate a file which is matched by a given path.
312      * @param {string} filePath The path to the target file.
313      * @returns {IterableIterator<FileEntry>} The found files.
314      * @private
315      */
316     _iterateFilesWithFile(filePath) {
317         debug(`File: ${filePath}`);
318
319         const { configArrayFactory } = internalSlotsMap.get(this);
320         const config = configArrayFactory.getConfigArrayForFile(filePath);
321         const ignored = this._isIgnoredFile(filePath, { config, direct: true });
322         const flag = ignored ? IGNORED : NONE;
323
324         return [{ config, filePath, flag }];
325     }
326
327     /**
328      * Iterate files in a given path.
329      * @param {string} directoryPath The path to the target directory.
330      * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
331      * @returns {IterableIterator<FileEntry>} The found files.
332      * @private
333      */
334     _iterateFilesWithDirectory(directoryPath, dotfiles) {
335         debug(`Directory: ${directoryPath}`);
336
337         return this._iterateFilesRecursive(
338             directoryPath,
339             { dotfiles, recursive: true, selector: null }
340         );
341     }
342
343     /**
344      * Iterate files which are matched by a given glob pattern.
345      * @param {string} pattern The glob pattern to iterate files.
346      * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default.
347      * @returns {IterableIterator<FileEntry>} The found files.
348      * @private
349      */
350     _iterateFilesWithGlob(pattern, dotfiles) {
351         debug(`Glob: ${pattern}`);
352
353         const directoryPath = path.resolve(getGlobParent(pattern));
354         const globPart = pattern.slice(directoryPath.length + 1);
355
356         /*
357          * recursive if there are `**` or path separators in the glob part.
358          * Otherwise, patterns such as `src/*.js`, it doesn't need recursive.
359          */
360         const recursive = /\*\*|\/|\\/u.test(globPart);
361         const selector = new Minimatch(pattern, minimatchOpts);
362
363         debug(`recursive? ${recursive}`);
364
365         return this._iterateFilesRecursive(
366             directoryPath,
367             { dotfiles, recursive, selector }
368         );
369     }
370
371     /**
372      * Iterate files in a given path.
373      * @param {string} directoryPath The path to the target directory.
374      * @param {Object} options The options to iterate files.
375      * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default.
376      * @param {boolean} [options.recursive] If `true` then it dives into sub directories.
377      * @param {InstanceType<Minimatch>} [options.selector] The matcher to choose files.
378      * @returns {IterableIterator<FileEntry>} The found files.
379      * @private
380      */
381     *_iterateFilesRecursive(directoryPath, options) {
382         debug(`Enter the directory: ${directoryPath}`);
383         const { configArrayFactory, extensionRegExp } = internalSlotsMap.get(this);
384
385         /** @type {ConfigArray|null} */
386         let config = null;
387
388         // Enumerate the files of this directory.
389         for (const filename of readdirSafeSync(directoryPath)) {
390             const filePath = path.join(directoryPath, filename);
391             const stat = statSafeSync(filePath); // TODO: Use `withFileTypes` in the future.
392
393             // Check if the file is matched.
394             if (stat && stat.isFile()) {
395                 if (!config) {
396                     config = configArrayFactory.getConfigArrayForFile(
397                         filePath,
398
399                         /*
400                          * We must ignore `ConfigurationNotFoundError` at this
401                          * point because we don't know if target files exist in
402                          * this directory.
403                          */
404                         { ignoreNotFoundError: true }
405                     );
406                 }
407                 const ignored = this._isIgnoredFile(filePath, { ...options, config });
408                 const flag = ignored ? IGNORED_SILENTLY : NONE;
409                 const matched = options.selector
410
411                     // Started with a glob pattern; choose by the pattern.
412                     ? options.selector.match(filePath)
413
414                     // Started with a directory path; choose by file extensions.
415                     : extensionRegExp.test(filePath);
416
417                 if (matched) {
418                     debug(`Yield: ${filename}${ignored ? " but ignored" : ""}`);
419                     yield {
420                         config: configArrayFactory.getConfigArrayForFile(filePath),
421                         filePath,
422                         flag
423                     };
424                 } else {
425                     debug(`Didn't match: ${filename}`);
426                 }
427
428             // Dive into the sub directory.
429             } else if (options.recursive && stat && stat.isDirectory()) {
430                 if (!config) {
431                     config = configArrayFactory.getConfigArrayForFile(
432                         filePath,
433                         { ignoreNotFoundError: true }
434                     );
435                 }
436                 const ignored = this._isIgnoredFile(
437                     filePath + path.sep,
438                     { ...options, config }
439                 );
440
441                 if (!ignored) {
442                     yield* this._iterateFilesRecursive(filePath, options);
443                 }
444             }
445         }
446
447         debug(`Leave the directory: ${directoryPath}`);
448     }
449
450     /**
451      * Check if a given file should be ignored.
452      * @param {string} filePath The path to a file to check.
453      * @param {Object} options Options
454      * @param {ConfigArray} [options.config] The config for this file.
455      * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default.
456      * @param {boolean} [options.direct] If `true` then this is a direct specified file.
457      * @returns {boolean} `true` if the file should be ignored.
458      * @private
459      */
460     _isIgnoredFile(filePath, {
461         config: providedConfig,
462         dotfiles = false,
463         direct = false
464     }) {
465         const {
466             configArrayFactory,
467             defaultIgnores,
468             ignoreFlag
469         } = internalSlotsMap.get(this);
470
471         if (ignoreFlag) {
472             const config =
473                 providedConfig ||
474                 configArrayFactory.getConfigArrayForFile(
475                     filePath,
476                     { ignoreNotFoundError: true }
477                 );
478             const ignores =
479                 config.extractConfig(filePath).ignores || defaultIgnores;
480
481             return ignores(filePath, dotfiles);
482         }
483
484         return !direct && defaultIgnores(filePath, dotfiles);
485     }
486 }
487
488 //------------------------------------------------------------------------------
489 // Public Interface
490 //------------------------------------------------------------------------------
491
492 module.exports = { FileEnumerator };