mirror of
https://github.com/abraunegg/onedrive
synced 2024-06-26 17:30:25 +02:00
71 lines
1.3 KiB
D
71 lines
1.3 KiB
D
import std.file, std.regex, std.stdio;
|
|
|
|
struct Config
|
|
{
|
|
private string filename;
|
|
private string[string] values;
|
|
|
|
this(string filename)
|
|
{
|
|
this.filename = filename;
|
|
}
|
|
|
|
string get(string key, string def = null)
|
|
{
|
|
import core.exception;
|
|
try {
|
|
return values[key];
|
|
} catch (RangeError e) {
|
|
if (def) return def;
|
|
throw new Exception("Missing config value: " ~ key);
|
|
}
|
|
}
|
|
|
|
void set(string key, string value)
|
|
{
|
|
values[key] = value;
|
|
}
|
|
|
|
void load()
|
|
{
|
|
values = null;
|
|
auto file = File(filename, "r");
|
|
auto r = regex("(?:^\\s*)(\\w+)(?:\\s*=\\s*\")(.*)(?:\"\\s*$)");
|
|
foreach (line; file.byLine()) {
|
|
auto c = matchFirst(line, 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);
|
|
}
|
|
}
|
|
}
|
|
|
|
void save()
|
|
{
|
|
if (exists(filename)) {
|
|
string bkpFilename = filename ~ "~";
|
|
rename(filename, bkpFilename);
|
|
}
|
|
auto file = File(filename, "w");
|
|
foreach (key, value; values) {
|
|
file.writeln(key, " = \"", value, "\"");
|
|
}
|
|
}
|
|
}
|
|
|
|
unittest
|
|
{
|
|
auto cfg = Config(tempDir() ~ "/test.conf");
|
|
cfg.set("test1", "1");
|
|
cfg.set("test2", "2");
|
|
cfg.set("test1", "3");
|
|
cfg.save();
|
|
cfg.load();
|
|
assert(cfg.get("test1") == "3");
|
|
assert(cfg.get("test2") == "2");
|
|
}
|