2010-03-22 23:25:12 +01:00
|
|
|
// TODO:
|
|
|
|
// 1. Handle quoted strings, including line breaks, so that this:
|
|
|
|
// foo = "bar
|
|
|
|
// baz"
|
|
|
|
// parses to {foo:"bar\n baz"}
|
|
|
|
// 2. Escape with \, so that this:
|
|
|
|
// foo = bar\
|
|
|
|
// \"baz
|
|
|
|
// parses to {foo:"bar\n \"baz"}
|
|
|
|
|
2010-03-06 01:12:31 +01:00
|
|
|
exports.parse = function(d) {
|
|
|
|
var ini = {'-':{}};
|
|
|
|
|
|
|
|
var section = '-';
|
|
|
|
|
|
|
|
var lines = d.split('\n');
|
|
|
|
for (var i=0; i<lines.length; i++) {
|
2010-03-10 09:17:15 +01:00
|
|
|
var line = lines[i].trim(),
|
|
|
|
rem = line.indexOf(";");
|
2010-03-06 01:12:31 +01:00
|
|
|
|
2010-03-10 09:17:15 +01:00
|
|
|
if (rem !== -1) line = line.substr(0, rem);
|
2010-03-06 01:12:31 +01:00
|
|
|
|
2010-03-10 09:17:15 +01:00
|
|
|
var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
|
|
|
|
|
|
|
|
var match = line.match(re);
|
2010-03-06 01:12:31 +01:00
|
|
|
if (match != null) {
|
2010-03-10 09:17:15 +01:00
|
|
|
if (match[1] != undefined) {
|
|
|
|
section = match[1].trim();
|
2010-03-06 01:12:31 +01:00
|
|
|
ini[section] = {};
|
|
|
|
} else {
|
2010-03-10 09:17:15 +01:00
|
|
|
var key = match[2].trim(),
|
|
|
|
value = (match[3]) ? (match[4] || "").trim() : true;
|
2010-03-06 01:12:31 +01:00
|
|
|
ini[section][key] = value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ini;
|
2010-03-22 23:25:12 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
function safe (val) {
|
|
|
|
return (val+"").replace(/[\n\r]+/g, " ");
|
2010-03-06 01:12:31 +01:00
|
|
|
}
|
2010-03-22 23:25:12 +01:00
|
|
|
|
|
|
|
exports.stringify = function (obj) {
|
|
|
|
// if the obj has a "-" section, then do that first.
|
|
|
|
var ini = "";
|
|
|
|
if ("-" in obj) {
|
|
|
|
for (var key in obj["-"]) {
|
|
|
|
ini += safe(key)+" = "+safe(obj["-"][key])+"\n";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (var section in obj) if (section !== "-") {
|
|
|
|
ini += "[" + safe(section) + "]\n";
|
|
|
|
for (var key in obj[section]) {
|
|
|
|
|
|
|
|
ini += safe(key) + ((obj[section][key] === true)
|
|
|
|
? "\n"
|
|
|
|
: " = "+safe(obj[section][key])+"\n");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ini;
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.encode = exports.stringify;
|
|
|
|
exports.decode = exports.parse;
|