check_site_lib.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 need_string(varname, required)
  13. local var = loadvar(varname)
  14. if required == false and var == nil then
  15. return nil
  16. end
  17. assert_type(var, 'string', "site.conf error: expected `" .. varname .. "' to be a string")
  18. return var
  19. end
  20. function need_string_match(varname, pat, required)
  21. local var = need_string(varname, required)
  22. if not var then
  23. return nil
  24. end
  25. assert(var:match(pat), "site.conf error: expected `" .. varname .. "' to match pattern `" .. pat .. "'")
  26. return var
  27. end
  28. function need_number(varname, required)
  29. local var = loadvar(varname)
  30. if required == false and var == nil then
  31. return nil
  32. end
  33. assert_type(var, 'number', "site.conf error: expected `" .. varname .. "' to be a number")
  34. return var
  35. end
  36. function need_boolean(varname, required)
  37. local var = loadvar(varname)
  38. if required == false and var == nil then
  39. return nil
  40. end
  41. assert_type(var, 'boolean', "site.conf error: expected `" .. varname .. "' to be a boolean")
  42. return var
  43. end
  44. function need_array(varname, subcheck, required)
  45. local var = loadvar(varname)
  46. if required == false and var == nil then
  47. return nil
  48. end
  49. assert_type(var, 'table', "site.conf error: expected `" .. varname .. "' to be an array")
  50. for _, e in ipairs(var) do
  51. subcheck(e)
  52. end
  53. return var
  54. end
  55. function need_table(varname, subcheck, required)
  56. local var = loadvar(varname)
  57. if required == false and var == nil then
  58. return nil
  59. end
  60. assert_type(var, 'table', "site.conf error: expected `" .. varname .. "' to be a table")
  61. for k, v in pairs(var) do
  62. subcheck(k, v)
  63. end
  64. return var
  65. end
  66. function need_string_array(varname, required)
  67. return assert(pcall(need_array, varname, function(e) assert_type(e, 'string') end, required),
  68. "site.conf error: expected `" .. varname .. "' to be a string array")
  69. end