5a1cc6b351f2f36974c46eb4bbf39c67ef75a4eb
[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("lfs")
30
31 -- Returns the content of file
32 function readfile(filename)
33         local fp = io.open(filename)
34         if fp == nil then
35                 error("Unable to open file for reading: " .. filename)
36         end
37         local data = fp:read("*a")
38         fp:close()
39         return data     
40 end
41
42 -- Writes given data to a file
43 function writefile(filename, data)
44         local fp = io.open(filename, "w")
45         if fp == nil then
46                 error("Unable to open file for writing: " .. filename)
47         end
48         fp:write(data)
49         fp:close()
50 end
51
52 -- Returns the file modification date/time of "path"
53 function mtime(path)
54         return lfs.attributes(path, "modification")
55 end
56
57 -- Simplified dirname function
58 function dirname(file)
59         return string.gsub(file, "[^/]+$", "")
60 end
61
62 -- Diriterator - alias for lfs.dir - filter . and ..
63 function dir(path)
64         local e = {}
65         for entry in lfs.dir(path) do
66                 if not(entry == "." or entry == "..") then
67                         table.insert(e, entry)
68                 end
69         end
70         return e
71 end