UNPKG

6.94 kBJavaScriptView Raw
1/**
2 * @fileoverview Utilities for working with globs and the filesystem.
3 * @author Ian VanSchooten
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const lodash = require("lodash"),
12 fs = require("fs"),
13 path = require("path"),
14 GlobSync = require("./glob"),
15
16 pathUtil = require("./path-util"),
17 IgnoredPaths = require("../ignored-paths");
18
19const debug = require("debug")("eslint:glob-util");
20
21//------------------------------------------------------------------------------
22// Helpers
23//------------------------------------------------------------------------------
24
25/**
26 * Checks if a provided path is a directory and returns a glob string matching
27 * all files under that directory if so, the path itself otherwise.
28 *
29 * Reason for this is that `glob` needs `/**` to collect all the files under a
30 * directory where as our previous implementation without `glob` simply walked
31 * a directory that is passed. So this is to maintain backwards compatibility.
32 *
33 * Also makes sure all path separators are POSIX style for `glob` compatibility.
34 *
35 * @param {Object} [options] An options object
36 * @param {string[]} [options.extensions=[".js"]] An array of accepted extensions
37 * @param {string} [options.cwd=process.cwd()] The cwd to use to resolve relative pathnames
38 * @returns {Function} A function that takes a pathname and returns a glob that
39 * matches all files with the provided extensions if
40 * pathname is a directory.
41 */
42function processPath(options) {
43 const cwd = (options && options.cwd) || process.cwd();
44 let extensions = (options && options.extensions) || [".js"];
45
46 extensions = extensions.map(ext => ext.replace(/^\./, ""));
47
48 let suffix = "/**";
49
50 if (extensions.length === 1) {
51 suffix += `/*.${extensions[0]}`;
52 } else {
53 suffix += `/*.{${extensions.join(",")}}`;
54 }
55
56 /**
57 * A function that converts a directory name to a glob pattern
58 *
59 * @param {string} pathname The directory path to be modified
60 * @returns {string} The glob path or the file path itself
61 * @private
62 */
63 return function(pathname) {
64 let newPath = pathname;
65 const resolvedPath = path.resolve(cwd, pathname);
66
67 if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isDirectory()) {
68 newPath = pathname.replace(/[/\\]$/, "") + suffix;
69 }
70
71 return pathUtil.convertPathToPosix(newPath);
72 };
73}
74
75//------------------------------------------------------------------------------
76// Public Interface
77//------------------------------------------------------------------------------
78
79/**
80 * Resolves any directory patterns into glob-based patterns for easier handling.
81 * @param {string[]} patterns File patterns (such as passed on the command line).
82 * @param {Object} options An options object.
83 * @returns {string[]} The equivalent glob patterns and filepath strings.
84 */
85function resolveFileGlobPatterns(patterns, options) {
86
87 const processPathExtensions = processPath(options);
88
89 return patterns.filter(p => p.length).map(processPathExtensions);
90}
91
92const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/;
93
94/**
95 * Build a list of absolute filesnames on which ESLint will act.
96 * Ignored files are excluded from the results, as are duplicates.
97 *
98 * @param {string[]} globPatterns Glob patterns.
99 * @param {Object} [providedOptions] An options object.
100 * @param {string} [providedOptions.cwd] CWD (considered for relative filenames)
101 * @param {boolean} [providedOptions.ignore] False disables use of .eslintignore.
102 * @param {string} [providedOptions.ignorePath] The ignore file to use instead of .eslintignore.
103 * @param {string} [providedOptions.ignorePattern] A pattern of files to ignore.
104 * @returns {string[]} Resolved absolute filenames.
105 */
106function listFilesToProcess(globPatterns, providedOptions) {
107 const options = providedOptions || { ignore: true };
108 const files = [];
109 const addedFilenames = new Set();
110
111 const cwd = options.cwd || process.cwd();
112
113 const getIgnorePaths = lodash.memoize(
114 optionsObj =>
115 new IgnoredPaths(optionsObj)
116 );
117
118 /**
119 * Executes the linter on a file defined by the `filename`. Skips
120 * any files that are already linted.
121 * @param {string} filename The file to be processed
122 * @param {boolean} isDirectPath True if the file
123 * was provided as a direct path (as opposed to being resolved from a glob)
124 * @param {IgnoredPaths} ignoredPaths An instance of IgnoredPaths
125 * @returns {void}
126 */
127 function addFile(filename, isDirectPath, ignoredPaths) {
128 if (addedFilenames.has(filename)) {
129 return;
130 }
131
132 const shouldProcessCustomIgnores = options.ignore !== false;
133 const shouldLintIgnoredDirectPaths = options.ignore === false;
134 const fileMatchesIgnorePatterns = ignoredPaths.contains(filename, "default") ||
135 (shouldProcessCustomIgnores && ignoredPaths.contains(filename, "custom"));
136
137 if (fileMatchesIgnorePatterns && isDirectPath && !shouldLintIgnoredDirectPaths) {
138 files.push({ filename, ignored: true });
139 addedFilenames.add(filename);
140 }
141
142 if (!fileMatchesIgnorePatterns || (isDirectPath && shouldLintIgnoredDirectPaths)) {
143 files.push({ filename, ignored: false });
144 addedFilenames.add(filename);
145 }
146 }
147
148 debug("Creating list of files to process.");
149 globPatterns.forEach(pattern => {
150 const file = path.resolve(cwd, pattern);
151
152 if (fs.existsSync(file) && fs.statSync(file).isFile()) {
153 const ignoredPaths = getIgnorePaths(options);
154
155 addFile(fs.realpathSync(file), true, ignoredPaths);
156 } else {
157
158 // regex to find .hidden or /.hidden patterns, but not ./relative or ../relative
159 const globIncludesDotfiles = dotfilesPattern.test(pattern);
160 let newOptions = options;
161
162 if (!options.dotfiles) {
163 newOptions = Object.assign({}, options, { dotfiles: globIncludesDotfiles });
164 }
165
166 const ignoredPaths = getIgnorePaths(newOptions);
167 const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker();
168 const globOptions = {
169 nodir: true,
170 dot: true,
171 cwd
172 };
173
174 new GlobSync(pattern, globOptions, shouldIgnore).found.forEach(globMatch => {
175 addFile(path.resolve(cwd, globMatch), false, ignoredPaths);
176 });
177 }
178 });
179
180 return files;
181}
182
183module.exports = {
184 resolveFileGlobPatterns,
185 listFilesToProcess
186};