Files: 5de6dc909e2df98bd080c4899ef2b265a415ab3d / lib / encode.js
1675 bytesRaw
1 | module.exports = function encodeConfig(conf) { |
2 | if (!conf) return '' |
3 | switch (typeof conf) { |
4 | case 'object': |
5 | var lines = [] |
6 | for (var k in conf) { |
7 | var value = conf[k] |
8 | if (k === 'networks' && Array.isArray(value)) { |
9 | value.forEach(function (network) { |
10 | lines.push('', encodeNetwork(network)) |
11 | }) |
12 | } else { |
13 | lines.push(encodeProperty(k, value)) |
14 | } |
15 | } |
16 | return lines.join('\n') |
17 | case 'string': |
18 | // fallthrough |
19 | case 'number': |
20 | return JSON.stringify(conf) |
21 | case 'boolean': |
22 | return conf ? '1' : '0' |
23 | default: |
24 | throw new Error("weird value: " + conf) |
25 | } |
26 | } |
27 | |
28 | function encodeNetwork(network) { |
29 | if (!network) return |
30 | var lines = [] |
31 | if (network._comment) { |
32 | lines.push('#' + network._comment) |
33 | var a = {} |
34 | for (var k in network) { |
35 | if (k !== '_comment') |
36 | a[k] = network[k] |
37 | } |
38 | network = a |
39 | } |
40 | lines.push('network={') |
41 | for (var k in network) { |
42 | lines.push('\t' + encodeProperty(k, network[k])) |
43 | } |
44 | lines.push('}') |
45 | return lines.join('\n') |
46 | } |
47 | |
48 | function encodeProperty(key, value) { |
49 | return key + '=' + encodeValue(value) |
50 | } |
51 | |
52 | function encodeValue(value) { |
53 | if (!value) return '' |
54 | switch (typeof value) { |
55 | case 'object': |
56 | if (Array.isArray(value)) { |
57 | return value.join(' ') |
58 | } |
59 | var items = [] |
60 | for (var k in value) { |
61 | items.push(encodeProperty(k, value[k])) |
62 | } |
63 | return items.join(' ') |
64 | case 'string': |
65 | case 'number': |
66 | return JSON.stringify(value) |
67 | case 'boolean': |
68 | return value ? '1' : '0' |
69 | default: |
70 | throw new Error("weird value: " + value) |
71 | } |
72 | } |
73 |
Built with git-ssb-web