smr/src/lua/pages.lua

96 lines
2.2 KiB
Lua
Raw Normal View History

--[[
Compiles all the pages under src/pages/ with etlua. See the etlua documentation
for more info (https://github.com/leafo/etlua)
]]
local et = require("etlua")
local config = require("config")
2023-03-12 04:31:08 +01:00
require("global")
local pagenames = {
"index",
"author_index",
"claim",
"paste",
"edit",
"read",
"nostory",
"cantedit",
"noauthor",
"login",
"author_paste",
"author_edit",
"search",
"error",
"edit_bio",
"parts/header",
"parts/footer",
"parts/motd",
"parts/search",
"parts/story_breif",
"parts/taglist"
}
2023-05-17 23:18:24 +02:00
--Functions available to all templates
local global_env = {
include = function(filename)
local fp = assert(io.open(filename,"r"))
local data = assert(fp:read("*a"))
fp:close()
return data
end,
}
local global_env_m = {
__index=global_env
}
local pages = {}
2023-06-20 02:22:41 +02:00
local etlua_short_pat = '%[string "etlua"%]'
for _,v in pairs(pagenames) do
local path = string.format(config.approot .. "pages/%s.etlua",v)
local parser = et.Parser()
local f = assert(io.open(path,"r"))
local fdata = assert(f:read("*a"))
2023-03-12 06:13:54 +01:00
local code, err = parser:compile_to_lua(fdata)
if not code then
errorf("Failed to parse %s: %s",path,err)
end
2023-02-20 05:32:37 +01:00
local func, err = parser:load(code)
if not func then
error(string.format("Failed to load %s: %s",path, err))
end
f:close()
2023-02-20 05:32:37 +01:00
assert(func, "Failed to load " .. path)
2023-03-12 06:13:54 +01:00
pages[v] = function(env)
assert(type(env) == "table","env must be a table")
2023-05-17 23:18:24 +02:00
-- Add our global metatable functions at the bottom metatable's __index
2023-06-20 02:22:41 +02:00
local cursor,max_depth = env, 10
while cursor ~= nil and getmetatable(cursor) and getmetatable(cursor).__index and max_depth > 0 do
2023-05-17 23:18:24 +02:00
cursor = getmetatable(cursor)
2023-06-20 02:22:41 +02:00
max_depth = max_depth - 1
end
if max_depth == 0 then
log(
LOG_WARN,
string.format([[
Failed to set environment on page %s correctly,
exceeded max depth when applying global functions: %s
]],
path,
debug.traceback()
)
)
2023-05-17 23:18:24 +02:00
end
setmetatable(cursor,global_env_m)
2023-06-20 02:22:41 +02:00
local success, ret = xpcall(function()
return parser:run(func, env)
end,function(err)
-- A function to tell us what template we errored in
-- if an error occures
return debug.traceback(err:gsub(etlua_short_pat,path))
end)
if not success then
error(ret:gsub(etlua_short_pat,path))
2023-03-12 06:13:54 +01:00
end
2023-06-20 02:22:41 +02:00
return table.concat(ret)
end
end
return pages