git ssb

16+

Dominic / patchbay



Tree: 2a8fa0681f7428cea97270806034311e55f4747b

Files: 2a8fa0681f7428cea97270806034311e55f4747b / config.js

2004 bytesRaw
1const nest = require('depnest')
2const fs = require('fs')
3const { join } = require('path')
4const { get, cloneDeep, isEqual } = require('lodash')
5
6// This is needed to over-ride config.sync.load in patchcore.
7// By baking a fresh module with the config inside it,
8// we avoid a race condition around trying to set / get the config
9
10function configModule (config) {
11 var _config = {
12 complete: config,
13 custom: readCustomConfig(config)
14 }
15
16 function Getter (conf) {
17 return function (path, fallback) {
18 if (!path) return conf
19 return get(conf, path, fallback)
20 }
21 }
22
23 function setCustomConfig (path, arg) {
24 if (!Array.isArray(path) && typeof path !== 'string') {
25 const next = path
26 return writeCustomConfig(next)
27 }
28
29 const next = cloneDeep(_config.custom)
30 next.set(path, arg)
31 writeCustomConfig(next)
32 }
33
34 return {
35 configModule: {
36 gives: nest({
37 'config.sync.load': true,
38 'config.sync.get': true,
39 'config.sync.getCustom': true,
40 'config.sync.setCustom': true
41 }),
42 create: api => nest({
43 'config.sync.load': () => _config.complete,
44 'config.sync.get': Getter(_config.complete),
45 'config.sync.getCustom': Getter(_config.custom),
46 'config.sync.setCustom': setCustomConfig
47 })
48 }
49 }
50
51 function readCustomConfig (config) {
52 const str = fs.readFileSync(
53 join(config.path, 'config'),
54 'utf8'
55 )
56 return JSON.parse(str)
57 }
58
59 function writeCustomConfig (next) {
60 if (typeof next !== 'object') throw new Error('config must be an object!')
61 if (isEqual(_config.custom, next)) return
62 if (get(_config.custom, 'caps.sign') !== get(next, 'caps.sign')) throw new Error('do not change the caps.sign!')
63
64 fs.writeFile(
65 join(_config.complete.path, 'config'),
66 JSON.stringify(next, null, 2),
67 (err) => {
68 if (err) return console.error(err)
69
70 _config.custom = next
71 }
72 )
73 }
74}
75
76module.exports = configModule
77

Built with git-ssb-web