1 local format = string.format;
2 local setmetatable, type = setmetatable, type;
4 local char = string.char;
5 local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
7 local io_open = io.open;
8 local os_remove = os.remove;
9 local tostring = tostring;
13 local indent = function(f, i)
25 local log = function (type, msg) return log(type, "datamanager", msg); end
28 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
31 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
35 return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
39 local function basicSerialize (o)
40 if type(o) == "number" or type(o) == "boolean" then
42 else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
43 return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
48 local function simplesave (f, o, ind)
49 if type(o) == "number" then
51 elseif type(o) == "string" then
52 f:write((format("%q", o):gsub("\\\n", "\\n")))
53 elseif type(o) == "table" then
55 for k,v in pairs(o) do
57 f:write("[", basicSerialize(k), "] = ")
58 simplesave(f, v, ind+1)
63 elseif type(o) == "boolean" then
64 f:write(o and "true" or "false");
66 error("cannot serialize a " .. type(o))
70 ------- API -------------
72 function getpath(username, host, datastore)
74 return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
76 return format("data/%s/%s.dat", encode(host), datastore);
78 return format("data/%s.dat", datastore);
82 function load(username, host, datastore)
83 local data, ret = loadfile(getpath(username, host, datastore));
85 log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
89 local success, ret = pcall(data);
91 log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
97 function store(username, host, datastore, data)
101 -- save the datastore
102 local f, msg = io_open(getpath(username, host, datastore), "w+");
104 log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
108 simplesave(f, data, 1);
110 if not next(data) then -- try to delete empty datastore
111 os_remove(getpath(username, host, datastore));
113 -- we write data even when we are deleting because lua doesn't have a
114 -- platform independent way of checking for non-exisitng files