2 * @fileoverview `OverrideTester` class.
4 * `OverrideTester` class handles `files` property and `excludedFiles` property
5 * of `overrides` config.
7 * It provides one method.
10 * Test if a file path matches the pair of `files` property and
11 * `excludedFiles` property. The `filePath` argument must be an absolute
14 * `ConfigArrayFactory` creates `OverrideTester` objects when it processes
15 * `overrides` properties.
17 * @author Toru Nagashima <https://github.com/mysticatea>
21 const assert = require("assert");
22 const path = require("path");
23 const util = require("util");
24 const { Minimatch } = require("minimatch");
25 const minimatchOpts = { dot: true, matchBase: true };
28 * @typedef {Object} Pattern
29 * @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
30 * @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
34 * Normalize a given pattern to an array.
35 * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
36 * @returns {string[]|null} Normalized patterns.
39 function normalizePatterns(patterns) {
40 if (Array.isArray(patterns)) {
41 return patterns.filter(Boolean);
43 if (typeof patterns === "string" && patterns) {
50 * Create the matchers of given patterns.
51 * @param {string[]} patterns The patterns.
52 * @returns {InstanceType<Minimatch>[] | null} The matchers.
54 function toMatcher(patterns) {
55 if (patterns.length === 0) {
58 return patterns.map(pattern => {
59 if (/^\.[/\\]/u.test(pattern)) {
63 // `./*.js` should not match with `subdir/foo.js`
64 { ...minimatchOpts, matchBase: false }
67 return new Minimatch(pattern, minimatchOpts);
72 * Convert a given matcher to string.
73 * @param {Pattern} matchers The matchers.
74 * @returns {string} The string expression of the matcher.
76 function patternToJson({ includes, excludes }) {
78 includes: includes && includes.map(m => m.pattern),
79 excludes: excludes && excludes.map(m => m.pattern)
84 * The class to test given paths are matched by the patterns.
86 class OverrideTester {
89 * Create a tester with given criteria.
90 * If there are no criteria, returns `null`.
91 * @param {string|string[]} files The glob patterns for included files.
92 * @param {string|string[]} excludedFiles The glob patterns for excluded files.
93 * @param {string} basePath The path to the base directory to test paths.
94 * @returns {OverrideTester|null} The created instance or `null`.
96 static create(files, excludedFiles, basePath) {
97 const includePatterns = normalizePatterns(files);
98 const excludePatterns = normalizePatterns(excludedFiles);
99 const allPatterns = includePatterns.concat(excludePatterns);
101 if (allPatterns.length === 0) {
105 // Rejects absolute paths or relative paths to parents.
106 for (const pattern of allPatterns) {
107 if (path.isAbsolute(pattern) || pattern.includes("..")) {
108 throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
112 const includes = toMatcher(includePatterns);
113 const excludes = toMatcher(excludePatterns);
115 return new OverrideTester([{ includes, excludes }], basePath);
119 * Combine two testers by logical and.
120 * If either of the testers was `null`, returns the other tester.
121 * The `basePath` property of the two must be the same value.
122 * @param {OverrideTester|null} a A tester.
123 * @param {OverrideTester|null} b Another tester.
124 * @returns {OverrideTester|null} Combined tester.
128 return a && new OverrideTester(a.patterns, a.basePath);
131 return new OverrideTester(b.patterns, b.basePath);
134 assert.strictEqual(a.basePath, b.basePath);
135 return new OverrideTester(a.patterns.concat(b.patterns), a.basePath);
139 * Initialize this instance.
140 * @param {Pattern[]} patterns The matchers.
141 * @param {string} basePath The base path.
143 constructor(patterns, basePath) {
145 /** @type {Pattern[]} */
146 this.patterns = patterns;
148 /** @type {string} */
149 this.basePath = basePath;
153 * Test if a given path is matched or not.
154 * @param {string} filePath The absolute path to the target file.
155 * @returns {boolean} `true` if the path was matched.
158 if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {
159 throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
161 const relativePath = path.relative(this.basePath, filePath);
163 return this.patterns.every(({ includes, excludes }) => (
164 (!includes || includes.some(m => m.match(relativePath))) &&
165 (!excludes || !excludes.some(m => m.match(relativePath)))
169 // eslint-disable-next-line jsdoc/require-description
171 * @returns {Object} a JSON compatible object.
174 if (this.patterns.length === 1) {
176 ...patternToJson(this.patterns[0]),
177 basePath: this.basePath
181 AND: this.patterns.map(patternToJson),
182 basePath: this.basePath
186 // eslint-disable-next-line jsdoc/require-description
188 * @returns {Object} an object to display by `console.log()`.
190 [util.inspect.custom]() {
191 return this.toJSON();
195 module.exports = { OverrideTester };