Added module for system abstraction
[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
35 if fp == nil then
36 error("Unable to open file for reading: " .. filename)
37 end
38
39 local data = fp:read("*a")
40 fp:close()
41 return data
42 end
43
44 -- Returns the content of file as array of lines
45 function readfilel(filename)
46 local fp = io.open(filename)
47 local line = ""
48 local data = {}
49
50 if fp == nil then
51 error("Unable to open file for reading: " .. filename)
52 end
53
54 while true do
55 line = fp:read()
56 if (line == nil) then break end
57 table.insert(data, line)
58 end
59
60 fp:close()
61 return data
62 end
63
64 -- Writes given data to a file
65 function writefile(filename, data)
66 local fp = io.open(filename, "w")
67 if fp == nil then
68 error("Unable to open file for writing: " .. filename)
69 end
70 fp:write(data)
71 fp:close()
72 end
73
74 -- Returns the file modification date/time of "path"
75 function mtime(path)
76 return lfs.attributes(path, "modification")
77 end
78
79 -- Simplified dirname function
80 function dirname(file)
81 return string.gsub(file, "[^/]+$", "")
82 end
83
84 -- Diriterator - alias for lfs.dir - filter . and ..
85 function dir(path)
86 local e = {}
87 for entry in lfs.dir(path) do
88 if not(entry == "." or entry == "..") then
89 table.insert(e, entry)
90 end
91 end
92 return e
93 end