abraunegg-onedrive/src/config.d

80 lines
1.8 KiB
D
Raw Normal View History

2015-09-14 19:21:06 +02:00
import std.file, std.regex, std.stdio;
static import log;
2015-09-01 20:45:34 +02:00
final class Config
2015-09-01 20:45:34 +02:00
{
public string refreshTokenFilePath;
public string statusTokenFilePath;
public string databaseFilePath;
public string uploadStateFilePath;
private string userConfigFilePath;
// hashmap for the values found in the user config file
2015-09-01 20:45:34 +02:00
private string[string] values;
this(string configDirName)
{
refreshTokenFilePath = configDirName ~ "/refresh_token";
statusTokenFilePath = configDirName ~ "/status_token";
2016-12-25 19:23:33 +01:00
databaseFilePath = configDirName ~ "/items.sqlite3";
uploadStateFilePath = configDirName ~ "/resume_upload";
userConfigFilePath = configDirName ~ "/config";
}
void init()
2015-09-01 20:45:34 +02:00
{
2015-09-24 18:59:17 +02:00
bool found = false;
found |= load("/etc/onedrive.conf");
found |= load("/usr/local/etc/onedrive.conf");
found |= load(userConfigFilePath);
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
}
string getValue(string key)
2015-09-01 20:45:34 +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
}
2016-09-18 11:37:41 +02:00
string getValue(string key, string value)
{
auto p = key in values;
if (p) {
return *p;
} else {
return value;
}
}
private bool load(string filename)
2015-09-01 20:45:34 +02:00
{
scope(failure) return false;
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 {
log.log("Malformed config line: ", line);
2015-09-22 14:48:18 +02:00
}
2015-09-01 20:45:34 +02:00
}
return true;
2015-09-01 20:45:34 +02:00
}
}
unittest
{
auto cfg = new Config("");
cfg.load("onedrive.conf");
assert(cfg.getValue("sync_dir") == "~/OneDrive");
2016-09-18 11:37:41 +02:00
assert(cfg.getValue("empty", "default") == "default");
2015-09-24 18:59:17 +02:00
}