summaryrefslogtreecommitdiff
path: root/xmake/core/base/xml.lua
blob: 1e644777fc6d3b7fed63dd1eef51328f3042552c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, Xmake Open Source Community.
--
-- @author      ruki
-- @file        xml.lua
--

-- define module: xml
local xml = xml or {}

-- load modules
local io    = require("base/io")
local os    = require("base/os")
local table = require("base/table")

-- XML node structure:
-- {
--     name     = "element-name" | nil (for non-element nodes)
--     kind     = "element" | "text" | "comment" | "cdata" | "doctype"
--     attrs    = { key = value, ... } or nil (only for elements)
--     text     = "raw text" (for text/comment/cdata/doctype nodes)
--     children = { child1, child2, ... } or nil (only for elements with children)
-- }
--
-- Example:
--   local doc = xml.decode("<root id='1'><item>foo</item><!--note--></root>")
--   doc.kind == "element"
--   doc.attrs.id == "1"
--   xml.find(doc, "root/item").kind == "element"
--   xml.text_of(doc) == ""       -- since root has no direct text nodes
--   doc.children[2].kind == "comment" and doc.children[2].text == "note"
--

-- decode entities
function xml._decode_entities(str)
    return (str:gsub("&lt;", "<")
               :gsub("&gt;", ">")
               :gsub("&apos;", "'")
               :gsub("&quot;", "\"")
               :gsub("&amp;", "&"))
end

-- encode raw text for xml element content
function xml._encode_text(str)
    return (str:gsub("&", "&amp;")
               :gsub("<", "&lt;")
               :gsub(">", "&gt;"))
end

-- encode attribute value for xml output
function xml._encode_attr(str)
    return xml._encode_text(str):gsub("\"", "&quot;")
end

-- parse attribute string to table (or nil if empty)
function xml._parse_attrs(attrstr)
    local attrs
    attrstr:gsub("([%w_:%-%.]+)%s*=%s*([\"'])(.-)%2", function(key, quote, value)
        attrs = attrs or {}
        attrs[key] = xml._decode_entities(value)
    end)
    return attrs
end

