minor adjustment to readme
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / cli-engine / config-array / ignore-pattern.js
1 /**
2  * @fileoverview `IgnorePattern` class.
3  *
4  * `IgnorePattern` class has the set of glob patterns and the base path.
5  *
6  * It provides two static methods.
7  *
8  * - `IgnorePattern.createDefaultIgnore(cwd)`
9  *      Create the default predicate function.
10  * - `IgnorePattern.createIgnore(ignorePatterns)`
11  *      Create the predicate function from multiple `IgnorePattern` objects.
12  *
13  * It provides two properties and a method.
14  *
15  * - `patterns`
16  *      The glob patterns that ignore to lint.
17  * - `basePath`
18  *      The base path of the glob patterns. If absolute paths existed in the
19  *      glob patterns, those are handled as relative paths to the base path.
20  * - `getPatternsRelativeTo(basePath)`
21  *      Get `patterns` as modified for a given base path. It modifies the
22  *      absolute paths in the patterns as prepending the difference of two base
23  *      paths.
24  *
25  * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
26  * `ignorePatterns` properties.
27  *
28  * @author Toru Nagashima <https://github.com/mysticatea>
29  */
30 "use strict";
31
32 //------------------------------------------------------------------------------
33 // Requirements
34 //------------------------------------------------------------------------------
35
36 const assert = require("assert");
37 const path = require("path");
38 const ignore = require("ignore");
39 const debug = require("debug")("eslint:ignore-pattern");
40
41 /** @typedef {ReturnType<import("ignore").default>} Ignore */
42
43 //------------------------------------------------------------------------------
44 // Helpers
45 //------------------------------------------------------------------------------
46
47 /**
48  * Get the path to the common ancestor directory of given paths.
49  * @param {string[]} sourcePaths The paths to calculate the common ancestor.
50  * @returns {string} The path to the common ancestor directory.
51  */
52 function getCommonAncestorPath(sourcePaths) {
53     let result = sourcePaths[0];
54
55     for (let i = 1; i < sourcePaths.length; ++i) {
56         const a = result;
57         const b = sourcePaths[i];
58
59         // Set the shorter one (it's the common ancestor if one includes the other).
60         result = a.length < b.length ? a : b;
61
62         // Set the common ancestor.
63         for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
64             if (a[j] !== b[j]) {
65                 result = a.slice(0, lastSepPos);
66                 break;
67             }
68             if (a[j] === path.sep) {
69                 lastSepPos = j;
70             }
71         }
72     }
73
74     return result || path.sep;
75 }
76
77 /**
78  * Make relative path.
79  * @param {string} from The source path to get relative path.
80  * @param {string} to The destination path to get relative path.
81  * @returns {string} The relative path.
82  */
83 function relative(from, to) {
84     const relPath = path.relative(from, to);
85
86     if (path.sep === "/") {
87         return relPath;
88     }
89     return relPath.split(path.sep).join("/");
90 }
91
92 /**
93  * Get the trailing slash if existed.
94  * @param {string} filePath The path to check.
95  * @returns {string} The trailing slash if existed.
96  */
97 function dirSuffix(filePath) {
98     const isDir = (
99         filePath.endsWith(path.sep) ||
100         (process.platform === "win32" && filePath.endsWith("/"))
101     );
102
103     return isDir ? "/" : "";
104 }
105
106 const DefaultPatterns = Object.freeze(["/node_modules/*", "/bower_components/*"]);
107 const DotPatterns = Object.freeze([".*", "!../"]);
108
109 //------------------------------------------------------------------------------
110 // Public
111 //------------------------------------------------------------------------------
112
113 class IgnorePattern {
114
115     /**
116      * The default patterns.
117      * @type {string[]}
118      */
119     static get DefaultPatterns() {
120         return DefaultPatterns;
121     }
122
123     /**
124      * Create the default predicate function.
125      * @param {string} cwd The current working directory.
126      * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
127      * The preficate function.
128      * The first argument is an absolute path that is checked.
129      * The second argument is the flag to not ignore dotfiles.
130      * If the predicate function returned `true`, it means the path should be ignored.
131      */
132     static createDefaultIgnore(cwd) {
133         return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
134     }
135
136     /**
137      * Create the predicate function from multiple `IgnorePattern` objects.
138      * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
139      * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
140      * The preficate function.
141      * The first argument is an absolute path that is checked.
142      * The second argument is the flag to not ignore dotfiles.
143      * If the predicate function returned `true`, it means the path should be ignored.
144      */
145     static createIgnore(ignorePatterns) {
146         debug("Create with: %o", ignorePatterns);
147
148         const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
149         const patterns = [].concat(
150             ...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
151         );
152         const ig = ignore().add([...DotPatterns, ...patterns]);
153         const dotIg = ignore().add(patterns);
154
155         debug("  processed: %o", { basePath, patterns });
156
157         return Object.assign(
158             (filePath, dot = false) => {
159                 assert(path.isAbsolute(filePath), "'filePath' should be an absolute path.");
160                 const relPathRaw = relative(basePath, filePath);
161                 const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
162                 const adoptedIg = dot ? dotIg : ig;
163                 const result = relPath !== "" && adoptedIg.ignores(relPath);
164
165                 debug("Check", { filePath, dot, relativePath: relPath, result });
166                 return result;
167             },
168             { basePath, patterns }
169         );
170     }
171
172     /**
173      * Initialize a new `IgnorePattern` instance.
174      * @param {string[]} patterns The glob patterns that ignore to lint.
175      * @param {string} basePath The base path of `patterns`.
176      */
177     constructor(patterns, basePath) {
178         assert(path.isAbsolute(basePath), "'basePath' should be an absolute path.");
179
180         /**
181          * The glob patterns that ignore to lint.
182          * @type {string[]}
183          */
184         this.patterns = patterns;
185
186         /**
187          * The base path of `patterns`.
188          * @type {string}
189          */
190         this.basePath = basePath;
191
192         /**
193          * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
194          *
195          * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
196          * It's `false` as-is for `ignorePatterns` property in config files.
197          * @type {boolean}
198          */
199         this.loose = false;
200     }
201
202     /**
203      * Get `patterns` as modified for a given base path. It modifies the
204      * absolute paths in the patterns as prepending the difference of two base
205      * paths.
206      * @param {string} newBasePath The base path.
207      * @returns {string[]} Modifired patterns.
208      */
209     getPatternsRelativeTo(newBasePath) {
210         assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
211         const { basePath, loose, patterns } = this;
212
213         if (newBasePath === basePath) {
214             return patterns;
215         }
216         const prefix = `/${relative(newBasePath, basePath)}`;
217
218         return patterns.map(pattern => {
219             const negative = pattern.startsWith("!");
220             const head = negative ? "!" : "";
221             const body = negative ? pattern.slice(1) : pattern;
222
223             if (body.startsWith("/") || body.startsWith("../")) {
224                 return `${head}${prefix}${body}`;
225             }
226             return loose ? pattern : `${head}${prefix}/**/${body}`;
227         });
228     }
229 }
230
231 module.exports = { IgnorePattern };