This repository has been archived by the owner on Dec 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
file.lua
112 lines (110 loc) · 3.38 KB
/
file.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
local fs=love.filesystem
local FILE={}
function FILE.isSafe(file)
return SYSTEM=='Web' or fs.getRealDirectory(file)~=fs.getSaveDirectory()
end
function FILE.load(name,args)
if not args then args='' end
if fs.getInfo(name) then
local F=fs.newFile(name)
assert(F:open'r','open error')
local s=F:read() F:close()
local mode=
STRING.sArg(args,'-luaon') and 'luaon' or
STRING.sArg(args,'-lua') and 'lua' or
STRING.sArg(args,'-json') and 'json' or
STRING.sArg(args,'-string') and 'string' or
s:sub(1,9):find('return%s*%{') and 'luaon' or
(s:sub(1,1)=='[' and s:sub(-1)==']' or s:sub(1,1)=='{' and s:sub(-1)=='}') and 'json' or
'string'
if mode=='luaon' then
local func,err_mes=loadstring(s)
if func then
setfenv(func,{})
local res=func()
return assert(res,'decode error')
else
error('decode error: '..err_mes)
end
elseif mode=='lua' then
local func,err_mes=loadstring(s)
if func then
local res=func()
return assert(res,'run error')
else
error('compile error: '..err_mes)
end
elseif mode=='json' then
local res=JSON.decode(s)
if res then
return res
end
error('decode error')
elseif mode=='string' then
return s
else
error('unknown mode')
end
elseif not STRING.sArg(args,'-canskip') then
error('no file')
end
end
function FILE.save(data,name,args)
if not args then args='' end
if STRING.sArg(args,'-d') and fs.getInfo(name) then
error('duplicate')
end
if type(data)=='table' then
if STRING.sArg(args,'-luaon') then
if STRING.sArg(args,'-expand') then
data=TABLE.dump(data)
else
data='return'..TABLE.dumpDeflate(data)
end
if not data then
error('encode error')
end
else
data=JSON.encode(data)
if not data then
error('encode error')
end
end
else
data=tostring(data)
end
local F=fs.newFile(name)
assert(F:open('w'),'open error')
F:write(data) F:flush() F:close()
end
function FILE.clear(path)
if not FILE.isSafe(path) and fs.getInfo(path).type=='directory' then
for _,name in next,fs.getDirectoryItems(path) do
name=path..'/'..name
if not FILE.isSafe(name) then
local t=fs.getInfo(name).type
if t=='file' then
fs.remove(name)
end
end
end
end
end
function FILE.clear_s(path)
if path=='' or (not FILE.isSafe(path) and fs.getInfo(path).type=='directory') then
for _,name in next,fs.getDirectoryItems(path) do
name=path..'/'..name
if not FILE.isSafe(name) then
local t=fs.getInfo(name).type
if t=='file' then
fs.remove(name)
elseif t=='directory' then
FILE.clear_s(name)
fs.remove(name)
end
end
end
fs.remove(path)
end
end
return FILE