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. 10
      test/fixtures/fixture.ini
  3. 25
      test/simple/test-ini.js

17
lib/ini.js

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

10
test/fixtures/fixture.ini

@ -1,10 +1,18 @@
; a comment
root=something 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] [section]
one=two one=two
Foo=Bar Foo=Bar
this=Your Mother! this=Your Mother!
blank= blank=
[Section Two] [Section Two]
something else=blah something else=blah

25
test/simple/test-ini.js

@ -14,7 +14,30 @@ fs.readFile(p,function(err, data) {
var iniContents = parse(data); var iniContents = parse(data);
assert.equal(typeof iniContents, 'object'); 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['-']['root'],'something');
assert.equal(iniContents['section']['blank'],''); assert.equal(iniContents['section']['blank'],'');

Loading…
Cancel
Save