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-24 18:59:17 +02:00
|
|
|
bool found = false;
|
2015-09-22 14:48:18 +02:00
|
|
|
foreach (filename; filenames) {
|
2015-09-24 18:59:17 +02:00
|
|
|
if (exists(filename)) {
|
|
|
|
found = true;
|
|
|
|
load(filename);
|
|
|
|
}
|
2015-09-22 14:48:18 +02:00
|
|
|
}
|
2015-09-24 18:59:17 +02:00
|
|
|
if (!found) throw new Exception("No config file found");
|
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-24 19:12:19 +02:00
|
|
|
auto p = key in values;
|
|
|
|
if (p) {
|
|
|
|
return *p;
|
|
|
|
} else {
|
2015-09-14 19:21:06 +02:00
|
|
|
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
|
|
|
{
|
2015-09-24 18:59:17 +02:00
|
|
|
auto file = File(filename, "r");
|
2015-09-25 21:39:18 +02:00
|
|
|
auto r = regex(`^\s*(\w+)\s*=\s*"(.*)"\s*$`);
|
2015-09-24 18:59:17 +02:00
|
|
|
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-22 14:48:18 +02:00
|
|
|
}
|
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
|
|
|
}
|
2015-09-24 18:59:17 +02:00
|
|
|
|
|
|
|
unittest
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
auto cfg = Config("empty");
|
|
|
|
assert(0);
|
|
|
|
} catch (Exception e) {
|
|
|
|
}
|
|
|
|
}
|