UNPKG

2.25 kBJavaScriptView Raw
1'use strict';
2
3exports.__esModule = true;
4
5const extname = require('path').extname;
6
7const log = require('debug')('eslint-plugin-import:utils:ignore');
8
9// one-shot memoized
10/** @type {Set<import('./types').Extension>} */ let cachedSet;
11/** @type {import('./types').ESLintSettings} */ let lastSettings;
12
13/** @type {import('./ignore').getFileExtensions} */
14function makeValidExtensionSet(settings) {
15 // start with explicit JS-parsed extensions
16 /** @type {Set<import('./types').Extension>} */
17 const exts = new Set(settings['import/extensions'] || ['.js', '.mjs', '.cjs']);
18
19 // all alternate parser extensions are also valid
20 if ('import/parsers' in settings) {
21 for (const parser in settings['import/parsers']) {
22 const parserSettings = settings['import/parsers'][parser];
23 if (!Array.isArray(parserSettings)) {
24 throw new TypeError('"settings" for ' + parser + ' must be an array');
25 }
26 parserSettings.forEach((ext) => exts.add(ext));
27 }
28 }
29
30 return exts;
31}
32exports.getFileExtensions = makeValidExtensionSet;
33
34/** @type {(context: import('eslint').Rule.RuleContext) => Set<import('./types').Extension>} */
35function validExtensions(context) {
36 if (cachedSet && context.settings === lastSettings) {
37 return cachedSet;
38 }
39
40 lastSettings = context.settings;
41 cachedSet = makeValidExtensionSet(context.settings);
42 return cachedSet;
43}
44
45/** @type {import('./ignore').hasValidExtension} */
46function hasValidExtension(path, context) {
47 // eslint-disable-next-line no-extra-parens
48 return validExtensions(context).has(/** @type {import('./types').Extension} */ (extname(path)));
49}
50exports.hasValidExtension = hasValidExtension;
51
52/** @type {import('./ignore').default} */
53exports.default = function ignore(path, context) {
54 // check extension whitelist first (cheap)
55 if (!hasValidExtension(path, context)) {
56 return true;
57 }
58
59 if (!('import/ignore' in context.settings)) {
60 return false;
61 }
62 const ignoreStrings = context.settings['import/ignore'];
63
64 for (let i = 0; i < ignoreStrings.length; i++) {
65 const regex = new RegExp(ignoreStrings[i]);
66 if (regex.test(path)) {
67 log(`ignoring ${path}, matched pattern /${ignoreStrings[i]}/`);
68 return true;
69 }
70 }
71
72 return false;
73};