-
Notifications
You must be signed in to change notification settings - Fork 1
/
work-mode.js
executable file
·85 lines (72 loc) · 2.21 KB
/
work-mode.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
#!/usr/bin/node
import crypto from "crypto";
import util from 'util';
import child_process from "child_process"
import path from "path"
import os from "os";
import fs from "fs"
const exec = util.promisify(child_process.exec);
async function dd(of, size) {
await exec(`dd if=/dev/zero of=${of} bs=1M count=${size}`);
}
async function mkfs(shaname) {
await exec(`mkfs ext3 -F ${shaname}`)
}
async function mount(dirName, shaName) {
await exec(`sudo mount ${shaName} ${dirName}`)
}
async function chown(dirName) {
await exec(`sudo chown ${os.userInfo().username} ${dirName}`)
}
async function umount(dirName) {
await exec(`sudo umount ${dirName}`)
}
async function mkdir(dirName) {
await exec(`mkdir ${dirName}`)
}
const configPaths = [`${os.homedir}/.work-mode.json`, `${os.homedir()}/.config/work-mode.json`];
const foundConfigPath = configPaths.find(path => fs.existsSync(path))
if(!foundConfigPath) {
console.error(`config not found in ${JSON.stringify(configPaths)}`)
}
const config = JSON.parse(fs.readFileSync(foundConfigPath));
function dirToSha(dirname) {
const shasum = crypto.createHash("sha256").update(dirname).digest("hex");
return shasum.slice(0, 8);
}
const workModeImgDirName = (config.workModeImgDirName || "~/.work-mode-imgs").replace("~", os.homedir);
async function workModeOn() {
Object.entries(config.directories).forEach(async ([dirname, config]) => {
const workModeDirExists = fs.existsSync(workModeImgDirName);
if(!workModeDirExists) {
mkdir(workModeImgDirName);
}
const shaName = dirToSha(dirname);
const fullImgPath = path.format({dir: workModeImgDirName, name: shaName})
const imgExists = fs.existsSync(fullImgPath);
if(!imgExists) {
await dd(fullImgPath, config.size);
await mkfs(fullImgPath);
}
await mount(dirname, fullImgPath);
await chown(dirname);
})
}
async function workModeOff() {
Object.entries(config.directories).forEach(async ([dirname]) => {
await umount(dirname);
})
}
const args = process.argv.slice(2)
if(args.length > 0){
switch(args[0]) {
case "on":
await workModeOn();
break;
case "off":
await workModeOff();
break;
default:
console.error("usage: work-mode <on/off>")
}
}