]> git.proxmox.com Git - pve-eslint.git/blame - eslint/tests/_utils/in-memory-fs.js
import 8.3.0 source
[pve-eslint.git] / eslint / tests / _utils / in-memory-fs.js
CommitLineData
eb39fafa 1/**
609c276f 2 * @fileoverview in-memory file system.
eb39fafa
DC
3 * @author Toru Nagashima <https://github.com/mysticatea>
4 */
5"use strict";
6
609c276f
TL
7//-----------------------------------------------------------------------------
8// Requirements
9//-----------------------------------------------------------------------------
10
eb39fafa 11const path = require("path");
56c4a2cb 12const { Volume, createFsFromVolume } = require("memfs");
eb39fafa 13
609c276f
TL
14//-----------------------------------------------------------------------------
15// Helpers
16//-----------------------------------------------------------------------------
eb39fafa 17
56c4a2cb
DC
18/**
19 * Define in-memory file system.
20 * @param {Object} options The options.
21 * @param {() => string} [options.cwd] The current working directory.
22 * @param {Object} [options.files] The initial files definition in the in-memory file system.
23 * @returns {import("fs")} The stubbed `ConfigArrayFactory` class.
24 */
25function defineInMemoryFs({
26 cwd = process.cwd,
27 files = {}
28} = {}) {
29
30 /**
31 * The in-memory file system for this mock.
32 * @type {import("fs")}
33 */
34 const fs = createFsFromVolume(new Volume());
35
36 fs.mkdirSync(cwd(), { recursive: true });
37
38 /*
39 * Write all files to the in-memory file system and compile all JavaScript
40 * files then set to `stubs`.
41 */
42 (function initFiles(directoryPath, definition) {
43 for (const [filename, content] of Object.entries(definition)) {
44 const filePath = path.resolve(directoryPath, filename);
45 const parentPath = path.dirname(filePath);
46
47 if (typeof content === "object") {
48 initFiles(filePath, content);
49 } else if (typeof content === "string") {
50 if (!fs.existsSync(parentPath)) {
51 fs.mkdirSync(parentPath, { recursive: true });
52 }
53 fs.writeFileSync(filePath, content);
54 } else {
55 throw new Error(`Invalid content: ${typeof content}`);
56 }
57 }
58 }(cwd(), files));
59
60 return fs;
61}
62
609c276f
TL
63//-----------------------------------------------------------------------------
64// Exports
65//-----------------------------------------------------------------------------
56c4a2cb 66
eb39fafa 67module.exports = {
609c276f 68 defineInMemoryFs
eb39fafa 69};