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