060e074c4b5777bb003fc502dbd463578a33bf6b
[project/luci.git] / libs / uci / luasrc / model / uci.lua
1 --[[
2 LuCI - UCI mpdel
3
4 Description:
5 Generalized UCI model
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 local uci = require("uci")
27 local util = require("luci.util")
28 local setmetatable = setmetatable
29 local rawget = rawget
30 local rawset = rawset
31 local error = error
32 local tostring = tostring
33
34 module("luci.model.uci", function(m) setmetatable(m, {__index = uci}) end)
35
36 local configs_mt = {}
37 local sections_mt = {}
38 local options_mt = {}
39
40 config = {}
41 setmetatable(config, configs_mt)
42
43 -- Level 1 (configs)
44 function configs_mt.__index(self, key)
45 local node = rawget(self, key)
46 if not node then
47 node = {}
48 node[".name"] = key
49 setmetatable(node, sections_mt)
50 rawset(self, key, node)
51 end
52 return node
53 end
54 function configs_mt.__newindex()
55 error("invalid operation")
56 end
57
58
59 -- Level 2 (sections)
60 function sections_mt.__index(self, key)
61 local node = rawget(self, key)
62 if not node then
63 node = {}
64 node[".conf"] = self[".name"]
65 node[".name"] = key
66 node[".type"] = uci.get(self[".name"], key)
67 setmetatable(node, options_mt)
68 rawset(self, key, node)
69 end
70 return node
71 end
72 function sections_mt.__newindex(self, key, value)
73 if not value then
74 if uci.delete(self[".name"], key) then
75 rawset(self, key, nil)
76 else
77 error("unable to delete section")
78 end
79 elseif key == "" then
80 key = uci.add(self[".name"], tostring(value))
81 if key then
82 rawset(self, "", self[key])
83 else
84 error("unable to create section")
85 end
86 else
87 if not uci.set(self[".name"], key, value) then
88 error("unable to create section")
89 end
90 end
91 end
92
93
94 -- Level 3 (options)
95 function options_mt.__index(self, key)
96 return uci.get(self[".conf"], self[".name"], key)
97 end
98 function options_mt.__newindex(self, key, value)
99 if not value then
100 if not uci.delete(self[".conf"], self[".name"], key) then
101 error("unable to delete option")
102 end
103 else
104 if not uci.set(self[".conf"], self[".name"], key, tostring(value)) then
105 error("unable to write option")
106 end
107 end
108 end