forked from TehShrike/k
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.js
62 lines (55 loc) · 1.23 KB
/
state.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
var path = require('path')
var collapseArgs = require('./collapse_arguments.js')
var os = require('os')
const { readFile, writeFile } = require('fs/promises')
const state_path = path.join(os.homedir(), '.k')
const load = async () => {
try {
const contents = await readFile(state_path, { encoding: 'utf8'})
return JSON.parse(contents)
} catch (err) {
if (err.code === 'ENOENT') {
return {}
}
throw err
}
}
const save = async config => writeFile(state_path, JSON.stringify(config, null, '\t'))
const update = async (key, value) => {
const current = await load()
await save({
...current,
[key]: value
})
}
module.exports = {
getterFactory(name) {
return async cb => {
const contents = await load()
const value = contents[name]
if (cb) {
cb(null, value)
} else {
console.log(value)
}
}
},
setterFactory(name) {
return async(...args) => {
const value = collapseArgs(args)
await update(name, value)
console.log(name + " is now " + value)
}
},
set: update,
async fetchAll(names, cb) {
const current = await load()
const values = names.map(name => current[name])
cb(...values)
},
async remove(name) {
const current = await load()
delete current[name]
await save(current)
}
}