UNPKG

1.9 kBJavaScriptView Raw
1/*
2 Copyright © 2019 Andrew Powell
3
4 This Source Code Form is subject to the terms of the Mozilla Public
5 License, v. 2.0. If a copy of the MPL was not distributed with this
6 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 The above copyright notice and this permission notice shall be
9 included in all copies or substantial portions of this Source Code Form.
10*/
11const { existsSync } = require('fs');
12
13const chalk = require('chalk');
14const execa = require('execa');
15
16const { info } = console;
17const key = 'webpack-plugin-ramdisk';
18
19const getRoot = (name) => {
20 const { platform } = process;
21
22 return platform === 'darwin' ? `/Volumes/${name}` : `/mnt/${name}`;
23};
24
25const create = (options) => {
26 const { platform } = process;
27 const { blocks, root } = options;
28 const commands = {
29 darwin: `hdiutil attach -nomount ram://${blocks}`,
30 linux: `sudo mkdir -p ${root}`
31 };
32 info(chalk.blue(`⬡ ${key}:`), 'Initializing RAMdisk. You may be prompted for credentials');
33 const { stdout: diskPath } = execa.commandSync(commands[platform]);
34
35 return diskPath.trim();
36};
37
38const mount = (options) => {
39 const { platform } = process;
40 const { bytes, diskPath, name, root } = options;
41 const commands = {
42 darwin: `diskutil erasevolume HFS+ ${name} ${diskPath}`,
43 linux: `sudo mount -t tmpfs -o size=${bytes} tmpfs ${root}`
44 };
45 return execa.commandSync(commands[platform]);
46};
47
48module.exports = {
49 cleanup(diskPath) {
50 const command =
51 process.platform === 'darwin' ? `hdiutil detach ${diskPath}` : `sudo umount ${diskPath}`;
52 return execa.commandSync(command);
53 },
54
55 init(opts) {
56 const root = getRoot(opts.name);
57 const blocks = opts.bytes / opts.blockSize;
58 const options = Object.assign({}, opts, { blocks, root });
59
60 if (!existsSync(root)) {
61 options.diskPath = create(options);
62 mount(options);
63 }
64
65 return root;
66 }
67};