/
_utils.js
458 lines (420 loc) · 16.1 KB
/
_utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/**
* @fileoverview Define classes what use the in-memory file system.
*
* This provides utilities to test `ConfigArrayFactory`,
* `CascadingConfigArrayFactory`, `FileEnumerator`, and `CLIEngine`.
*
* - `defineConfigArrayFactoryWithInMemoryFileSystem({ cwd, files })`
* - `defineCascadingConfigArrayFactoryWithInMemoryFileSystem({ cwd, files })`
* - `defineFileEnumeratorWithInMemoryFileSystem({ cwd, files })`
* - `defineCLIEngineWithInMemoryFileSystem({ cwd, files })`
*
* Those functions define correspond classes with the in-memory file system.
* Those search config files, parsers, and plugins in the `files` option via the
* in-memory file system.
*
* For each test case, it makes more readable if we define minimal files the
* test case requires.
*
* For example:
*
* ```js
* const { ConfigArrayFactory } = defineConfigArrayFactoryWithInMemoryFileSystem({
* files: {
* "node_modules/eslint-config-foo/index.js": `
* module.exports = {
* parser: "./parser",
* rules: {
* "no-undef": "error"
* }
* }
* `,
* "node_modules/eslint-config-foo/parser.js": `
* module.exports = {
* parse() {}
* }
* `,
* ".eslintrc.json": JSON.stringify({ root: true, extends: "foo" })
* }
* });
* const factory = new ConfigArrayFactory();
* const config = factory.loadFile(".eslintrc.json");
*
* assert(config[0].name === ".eslintrc.json » eslint-config-foo");
* assert(config[0].filePath === path.resolve("node_modules/eslint-config-foo/index.js"));
* assert(config[0].parser.filePath === path.resolve("node_modules/eslint-config-foo/parser.js"));
*
* assert(config[1].name === ".eslintrc.json");
* assert(config[1].filePath === path.resolve(".eslintrc.json"));
* assert(config[1].root === true);
* ```
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
// To use TypeScript type annotations for VSCode intellisense.
/* eslint-disable valid-jsdoc */
const path = require("path");
const vm = require("vm");
const Proxyquire = require("proxyquire/lib/proxyquire");
const { defineInMemoryFs } = require("../_utils");
const CascadingConfigArrayFactoryPath =
require.resolve("../../../lib/cli-engine/cascading-config-array-factory");
const CLIEnginePath =
require.resolve("../../../lib/cli-engine/cli-engine");
const ConfigArrayFactoryPath =
require.resolve("../../../lib/cli-engine/config-array-factory");
const FileEnumeratorPath =
require.resolve("../../../lib/cli-engine/file-enumerator");
const IgnoredPathsPath =
require.resolve("../../../lib/cli-engine/ignored-paths");
const LoadRulesPath =
require.resolve("../../../lib/cli-engine/load-rules");
const ESLintAllPath =
require.resolve("../../../conf/eslint-all");
const ESLintRecommendedPath =
require.resolve("../../../conf/eslint-recommended");
// Ensure the needed files has been loaded and cached.
require(CascadingConfigArrayFactoryPath);
require(CLIEnginePath);
require(ConfigArrayFactoryPath);
require(FileEnumeratorPath);
require(IgnoredPathsPath);
require(LoadRulesPath);
require("js-yaml");
require("espree");
// Override `_require` in order to throw runtime errors in stubs.
const ERRORED = Symbol("errored");
const proxyquire = new class extends Proxyquire {
_require(...args) {
const retv = super._require(...args); // eslint-disable-line no-underscore-dangle
if (retv[ERRORED]) {
throw retv[ERRORED];
}
return retv;
}
}(module).noCallThru().noPreserveCache();
// Separated (sandbox) context to compile fixture files.
const context = vm.createContext();
/**
* Check if a given path is an existing file.
* @param {import("fs")} fs The file system.
* @param {string} filePath Tha path to a file to check.
* @returns {boolean} `true` if the file existed.
*/
function isExistingFile(fs, filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (error) {
return false;
}
}
/**
* Get some paths to test.
* @param {string} prefix The prefix to try.
* @returns {string[]} The paths to test.
*/
function getTestPaths(prefix) {
return [
path.join(prefix),
path.join(`${prefix}.js`),
path.join(prefix, "index.js")
];
}
/**
* Iterate the candidate paths of a given request to resolve.
* @param {string} request Tha package name or file path to resolve.
* @param {string} relativeTo Tha path to the file what called this resolving.
* @returns {IterableIterator<string>} The candidate paths.
*/
function *iterateCandidatePaths(request, relativeTo) {
if (path.isAbsolute(request)) {
yield* getTestPaths(request);
return;
}
if (/^\.{1,2}[/\\]/u.test(request)) {
yield* getTestPaths(path.resolve(path.dirname(relativeTo), request));
return;
}
let prevPath = path.resolve(relativeTo);
let dirPath = path.dirname(prevPath);
while (dirPath && dirPath !== prevPath) {
yield* getTestPaths(path.join(dirPath, "node_modules", request));
prevPath = dirPath;
dirPath = path.dirname(dirPath);
}
}
/**
* Resolve a given module name or file path relatively in the given file system.
* @param {import("fs")} fs The file system.
* @param {string} request Tha package name or file path to resolve.
* @param {string} relativeTo Tha path to the file what called this resolving.
* @returns {void}
*/
function fsResolve(fs, request, relativeTo) {
for (const filePath of iterateCandidatePaths(request, relativeTo)) {
if (isExistingFile(fs, filePath)) {
return filePath;
}
}
throw Object.assign(
new Error(`Cannot find module '${request}'`),
{ code: "MODULE_NOT_FOUND" }
);
}
/**
* Compile a JavaScript file.
* This is used to compile only fixture files, so this is minimam.
* @param {import("fs")} fs The file system.
* @param {Object} stubs The stubs.
* @param {string} filePath The path to a JavaScript file to compile.
* @param {string} content The source code to compile.
* @returns {any} The exported value.
*/
function compile(fs, stubs, filePath, content) {
const code = `(function(exports, require, module, __filename, __dirname) { ${content} })`;
const f = vm.runInContext(code, context);
const exports = {};
const module = { exports };
f.call(
exports,
exports,
request => {
const modulePath = fsResolve(fs, request, filePath);
const stub = stubs[modulePath];
if (stub[ERRORED]) {
throw stub[ERRORED];
}
return stub;
},
module,
filePath,
path.dirname(filePath)
);
return module.exports;
}
/**
* Import a given file path in the given file system.
* @param {import("fs")} fs The file system.
* @param {Object} stubs The stubs.
* @param {string} absolutePath Tha file path to import.
* @returns {void}
*/
function fsImportFresh(fs, stubs, absolutePath) {
if (absolutePath === ESLintAllPath) {
return require(ESLintAllPath);
}
if (absolutePath === ESLintRecommendedPath) {
return require(ESLintRecommendedPath);
}
if (fs.existsSync(absolutePath)) {
return compile(
fs,
stubs,
absolutePath,
fs.readFileSync(absolutePath, "utf8")
);
}
throw Object.assign(
new Error(`Cannot find module '${absolutePath}'`),
{ code: "MODULE_NOT_FOUND" }
);
}
/**
* Define stubbed `ConfigArrayFactory` class what uses the in-memory file system.
* @param {Object} options The options.
* @param {() => string} [options.cwd] The current working directory.
* @param {Object} [options.files] The initial files definition in the in-memory file system.
* @returns {{ fs: import("fs"), RelativeModuleResolver: import("../../../lib/shared/relative-module-resolver"), ConfigArrayFactory: import("../../../lib/cli-engine/config-array-factory")["ConfigArrayFactory"] }} The stubbed `ConfigArrayFactory` class.
*/
function defineConfigArrayFactoryWithInMemoryFileSystem({
cwd = process.cwd,
files = {}
} = {}) {
const fs = defineInMemoryFs({ cwd, files });
const RelativeModuleResolver = { resolve: fsResolve.bind(null, fs) };
/*
* Stubs for proxyquire.
* This contains the JavaScript files in `options.files`.
*/
const stubs = {};
stubs.fs = fs;
stubs["import-fresh"] = fsImportFresh.bind(null, fs, stubs);
stubs["../shared/relative-module-resolver"] = RelativeModuleResolver;
/*
* Write all files to the in-memory file system and compile all JavaScript
* files then set to `stubs`.
*/
(function initFiles(directoryPath, definition) {
for (const [filename, content] of Object.entries(definition)) {
const filePath = path.resolve(directoryPath, filename);
if (typeof content === "object") {
initFiles(filePath, content);
continue;
}
/*
* Compile then stub if this file is a JavaScript file.
* For parsers and plugins that `require()` will import.
*/
if (path.extname(filePath) === ".js") {
Object.defineProperty(stubs, filePath, {
configurable: true,
enumerable: true,
get() {
let stub;
try {
stub = compile(fs, stubs, filePath, content);
} catch (error) {
stub = { [ERRORED]: error };
}
Object.defineProperty(stubs, filePath, {
configurable: true,
enumerable: true,
value: stub
});
return stub;
}
});
}
}
}(cwd(), files));
// Load the stubbed one.
const { ConfigArrayFactory } = proxyquire(ConfigArrayFactoryPath, stubs);
// Override the default cwd.
return {
fs,
stubs,
RelativeModuleResolver,
ConfigArrayFactory: cwd === process.cwd
? ConfigArrayFactory
: class extends ConfigArrayFactory {
constructor(options) {
super({ cwd: cwd(), ...options });
}
}
};
}
/**
* Define stubbed `CascadingConfigArrayFactory` class what uses the in-memory file system.
* @param {Object} options The options.
* @param {() => string} [options.cwd] The current working directory.
* @param {Object} [options.files] The initial files definition in the in-memory file system.
* @returns {{ fs: import("fs"), RelativeModuleResolver: import("../../../lib/shared/relative-module-resolver"), ConfigArrayFactory: import("../../../lib/cli-engine/config-array-factory")["ConfigArrayFactory"], CascadingConfigArrayFactory: import("../../../lib/cli-engine/cascading-config-array-factory")["CascadingConfigArrayFactory"] }} The stubbed `CascadingConfigArrayFactory` class.
*/
function defineCascadingConfigArrayFactoryWithInMemoryFileSystem({
cwd = process.cwd,
files = {}
} = {}) {
const { fs, stubs, RelativeModuleResolver, ConfigArrayFactory } =
defineConfigArrayFactoryWithInMemoryFileSystem({ cwd, files });
const loadRules = proxyquire(LoadRulesPath, stubs);
const { CascadingConfigArrayFactory } =
proxyquire(CascadingConfigArrayFactoryPath, {
"./config-array-factory": { ConfigArrayFactory },
"./load-rules": loadRules
});
// Override the default cwd.
return {
fs,
RelativeModuleResolver,
ConfigArrayFactory,
CascadingConfigArrayFactory: cwd === process.cwd
? CascadingConfigArrayFactory
: class extends CascadingConfigArrayFactory {
constructor(options) {
super({ cwd: cwd(), ...options });
}
}
};
}
/**
* Define stubbed `FileEnumerator` class what uses the in-memory file system.
* @param {Object} options The options.
* @param {() => string} [options.cwd] The current working directory.
* @param {Object} [options.files] The initial files definition in the in-memory file system.
* @returns {{ fs: import("fs"), RelativeModuleResolver: import("../../../lib/shared/relative-module-resolver"), ConfigArrayFactory: import("../../../lib/cli-engine/config-array-factory")["ConfigArrayFactory"], CascadingConfigArrayFactory: import("../../../lib/cli-engine/cascading-config-array-factory")["CascadingConfigArrayFactory"], IgnoredPaths: import("../../../lib/cli-engine/ignored-paths")["IgnoredPaths"], FileEnumerator: import("../../../lib/cli-engine/file-enumerator")["FileEnumerator"] }} The stubbed `FileEnumerator` class.
*/
function defineFileEnumeratorWithInMemoryFileSystem({
cwd = process.cwd,
files = {}
} = {}) {
const {
fs,
RelativeModuleResolver,
ConfigArrayFactory,
CascadingConfigArrayFactory
} =
defineCascadingConfigArrayFactoryWithInMemoryFileSystem({ cwd, files });
const { IgnoredPaths } = proxyquire(IgnoredPathsPath, { fs });
const { FileEnumerator } = proxyquire(FileEnumeratorPath, {
fs,
"./cascading-config-array-factory": { CascadingConfigArrayFactory },
"./ignored-paths": { IgnoredPaths }
});
// Override the default cwd.
return {
fs,
RelativeModuleResolver,
ConfigArrayFactory,
CascadingConfigArrayFactory,
IgnoredPaths,
FileEnumerator: cwd === process.cwd
? FileEnumerator
: class extends FileEnumerator {
constructor(options) {
super({ cwd: cwd(), ...options });
}
}
};
}
/**
* Define stubbed `CLIEngine` class what uses the in-memory file system.
* @param {Object} options The options.
* @param {() => string} [options.cwd] The current working directory.
* @param {Object} [options.files] The initial files definition in the in-memory file system.
* @returns {{ fs: import("fs"), RelativeModuleResolver: import("../../../lib/shared/relative-module-resolver"), ConfigArrayFactory: import("../../../lib/cli-engine/config-array-factory")["ConfigArrayFactory"], CascadingConfigArrayFactory: import("../../../lib/cli-engine/cascading-config-array-factory")["CascadingConfigArrayFactory"], IgnoredPaths: import("../../../lib/cli-engine/ignored-paths")["IgnoredPaths"], FileEnumerator: import("../../../lib/cli-engine/file-enumerator")["FileEnumerator"], CLIEngine: import("../../../lib/cli-engine/cli-engine")["CLIEngine"], getCLIEngineInternalSlots: import("../../../lib/cli-engine/cli-engine")["getCLIEngineInternalSlots"] }} The stubbed `CLIEngine` class.
*/
function defineCLIEngineWithInMemoryFileSystem({
cwd = process.cwd,
files = {}
} = {}) {
const {
fs,
RelativeModuleResolver,
ConfigArrayFactory,
CascadingConfigArrayFactory,
IgnoredPaths,
FileEnumerator
} =
defineFileEnumeratorWithInMemoryFileSystem({ cwd, files });
const { CLIEngine, getCLIEngineInternalSlots } = proxyquire(CLIEnginePath, {
fs,
"./cascading-config-array-factory": { CascadingConfigArrayFactory },
"./file-enumerator": { FileEnumerator },
"./ignored-paths": { IgnoredPaths },
"../shared/relative-module-resolver": RelativeModuleResolver
});
// Override the default cwd.
return {
fs,
RelativeModuleResolver,
ConfigArrayFactory,
CascadingConfigArrayFactory,
IgnoredPaths,
FileEnumerator,
CLIEngine: cwd === process.cwd
? CLIEngine
: class extends CLIEngine {
constructor(options) {
super({ cwd: cwd(), ...options });
}
},
getCLIEngineInternalSlots
};
}
module.exports = {
defineConfigArrayFactoryWithInMemoryFileSystem,
defineCascadingConfigArrayFactoryWithInMemoryFileSystem,
defineFileEnumeratorWithInMemoryFileSystem,
defineCLIEngineWithInMemoryFileSystem
};