scripts: add functions need_one_of and need_array_of to check_site_lib.lua

need_one_of(varname, array, required) checks weather the value of the specified variable is part of given array.
need_array_of(varname, array, required) is similar to need_one_of() but assume that varname points to an array.
This commit is contained in:
kb-light 2016-08-03 10:50:24 +02:00
parent c84bb17915
commit 21e033213c
1 changed files with 39 additions and 0 deletions

View File

@ -7,6 +7,27 @@ local function loadvar(varname)
end
end
local function array_to_string(array)
local string = ''
for _, v in ipairs(array) do
if #string >= 1 then
string = string .. ', '
end
string = string .. v
end
return '[' .. string .. ']'
end
local function assert_one_of(var, array, msg)
for _, v in ipairs(array) do
if v == var then
return true
end
end
error(msg)
end
local function assert_type(var, t, msg)
assert(type(var) == t, msg)
end
@ -99,7 +120,25 @@ function need_table(varname, subcheck, required)
return var
end
function need_one_of(varname, array, required)
local var = loadvar(varname)
if required == false and var == nil then
return nil
end
assert_one_of(var, array, "site.conf error: expected `" .. varname .. "' to be one of given array: " .. array_to_string(array))
return var
end
function need_string_array(varname, required)
return assert(pcall(need_array, varname, function(e) assert_type(e, 'string') end, required),
"site.conf error: expected `" .. varname .. "' to be a string array")
end
function need_array_of(varname, array, required)
local ok, var = pcall(need_array, varname, function(e) assert_one_of(e, array) end,required)
assert(ok, "site.conf error: expected `" .. varname .. "' to be a subset of given array: " .. array_to_string(array))
return var
end