]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | /** |
2 | * @fileoverview utils for rule tests. | |
3 | * @author 唯然<weiran.zsd@outlook.com> | |
4 | */ | |
5 | ||
6 | "use strict"; | |
7 | ||
8 | const path = require("path"); | |
9 | const { Volume, createFsFromVolume } = require("memfs"); | |
10 | ||
11 | /** | |
12 | * Prevents leading spaces in a multiline template literal from appearing in the resulting string | |
13 | * @param {string[]} strings The strings in the template literal | |
14 | * @param {any[]} values The interpolation values in the template literal. | |
15 | * @returns {string} The template literal, with spaces removed from all lines | |
16 | */ | |
17 | function unIndent(strings, ...values) { | |
18 | const text = strings | |
19 | .map((s, i) => (i === 0 ? s : values[i - 1] + s)) | |
20 | .join(""); | |
21 | const lines = text.replace(/^\n/u, "").replace(/\n\s*$/u, "").split("\n"); | |
22 | const lineIndents = lines.filter(line => line.trim()).map(line => line.match(/ */u)[0].length); | |
23 | const minLineIndent = Math.min(...lineIndents); | |
24 | ||
25 | return lines.map(line => line.slice(minLineIndent)).join("\n"); | |
26 | } | |
27 | ||
28 | /** | |
29 | * Define in-memory file system. | |
30 | * @param {Object} options The options. | |
31 | * @param {() => string} [options.cwd] The current working directory. | |
32 | * @param {Object} [options.files] The initial files definition in the in-memory file system. | |
33 | * @returns {import("fs")} The stubbed `ConfigArrayFactory` class. | |
34 | */ | |
35 | function defineInMemoryFs({ | |
36 | cwd = process.cwd, | |
37 | files = {} | |
38 | } = {}) { | |
39 | ||
40 | /** | |
41 | * The in-memory file system for this mock. | |
42 | * @type {import("fs")} | |
43 | */ | |
44 | const fs = createFsFromVolume(new Volume()); | |
45 | ||
46 | fs.mkdirSync(cwd(), { recursive: true }); | |
47 | ||
48 | /* | |
49 | * Write all files to the in-memory file system and compile all JavaScript | |
50 | * files then set to `stubs`. | |
51 | */ | |
52 | (function initFiles(directoryPath, definition) { | |
53 | for (const [filename, content] of Object.entries(definition)) { | |
54 | const filePath = path.resolve(directoryPath, filename); | |
55 | const parentPath = path.dirname(filePath); | |
56 | ||
57 | if (typeof content === "object") { | |
58 | initFiles(filePath, content); | |
59 | } else if (typeof content === "string") { | |
60 | if (!fs.existsSync(parentPath)) { | |
61 | fs.mkdirSync(parentPath, { recursive: true }); | |
62 | } | |
63 | fs.writeFileSync(filePath, content); | |
64 | } else { | |
65 | throw new Error(`Invalid content: ${typeof content}`); | |
66 | } | |
67 | } | |
68 | }(cwd(), files)); | |
69 | ||
70 | return fs; | |
71 | } | |
72 | ||
73 | module.exports = { | |
74 | defineInMemoryFs, | |
75 | unIndent | |
76 | }; |