git ssb

1+

cel / wpa-conf-codec



Commit f1015df18e879cbad5fe6cb3f49e783d6063f2c3

Implement decode

cel committed on 2/13/2017, 8:26:37 AM
Parent: 01f23d6f452892e1028b47e668d3d8850c66942b

Files changed

lib/decode.jschanged
test/index.jschanged
lib/decode.jsView
@@ -1,6 +1,85 @@
1-module.exports = function (txt) {
1 +module.exports = function parseConfig(txt) {
22 var lines = txt.split(/\s*[\n\r]+\s*/g)
3 + var state = 'begin'
4 + var preNetworkComments = []
5 + var prop
6 + var network
7 + var conf = {
8 + networks: []
9 + }
310 lines.forEach(function (line) {
4- throw new Error('not implemented')
11 + line = line.trim()
12 + switch (state) {
13 + case 'begin':
14 + if (line[0] === '#') {
15 + preNetworkComments.push(line.substr(1))
16 + } else if (/^network={/.test(line)) {
17 + state = 'network'
18 + network = {}
19 + conf.networks.push(network)
20 + if (preNetworkComments.length > 0) {
21 + network._comment = preNetworkComments.join('\n')
22 + preNetworkComments = []
23 + }
24 + } else if (prop = parseProperty(line)) {
25 + conf[prop.name] = prop.value
26 + if (preNetworkComments.length > 0) {
27 + // should comments before global config items be handled?
28 + preNetworkComments = []
29 + }
30 + }
31 + break
32 + case 'network':
33 + if (line[0] === '#') {
34 + // should comments in network blocks be handled?
35 + } else if (line === '}') {
36 + state = 'begin'
37 + } else if (prop = parseProperty(line)) {
38 + network[prop.name] = prop.value
39 + } else {
40 + throw new Error('unexpected line in network block: ' + line)
41 + }
42 + break
43 + }
544 })
45 + return conf
646 }
47 +
48 +function hasEqual(str) {
49 + return str.indexOf('=') !== -1
50 +}
51 +
52 +function asJSON(str) {
53 + try {
54 + return JSON.stringify(str)
55 + } catch(e) {
56 + }
57 +}
58 +
59 +function parseProperty(line) {
60 + var m = /^([^=]*)=(.*)$/.exec(line)
61 + if (m) return {name: m[1], value: parseValue(m[2])}
62 +}
63 +
64 +function parseValue(value) {
65 + try {
66 + return JSON.parse(value)
67 + } catch(e) {}
68 + if (m = /^"(.*)"$/.exec(value)) {
69 + return m[1]
70 + }
71 + var vals = value.split(' ') // can spaces be escaped here?
72 + if (vals.length > 0 && vals.every(hasEqual)) {
73 + // is this just for ctrl_interface?
74 + var obj = {}
75 + vals.map(parseProperty).forEach(function (prop) {
76 + obj[prop.name] = prop.value
77 + })
78 + return obj
79 + }
80 + if (vals.length === 1) {
81 + return vals[0]
82 + } else {
83 + return vals
84 + }
85 +}
test/index.jsView
@@ -8,9 +8,11 @@
88 var networksObj = require('./networks.json')
99
1010 test('decode', function (t) {
1111 t.deepEquals(wpa.decode(networksTxt), networksObj)
12 + t.end()
1213 })
1314
1415 test('encode', function (t) {
1516 t.deepEquals(wpa.encode(networksObj), networksTxt)
17 + t.end()
1618 })

Built with git-ssb-web