1 module pkm.config; 2 3 import std.conv: to; 4 import std.file: exists; 5 import std.stdio: writeln; 6 import std.array: split; 7 8 import dyaml; 9 10 Config getConfig(string[] paths) { 11 foreach (path; paths) { 12 if (path.exists) { 13 return __getConfig(path); 14 } 15 } 16 return Config(); 17 } 18 19 Config __getConfig(string configPath) { 20 Node root; 21 try { 22 root = Loader.fromFile(configPath).load(); 23 } catch (YAMLException e) { 24 writeln("Error: Invalid config. Using default configuration."); 25 return Config(); 26 } 27 28 Config conf; 29 30 const NodeType mapping = NodeType.mapping; 31 32 if (root.type != mapping) return conf; 33 34 root.getKey!string(&conf.yaypath, "yaypath"); 35 root.getKey!bool(&conf.yaysearch, "yaysearch"); 36 root.getKey!bool(&conf.color, "color"); 37 root.getKey!bool(&conf.auronly, "auronly"); 38 39 if (root.hasKeyType!mapping("custom")) { 40 auto custom = root["custom"].mappingKeys; 41 foreach (key; custom) { 42 if (key.type == NodeType..string) { 43 string keyname = key.as!string; 44 conf.custom ~= keyname; 45 conf.args ~= root["custom"][keyname].as!string.split(' '); 46 } 47 } 48 // writeln(conf.custom); 49 // writeln(conf.args); 50 } 51 52 return conf; 53 } 54 55 string configGetGlobal(string configPath, string field) { 56 Node root = Loader.fromFile(configPath).load(); 57 58 if (root.type != NodeType.mapping) return ""; 59 if (!root.hasKeyAs!string(field)) return ""; 60 61 return root[field].as!string; 62 } 63 64 private bool hasKeyType(NodeType T)(Node node, string key) { 65 if (node.containsKey(key)) { 66 if (node[key].type == T) { 67 return true; 68 } 69 } 70 return false; 71 } 72 73 private bool hasKeyAs(T)(Node node, string key) { 74 if (node.containsKey(key)) { 75 if (node[key].convertsTo!T) { 76 return true; 77 } 78 } 79 return false; 80 } 81 82 private void getKey(T)(Node node, T* variable, string field) { 83 if (node.hasKeyAs!T(field)) { 84 *variable = node[field].as!T; 85 } 86 } 87 88 89 struct Config { 90 string yaypath = ""; 91 bool yaysearch = false; 92 bool color = true; 93 bool auronly = false; 94 string[] custom = []; 95 string[][] args = []; 96 }