* luci/libs: uvl: fix handling of boolean options, better error descriptions, impleme...
[project/luci.git] / libs / uvl / luasrc / uvl / datatypes.lua
1 --[[
2
3 UCI Validation Layer - Datatype Tests
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11 http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17 module( "luci.uvl.datatypes", package.seeall )
18
19 require("luci.fs")
20 require("luci.ip")
21 require("luci.util")
22
23
24 function boolean( val )
25 if val == "1" or val == "yes" or val == "on" then
26 return true
27 elseif val == "0" or val == "no" or val == "off" then
28 return true
29 end
30
31 return false
32 end
33
34 function integer( val )
35 local n = tonumber(val)
36 if n ~= nil and math.floor(n) == n then
37 return true
38 end
39
40 return false
41 end
42
43 function float( val )
44 return ( tonumber(val) ~= nil )
45 end
46
47 function ip4addr( val )
48 if val then
49 return luci.ip.IPv4(val) and true or false
50 end
51
52 return false
53 end
54
55 function ip4prefix( val )
56 val = tonumber(val)
57 return ( val and val >= 0 and val <= 32 )
58 end
59
60 function ip6addr( val )
61 if val then
62 return luci.ip.IPv6(val) and true or false
63 end
64
65 return false
66 end
67
68 function ip6prefix( val )
69 val = tonumber(val)
70 return ( val and val >= 0 and val <= 128 )
71 end
72
73 function macaddr( val )
74 if val and val:match(
75 "^[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+:" ..
76 "[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+$"
77 ) then
78 local parts = luci.util.split( val, ":" )
79
80 for i = 1,6 do
81 parts[i] = tonumber( parts[i], 16 )
82 if parts[i] < 0 or parts[i] > 255 then
83 return false
84 end
85 end
86
87 return true
88 end
89
90 return false
91 end
92
93 function hostname( val )
94 if val and val:match("[a-zA-Z0-9_][a-zA-Z0-9_%-%.]*") then
95 return true -- XXX: ToDo: need better solution
96 end
97
98 return false
99 end
100
101 function string( val )
102 return true -- Everything qualifies as valid string
103 end
104
105 function directory( val, seen )
106 local s = luci.fs.stat( val )
107 seen = seen or { }
108
109 if s and not seen[s.ino] then
110 seen[s.ino] = true
111 if s.type == "directory" then
112 return true
113 elseif s.type == "link" then
114 return directory( luci.fs.readlink(val), seen )
115 end
116 end
117
118 return false
119 end
120
121 function file( val, seen )
122 local s = luci.fs.stat( val )
123 seen = seen or { }
124
125 if s and not seen[s.ino] then
126 seen[s.ino] = true
127 if s.type == "regular" then
128 return true
129 elseif s.type == "link" then
130 return file( luci.fs.readlink(val), seen )
131 end
132 end
133
134 return false
135 end