abraunegg-onedrive/src/config.d

49 lines
924 B
D
Raw Normal View History

2015-09-14 19:21:06 +02:00
import std.file, std.regex, std.stdio;
2015-09-01 20:45:34 +02:00
2015-09-14 19:21:06 +02:00
struct Config
2015-09-01 20:45:34 +02:00
{
private string[string] values;
2015-09-22 14:48:18 +02:00
this(string[] filenames...)
2015-09-01 20:45:34 +02:00
{
2015-09-22 14:48:18 +02:00
foreach (filename; filenames) {
load(filename);
}
2015-09-01 20:45:34 +02:00
}
2015-09-22 14:48:18 +02:00
string get(string key)
2015-09-01 20:45:34 +02:00
{
2015-09-14 19:21:06 +02:00
import core.exception;
try {
return values[key];
} catch (RangeError e) {
throw new Exception("Missing config value: " ~ key);
}
2015-09-01 20:45:34 +02:00
}
2015-09-22 14:48:18 +02:00
private void load(string filename)
2015-09-01 20:45:34 +02:00
{
if (exists(filename)) {
2015-09-22 14:48:18 +02:00
auto file = File(filename, "r");
auto r = regex("(?:^\\s*)(\\w+)(?:\\s*=\\s*\")(.*)(?:\"\\s*$)");
foreach (line; file.byLine()) {
auto c = line.matchFirst(r);
if (!c.empty) {
c.popFront(); // skip the whole match
string key = c.front.dup;
c.popFront();
values[key] = c.front.dup;
} else {
writeln("Malformed config line: ", line);
}
}
2015-09-01 20:45:34 +02:00
}
}
}
unittest
{
2015-09-22 14:48:18 +02:00
auto cfg = Config("empty", "onedrive.conf");
assert(cfg.get("sync_dir") == "~/OneDrive");
2015-09-01 20:45:34 +02:00
}