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