check_site_lib.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. local function loadvar(varname)
  2. local ok, val = pcall(assert(loadstring('return site.' .. varname)))
  3. if ok then
  4. return val
  5. else
  6. return nil
  7. end
  8. end
  9. local function assert_type(var, t, msg)
  10. assert(type(var) == t, msg)
  11. end
  12. function assert_uci_name(var)
  13. -- We don't use character classes like %w here to be independent of the locale
  14. assert(var:match('^[0-9a-zA-Z_]+$'), "site.conf error: `" .. var .. "' is not a valid config section name (only alphanumeric characters and the underscore are allowed)")
  15. end
  16. function need_string(varname, required)
  17. local var = loadvar(varname)
  18. if required == false and var == nil then
  19. return nil
  20. end
  21. assert_type(var, 'string', "site.conf error: expected `" .. varname .. "' to be a string")
  22. return var
  23. end
  24. function need_string_match(varname, pat, required)
  25. local var = need_string(varname, required)
  26. if not var then
  27. return nil
  28. end
  29. assert(var:match(pat), "site.conf error: expected `" .. varname .. "' to match pattern `" .. pat .. "'")
  30. return var
  31. end
  32. function need_number(varname, required)
  33. local var = loadvar(varname)
  34. if required == false and var == nil then
  35. return nil
  36. end
  37. assert_type(var, 'number', "site.conf error: expected `" .. varname .. "' to be a number")
  38. return var
  39. end
  40. function need_boolean(varname, required)
  41. local var = loadvar(varname)
  42. if required == false and var == nil then
  43. return nil
  44. end
  45. assert_type(var, 'boolean', "site.conf error: expected `" .. varname .. "' to be a boolean")
  46. return var
  47. end
  48. function need_array(varname, subcheck, required)
  49. local var = loadvar(varname)
  50. if required == false and var == nil then
  51. return nil
  52. end
  53. assert_type(var, 'table', "site.conf error: expected `" .. varname .. "' to be an array")
  54. for _, e in ipairs(var) do
  55. subcheck(e)
  56. end
  57. return var
  58. end
  59. function need_table(varname, subcheck, required)
  60. local var = loadvar(varname)
  61. if required == false and var == nil then
  62. return nil
  63. end
  64. assert_type(var, 'table', "site.conf error: expected `" .. varname .. "' to be a table")
  65. if subcheck then
  66. for k, v in pairs(var) do
  67. subcheck(k, v)
  68. end
  69. end
  70. return var
  71. end
  72. function need_string_array(varname, required)
  73. return assert(pcall(need_array, varname, function(e) assert_type(e, 'string') end, required),
  74. "site.conf error: expected `" .. varname .. "' to be a string array")
  75. end