|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 Components.utils.import("resource://gre/modules/Services.jsm"); |
|
6 |
|
7 this.EXPORTED_SYMBOLS = [ |
|
8 "parseKeyValuePairs", |
|
9 "parseKeyValuePairsFromFile" |
|
10 ]; |
|
11 |
|
12 const Cc = Components.classes; |
|
13 const Ci = Components.interfaces; |
|
14 |
|
15 this.parseKeyValuePairs = function parseKeyValuePairs(text) { |
|
16 let lines = text.split('\n'); |
|
17 let data = {}; |
|
18 for (let i = 0; i < lines.length; i++) { |
|
19 if (lines[i] == '') |
|
20 continue; |
|
21 |
|
22 // can't just .split() because the value might contain = characters |
|
23 let eq = lines[i].indexOf('='); |
|
24 if (eq != -1) { |
|
25 let [key, value] = [lines[i].substring(0, eq), |
|
26 lines[i].substring(eq + 1)]; |
|
27 if (key && value) |
|
28 data[key] = value.replace(/\\n/g, "\n").replace(/\\\\/g, "\\"); |
|
29 } |
|
30 } |
|
31 return data; |
|
32 } |
|
33 |
|
34 this.parseKeyValuePairsFromFile = function parseKeyValuePairsFromFile(file) { |
|
35 let fstream = Cc["@mozilla.org/network/file-input-stream;1"]. |
|
36 createInstance(Ci.nsIFileInputStream); |
|
37 fstream.init(file, -1, 0, 0); |
|
38 let is = Cc["@mozilla.org/intl/converter-input-stream;1"]. |
|
39 createInstance(Ci.nsIConverterInputStream); |
|
40 is.init(fstream, "UTF-8", 1024, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); |
|
41 let str = {}; |
|
42 let contents = ''; |
|
43 while (is.readString(4096, str) != 0) { |
|
44 contents += str.value; |
|
45 } |
|
46 is.close(); |
|
47 fstream.close(); |
|
48 return parseKeyValuePairs(contents); |
|
49 } |