35b8289af40204b9ca69174f90eb93dc7b6b450e
[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 posix.umask("rwx------")
31
32 -- Glob
33 glob = posix.glob
34
35 -- Checks whether a file exists
36 function isfile(filename)
37 local fp = io.open(filename, "r")
38 if fp then fp:close() end
39 return fp ~= nil
40 end
41
42 -- Returns the content of file
43 function readfile(filename)
44 local fp, err = io.open(filename)
45
46 if fp == nil then
47 return nil, err
48 end
49
50 local data = fp:read("*a")
51 fp:close()
52 return data
53 end
54
55 -- Writes given data to a file
56 function writefile(filename, data)
57 local fp, err = io.open(filename, "w")
58
59 if fp == nil then
60 return nil, err
61 end
62
63 fp:write(data)
64 fp:close()
65
66 return true
67 end
68
69 -- Returns the file modification date/time of "path"
70 function mtime(path)
71 return posix.stat(path, "mtime")
72 end
73
74 -- basename wrapper
75 basename = posix.basename
76
77 -- dirname wrapper
78 dirname = posix.dirname
79
80 -- dir wrapper
81 dir = posix.dir
82
83 -- wrapper for posix.mkdir
84 function mkdir(path, recursive)
85 if recursive then
86 local base = "."
87
88 if path:sub(1,1) == "/" then
89 base = ""
90 path = path:gsub("^/+","")
91 end
92
93 for elem in path:gmatch("([^/]+)/*") do
94 base = base .. "/" .. elem
95
96 local stat = posix.stat( base )
97
98 if not stat then
99 local stat, errmsg, errno = posix.mkdir( base )
100
101 if type(stat) ~= "number" or stat ~= 0 then
102 return stat, errmsg, errno
103 end
104 else
105 if stat.type ~= "directory" then
106 return nil, base .. ": File exists", 17
107 end
108 end
109 end
110
111 return 0
112 else
113 return posix.mkdir( path )
114 end
115 end
116
117 -- Alias for posix.rmdir
118 rmdir = posix.rmdir
119
120 -- Alias for posix.stat
121 stat = posix.stat
122
123 -- Alias for posix.chmod
124 chmod = posix.chmod
125
126 -- Alias for posix.link
127 link = posix.link
128
129 -- Alias for posix.unlink
130 unlink = posix.unlink