check_site_lib.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. if subcheck then
  62. for k, v in pairs(var) do
  63. subcheck(k, v)
  64. end
  65. end
  66. return var
  67. end
  68. function need_string_array(varname, required)
  69. return assert(pcall(need_array, varname, function(e) assert_type(e, 'string') end, required),
  70. "site.conf error: expected `" .. varname .. "' to be a string array")
  71. end