UNPKG

2.79 kBJavaScriptView Raw
1'use strict';
2const normalizeExtensions = require('./lib/extensions');
3const {classify, hasExtension, isHelperish, matches, normalizeFileForMatching, normalizeGlobs, normalizePatterns} = require('./lib/globs');
4const loadConfig = require('./lib/load-config');
5const providerManager = require('./lib/provider-manager');
6
7const configCache = new Map();
8const helperCache = new Map();
9
10function load(projectDir, overrides) {
11 const cacheKey = `${JSON.stringify(overrides)}\n${projectDir}`;
12 if (helperCache.has(cacheKey)) {
13 return helperCache.get(cacheKey);
14 }
15
16 let conf;
17 let providers;
18 if (configCache.has(projectDir)) {
19 ({conf, providers} = configCache.get(projectDir));
20 } else {
21 conf = loadConfig({resolveFrom: projectDir});
22
23 providers = [];
24 if (Reflect.has(conf, 'babel')) {
25 const {level, main} = providerManager.babel(projectDir);
26 providers.push({
27 level,
28 main: main({config: conf.babel}),
29 type: 'babel'
30 });
31 }
32
33 if (Reflect.has(conf, 'typescript')) {
34 const {level, main} = providerManager.typescript(projectDir);
35 providers.push({
36 level,
37 main: main({config: conf.typescript}),
38 type: 'typescript'
39 });
40 }
41
42 configCache.set(projectDir, {conf, providers});
43 }
44
45 const extensions = overrides && overrides.extensions ?
46 normalizeExtensions(overrides.extensions) :
47 normalizeExtensions(conf.extensions, providers);
48
49 let helperPatterns = [];
50 if (overrides && overrides.helpers !== undefined) {
51 if (!Array.isArray(overrides.helpers) || overrides.helpers.length === 0) {
52 throw new Error('The ’helpers’ override must be an array containing glob patterns.');
53 }
54
55 helperPatterns = normalizePatterns(overrides.helpers);
56 }
57
58 const globs = {
59 cwd: projectDir,
60 ...normalizeGlobs({
61 extensions,
62 files: overrides && overrides.files ? overrides.files : conf.files,
63 providers
64 })
65 };
66
67 const classifyForESLint = file => {
68 const {isTest} = classify(file, globs);
69 let isHelper = false;
70 if (!isTest && hasExtension(globs.extensions, file)) {
71 file = normalizeFileForMatching(projectDir, file);
72 isHelper = isHelperish(file) || (helperPatterns.length > 0 && matches(file, helperPatterns));
73 }
74
75 return {isHelper, isTest};
76 };
77
78 const helper = Object.freeze({
79 classifyFile: classifyForESLint,
80 classifyImport: importPath => {
81 if (hasExtension(globs.extensions, importPath)) {
82 // The importPath has one of the test file extensions: we can classify
83 // it directly.
84 return classifyForESLint(importPath);
85 }
86
87 // Add the first extension. If multiple extensions are available, assume
88 // patterns are not biased to any particular extension.
89 return classifyForESLint(`${importPath}.${globs.extensions[0]}`);
90 }
91 });
92 helperCache.set(cacheKey, helper);
93 return helper;
94}
95
96exports.load = load;