-- append normalized text node to top element on stack
function xml._append_text(stack, text, opt)
    opt = opt or {}
    if opt.trim_text ~= false then
        text = text:gsub("^%s+", ""):gsub("%s+$", "")
    end
    if text ~= "" then
        local top = stack[#stack]
        top.children = top.children or {}
        table.insert(top.children, xml.text(xml._decode_entities(text)))
    end
end

-- ensure closing tag matches stack and pop it
function xml._handle_closing(stack, tagname)
    local top = stack[#stack]
    if not top or top.name ~= tagname then
        return nil, string.format("malformed xml: unexpected closing </%s>", tagname)
    end
    table.remove(stack)
    return true
end

-- create an xml element node
-- e.g. `local node = xml.new({name = "item", attrs = {id = "1"}, children = {xml.text("value")}})`
function xml.new(opt)
    opt = opt or {}
    return {
        name = opt.name,
        attrs = opt.attrs,
        kind = opt.kind or "element",
        text = opt.text,
        children = opt.children
    }
end

-- create a text node
-- e.g. `local textnode = xml.text("hello")`
function xml.text(value)
    return xml.new({kind = "text", text = value or ""})
end

-- create an empty element node
-- e.g. `local br = xml.empty("br", {class = "line"})`
function xml.empty(name, attrs)
    return xml.new({name = name, attrs = attrs})
end

-- create a comment node
-- e.g. `local comment = xml.comment("generated by xmake")`
function xml.comment(value)
    return xml.new({kind = "comment", text = value or ""})
end

-- create a CDATA node
-- e.g. `local cdata = xml.cdata("if (a < b) { ... }")`
function xml.cdata(value)
    return xml.new({kind = "cdata", text = value or ""})
end

-- create a doctype node
-- e.g. `local doc = xml.doctype('html')`
function xml.doctype(value)
    return xml.new({kind = "doctype", text = value or ""})
end

-- decode xml string to tree node(s)
-- e.g. `local doc, err = xml.decode("<root><item>foo</item></root>")`
function xml.decode(data, opt)
    opt = opt or {}
    local root = {name = "__root__", attrs = {}, children = {}}
    local stack = {root}
    local i = 1
    local len = #data
    while i <= len do
        local lt = data:find("<", i, true)
        if not lt then
            local text = data:sub(i)
            xml._append_text(stack, text, opt)
            break
        end
        if lt > i then
            local text = data:sub(i, lt - 1)
            xml._append_text(stack, text, opt)
        end
        if data:sub(lt + 1, lt + 3) == "!--" then
            local close = data:find("-->", lt + 4, true)
            if not close then
                return nil, "unterminated xml comment"
            end
            local value = data:sub(lt + 4, close - 1)
            local top = stack[#stack]
            top.children = top.children or {}
            table.insert(top.children, xml.comment(value))
            i = close + 3
        elseif data:sub(lt + 1, lt + 8) == "![CDATA[" then
            local close = data:find("]]>", lt + 9, true)
            if not close then
                return nil, "unterminated cdata section"
            end
            local value = data:sub(lt + 9, close - 1)
            local top = stack[#stack]
            top.children = top.children or {}
            table.insert(top.children, xml.cdata(value))
            i = close + 3
        elseif data:sub(lt + 1, lt + 9):upper() == "!DOCTYPE" then
            local close = data:find(">", lt + 9)
            if not close then
                return nil, "unterminated doctype declaration"
            end
            local value = data:sub(lt + 10, close - 1)
            local top = stack[#stack]
            top.children = top.children or {}
            table.insert(top.children, xml.doctype(value))
            i = close + 1
        elseif data:sub(lt + 1, lt + 1) == "?" then
            local close = data:find("?>", lt + 2, true)
            if not close then
                return nil, "unterminated xml declaration"
            end
            i = close + 2
        elseif data:sub(lt + 1, lt + 1) == "!" then
            local close = data:find(">", lt + 2)
            if not close then
                return nil, "unterminated xml declaration"
            end
            i = close + 1
        elseif data:sub(lt + 1, lt + 1) == "/" then
            local close = data:find(">", lt + 1)
            if not close then
                return nil, "unterminated closing tag"
            end
            local tagname = data:sub(lt + 2, close - 1):match("^%s*([^%s>]+)")
            local ok, err = xml._handle_closing(stack, tagname)
            if not ok then
                return nil, err
            end
            i = close + 1
        else
            local close = data:find(">", lt + 1)
            if not close then
                return nil, "unterminated opening tag"
            end
            local inside = data:sub(lt + 1, close - 1)
            local selfclose = inside:find("/%s*$")
            if selfclose then
                inside = inside:gsub("/%s*$", "")
            end
            local tagname, attrstr = inside:match("^%s*([^%s>]+)%s*(.-)%s*$")
            local attrs = xml._parse_attrs(attrstr or "")
            local node = xml.empty(tagname, attrs)
            local top = stack[#stack]
            top.children = top.children or {}
            table.insert(top.children, node)
            if not selfclose then
                table.insert(stack, node)
            end
            i = close + 1
        end
    end
    if #stack ~= 1 then
        return nil, "malformed xml: unclosed tags"
    end
    if #root.children == 1 then
        return root.children[1]
    end
    return root.children
end

-- compute indent string for pretty output
function xml._indent(opt, level)
    if not opt.pretty then
        return ""
    end
    local indent = opt.indent or 4
    local indentchar = opt.indentchar or " "
    if type(indent) == "number" then
        return string.rep(indentchar, indent * level)
    end
    return indent:rep(level)
end

function xml._encode_node(node, opt, level)
    opt = opt or {}
    level = level or 0
    if node.kind == "text" then
        local indent = xml._indent(opt, level)
        local text = xml._encode_text(tostring(node.text or ""))
        if opt.pretty then
            return indent .. text
        end
        return text
    elseif node.kind == "comment" then
        return xml._indent(opt, level) .. string.format("<!--%s-->", tostring(node.text or ""))
    elseif node.kind == "cdata" then
        return xml._indent(opt, level) .. string.format("<![CDATA[%s]]>", tostring(node.text or ""))
    elseif node.kind == "doctype" then
        return xml._indent(opt, level) .. string.format("<!DOCTYPE %s>", tostring(node.text or ""))
    end
    local attrs = {}
    for k, v in pairs(node.attrs or {}) do
        table.insert(attrs, string.format('%s="%s"', k, xml._encode_attr(tostring(v))))
    end
    table.sort(attrs)
    local open = "<" .. node.name
    if #attrs > 0 then
        open = open .. " " .. table.concat(attrs, " ")
    end
    if not node.children or #node.children == 0 then
        return xml._indent(opt, level) .. open .. "/>"
    end
    local newline = opt.pretty and "\n" or ""
    if #node.children == 1 and node.children[1].kind == "text" then
        local text = xml._encode_text(tostring(node.children[1].text or ""))
        return string.format("%s%s>%s</%s>", xml._indent(opt, level), open, text, node.name)
    end
    local result = {}
    table.insert(result, xml._indent(opt, level) .. open .. ">")
    if node.children then
        for _, child in ipairs(node.children) do
            table.insert(result, xml._encode_node(child, opt, level + 1))
        end
    end
    table.insert(result, xml._indent(opt, level) .. "</" .. node.name .. ">")
    return table.concat(result, newline ~= "" and newline or "")
end

-- encode xml node to string
-- e.g. `local xmlstr = xml.encode(node, {pretty = true, indent = 2})`
function xml.encode(node, opt)
    opt = opt or {}
    return xml._encode_node(node, opt, 0)
end

-- load xml file
-- e.g. `local doc, err = xml.load("foo.xml")`
function xml.load(filepath, opt)
    local data, err = io.readfile(filepath, opt)
    if not data then
        return nil, err
    end
    return xml.decode(data, opt)
end

-- save xml node to file
-- e.g. `assert(xml.save("foo.xml", node, {pretty = true}))`
function xml.save(filepath, node, opt)
    local data = xml.encode(node, opt)
    if not data then
        return nil, "failed to encode xml"
    end
    return io.writefile(filepath, data, opt)
end

-- find the first matching node by name or path (e.g. "root/item/subitem")
-- returns nil if not found
function xml.find(node, path)
    if not node or not path or path == "" then
        return nil
    end
    local segments = path:split("/", {strict = true})
    local current = {node}
    for _, segment in ipairs(segments) do
        local next_level = {}
        for _, parent in ipairs(current) do
            if parent.children then
                for _, child in ipairs(parent.children) do
                    if child.name == segment then
                        table.insert(next_level, child)
                    end
                end
            end
        end
        if #next_level == 0 then
            return nil
        end
        current = next_level
    end
    return current[1]
end

-- get concatenated text from child nodes
-- e.g. `local text = xml.text_of(xml.decode("<item>foo</item>"))`
function xml.text_of(node)
    if not node or not node.children then
        return ""
    end
    local buffer = {}
    for _, child in ipairs(node.children) do
        if child.kind == "text" then
            table.insert(buffer, child.text or "")
        end
    end
    return table.concat(buffer, "")
end

return xml