0003-scripts-add-functions-need_one_of-and-need_array_of-to-check_site_lib.lua.patch 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. From: Karsten Böddeker <freifunk@kb-light.de>
  2. Date: Wed, 3 Aug 2016 10:50:24 +0200
  3. Subject: scripts: add functions need_one_of and need_array_of to check_site_lib.lua
  4. need_one_of(varname, array, required) checks weather the value of the specified variable is part of given array.
  5. need_array_of(varname, array, required) is similar to need_one_of() but assume that varname points to an array.
  6. diff --git a/scripts/check_site_lib.lua b/scripts/check_site_lib.lua
  7. index 766b94a..49a7f50 100644
  8. --- a/scripts/check_site_lib.lua
  9. +++ b/scripts/check_site_lib.lua
  10. @@ -7,6 +7,27 @@ local function loadvar(varname)
  11. end
  12. end
  13. +local function array_to_string(array)
  14. + local string = ''
  15. + for _, v in ipairs(array) do
  16. + if #string >= 1 then
  17. + string = string .. ', '
  18. + end
  19. + string = string .. v
  20. + end
  21. + return '[' .. string .. ']'
  22. +end
  23. +
  24. +local function assert_one_of(var, array, msg)
  25. + for _, v in ipairs(array) do
  26. + if v == var then
  27. + return true
  28. + end
  29. + end
  30. +
  31. + error(msg)
  32. +end
  33. +
  34. local function assert_type(var, t, msg)
  35. assert(type(var) == t, msg)
  36. end
  37. @@ -99,7 +120,25 @@ function need_table(varname, subcheck, required)
  38. return var
  39. end
  40. +function need_one_of(varname, array, required)
  41. + local var = loadvar(varname)
  42. +
  43. + if required == false and var == nil then
  44. + return nil
  45. + end
  46. +
  47. + assert_one_of(var, array, "site.conf error: expected `" .. varname .. "' to be one of given array: " .. array_to_string(array))
  48. +
  49. + return var
  50. +end
  51. +
  52. function need_string_array(varname, required)
  53. return assert(pcall(need_array, varname, function(e) assert_type(e, 'string') end, required),
  54. "site.conf error: expected `" .. varname .. "' to be a string array")
  55. end
  56. +
  57. +function need_array_of(varname, array, required)
  58. + local ok, var = pcall(need_array, varname, function(e) assert_one_of(e, array) end,required)
  59. + assert(ok, "site.conf error: expected `" .. varname .. "' to be a subset of given array: " .. array_to_string(array))
  60. + return var
  61. +end