1 | -- resty-gitweb@utils/builder.lua |
2 | -- XML (HTML, Atom, RSS) builder class |
3 |
|
4 | -- Copyright (c) 2020 Joshua 'joshuas3' Stockin |
5 | -- <https://git.joshstock.in/resty-gitweb> |
6 | -- This software is licensed under the MIT License. |
7 |
|
8 | local builder = {} |
9 |
|
10 | builder.__index = function(t, k) |
11 | if builder[k] then return builder[k] end |
12 | return builder.createobject({}, k) |
13 | end |
14 |
|
15 | builder.__call = function(self, opts) |
16 | for i,v in pairs(opts) do |
17 | if type(i) ~= "number" then |
18 | self._attributes[i] = v |
19 | else |
20 | table.insert(self._objects, v) |
21 | end |
22 | end |
23 | return self |
24 | end |
25 |
|
26 | function builder.createobject(attr, tag) |
27 | local o = {} |
28 | o._type = "object" |
29 | o._tag = tag |
30 | o._attributes = attr or {} |
31 | o._objects = {} |
32 | setmetatable(o, builder) |
33 | return o |
34 | end |
35 |
|
36 | function builder:new(doctype) |
37 | local o = {} |
38 | o._type = "root" |
39 | o._doctype = doctype |
40 | o._objects = {} |
41 | setmetatable(o, self) |
42 | return o |
43 | end |
44 |
|
45 | function builder:build() |
46 | local str = "" |
47 | if self._type == "root" then |
48 | if self._doctype:lower() == "html" then |
49 | str = str .. "<!DOCTYPE html>\n" |
50 | end |
51 | end |
52 | if self._type == "object" then |
53 | if self._tag then |
54 | str = str .. "<" .. self._tag |
55 | end |
56 | for i,v in pairs(self._attributes) do |
57 | if i:sub(1,1) ~= "_" then |
58 | str = str .. " " .. i .. "=\"" .. tostring(v) .. "\"" |
59 | end |
60 | end |
61 | str = str .. ">" |
62 | end |
63 | if self._type == "object" or self._type == "root" then |
64 | for _,v in pairs(self._objects) do |
65 | if type(v) == "table" then |
66 | str = str .. v:build() |
67 | else |
68 | str = str .. v |
69 | end |
70 | end |
71 | end |
72 | if self._type == "object" then |
73 | if self._attributes._closetag ~= false then |
74 | str = str .. "</" .. self._tag .. ">" |
75 | end |
76 | end |
77 | return str |
78 | end |
79 |
|
80 | return builder |
81 |
|