6e8859a0de11743b680a0baea1e11109e6eb0b14
[project/luci.git] / src / ffluci / fs.lua
1 --[[
2 FFLuCI - 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("ffluci.fs", package.seeall)
28
29 require("posix")
30
31 -- Checks whether a file exists
32 function isfile(filename)
33         local fp = io.open(path, "r")
34         if file then file:close() end
35         return file ~= nil
36 end     
37
38 -- Returns the content of file
39 function readfile(filename)
40         local fp, err = io.open(filename)
41         
42         if fp == nil then
43                 return nil, err
44         end
45         
46         local data = fp:read("*a")
47         fp:close()
48         return data     
49 end
50
51 -- Returns the content of file as array of lines
52 function readfilel(filename)
53         local fp, err = io.open(filename)
54         local line = ""
55         local data = {}
56                 
57         if fp == nil then
58                 return nil, err
59         end
60         
61         while true do
62                 line = fp:read()
63                 if (line == nil) then break end
64                 table.insert(data, line)
65         end     
66         
67         fp:close()
68         return data     
69 end
70
71 -- Writes given data to a file
72 function writefile(filename, data)
73         local fp, err = io.open(filename, "w")
74         
75         if fp == nil then
76                 return nil, err
77         end
78         
79         fp:write(data)
80         fp:close()
81         
82         return true
83 end
84
85 -- Returns the file modification date/time of "path"
86 function mtime(path)
87         return posix.stat(path, "mtime")
88 end
89
90 -- basename wrapper
91 basename = posix.basename
92
93 -- dirname wrapper
94 dirname = posix.dirname
95
96 -- dir wrapper
97 function dir(path)
98         local dir = {}
99         for node in posix.files(path) do
100                 table.insert(dir, 1, node)
101         end 
102         return dir
103 end
104
105 -- Alias for lfs.mkdir
106 mkdir = posix.mkdir