2017-09-14 11:20:26 +00:00
|
|
|
/**
|
2018-09-11 22:27:47 +00:00
|
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
2017-09-14 11:20:26 +00:00
|
|
|
*
|
2018-02-17 02:24:55 +00:00
|
|
|
* This source code is licensed under the MIT license found in the
|
|
|
|
* LICENSE file in the root directory of this source tree.
|
2017-09-14 11:20:26 +00:00
|
|
|
*
|
|
|
|
* @format
|
|
|
|
*/
|
|
|
|
|
|
|
|
'use strict';
|
|
|
|
|
2018-09-17 12:43:43 +00:00
|
|
|
const path = require('path');
|
|
|
|
const MemoryFS = require('metro-memory-fs');
|
|
|
|
let fs;
|
2017-09-14 11:20:26 +00:00
|
|
|
|
2018-09-17 12:43:43 +00:00
|
|
|
function setMockFilesystem(object, platform) {
|
|
|
|
reset(platform);
|
|
|
|
const root = platform === 'win32' ? 'c:\\' : '/';
|
2018-04-25 14:03:24 +00:00
|
|
|
mockDir(root, {...object});
|
2018-09-17 12:43:43 +00:00
|
|
|
return root;
|
2017-09-14 11:20:26 +00:00
|
|
|
}
|
|
|
|
|
2018-04-25 14:03:24 +00:00
|
|
|
function mockDir(dirPath, desc) {
|
|
|
|
for (const entName in desc) {
|
|
|
|
const ent = desc[entName];
|
2018-09-17 12:43:43 +00:00
|
|
|
const entPath = path.join(dirPath, entName);
|
2018-04-25 14:03:24 +00:00
|
|
|
if (typeof ent === 'string' || ent instanceof Buffer) {
|
|
|
|
fs.writeFileSync(entPath, ent);
|
|
|
|
continue;
|
2017-09-14 11:20:26 +00:00
|
|
|
}
|
2018-04-25 14:03:24 +00:00
|
|
|
if (typeof ent !== 'object') {
|
|
|
|
throw new Error(require('util').format('invalid entity:', ent));
|
2017-09-14 11:20:26 +00:00
|
|
|
}
|
2018-04-25 14:03:24 +00:00
|
|
|
if (ent.SYMLINK != null) {
|
|
|
|
fs.symlinkSync(ent.SYMLINK, entPath);
|
|
|
|
continue;
|
2017-09-14 11:20:26 +00:00
|
|
|
}
|
2018-04-25 14:03:24 +00:00
|
|
|
fs.mkdirSync(entPath);
|
|
|
|
mockDir(entPath, ent);
|
2017-09-14 11:20:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-17 12:43:43 +00:00
|
|
|
function reset(platform) {
|
|
|
|
if (path.mock == null) {
|
|
|
|
throw new Error(
|
|
|
|
'to use this "fs" module mock, you must also mock the "path" module',
|
|
|
|
);
|
|
|
|
}
|
|
|
|
path.mock.reset(platform);
|
|
|
|
const cwd = () => (platform === 'win32' ? 'c:\\' : '/');
|
|
|
|
fs = new MemoryFS({platform, cwd});
|
|
|
|
Object.assign(mockFs, fs);
|
|
|
|
}
|
|
|
|
|
|
|
|
const mockFs = {};
|
|
|
|
mockFs.__setMockFilesystem = setMockFilesystem;
|
|
|
|
mockFs.mock = {clear: reset};
|
|
|
|
|
|
|
|
reset('posix');
|
2018-04-25 14:03:24 +00:00
|
|
|
|
2018-09-17 12:43:43 +00:00
|
|
|
module.exports = mockFs;
|