Browse Source

More ini parser features.

Update the ini parser to support some more whitespace cases, turn lines
without an equal sign into a "flag" that's just true if set, and support
comments.
v0.7.4-release
isaacs 15 years ago
committed by Ryan Dahl
parent
commit
976983960d
  1. 17
      lib/ini.js
  2. 8
      test/fixtures/fixture.ini
  3. 25
      test/simple/test-ini.js

17
lib/ini.js

@ -1,22 +1,25 @@
exports.parse = function(d) {
var trim = function(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }
var ini = {'-':{}};
var section = '-';
var lines = d.split('\n');
for (var i=0; i<lines.length; i++) {
var line = lines[i].trim(),
rem = line.indexOf(";");
var re = /(.*)=(.*)|\[([a-z:\.0-9_\s]+)\]/i;
if (rem !== -1) line = line.substr(0, rem);
var match = lines[i].match(re);
var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
var match = line.match(re);
if (match != null) {
if (match[3] != undefined) {
section = match[3];
if (match[1] != undefined) {
section = match[1].trim();
ini[section] = {};
} else {
var key = trim(match[1]);
var value = trim(match[2]);
var key = match[2].trim(),
value = (match[3]) ? (match[4] || "").trim() : true;
ini[section][key] = value;
}
}

8
test/fixtures/fixture.ini

@ -1,5 +1,13 @@
; a comment
root=something
url = http://example.com/?foo=bar
[ the section with whitespace ]
this has whitespace = yep ; and a comment; and then another
just a flag, no value.
[section]
one=two
Foo=Bar

25
test/simple/test-ini.js

@ -14,7 +14,30 @@ fs.readFile(p,function(err, data) {
var iniContents = parse(data);
assert.equal(typeof iniContents, 'object');
assert.deepEqual(iniContents,{"-":{"root":"something"},"section":{"one":"two","Foo":"Bar","this":"Your Mother!","blank":""},"Section Two":{"something else":"blah","remove":"whitespace"}})
var expect =
{ "-" :
{ "root" : "something"
, "url" : "http://example.com/?foo=bar"
}
, "the section with whitespace" :
{ "this has whitespace" : "yep"
, "just a flag, no value." : true
}
, "section" :
{ "one" : "two"
, "Foo" : "Bar"
, "this" : "Your Mother!"
, "blank" : ""
}
, "Section Two" :
{ "something else" : "blah"
, "remove" : "whitespace"
}
};
assert.deepEqual(iniContents, expect,
"actual: \n"+inspect(iniContents) +"\n≠\nexpected:\n"+inspect(expect))
assert.equal(iniContents['-']['root'],'something');
assert.equal(iniContents['section']['blank'],'');

Loading…
Cancel
Save