Приведение в более приличный вид с выносом используемых базовых функций в отдельную...
[lua-filemanager.git] / usr / lib / lua / luafm.lua
1 #!/usr/bin/lua
2
3 local uci = require "uci" 
4 local fs = require "nixio.fs"
5 local u_c = uci.cursor()
6 local basepath = u_c.get("filemanager","config","basedir")
7
8 local _M = {}
9
10 local bp = basepath:match("(.*)/")
11 if bp and bp ~= "" then
12   basepath = bp 
13 end
14 _M.basepath = basepath;
15
16 function _M.is_in_dir(file, dir)
17   if file == dir then
18     return true
19   else   
20     return file:sub(1, #dir) == dir
21   end  
22 end
23
24 function _M.path_valid(path)
25   return _M.is_in_dir(path,_M.basepath) and fs.access(path,"r")
26 end
27
28 function _M.dir_path_valid(path)
29   return _M.is_in_dir(path,_M.basepath) and fs.stat(path,"type")=="dir" and fs.access(path,"w")
30 end
31
32 function _M.new_path_valid(path)
33   local dirpath = fs.dirname(path)
34   return _M.is_in_dir(dirpath,_M.basepath) and fs.access(dirpath,"w")
35 end
36
37 function _M.make_path(path)
38   local realpath = fs.realpath(_M.basepath..'/'..path)
39   if _M.path_valid(realpath) then
40     return realpath
41   else
42     return nil
43   end    
44 end
45
46 function _M.make_new_path(path)
47   local realpath = fs.realpath(fs.dirname(_M.basepath..'/'..path))..'/'..fs.basename(path)
48   if _M.new_path_valid(realpath) then
49     return realpath
50   else
51     return nil
52   end    
53 end
54
55 function _M.make_dir_path(path)
56   local realpath = fs.realpath(_M.basepath..'/'..path)
57   if _M.dir_path_valid(realpath) then
58     return realpath
59   else
60     return nil
61   end    
62 end
63
64 function _M.rm(item)
65   local ftype = fs.stat(item,"type")
66   if ftype == "reg" then
67     return fs.remove(item)
68   elseif ftype == "dir" then
69     local dir = fs.dir(item)
70     for file in dir do
71       if not _M.rm(item..'/'..file) then
72         return false
73       end
74     end
75     return fs.rmdir(item)  
76   else
77     return false  
78   end
79 end
80
81 function _M.chmod(item,mode,recursive)
82   local result = fs.chmod(item,mode)
83   if result and recursive then
84     local dir = fs.dir(item)
85     if dir then
86       for file in dir do
87         local ftype = fs.stat(item..'/'..file,"type")
88         if ftype == "dir" then
89           result = _M.chmod(item..'/'..file,mode,recursive)
90         elseif ftype == "reg" then
91           result = _M.chmod(item..'/'..file,string.gsub(mode,"x","-"),false)  
92         end
93         if not result then
94           break
95         end  
96       end
97     end
98   end
99   return result
100 end
101
102 return _M