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.
This commit is contained in:
isaacs 2010-03-10 00:17:15 -08:00 коммит произвёл Ryan Dahl
Родитель 70b2a44579
Коммит 976983960d
3 изменённых файлов: 43 добавлений и 9 удалений

Просмотреть файл

@ -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;
}
}

10
test/fixtures/fixture.ini поставляемый
Просмотреть файл

@ -1,10 +1,18 @@
; 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
this=Your Mother!
blank=
blank=
[Section Two]
something else=blah

Просмотреть файл

@ -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'],'');