2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
12 local setmetatable, loadfile, pcall, rawget, rawset, io =
13 setmetatable, loadfile, pcall, rawget, rawset, io;
15 module "configmanager"
19 local config = { ["*"] = { core = {} } };
21 local global_config = config["*"];
23 -- When host not found, use global
24 setmetatable(config, { __index = function () return global_config; end});
25 local host_mt = { __index = global_config };
27 -- When key not found in section, check key in global's section
28 function section_mt(section_name)
29 return { __index = function (t, k)
30 local section = rawget(global_config, section_name);
31 if not section then return nil; end
40 function get(host, section, key)
41 local sec = config[host][section];
48 function set(host, section, key, value)
49 if host and section and key then
50 local hostconfig = rawget(config, host);
51 if not hostconfig then
52 hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
54 if not rawget(hostconfig, section) then
55 hostconfig[section] = setmetatable({}, section_mt(section));
57 hostconfig[section][key] = value;
63 function load(filename, format)
64 format = format or filename:match("%w+$");
66 if parsers[format] and parsers[format].load then
67 local f, err = io.open(filename);
69 local ok, err = parsers[format].load(f:read("*a"));
77 return nil, "no parser specified";
79 return nil, "no parser for "..(format);
83 function save(filename, format)
86 function addparser(format, parser)
87 if format and parser then
88 parsers[format] = parser;
92 -- Built-in Lua parser
94 local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
95 local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
97 function parsers.lua.load(data)
99 -- The ' = true' are needed so as not to set off __newindex when we assign the functions below
100 env = setmetatable({ Host = true; host = true; Component = true, component = true }, { __index = function (t, k)
101 return rawget(_G, k) or
102 function (settings_table)
103 config[__currenthost or "*"][k] = settings_table;
106 __newindex = function (t, k, v)
107 set(env.__currenthost or "*", "core", k, v);
110 function env.Host(name)
111 rawset(env, "__currenthost", name);
112 -- Needs at least one setting to logically exist :)
113 set(name or "*", "core", "defined", true);
117 function env.Component(name)
118 return function (module)
119 set(name, "core", "component_module", module);
120 -- Don't load the global modules by default
121 set(name, "core", "modules_enable", false);
122 rawset(env, "__currenthost", name);
125 env.component = env.Component;
127 local chunk, err = loadstring(data);
135 local ok, err = pcall(chunk);