Files: 7a38947d54fe9264b5f5439a6d63342d00ccaae5 / lib / decode.js
2134 bytesRaw
1 | var decodeValueFns = { |
2 | group: decodeSet, |
3 | pairwise: decodeSet, |
4 | key_mgmt: decodeSet, |
5 | proto: decodeSet, |
6 | eap: decodeSet, |
7 | ctrl_interface: decodeObj, |
8 | driver_param: decodeObj, |
9 | } |
10 | |
11 | function defaultDecodeValue(value) { |
12 | try { |
13 | return JSON.parse(value) |
14 | } catch(e) {} |
15 | var m = /^"(.*)"$/.exec(value) |
16 | if (m) return m[1] |
17 | return value |
18 | } |
19 | |
20 | function decodeSet(value) { |
21 | return value.split(' ') |
22 | } |
23 | |
24 | function decodeObj(str) { |
25 | var obj = {} |
26 | str.split(' ').map(decodeProperty).forEach(function (prop) { |
27 | obj[prop.name] = prop.value |
28 | }) |
29 | return obj |
30 | } |
31 | |
32 | function decodeProperty(line) { |
33 | var m = /^([^=]*)=(.*)$/.exec(line) |
34 | if (!m) return |
35 | var name = m[1] |
36 | var decodeValue = decodeValueFns[name] || defaultDecodeValue |
37 | return {name: name, value: decodeValue(m[2])} |
38 | } |
39 | |
40 | module.exports = function decodeConfig(txt) { |
41 | var lines = txt.split(/\s*[\n\r]+\s*/g) |
42 | var state = 'begin' |
43 | var preNetworkComments = [] |
44 | var prop |
45 | var network |
46 | var conf = { |
47 | networks: [] |
48 | } |
49 | lines.forEach(function (line) { |
50 | line = line.trim() |
51 | switch (state) { |
52 | case 'begin': |
53 | if (line[0] === '#') { |
54 | preNetworkComments.push(line.substr(1)) |
55 | } else if (/^network={/.test(line)) { |
56 | state = 'network' |
57 | network = {} |
58 | conf.networks.push(network) |
59 | if (preNetworkComments.length > 0) { |
60 | network._comment = preNetworkComments.join('\n') |
61 | preNetworkComments = [] |
62 | } |
63 | } else if (prop = decodeProperty(line)) { |
64 | conf[prop.name] = prop.value |
65 | if (preNetworkComments.length > 0) { |
66 | // should comments before global config items be handled? |
67 | preNetworkComments = [] |
68 | } |
69 | } |
70 | break |
71 | case 'network': |
72 | if (line[0] === '#') { |
73 | // should comments in network blocks be handled? |
74 | } else if (line === '}') { |
75 | state = 'begin' |
76 | } else if (prop = decodeProperty(line)) { |
77 | network[prop.name] = prop.value |
78 | } else { |
79 | throw new Error('unexpected line in network block: ' + line) |
80 | } |
81 | break |
82 | } |
83 | }) |
84 | return conf |
85 | } |
86 |
Built with git-ssb-web