check_site_lib.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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_array(varname, subcheck, required)
  37. local var = loadvar(varname)
  38. if required == false and var == nil then
  39. return nil
  40. end
  41. assert_type(var, 'table', "site.conf error: expected `" .. varname .. "' to be an array")
  42. for _, e in ipairs(var) do
  43. subcheck(e)
  44. end
  45. return var
  46. end
  47. function need_table(varname, subcheck, required)
  48. local var = loadvar(varname)
  49. if required == false and var == nil then
  50. return nil
  51. end
  52. assert_type(var, 'table', "site.conf error: expected `" .. varname .. "' to be a table")
  53. for k, v in pairs(var) do
  54. subcheck(k, v)
  55. end
  56. return var
  57. end
  58. function need_string_array(varname, required)
  59. return assert(pcall(need_array, varname, function(e) assert_type(e, 'string') end, required),
  60. "site.conf error: expected `" .. varname .. "' to be a string array")
  61. end