-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpersistance.js
More file actions
49 lines (49 loc) · 1.78 KB
/
persistance.js
File metadata and controls
49 lines (49 loc) · 1.78 KB
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
import { Str } from "@merrymake/utils";
import { existsSync } from "fs";
import { mkdir, readFile, writeFile } from "fs/promises";
import { homedir } from "os";
const EOL_COMMENT_CHAR = "//";
const configFolder = homedir() + "/.merrymake/";
const configFile = configFolder + "config";
const configLine = {};
const config = {};
const fileContent = [];
const configReady = (async () => {
if (!existsSync(configFolder))
await mkdir(configFolder);
if (existsSync(configFile))
(await readFile(configFile, "utf-8")).split("\n").forEach((line, index) => {
const [assignment, comment] = Str.partitionLeft(line, EOL_COMMENT_CHAR);
const [key, value] = Str.partitionLeft(assignment, "=");
fileContent.push([key, value, comment]);
if (key.length > 0) {
config[key] = value;
configLine[key] = index;
}
});
})();
let configWriteFinished = Promise.resolve();
export function waitForConfigWrite() {
return configWriteFinished;
}
export async function getConfig(key) {
if (config[key] !== undefined)
return config[key];
await configReady;
return config[key];
}
export function setConfig(entries) {
Object.entries(entries).forEach(([k, v]) => (entries[k] = v));
configWriteFinished = configWriteFinished.then(async () => {
await configReady;
Object.entries(entries).forEach(([k, v]) => {
if (configLine[k] === undefined)
fileContent.push([k, v, ""]);
else
fileContent[configLine[k]][1] = v;
});
await writeFile(configFile, fileContent
.map((line) => `${line[0].length > 0 ? line[0] + "=" : ""}${line[1]}${line[2].length > 0 ? "//" + line[2] : ""}`)
.join("\n"));
});
}