* libs/web: Switched from HTTP-Basic-Auth to Session-Auth
[project/luci.git] / libs / core / luasrc / fs.lua
1 --[[
2 LuCI - Filesystem tools
3
4 Description:
5 A module offering often needed filesystem manipulation functions
6
7 FileId:
8 $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
16
17 http://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26
27 module("luci.fs", package.seeall)
28
29 require("posix")
30
31 -- Access
32 access = posix.access
33
34 -- Glob
35 glob = posix.glob
36
37 -- Checks whether a file exists
38 function isfile(filename)
39 local fp = io.open(filename, "r")
40 if fp then fp:close() end
41 return fp ~= nil
42 end
43
44 -- Returns the content of file
45 function readfile(filename)
46 local fp, err = io.open(filename)
47
48 if fp == nil then
49 return nil, err
50 end
51
52 local data = fp:read("*a")
53 fp:close()
54 return data
55 end
56
57 -- Writes given data to a file
58 function writefile(filename, data)
59 local fp, err = io.open(filename, "w")
60
61 if fp == nil then
62 return nil, err
63 end
64
65 fp:write(data)
66 fp:close()
67
68 return true
69 end
70
71 -- Returns the file modification date/time of "path"
72 function mtime(path)
73 return posix.stat(path, "mtime")
74 end
75
76 -- basename wrapper
77 basename = posix.basename
78
79 -- dirname wrapper
80 dirname = posix.dirname
81
82 -- dir wrapper
83 dir = posix.dir
84
85 -- wrapper for posix.mkdir
86 function mkdir(path, recursive)
87 if recursive then
88 local base = "."
89
90 if path:sub(1,1) == "/" then
91 base = ""
92 path = path:gsub("^/+","")
93 end
94
95 for elem in path:gmatch("([^/]+)/*") do
96 base = base .. "/" .. elem
97
98 local stat = posix.stat( base )
99
100 if not stat then
101 local stat, errmsg, errno = posix.mkdir( base )
102
103 if type(stat) ~= "number" or stat ~= 0 then
104 return stat, errmsg, errno
105 end
106 else
107 if stat.type ~= "directory" then
108 return nil, base .. ": File exists", 17
109 end
110 end
111 end
112
113 return 0
114 else
115 return posix.mkdir( path )
116 end
117 end
118
119 -- Alias for posix.rmdir
120 rmdir = posix.rmdir
121
122 -- Alias for posix.stat
123 stat = posix.stat
124
125 -- Alias for posix.chmod
126 chmod = posix.chmod
127
128 -- Alias for posix.link
129 link = posix.link
130
131 -- Alias for posix.unlink
132 unlink = posix.unlink