-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersistor.lua
79 lines (72 loc) · 2.03 KB
/
persistor.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
local lfs = require 'lfs'
local M = {}
local function purge_tree (path)
local mode = lfs.attributes(path, 'mode')
if mode == 'directory' then
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
purge_tree (path..'/'..file)
end
end
lfs.rmdir(path)
elseif mode == 'file' then
os.remove(path)
end
end
local supported_types = {
['string'] = function(s) return s end,
['number'] = tonumber,
['boolean'] = function (s) return s=='true' end,
}
local filepath_cache = setmetatable({}, {__mode='v'})
local function new_mt(p)
local mt = {
__index = function(_, key)
local filepath = p..'/'..key
local mode = lfs.attributes(filepath, 'mode')
if mode == 'directory' then
local proxy = filepath_cache[filepath] or setmetatable({}, new_mt(filepath))
filepath_cache[filepath] = proxy
return proxy
elseif mode == 'file' then
local f = assert(io.open(filepath, 'r'))
local valuetype = f:read('*l')
local typecast = assert(supported_types[valuetype], 'unsupported type')
local value = typecast( f:read('*a') )
f:close()
return value
end
end,
__newindex = function(table, key, value)
local filepath = p..'/'..key
purge_tree(filepath)
filepath_cache[filepath] = nil
if type(value) == 'table' then
assert(lfs.mkdir(filepath))
--recursively add table content
local subtable = table[key]
for k, v in pairs(value) do
subtable[k] = v
end
elseif value == nil then
os.remove(filepath)
else -- value ~= nil
local f = assert(io.open(filepath, 'w'))
f:write(type(value)..'\n'..tostring(value))
f:close()
end
end
}
return mt
end
M.new = function (root, clear)
root = root or assert(lfs.currentdir())..'/tmp-persistor'
if clear then
purge_tree(root)
end
if not lfs.attributes(root) then
assert(lfs.mkdir(root))
end
return setmetatable({}, new_mt(root))
end
return M