• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarmodules / Penlight / 477

12 Feb 2024 09:01AM UTC coverage: 89.675% (+0.7%) from 88.938%
477

push

appveyor

web-flow
fix(doc): typo in example (#463)

5489 of 6121 relevant lines covered (89.67%)

346.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.6
/lua/pl/xml.lua
1
--- XML LOM Utilities.
2
--
3
-- This implements some useful things on [LOM](http://matthewwild.co.uk/projects/luaexpat/lom.html) documents, such as returned by `lxp.lom.parse`.
4
-- In particular, it can convert LOM back into XML text, with optional pretty-printing control.
5
-- It is based on stanza.lua from [Prosody](http://hg.prosody.im/trunk/file/4621c92d2368/util/stanza.lua)
6
--
7
--     > d = xml.parse "<nodes><node id='1'>alice</node></nodes>"
8
--     > = d
9
--     <nodes><node id='1'>alice</node></nodes>
10
--     > = xml.tostring(d,'','  ')
11
--     <nodes>
12
--        <node id='1'>alice</node>
13
--     </nodes>
14
--
15
-- Can be used as a lightweight one-stop-shop for simple XML processing; a simple XML parser is included
16
-- but the default is to use `lxp.lom` if it can be found.
17
-- <pre>
18
-- Prosody IM
19
-- Copyright (C) 2008-2010 Matthew Wild
20
-- Copyright (C) 2008-2010 Waqas Hussain--
21
-- classic Lua XML parser by Roberto Ierusalimschy.
22
-- modified to output LOM format.
23
-- http://lua-users.org/wiki/LuaXml
24
-- </pre>
25
-- See @{06-data.md.XML|the Guide}
26
--
27
-- Dependencies: `pl.utils`
28
--
29
-- Soft Dependencies: `lxp.lom` (fallback is to use basic Lua parser)
30
-- @module pl.xml
31

32
local utils = require 'pl.utils'
16✔
33
local split         =   utils.split
16✔
34
local t_insert      =  table.insert
16✔
35
local t_concat      =  table.concat
16✔
36
local t_remove      =  table.remove
16✔
37
local s_match       =  string.match
16✔
38
local tostring      =      tostring
16✔
39
local setmetatable  =  setmetatable
16✔
40
local getmetatable  =  getmetatable
16✔
41
local pairs         =         pairs
16✔
42
local ipairs        =        ipairs
16✔
43
local type          =          type
16✔
44
local next          =          next
16✔
45
local print         =         print
16✔
46
local unpack        =  utils.unpack
16✔
47
local s_gsub        =   string.gsub
16✔
48
local s_sub         =    string.sub
16✔
49
local s_find        =   string.find
16✔
50
local pcall         =         pcall
16✔
51
local require       =       require
16✔
52

53

54
utils.raise_deprecation {
32✔
55
  source = "Penlight " .. utils._VERSION,
16✔
56
  message = "the contents of module 'pl.xml' has been deprecated, please use a more specialized library instead",
8✔
57
  version_removed = "2.0.0",
8✔
58
  deprecated_after = "1.11.0",
8✔
59
  no_trace = true,
8✔
60
}
61

62

63

64
local _M = {}
16✔
65
local Doc = { __type = "doc" };
16✔
66
Doc.__index = Doc;
16✔
67

68

69
local function is_text(s) return type(s) == 'string' end
8,304✔
70
local function is_tag(d) return type(d) == 'table' and is_text(d.tag) end
3,612✔
71

72

73

74
--- create a new document node.
75
-- @tparam string tag the tag name
76
-- @tparam[opt={}] table attr attributes (table of name-value pairs)
77
-- @return the Node object
78
-- @see xml.elem
79
-- @usage
80
-- local doc = xml.new("main", { hello = "world", answer = "42" })
81
-- print(doc)  -->  <main hello='world' answer='42'/>
82
function _M.new(tag, attr)
16✔
83
  if type(tag) ~= "string" then
1,600✔
84
    error("expected 'tag' to be a string value, got: " .. type(tag), 2)
8✔
85
  end
86
  attr = attr or {}
1,592✔
87
  if type(attr) ~= "table" then
1,592✔
88
    error("expected 'attr' to be a table value, got: " .. type(attr), 2)
8✔
89
  end
90

91
  local doc = { tag = tag, attr = attr, last_add = {}};
1,584✔
92
  return setmetatable(doc, Doc);
1,584✔
93
end
94

95

96
--- parse an XML document. By default, this uses lxp.lom.parse, but
97
-- falls back to basic_parse, or if `use_basic` is truthy
98
-- @param text_or_filename  file or string representation
99
-- @param is_file whether text_or_file is a file name or not
100
-- @param use_basic do a basic parse
101
-- @return a parsed LOM document with the document metatatables set
102
-- @return nil, error the error can either be a file error or a parse error
103
function _M.parse(text_or_filename, is_file, use_basic)
16✔
104
  local parser,status,lom
105
  if use_basic then
168✔
106
    parser = _M.basic_parse
160✔
107
  else
108
    status,lom = pcall(require,'lxp.lom')
8✔
109
    if not status then
8✔
110
      parser = _M.basic_parse
8✔
111
    else
112
      parser = lom.parse
×
113
    end
114
  end
115

116
  if is_file then
168✔
117
    local text, err = utils.readfile(text_or_filename)
8✔
118
    if not text then
8✔
119
      return nil, err
×
120
    end
121
    text_or_filename = text
8✔
122
  end
123

124
  local doc, err = parser(text_or_filename)
168✔
125
  if not doc then
168✔
126
    return nil, err
×
127
  end
128

129
  if lom then
168✔
130
    _M.walk(doc, false, function(_, d)
16✔
131
      setmetatable(d, Doc)
120✔
132
    end)
133
  end
134
  return doc
168✔
135
end
136

137

138
--- Create a Node with a set of children (text or Nodes) and attributes.
139
-- @tparam string tag a tag name
140
-- @tparam table|string items either a single child (text or Node), or a table where the hash
141
-- part is the attributes and the list part is the children (text or Nodes).
142
-- @return the new Node
143
-- @see xml.new
144
-- @see xml.tags
145
-- @usage
146
-- local doc = xml.elem("top", "hello world")                -- <top>hello world</top>
147
-- local doc = xml.elem("main", xml.new("child"))            -- <main><child/></main>
148
-- local doc = xml.elem("main", { "this ", "is ", "nice" })  -- <main>this is nice</main>
149
-- local doc = xml.elem("main", { xml.new "this",
150
--                                xml.new "is",
151
--                                xml.new "nice" })          -- <main><this/><is/><nice/></main>
152
-- local doc = xml.elem("main", { hello = "world" })         -- <main hello='world'/>
153
-- local doc = xml.elem("main", {
154
--   "prefix",
155
--   xml.elem("child", { "this ", "is ", "nice"}),
156
--   "postfix",
157
--   attrib = "value"
158
-- })   -- <main attrib='value'>prefix<child>this is nice</child>postfix</main>"
159
function _M.elem(tag, items)
16✔
160
  local s = _M.new(tag)
1,072✔
161
  if is_text(items) then items = {items} end
1,608✔
162
  if is_tag(items) then
1,608✔
163
    t_insert(s,items)
8✔
164
  elseif type(items) == 'table' then
1,064✔
165
    for k,v in pairs(items) do
1,968✔
166
      if is_text(k) then
2,028✔
167
        s.attr[k] = v
192✔
168
        t_insert(s.attr,k)
192✔
169
      else
170
        s[k] = v
1,160✔
171
      end
172
    end
173
  end
174
  return s
1,072✔
175
end
176

177

178
--- given a list of names, return a number of element constructors.
179
-- If passing a comma-separated string, then whitespace surrounding the values
180
-- will be stripped.
181
--
182
-- The returned constructor functions are a shortcut to `xml.elem` where you
183
-- no longer provide the tag-name, but only the `items` table.
184
-- @tparam string|table list a list of names, or a comma-separated string.
185
-- @return (multiple) constructor functions; `function(items)`. For the `items`
186
-- parameter see `xml.elem`.
187
-- @see xml.elem
188
-- @usage
189
-- local new_parent, new_child = xml.tags 'mom, kid'
190
-- doc = new_parent {new_child 'Bob', new_child 'Annie'}
191
-- -- <mom><kid>Bob</kid><kid>Annie</kid></mom>
192
function _M.tags(list)
16✔
193
  local ctors = {}
40✔
194
  if is_text(list) then
60✔
195
    list = split(list:match("^%s*(.-)%s*$"),'%s*,%s*')
48✔
196
  end
197
  for i,tag in ipairs(list) do
176✔
198
    local function ctor(items)
199
      return _M.elem(tag,items)
240✔
200
    end
201
    ctors[i] = ctor
136✔
202
  end
203
  return unpack(ctors)
40✔
204
end
205

206

207
--- Adds a document Node, at current position.
208
-- This updates the last inserted position to the new Node.
209
-- @tparam string tag the tag name
210
-- @tparam[opt={}] table attrs attributes (table of name-value pairs)
211
-- @return the current node (`self`)
212
-- @usage
213
-- local doc = xml.new("main")
214
-- doc:addtag("penlight", { hello = "world"})
215
-- doc:addtag("expat")  -- added to 'penlight' since position moved
216
-- print(doc)  -->  <main><penlight hello='world'><expat/></penlight></main>
217
function Doc:addtag(tag, attrs)
16✔
218
  local s = _M.new(tag, attrs)
192✔
219
  self:add_child(s)
192✔
220
  t_insert(self.last_add, s)
192✔
221
  return self
192✔
222
end
223

224

225
--- Adds a text node, at current position.
226
-- @tparam string text a string
227
-- @return the current node (`self`)
228
-- @usage
229
-- local doc = xml.new("main")
230
-- doc:text("penlight")
231
-- doc:text("expat")
232
-- print(doc)  -->  <main><penlightexpat</main>
233
function Doc:text(text)
16✔
234
  self:add_child(text)
144✔
235
  return self
144✔
236
end
237

238

239
--- Moves current position up one level.
240
-- @return the current node (`self`)
241
function Doc:up()
16✔
242
  t_remove(self.last_add)
144✔
243
  return self
144✔
244
end
245

246

247
--- Resets current position to top level.
248
-- Resets to the `self` node.
249
-- @return the current node (`self`)
250
function Doc:reset()
16✔
251
  local last_add = self.last_add
8✔
252
  for i = 1,#last_add do
32✔
253
    last_add[i] = nil
24✔
254
  end
255
  return self
8✔
256
end
257

258

259
--- Append a child to the current Node (ignoring current position).
260
-- @param child a child node (either text or a document)
261
-- @return the current node (`self`)
262
-- @usage
263
-- local doc = xml.new("main")
264
-- doc:add_direct_child("dog")
265
-- doc:add_direct_child(xml.new("child"))
266
-- doc:add_direct_child("cat")
267
-- print(doc)  -->  <main>dog<child/>cat</main>
268
function Doc:add_direct_child(child)
16✔
269
  t_insert(self, child)
504✔
270
  return self
504✔
271
end
272

273

274
--- Append a child at the current position (without changing position).
275
-- @param child a child node (either text or a document)
276
-- @return the current node (`self`)
277
-- @usage
278
-- local doc = xml.new("main")
279
-- doc:addtag("one")
280
-- doc:add_child(xml.new("item1"))
281
-- doc:add_child(xml.new("item2"))
282
-- doc:add_child(xml.new("item3"))
283
-- print(doc)  -->  <main><one><item1/><item2/><item3/></one></main>
284
function Doc:add_child(child)
16✔
285
  (self.last_add[#self.last_add] or self):add_direct_child(child)
472✔
286
  return self
472✔
287
end
288

289

290
--accessing attributes: useful not to have to expose implementation (attr)
291
--but also can allow attr to be nil in any future optimizations
292

293

294
--- Set attributes of a document node.
295
-- Will add/overwrite values, but will not remove existing ones.
296
-- Operates on the Node itself, will not take position into account.
297
-- @tparam table t a table containing attribute/value pairs
298
-- @return the current node (`self`)
299
function Doc:set_attribs(t)
16✔
300
  -- TODO: keep array part in sync
301
  for k,v in pairs(t) do
80✔
302
    self.attr[k] = v
48✔
303
  end
304
  return self
32✔
305
end
306

307

308
--- Set a single attribute of a document node.
309
-- Operates on the Node itself, will not take position into account.
310
-- @param a attribute
311
-- @param v its value, pass in `nil` to delete the attribute
312
-- @return the current node (`self`)
313
function Doc:set_attrib(a,v)
16✔
314
  -- TODO: keep array part in sync
315
  self.attr[a] = v
16✔
316
  return self
16✔
317
end
318

319

320
--- Gets the attributes of a document node.
321
-- Operates on the Node itself, will not take position into account.
322
-- @return table with attributes (attribute/value pairs)
323
function Doc:get_attribs()
16✔
324
  return self.attr
8✔
325
end
326

327

328

329
local template_cache do
16✔
330
  local templ_cache = {}
16✔
331

332
  -- @param templ a template, a string being valid xml to be parsed, or a Node object
333
  function template_cache(templ)
14✔
334
    if is_text(templ) then
144✔
335
      if templ_cache[templ] then
88✔
336
        -- cache hit
337
        return templ_cache[templ]
×
338

339
      else
340
        -- parse and cache
341
        local ptempl, err = _M.parse(templ,false,true)
88✔
342
        if not ptempl then
88✔
343
          return nil, err
×
344
        end
345
        templ_cache[templ] = ptempl
88✔
346
        return ptempl
88✔
347
      end
348
    end
349

350
    if is_tag(templ) then
12✔
351
      return templ
8✔
352
    end
353

354
    return nil, "template is not a document"
×
355
  end
356
end
357

358

359
do
360
  local function is_data(data)
361
    return #data == 0 or type(data[1]) ~= 'table'
16✔
362
  end
363

364

365
  local function prepare_data(data)
366
    -- a hack for ensuring that $1 maps to first element of data, etc.
367
    -- Either this or could change the gsub call just below.
368
    for i,v in ipairs(data) do
16✔
369
      data[tostring(i)] = v
×
370
    end
371
  end
372

373
  --- create a substituted copy of a document,
374
  -- @param template may be a document or a string representation which will be parsed and cached
375
  -- @param data a table of name-value pairs or a list of such tables
376
  -- @return an XML document
377
  function Doc.subst(template, data)
16✔
378
    if type(data) ~= 'table' or not next(data) then
8✔
379
      return nil, "data must be a non-empty table"
×
380
    end
381

382
    if is_data(data) then
12✔
383
      prepare_data(data)
×
384
    end
385

386
    local templ, err = template_cache(template)
8✔
387
    if err then
8✔
388
      return nil, err
×
389
    end
390

391
    local function _subst(item)
392
      return _M.clone(templ, function(s)
24✔
393
        return s:gsub('%$(%w+)', item)
112✔
394
      end)
395
    end
396

397
    if is_data(data) then
12✔
398
      return _subst(data)
×
399
    end
400

401
    local list = {}
8✔
402
    for _, item in ipairs(data) do
24✔
403
      prepare_data(item)
16✔
404
      t_insert(list, _subst(item))
24✔
405
    end
406

407
    if data.tag then
8✔
408
      list = _M.elem(data.tag,list)
×
409
    end
410
    return list
8✔
411
  end
412
end
413

414

415
--- Return the first child with a given tag name (non-recursive).
416
-- @param tag the tag name
417
-- @return the child Node found or `nil` if not found
418
function Doc:child_with_name(tag)
16✔
419
  for _, child in ipairs(self) do
24✔
420
    if child.tag == tag then
24✔
421
      return child
8✔
422
    end
423
  end
424
end
425

426

427
do
428
  -- @param self document node to traverse
429
  -- @param tag tag-name to look for
430
  -- @param list array table to add the matching ones to
431
  -- @param recurse if truthy, recursively search the node
432
  local function _children_with_name(self, tag, list, recurse)
433
    -- TODO: protect against recursion
434
    for _, child in ipairs(self) do
648✔
435
      if type(child) == 'table' then
368✔
436
        if child.tag == tag then
256✔
437
          t_insert(list, child)
56✔
438
        end
439
        if recurse then
256✔
440
          _children_with_name(child, tag, list, recurse)
256✔
441
        end
442
      end
443
    end
444
  end
445

446
  --- Returns all elements in a document that have a given tag.
447
  -- @tparam string tag a tag name
448
  -- @tparam[opt=false] boolean dont_recurse optionally only return the immediate children with this tag name
449
  -- @return a list of elements found, list will be empty if none was found.
450
  function Doc:get_elements_with_name(tag, dont_recurse)
16✔
451
    local res = {}
24✔
452
    _children_with_name(self, tag, res, not dont_recurse)
24✔
453
    return res
24✔
454
  end
455
end
456

457

458

459
--- Iterator over all children of a document node, including text nodes.
460
-- This function is not recursive, so returns only direct child nodes.
461
-- @return iterator that returns a single Node per iteration.
462
function Doc:children()
16✔
463
  local i = 0;
16✔
464
  return function (a)
465
    i = i + 1
40✔
466
    return a[i];
40✔
467
  end, self, i;
16✔
468
end
469

470

471
--- Return the first child element of a node, if it exists.
472
-- This will skip text nodes.
473
-- @return first child Node or `nil` if there is none.
474
function Doc:first_childtag()
16✔
475
  if #self == 0 then
16✔
476
    return
×
477
  end
478
  for _, t in ipairs(self) do
40✔
479
    if is_tag(t) then
48✔
480
      return t
8✔
481
    end
482
  end
483
end
484

485

486
--- Iterator that matches tag names, and a namespace (non-recursive).
487
-- @tparam[opt=nil] string tag tag names to return. Returns all tags if not provided.
488
-- @tparam[opt=nil] string xmlns the namespace value ('xmlns' attribute) to return. If not
489
-- provided will match all namespaces.
490
-- @return iterator that returns a single Node per iteration.
491
function Doc:matching_tags(tag, xmlns)
16✔
492
  -- TODO: this doesn't make sense??? namespaces are not "xmnls", as matched below
493
  -- but "xmlns:name"... so should be a string-prefix match if anything...
494
  xmlns = xmlns or self.attr.xmlns;
495
  local tags = self
×
496
  local next_i = 1
×
497
  local max_i = #tags
×
498
  local node
499
  return function ()
500
      for i = next_i, max_i do
×
501
        node = tags[i];
502
        if (not tag or node.tag == tag) and
×
503
           (not xmlns or xmlns == node.attr.xmlns) then
×
504
          next_i = i + 1
×
505
          return node
×
506
        end
507
      end
508
    end, tags, next_i
×
509
end
510

511

512
--- Iterator over all child tags of a document node. This will skip over
513
-- text nodes.
514
-- @return iterator that returns a single Node per iteration.
515
function Doc:childtags()
16✔
516
  local i = 0;
24✔
517
  return function (a)
518
    local v
519
      repeat
520
        i = i + 1
64✔
521
        v = self[i]
64✔
522
        if v and type(v) == 'table' then
64✔
523
          return v
40✔
524
        end
525
      until not v
24✔
526
    end, self[1], i;
32✔
527
end
528

529

530
--- Visit child Nodes of a node and call a function, possibly modifying the document.
531
-- Text elements will be skipped.
532
-- This is not recursive, so only direct children will be passed.
533
-- @tparam function callback a function with signature `function(node)`, passed the node.
534
-- The element will be updated with the returned value, or deleted if it returns `nil`.
535
function Doc:maptags(callback)
16✔
536
  local i = 1;
16✔
537

538
  while i <= #self do
96✔
539
    if is_tag(self[i]) then
120✔
540
      local ret = callback(self[i]);
48✔
541
      if ret == nil then
48✔
542
        -- remove it
543
        t_remove(self, i);
30✔
544

545
      else
546
        -- update it
547
        self[i] = ret;
24✔
548
        i = i + 1;
24✔
549
      end
550
    else
551
      i = i + 1
32✔
552
    end
553
  end
554

555
  return self;
16✔
556
end
557

558

559
do
560
  local escape_table = {
16✔
561
    ["'"] = "&apos;",
8✔
562
    ['"'] = "&quot;",
8✔
563
    ["<"] = "&lt;",
8✔
564
    [">"] = "&gt;",
8✔
565
    ["&"] = "&amp;",
8✔
566
  }
567

568
  --- Escapes a string for safe use in xml.
569
  -- Handles quotes(single+double), less-than, greater-than, and ampersand.
570
  -- @tparam string str string value to escape
571
  -- @return escaped string
572
  -- @usage
573
  -- local esc = xml.xml_escape([["'<>&]])  --> "&quot;&apos;&lt;&gt;&amp;"
574
  function _M.xml_escape(str)
16✔
575
    return (s_gsub(str, "['&<>\"]", escape_table))
664✔
576
  end
577
end
578
local xml_escape = _M.xml_escape
16✔
579

580
do
581
  local escape_table = {
16✔
582
    quot = '"',
8✔
583
    apos = "'",
8✔
584
    lt = "<",
8✔
585
    gt = ">",
8✔
586
    amp = "&",
8✔
587
  }
588

589
  --- Unescapes a string from xml.
590
  -- Handles quotes(single+double), less-than, greater-than, and ampersand.
591
  -- @tparam string str string value to unescape
592
  -- @return unescaped string
593
  -- @usage
594
  -- local unesc = xml.xml_escape("&quot;&apos;&lt;&gt;&amp;")  --> [["'<>&]]
595
  function _M.xml_unescape(str)
16✔
596
    return (str:gsub( "&(%a+);", escape_table))
1,280✔
597
  end
598
end
599
local xml_unescape = _M.xml_unescape
16✔
600

601
-- pretty printing
602
-- if indent, then put each new tag on its own line
603
-- if attr_indent, put each new attribute on its own line
604
local function _dostring(t, buf, parentns, block_indent, tag_indent, attr_indent)
605
  local nsid = 0
1,184✔
606
  local tag = t.tag
1,184✔
607

608
  local lf = ""
1,184✔
609
  if tag_indent then
1,184✔
610
    lf = '\n'..block_indent
144✔
611
  end
612

613
  local alf = " "
1,184✔
614
  if attr_indent then
1,184✔
615
    alf = '\n'..block_indent..attr_indent
×
616
  end
617

618
  t_insert(buf, lf.."<"..tag)
1,184✔
619

620
  local function write_attr(k,v)
621
    if s_find(k, "\1", 1, true) then
256✔
622
      nsid = nsid + 1
×
623
      local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$")
×
624
      t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'")
×
625

626
    elseif not (k == "xmlns" and v == parentns) then
256✔
627
      t_insert(buf, alf..k.."='"..xml_escape(v).."'");
384✔
628
    end
629
  end
630

631
  -- it's useful for testing to have predictable attribute ordering, if available
632
  if #t.attr > 0 then
1,184✔
633
    -- TODO: the key-value list is leading, what if they are not in-sync
634
    for _,k in ipairs(t.attr) do
144✔
635
      write_attr(k,t.attr[k])
80✔
636
    end
637
  else
638
    for k, v in pairs(t.attr) do
1,296✔
639
      write_attr(k,v)
176✔
640
    end
641
  end
642

643
  local len = #t
1,184✔
644
  local has_children
645

646
  if len == 0 then
1,184✔
647
    t_insert(buf, attr_indent and '\n'..block_indent.."/>" or "/>")
512✔
648

649
  else
650
    t_insert(buf, ">");
672✔
651

652
    for n = 1, len do
1,784✔
653
      local child = t[n]
1,112✔
654

655
      if child.tag then
1,112✔
656
        has_children = true
712✔
657
        _dostring(child, buf, t.attr.xmlns, block_indent and block_indent..tag_indent, tag_indent, attr_indent)
1,068✔
658

659
      else
660
        -- text element
661
        t_insert(buf, xml_escape(child))
600✔
662
      end
663
    end
664

665
    t_insert(buf, (has_children and lf or '').."</"..tag..">");
672✔
666
  end
667
end
668

669
--- Function to pretty-print an XML document.
670
-- @param doc an XML document
671
-- @tparam[opt] string|int b_ind an initial block-indent (required when `t_ind` is set)
672
-- @tparam[opt] string|int t_ind an tag-indent for each level (required when `a_ind` is set)
673
-- @tparam[opt] string|int a_ind if given, indent each attribute pair and put on a separate line
674
-- @tparam[opt] string|bool xml_preface force prefacing with default or custom <?xml...>, if truthy then `&lt;?xml version='1.0'?&gt;` will be used as default.
675
-- @return a string representation
676
-- @see Doc:tostring
677
function _M.tostring(doc, b_ind, t_ind, a_ind, xml_preface)
16✔
678
  local buf = {}
472✔
679

680
  if type(b_ind) == "number" then b_ind = (" "):rep(b_ind) end
472✔
681
  if type(t_ind) == "number" then t_ind = (" "):rep(t_ind) end
472✔
682
  if type(a_ind) == "number" then a_ind = (" "):rep(a_ind) end
472✔
683

684
  if xml_preface then
472✔
685
    if type(xml_preface) == "string" then
8✔
686
      buf[1] = xml_preface
×
687
    else
688
      buf[1] = "<?xml version='1.0'?>"
8✔
689
    end
690
  end
691

692
  _dostring(doc, buf, nil, b_ind, t_ind, a_ind, xml_preface)
472✔
693

694
  return t_concat(buf)
472✔
695
end
696

697

698
Doc.__tostring = _M.tostring
16✔
699

700

701
--- Method to pretty-print an XML document.
702
-- Invokes `xml.tostring`.
703
-- @tparam[opt] string|int b_ind an initial indent (required when `t_ind` is set)
704
-- @tparam[opt] string|int t_ind an indent for each level (required when `a_ind` is set)
705
-- @tparam[opt] string|int a_ind if given, indent each attribute pair and put on a separate line
706
-- @tparam[opt="&lt;?xml version='1.0'?&gt;"] string xml_preface force prefacing with default or custom <?xml...>
707
-- @return a string representation
708
-- @see xml.tostring
709
function Doc:tostring(b_ind, t_ind, a_ind, xml_preface)
16✔
710
  return _M.tostring(self, b_ind, t_ind, a_ind, xml_preface)
304✔
711
end
712

713

714
--- get the full text value of an element.
715
-- @return a single string with all text elements concatenated
716
-- @usage
717
-- local doc = xml.new("main")
718
-- doc:text("one")
719
-- doc:add_child(xml.elem "two")
720
-- doc:text("three")
721
--
722
-- local t = doc:get_text()    -->  "onethree"
723
function Doc:get_text()
16✔
724
  local res = {}
72✔
725
  for i,el in ipairs(self) do
160✔
726
    if is_text(el) then t_insert(res,el) end
132✔
727
  end
728
  return t_concat(res);
72✔
729
end
730

731

732
do
733
  local function _copy(object, kind, parent, strsubst, lookup_table)
734
    if type(object) ~= "table" then
512✔
735
      if strsubst and is_text(object) then
400✔
736
        return strsubst(object, kind, parent)
176✔
737
      else
738
        return object
136✔
739
      end
740
    end
741

742
    if lookup_table[object] then
200✔
743
      error("recursion detected")
8✔
744
    end
745
    lookup_table[object] = true
192✔
746

747
    local new_table = {}
192✔
748
    lookup_table[object] = new_table
192✔
749

750
    local tag = object.tag
192✔
751
    new_table.tag = _copy(tag, '*TAG', parent, strsubst, lookup_table)
288✔
752

753
    if object.attr then
192✔
754
      local res = {}
192✔
755
      for attr, value in pairs(object.attr) do
272✔
756
        if type(attr) == "string" then
80✔
757
          res[attr] = _copy(value, attr, object, strsubst, lookup_table)
60✔
758
        end
759
      end
760
      new_table.attr = res
192✔
761
    end
762

763
    for index = 1, #object do
416✔
764
      local v = _copy(object[index], '*TEXT', object, strsubst, lookup_table)
232✔
765
      t_insert(new_table,v)
224✔
766
    end
767

768
    return setmetatable(new_table, getmetatable(object))
184✔
769
  end
770

771
  --- Returns a copy of a document.
772
  -- The `strsubst` parameter is a callback with signature `function(object, kind, parent)`.
773
  --
774
  -- Param `kind` has the following values, and parameters:
775
  --
776
  -- - `"*TAG"`: `object` is the tag-name, `parent` is the Node object. Returns the new tag name.
777
  --
778
  -- - `"*TEXT"`: `object` is the text-element, `parent` is the Node object. Returns the new text value.
779
  --
780
  -- - other strings not prefixed with `*`: `kind` is the attribute name, `object` is the
781
  --   attribute value, `parent` is the Node object. Returns the new attribute value.
782
  --
783
  -- @tparam Node|string doc a Node object or string (text node)
784
  -- @tparam[opt] function strsubst an optional function for handling string copying
785
  -- which could do substitution, etc.
786
  -- @return copy of the document
787
  -- @see Doc:filter
788
  function _M.clone(doc, strsubst)
16✔
789
    return _copy(doc, nil, nil, strsubst, {})
48✔
790
  end
791
end
792

793

794
--- Returns a copy of a document.
795
-- This is the method version of `xml.clone`.
796
-- @see xml.clone
797
-- @name Doc:filter
798
-- @tparam[opt] function strsubst an optional function for handling string copying
799
Doc.filter = _M.clone -- also available as method
16✔
800

801
do
802
  local function _compare(t1, t2, recurse_check)
803

804
    local ty1 = type(t1)
464✔
805
    local ty2 = type(t2)
464✔
806

807
    if ty1 ~= ty2 then
464✔
808
      return false, 'type mismatch'
16✔
809
    end
810

811
    if ty1 == 'string' then
448✔
812
      if t1 == t2 then
104✔
813
        return true
96✔
814
      else
815
        return false, 'text '..t1..' ~= text '..t2
8✔
816
      end
817
    end
818

819
    if ty1 ~= 'table' or ty2 ~= 'table' then
344✔
820
      return false, 'not a document'
8✔
821
    end
822

823
    if recurse_check[t1] then
336✔
824
      return false, "recursive document"
8✔
825
    end
826
    recurse_check[t1] = true
328✔
827

828
    if t1.tag ~= t2.tag then
328✔
829
      return false, 'tag  '..t1.tag..' ~= tag '..t2.tag
8✔
830
    end
831

832
    if #t1 ~= #t2 then
320✔
833
      return false, 'size '..#t1..' ~= size '..#t2..' for tag '..t1.tag
8✔
834
    end
835

836
    -- compare attributes
837
    for k,v in pairs(t1.attr) do
479✔
838
      local t2_value = t2.attr[k]
183✔
839
      if type(k) == "string" then
183✔
840
        if t2_value ~= v then return false, 'mismatch attrib' end
119✔
841
      else
842
        if t2_value ~= nil and t2_value ~= v then return false, "mismatch attrib order" end
64✔
843
      end
844
    end
845
    for k,v in pairs(t2.attr) do
438✔
846
      local t1_value = t1.attr[k]
150✔
847
      if type(k) == "string" then
150✔
848
        if t1_value ~= v then return false, 'mismatch attrib' end
110✔
849
      else
850
        if t1_value ~= nil and t1_value ~= v then return false, "mismatch attrib order" end
40✔
851
      end
852
    end
853

854
    -- compare children
855
    for i = 1, #t1 do
600✔
856
      local ok, err = _compare(t1[i], t2[i], recurse_check)
336✔
857
      if not ok then
336✔
858
        return ok, err
24✔
859
      end
860
    end
861
    return true
264✔
862
  end
863

864
  --- Compare two documents or elements.
865
  -- Equality is based on tag, child nodes (text and tags), attributes and order
866
  -- of those (order only fails if both are given, and not equal).
867
  -- @tparam Node|string t1 a Node object or string (text node)
868
  -- @tparam Node|string t2 a Node object or string (text node)
869
  -- @treturn boolean `true` when the Nodes are equal.
870
  function _M.compare(t1,t2)
16✔
871
    return _compare(t1, t2, {})
128✔
872
  end
873
end
874

875

876
--- is this value a document element?
877
-- @param d any value
878
-- @treturn boolean `true` if it is a `table` with property `tag` being a string value.
879
-- @name is_tag
880
_M.is_tag = is_tag
16✔
881

882

883
do
884
  local function _walk(doc, depth_first, operation, recurse_check)
885
    if not depth_first then operation(doc.tag, doc) end
520✔
886
    for _,d in ipairs(doc) do
1,112✔
887
      if is_tag(d) then
912✔
888
        assert(not recurse_check[d], "recursion detected")
408✔
889
        recurse_check[d] = true
400✔
890
        _walk(d, depth_first, operation, recurse_check)
400✔
891
      end
892
    end
893
    if depth_first then operation(doc.tag, doc) end
504✔
894
  end
895

896
  --- Calls a function recursively over Nodes in the document.
897
  -- Will only call on tags, it will skip text nodes.
898
  -- The function signature for `operation` is `function(tag_name, Node)`.
899
  -- @tparam Node|string doc a Node object or string (text node)
900
  -- @tparam boolean depth_first visit child nodes first, then the current node
901
  -- @tparam function operation a function which will receive the current tag name and current node.
902
  function _M.walk(doc, depth_first, operation)
16✔
903
    return _walk(doc, depth_first, operation, {})
120✔
904
  end
905
end
906

907

908
local html_empty_elements = { --lists all HTML empty (void) elements
16✔
909
    br      = true,
8✔
910
    img     = true,
8✔
911
    meta    = true,
8✔
912
    frame   = true,
8✔
913
    area    = true,
8✔
914
    hr      = true,
8✔
915
    base    = true,
8✔
916
    col     = true,
8✔
917
    link    = true,
8✔
918
    input   = true,
8✔
919
    option  = true,
8✔
920
    param   = true,
8✔
921
    isindex = true,
8✔
922
    embed = true,
8✔
923
}
924

925
--- Parse a well-formed HTML file as a string.
926
-- Tags are case-insensitive, DOCTYPE is ignored, and empty elements can be .. empty.
927
-- @param s the HTML
928
function _M.parsehtml(s)
16✔
929
    return _M.basic_parse(s,false,true)
24✔
930
end
931

932
--- Parse a simple XML document using a pure Lua parser based on Robero Ierusalimschy's original version.
933
-- @param s the XML document to be parsed.
934
-- @param all_text  if true, preserves all whitespace. Otherwise only text containing non-whitespace is included.
935
-- @param html if true, uses relaxed HTML rules for parsing
936
function _M.basic_parse(s, all_text, html)
16✔
937
    local stack = {}
192✔
938
    local top = {}
192✔
939

940
    local function parseargs(s)
941
      local arg = {}
1,360✔
942
      s:gsub("([%w:%-_]+)%s*=%s*([\"'])(.-)%2", function (w, _, a)
2,720✔
943
        if html then w = w:lower() end
712✔
944
        arg[w] = xml_unescape(a)
1,068✔
945
      end)
946
      if html then
1,360✔
947
        s:gsub("([%w:%-_]+)%s*=%s*([^\"']+)%s*", function (w, a)
192✔
948
          w = w:lower()
24✔
949
          arg[w] = xml_unescape(a)
24✔
950
        end)
951
      end
952
      return arg
1,360✔
953
    end
954

955
    t_insert(stack, top)
192✔
956
    local ni,c,label,xarg, empty, _, istart
957
    local i = 1
192✔
958
    local j
959
    -- we're not interested in <?xml version="1.0"?>
960
    _,istart = s_find(s,'^%s*<%?[^%?]+%?>%s*')
192✔
961
    if not istart then -- or <!DOCTYPE ...>
192✔
962
        _,istart = s_find(s,'^%s*<!DOCTYPE.->%s*')
184✔
963
    end
964
    if istart then i = istart+1 end
192✔
965
    while true do
966
        ni,j,c,label,xarg, empty = s_find(s, "<([%/!]?)([%w:%-_]+)(.-)(%/?)>", i)
2,480✔
967
        if not ni then break end
2,480✔
968
        if c == "!" then -- comment
2,288✔
969
            -- case where there's no space inside comment
970
            if not (label:match '%-%-$' and xarg == '') then
16✔
971
                if xarg:match '%-%-$' then -- we've grabbed it all
16✔
972
                    j = j - 2
8✔
973
                end
974
                -- match end of comment
975
                _,j = s_find(s, "-->", j, true)
16✔
976
            end
977
        else
978
            local text = s_sub(s, i, ni-1)
2,272✔
979
            if html then
2,272✔
980
                label = label:lower()
264✔
981
                if html_empty_elements[label] then empty = "/" end
176✔
982
            end
983
            if all_text or not s_find(text, "^%s*$") then
2,272✔
984
                t_insert(top, xml_unescape(text))
816✔
985
            end
986
            if empty == "/" then  -- empty element tag
2,272✔
987
                t_insert(top, setmetatable({tag=label, attr=parseargs(xarg), empty=1},Doc))
672✔
988
            elseif c == "" then   -- start tag
1,824✔
989
                top = setmetatable({tag=label, attr=parseargs(xarg)},Doc)
1,368✔
990
                t_insert(stack, top)   -- new level
912✔
991
            else  -- end tag
992
                local toclose = t_remove(stack)  -- remove top
912✔
993
                top = stack[#stack]
912✔
994
                if #stack < 1 then
912✔
995
                    error("nothing to close with "..label..':'..text)
×
996
                end
997
                if toclose.tag ~= label then
912✔
998
                    error("trying to close "..toclose.tag.." with "..label.." "..text)
×
999
                end
1000
                t_insert(top, toclose)
912✔
1001
            end
1002
        end
1003
        i = j+1
2,288✔
1004
    end
1005
    local text = s_sub(s, i)
192✔
1006
    if all_text or  not s_find(text, "^%s*$") then
192✔
1007
        t_insert(stack[#stack], xml_unescape(text))
×
1008
    end
1009
    if #stack > 1 then
192✔
1010
        error("unclosed "..stack[#stack].tag)
×
1011
    end
1012
    local res = stack[1]
192✔
1013
    return is_text(res[1]) and res[2] or res[1]
288✔
1014
end
1015

1016
do
1017
  local match do
16✔
1018

1019
    local function empty(attr) return not attr or not next(attr) end
1,512✔
1020

1021
    local append_capture do
16✔
1022
      -- returns the key,value pair from a table if it has exactly one entry
1023
      local function has_one_element(t)
1024
          local key,value = next(t)
288✔
1025
          if next(t,key) ~= nil then return false end
288✔
1026
          return key,value
176✔
1027
      end
1028

1029
      function append_capture(res,tbl)
14✔
1030
          if not empty(tbl) then -- no point in capturing empty tables...
432✔
1031
              local key
1032
              if tbl._ then  -- if $_ was set then it is meant as the top-level key for the captured table
288✔
1033
                  key = tbl._
176✔
1034
                  tbl._ = nil
176✔
1035
                  if empty(tbl) then return end
264✔
1036
              end
1037
              -- a table with only one pair {[0]=value} shall be reduced to that value
1038
              local numkey,val = has_one_element(tbl)
288✔
1039
              if numkey == 0 then tbl = val end
288✔
1040
              if key then
288✔
1041
                  res[key] = tbl
176✔
1042
              else -- otherwise, we append the captured table
1043
                  t_insert(res,tbl)
112✔
1044
              end
1045
          end
1046
      end
1047
    end
1048

1049
    local function make_number(pat)
1050
        if pat:find '^%d+$' then -- $1 etc means use this as an array location
696✔
1051
            pat = tonumber(pat)
272✔
1052
        end
1053
        return pat
696✔
1054
    end
1055

1056
    local function capture_attrib(res,pat,value)
1057
        pat = make_number(pat:sub(2))
1,152✔
1058
        res[pat] = value
576✔
1059
        return true
576✔
1060
    end
1061

1062
    function match(d,pat,res,keep_going)
14✔
1063
        local ret = true
1,480✔
1064
        if d == nil then d = '' end --return false end
1,480✔
1065
        -- attribute string matching is straight equality, except if the pattern is a $ capture,
1066
        -- which always succeeds.
1067
        if is_text(d) then
2,220✔
1068
            if not is_text(pat) then return false end
936✔
1069
            if _M.debug then print(d,pat) end
624✔
1070
            if pat:find '^%$' then
624✔
1071
                return capture_attrib(res,pat,d)
576✔
1072
            else
1073
                return d == pat
48✔
1074
            end
1075
        else
1076
        if _M.debug then print(d.tag,pat.tag) end
856✔
1077
            -- this is an element node. For a match to succeed, the attributes must
1078
            -- match as well.
1079
            -- a tagname in the pattern ending with '-' is a wildcard and matches like an attribute
1080
            local tagpat = pat.tag:match '^(.-)%-$'
856✔
1081
            if tagpat then
856✔
1082
                tagpat = make_number(tagpat)
180✔
1083
                res[tagpat] = d.tag
120✔
1084
            end
1085
            if d.tag == pat.tag or tagpat then
856✔
1086

1087
                if not empty(pat.attr) then
1,116✔
1088
                    if empty(d.attr) then ret =  false
432✔
1089
                    else
1090
                        for prop,pval in pairs(pat.attr) do
656✔
1091
                            local dval = d.attr[prop]
368✔
1092
                            if not match(dval,pval,res) then ret = false;  break end
552✔
1093
                        end
1094
                    end
1095
                end
1096
                -- the pattern may have child nodes. We match partially, so that {P1,P2} shall match {X,P1,X,X,P2,..}
1097
                if ret and #pat > 0 then
744✔
1098
                    local i,j = 1,1
520✔
1099
                    local function next_elem()
1100
                        j = j + 1  -- next child element of data
1,088✔
1101
                        if is_text(d[j]) then j = j + 1 end
1,632✔
1102
                        return j <= #d
1,088✔
1103
                    end
1104
                    repeat
1105
                        local p = pat[i]
784✔
1106
                        -- repeated {{<...>}} patterns  shall match one or more elements
1107
                        -- so e.g. {P+} will match {X,X,P,P,X,P,X,X,X}
1108
                        if is_tag(p) and p.repeated then
1,176✔
1109
                            local found
1110
                            repeat
1111
                                local tbl = {}
304✔
1112
                                ret = match(d[j],p,tbl,false)
456✔
1113
                                if ret then
304✔
1114
                                    found = false --true
288✔
1115
                                    append_capture(res,tbl)
288✔
1116
                                end
1117
                            until not next_elem() or (found and not ret)
456✔
1118
                            i = i + 1
80✔
1119
                        else
1120
                            ret = match(d[j],p,res,false)
1,056✔
1121
                            if ret then i = i + 1 end
704✔
1122
                        end
1123
                    until not next_elem() or i > #pat -- run out of elements or patterns to match
1,176✔
1124
                    -- if every element in our pattern matched ok, then it's been a successful match
1125
                    if i > #pat then return true end
520✔
1126
                end
1127
                if ret then return true end
312✔
1128
            else
1129
                ret = false
112✔
1130
            end
1131
            -- keep going anyway - look at the children!
1132
            if keep_going then
200✔
1133
                for child in d:childtags() do
32✔
1134
                    ret = match(child,pat,res,keep_going)
24✔
1135
                    if ret then break end
16✔
1136
                end
1137
            end
1138
        end
1139
        return ret
200✔
1140
    end
1141
  end
1142

1143
  --- does something...
1144
  function Doc:match(pat)
16✔
1145
      local err
1146
      pat,err = template_cache(pat)
132✔
1147
      if not pat then return nil, err end
88✔
1148
      _M.walk(pat,false,function(_,d)
176✔
1149
          if is_text(d[1]) and is_tag(d[2]) and is_text(d[3]) and
564✔
1150
            d[1]:find '%s*{{' and d[3]:find '}}%s*' then
80✔
1151
            t_remove(d,1)
80✔
1152
            t_remove(d,2)
80✔
1153
            d[1].repeated = true
80✔
1154
          end
1155
      end)
1156

1157
      local res = {}
88✔
1158
      local ret = match(self,pat,res,true)
88✔
1159
      return res,ret
88✔
1160
  end
1161
end
1162

1163

1164
return _M
16✔
1165

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc