2 * @fileoverview `FileEnumerator` class.
4 * `FileEnumerator` class has two responsibilities:
6 * 1. Find target files by processing glob patterns.
7 * 2. Tie each target file and appropriate configuration.
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.
19 * const enumerator = new FileEnumerator();
20 * const linter = new Linter();
22 * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) {
23 * const code = fs.readFileSync(filePath, "utf8");
24 * const messages = linter.verify(code, config, filePath);
26 * console.log(messages);
29 * @author Toru Nagashima <https://github.com/mysticatea>
33 //------------------------------------------------------------------------------
35 //------------------------------------------------------------------------------
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");
47 //------------------------------------------------------------------------------
49 //------------------------------------------------------------------------------
51 const minimatchOpts = { dot: true, matchBase: true };
52 const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u;
54 const IGNORED_SILENTLY = 1;
57 // For VSCode intellisense
58 /** @typedef {ReturnType<CascadingConfigArrayFactory["getConfigArrayForFile"]>} ConfigArray */
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.
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.
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.
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.
97 /** @type {WeakMap<FileEnumerator, FileEnumeratorInternalSlots>} */
98 const internalSlotsMap = new WeakMap();
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.
105 function isGlobPattern(pattern) {
106 return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern);
110 * Get stats of a given path.
111 * @param {string} filePath The path to target file.
112 * @returns {fs.Stats|null} The stats.
115 function statSafeSync(filePath) {
117 return fs.statSync(filePath);
119 /* istanbul ignore next */
120 if (error.code !== "ENOENT") {
128 * Get filenames in a given path to a directory.
129 * @param {string} directoryPath The path to target directory.
130 * @returns {string[]} The filenames.
133 function readdirSafeSync(directoryPath) {
135 return fs.readdirSync(directoryPath);
137 /* istanbul ignore next */
138 if (error.code !== "ENOENT") {
146 * The error type when no files match a glob.
148 class NoFilesFoundError extends Error {
150 // eslint-disable-next-line jsdoc/require-description
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.
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 };
163 * The error type when there are files matched by a glob, but all of them have been ignored.
165 class AllFilesIgnoredError extends Error {
167 // eslint-disable-next-line jsdoc/require-description
169 * @param {string} pattern The glob pattern which was not found.
171 constructor(pattern) {
172 super(`All files matched by '${pattern}' are ignored.`);
173 this.messageTemplate = "all-files-ignored";
174 this.messageData = { pattern };
179 * This class provides the functionality that enumerates every file which is
180 * matched by given glob patterns and that configuration.
182 class FileEnumerator {
185 * Initialize this enumerator.
186 * @param {FileEnumeratorOptions} options The options.
190 configArrayFactory = new CascadingConfigArrayFactory({ cwd }),
191 extensions = [".js"],
192 globInputPaths = true,
193 errorOnUnmatchedPattern = true,
196 internalSlotsMap.set(this, {
199 defaultIgnores: IgnorePattern.createDefaultIgnore(cwd),
200 extensionRegExp: new RegExp(
202 .map(ext => escapeRegExp(
212 errorOnUnmatchedPattern,
218 * The `RegExp` object that tests if a file path has the allowed file extensions.
221 get extensionRegExp() {
222 return internalSlotsMap.get(this).extensionRegExp;
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.
230 *iterateFiles(patternOrPatterns) {
231 const { globInputPaths, errorOnUnmatchedPattern } = internalSlotsMap.get(this);
232 const patterns = Array.isArray(patternOrPatterns)
234 : [patternOrPatterns];
236 debug("Start to iterate files: %o", patterns);
238 // The set of paths to remove duplicate.
239 const set = new Set();
241 for (const pattern of patterns) {
242 let foundRegardlessOfIgnored = false;
245 // Skip empty string.
250 // Iterate files of this pttern.
251 for (const { config, filePath, flag } of this._iterateFiles(pattern)) {
252 foundRegardlessOfIgnored = true;
253 if (flag === IGNORED_SILENTLY) {
258 // Remove duplicate paths while yielding paths.
259 if (!set.has(filePath)) {
264 ignored: flag === IGNORED
269 // Raise an error if any files were not found.
270 if (errorOnUnmatchedPattern) {
271 if (!foundRegardlessOfIgnored) {
272 throw new NoFilesFoundError(
274 !globInputPaths && isGlob(pattern)
278 throw new AllFilesIgnoredError(pattern);
283 debug(`Complete iterating files: ${JSON.stringify(patterns)}`);
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.
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);
297 if (stat && stat.isDirectory()) {
298 return this._iterateFilesWithDirectory(absolutePath, isDot);
300 if (stat && stat.isFile()) {
301 return this._iterateFilesWithFile(absolutePath);
303 if (globInputPaths && isGlobPattern(pattern)) {
304 return this._iterateFilesWithGlob(absolutePath, isDot);
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.
316 _iterateFilesWithFile(filePath) {
317 debug(`File: ${filePath}`);
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;
324 return [{ config, filePath, flag }];
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.
334 _iterateFilesWithDirectory(directoryPath, dotfiles) {
335 debug(`Directory: ${directoryPath}`);
337 return this._iterateFilesRecursive(
339 { dotfiles, recursive: true, selector: null }
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.
350 _iterateFilesWithGlob(pattern, dotfiles) {
351 debug(`Glob: ${pattern}`);
353 const directoryPath = path.resolve(getGlobParent(pattern));
354 const globPart = pattern.slice(directoryPath.length + 1);
357 * recursive if there are `**` or path separators in the glob part.
358 * Otherwise, patterns such as `src/*.js`, it doesn't need recursive.
360 const recursive = /\*\*|\/|\\/u.test(globPart);
361 const selector = new Minimatch(pattern, minimatchOpts);
363 debug(`recursive? ${recursive}`);
365 return this._iterateFilesRecursive(
367 { dotfiles, recursive, selector }
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.
381 *_iterateFilesRecursive(directoryPath, options) {
382 debug(`Enter the directory: ${directoryPath}`);
383 const { configArrayFactory, extensionRegExp } = internalSlotsMap.get(this);
385 /** @type {ConfigArray|null} */
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.
393 // Check if the file is matched.
394 if (stat && stat.isFile()) {
396 config = configArrayFactory.getConfigArrayForFile(
400 * We must ignore `ConfigurationNotFoundError` at this
401 * point because we don't know if target files exist in
404 { ignoreNotFoundError: true }
407 const ignored = this._isIgnoredFile(filePath, { ...options, config });
408 const flag = ignored ? IGNORED_SILENTLY : NONE;
409 const matched = options.selector
411 // Started with a glob pattern; choose by the pattern.
412 ? options.selector.match(filePath)
414 // Started with a directory path; choose by file extensions.
415 : extensionRegExp.test(filePath);
418 debug(`Yield: ${filename}${ignored ? " but ignored" : ""}`);
420 config: configArrayFactory.getConfigArrayForFile(filePath),
425 debug(`Didn't match: ${filename}`);
428 // Dive into the sub directory.
429 } else if (options.recursive && stat && stat.isDirectory()) {
431 config = configArrayFactory.getConfigArrayForFile(
433 { ignoreNotFoundError: true }
436 const ignored = this._isIgnoredFile(
438 { ...options, config }
442 yield* this._iterateFilesRecursive(filePath, options);
447 debug(`Leave the directory: ${directoryPath}`);
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.
460 _isIgnoredFile(filePath, {
461 config: providedConfig,
469 } = internalSlotsMap.get(this);
474 configArrayFactory.getConfigArrayForFile(
476 { ignoreNotFoundError: true }
479 config.extractConfig(filePath).ignores || defaultIgnores;
481 return ignores(filePath, dotfiles);
484 return !direct && defaultIgnores(filePath, dotfiles);
488 //------------------------------------------------------------------------------
490 //------------------------------------------------------------------------------
492 module.exports = { FileEnumerator };