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

lunarmodules / Penlight / 7742759193

01 Feb 2024 02:24PM UTC coverage: 88.938% (-0.7%) from 89.675%
7742759193

push

github

web-flow
docs: Fix typos (#462)

7 of 7 new or added lines in 2 files covered. (100.0%)

120 existing lines in 14 files now uncovered.

5443 of 6120 relevant lines covered (88.94%)

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

53

54
utils.raise_deprecation {
24✔
55
  source = "Penlight " .. utils._VERSION,
12✔
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 = {}
12✔
65
local Doc = { __type = "doc" };
12✔
66
Doc.__index = Doc;
12✔
67

68

69
local function is_text(s) return type(s) == 'string' end
6,228✔
70
local function is_tag(d) return type(d) == 'table' and is_text(d.tag) end
2,496✔
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)
12✔
83
  if type(tag) ~= "string" then
1,200✔
84
    error("expected 'tag' to be a string value, got: " .. type(tag), 2)
6✔
85
  end
86
  attr = attr or {}
1,194✔
87
  if type(attr) ~= "table" then
1,194✔
88
    error("expected 'attr' to be a table value, got: " .. type(attr), 2)
6✔
89
  end
90

91
  local doc = { tag = tag, attr = attr, last_add = {}};
1,188✔
92
  return setmetatable(doc, Doc);
1,188✔
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)
12✔
104
  local parser,status,lom
105
  if use_basic then
126✔
106
    parser = _M.basic_parse
120✔
107
  else
108
    status,lom = pcall(require,'lxp.lom')
6✔
109
    if not status then
6✔
110
      parser = _M.basic_parse
6✔
111
    else
112
      parser = lom.parse
×
113
    end
114
  end
115

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

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

129
  if lom then
126✔
130
    _M.walk(doc, false, function(_, d)
12✔
131
      setmetatable(d, Doc)
90✔
132
    end)
133
  end
134
  return doc
126✔
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)
12✔
160
  local s = _M.new(tag)
804✔
161
  if is_text(items) then items = {items} end
1,072✔
162
  if is_tag(items) then
1,072✔
163
    t_insert(s,items)
6✔
164
  elseif type(items) == 'table' then
798✔
165
    for k,v in pairs(items) do
1,476✔
166
      if is_text(k) then
1,352✔
167
        s.attr[k] = v
144✔
168
        t_insert(s.attr,k)
144✔
169
      else
170
        s[k] = v
870✔
171
      end
172
    end
173
  end
174
  return s
804✔
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)
12✔
193
  local ctors = {}
30✔
194
  if is_text(list) then
40✔
195
    list = split(list:match("^%s*(.-)%s*$"),'%s*,%s*')
32✔
196
  end
197
  for i,tag in ipairs(list) do
132✔
198
    local function ctor(items)
199
      return _M.elem(tag,items)
180✔
200
    end
201
    ctors[i] = ctor
102✔
202
  end
203
  return unpack(ctors)
30✔
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)
12✔
218
  local s = _M.new(tag, attrs)
144✔
219
  self:add_child(s)
144✔
220
  t_insert(self.last_add, s)
144✔
221
  return self
144✔
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)
12✔
234
  self:add_child(text)
108✔
235
  return self
108✔
236
end
237

238

239
--- Moves current position up one level.
240
-- @return the current node (`self`)
241
function Doc:up()
12✔
242
  t_remove(self.last_add)
108✔
243
  return self
108✔
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()
12✔
251
  local last_add = self.last_add
6✔
252
  for i = 1,#last_add do
24✔
253
    last_add[i] = nil
18✔
254
  end
255
  return self
6✔
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)
12✔
269
  t_insert(self, child)
378✔
270
  return self
378✔
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)
12✔
285
  (self.last_add[#self.last_add] or self):add_direct_child(child)
354✔
286
  return self
354✔
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)
12✔
300
  -- TODO: keep array part in sync
301
  for k,v in pairs(t) do
60✔
302
    self.attr[k] = v
36✔
303
  end
304
  return self
24✔
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)
12✔
314
  -- TODO: keep array part in sync
315
  self.attr[a] = v
12✔
316
  return self
12✔
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()
12✔
324
  return self.attr
6✔
325
end
326

327

328

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

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

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

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

UNCOV
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'
12✔
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
12✔
UNCOV
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)
12✔
378
    if type(data) ~= 'table' or not next(data) then
6✔
UNCOV
379
      return nil, "data must be a non-empty table"
×
380
    end
381

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

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

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

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

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

407
    if data.tag then
6✔
UNCOV
408
      list = _M.elem(data.tag,list)
×
409
    end
410
    return list
6✔
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)
12✔
419
  for _, child in ipairs(self) do
18✔
420
    if child.tag == tag then
18✔
421
      return child
6✔
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
486✔
435
      if type(child) == 'table' then
276✔
436
        if child.tag == tag then
192✔
437
          t_insert(list, child)
42✔
438
        end
439
        if recurse then
192✔
440
          _children_with_name(child, tag, list, recurse)
192✔
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)
12✔
451
    local res = {}
18✔
452
    _children_with_name(self, tag, res, not dont_recurse)
18✔
453
    return res
18✔
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()
12✔
463
  local i = 0;
12✔
464
  return function (a)
465
    i = i + 1
30✔
466
    return a[i];
30✔
467
  end, self, i;
12✔
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()
12✔
475
  if #self == 0 then
12✔
UNCOV
476
    return
×
477
  end
478
  for _, t in ipairs(self) do
30✔
479
    if is_tag(t) then
32✔
480
      return t
6✔
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)
12✔
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;
UNCOV
495
  local tags = self
×
UNCOV
496
  local next_i = 1
×
497
  local max_i = #tags
×
498
  local node
499
  return function ()
UNCOV
500
      for i = next_i, max_i do
×
501
        node = tags[i];
502
        if (not tag or node.tag == tag) and
×
UNCOV
503
           (not xmlns or xmlns == node.attr.xmlns) then
×
504
          next_i = i + 1
×
505
          return node
×
506
        end
507
      end
UNCOV
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()
12✔
516
  local i = 0;
18✔
517
  return function (a)
518
    local v
519
      repeat
520
        i = i + 1
48✔
521
        v = self[i]
48✔
522
        if v and type(v) == 'table' then
48✔
523
          return v
30✔
524
        end
525
      until not v
18✔
526
    end, self[1], i;
24✔
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)
12✔
536
  local i = 1;
12✔
537

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

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

555
  return self;
12✔
556
end
557

558

559
do
560
  local escape_table = {
12✔
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)
12✔
575
    return (s_gsub(str, "['&<>\"]", escape_table))
498✔
576
  end
577
end
578
local xml_escape = _M.xml_escape
12✔
579

580
do
581
  local escape_table = {
12✔
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)
12✔
596
    return (str:gsub( "&(%a+);", escape_table))
960✔
597
  end
598
end
599
local xml_unescape = _M.xml_unescape
12✔
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
888✔
606
  local tag = t.tag
888✔
607

608
  local lf = ""
888✔
609
  if tag_indent then
888✔
610
    lf = '\n'..block_indent
108✔
611
  end
612

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

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

620
  local function write_attr(k,v)
621
    if s_find(k, "\1", 1, true) then
192✔
UNCOV
622
      nsid = nsid + 1
×
UNCOV
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
192✔
627
      t_insert(buf, alf..k.."='"..xml_escape(v).."'");
256✔
628
    end
629
  end
630

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

643
  local len = #t
888✔
644
  local has_children
645

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

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

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

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

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

665
    t_insert(buf, (has_children and lf or '').."</"..tag..">");
504✔
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)
12✔
678
  local buf = {}
354✔
679

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

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

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

694
  return t_concat(buf)
354✔
695
end
696

697

698
Doc.__tostring = _M.tostring
12✔
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)
12✔
710
  return _M.tostring(self, b_ind, t_ind, a_ind, xml_preface)
228✔
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()
12✔
724
  local res = {}
54✔
725
  for i,el in ipairs(self) do
120✔
726
    if is_text(el) then t_insert(res,el) end
88✔
727
  end
728
  return t_concat(res);
54✔
729
end
730

731

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

742
    if lookup_table[object] then
150✔
743
      error("recursion detected")
6✔
744
    end
745
    lookup_table[object] = true
144✔
746

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

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

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

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

768
    return setmetatable(new_table, getmetatable(object))
138✔
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)
12✔
789
    return _copy(doc, nil, nil, strsubst, {})
36✔
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
12✔
800

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

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

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

811
    if ty1 == 'string' then
336✔
812
      if t1 == t2 then
78✔
813
        return true
72✔
814
      else
815
        return false, 'text '..t1..' ~= text '..t2
6✔
816
      end
817
    end
818

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

823
    if recurse_check[t1] then
252✔
824
      return false, "recursive document"
6✔
825
    end
826
    recurse_check[t1] = true
246✔
827

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

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

836
    -- compare attributes
837
    for k,v in pairs(t1.attr) do
359✔
838
      local t2_value = t2.attr[k]
137✔
839
      if type(k) == "string" then
137✔
840
        if t2_value ~= v then return false, 'mismatch attrib' end
89✔
841
      else
842
        if t2_value ~= nil and t2_value ~= v then return false, "mismatch attrib order" end
48✔
843
      end
844
    end
845
    for k,v in pairs(t2.attr) do
323✔
846
      local t1_value = t1.attr[k]
107✔
847
      if type(k) == "string" then
107✔
848
        if t1_value ~= v then return false, 'mismatch attrib' end
77✔
849
      else
850
        if t1_value ~= nil and t1_value ~= v then return false, "mismatch attrib order" end
30✔
851
      end
852
    end
853

854
    -- compare children
855
    for i = 1, #t1 do
450✔
856
      local ok, err = _compare(t1[i], t2[i], recurse_check)
252✔
857
      if not ok then
252✔
858
        return ok, err
18✔
859
      end
860
    end
861
    return true
198✔
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)
12✔
871
    return _compare(t1, t2, {})
96✔
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
12✔
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
390✔
886
    for _,d in ipairs(doc) do
834✔
887
      if is_tag(d) then
608✔
888
        assert(not recurse_check[d], "recursion detected")
306✔
889
        recurse_check[d] = true
300✔
890
        _walk(d, depth_first, operation, recurse_check)
300✔
891
      end
892
    end
893
    if depth_first then operation(doc.tag, doc) end
378✔
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)
12✔
903
    return _walk(doc, depth_first, operation, {})
90✔
904
  end
905
end
906

907

908
local html_empty_elements = { --lists all HTML empty (void) elements
12✔
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)
12✔
929
    return _M.basic_parse(s,false,true)
18✔
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)
12✔
937
    local stack = {}
144✔
938
    local top = {}
144✔
939

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

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

1016
do
1017
  local match do
12✔
1018

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

1021
    local append_capture do
12✔
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)
216✔
1025
          if next(t,key) ~= nil then return false end
216✔
1026
          return key,value
132✔
1027
      end
1028

1029
      function append_capture(res,tbl)
10✔
1030
          if not empty(tbl) then -- no point in capturing empty tables...
288✔
1031
              local key
1032
              if tbl._ then  -- if $_ was set then it is meant as the top-level key for the captured table
216✔
1033
                  key = tbl._
132✔
1034
                  tbl._ = nil
132✔
1035
                  if empty(tbl) then return end
176✔
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)
216✔
1039
              if numkey == 0 then tbl = val end
216✔
1040
              if key then
216✔
1041
                  res[key] = tbl
132✔
1042
              else -- otherwise, we append the captured table
1043
                  t_insert(res,tbl)
84✔
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
522✔
1051
            pat = tonumber(pat)
204✔
1052
        end
1053
        return pat
522✔
1054
    end
1055

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

1062
    function match(d,pat,res,keep_going)
10✔
1063
        local ret = true
1,110✔
1064
        if d == nil then d = '' end --return false end
1,110✔
1065
        -- attribute string matching is straight equality, except if the pattern is a $ capture,
1066
        -- which always succeeds.
1067
        if is_text(d) then
1,480✔
1068
            if not is_text(pat) then return false end
624✔
1069
            if _M.debug then print(d,pat) end
468✔
1070
            if pat:find '^%$' then
468✔
1071
                return capture_attrib(res,pat,d)
432✔
1072
            else
1073
                return d == pat
36✔
1074
            end
1075
        else
1076
        if _M.debug then print(d.tag,pat.tag) end
642✔
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 '^(.-)%-$'
642✔
1081
            if tagpat then
642✔
1082
                tagpat = make_number(tagpat)
120✔
1083
                res[tagpat] = d.tag
90✔
1084
            end
1085
            if d.tag == pat.tag or tagpat then
642✔
1086

1087
                if not empty(pat.attr) then
744✔
1088
                    if empty(d.attr) then ret =  false
288✔
1089
                    else
1090
                        for prop,pval in pairs(pat.attr) do
492✔
1091
                            local dval = d.attr[prop]
276✔
1092
                            if not match(dval,pval,res) then ret = false;  break end
368✔
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
558✔
1098
                    local i,j = 1,1
390✔
1099
                    local function next_elem()
1100
                        j = j + 1  -- next child element of data
816✔
1101
                        if is_text(d[j]) then j = j + 1 end
1,088✔
1102
                        return j <= #d
816✔
1103
                    end
1104
                    repeat
1105
                        local p = pat[i]
588✔
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
784✔
1109
                            local found
1110
                            repeat
1111
                                local tbl = {}
228✔
1112
                                ret = match(d[j],p,tbl,false)
304✔
1113
                                if ret then
228✔
1114
                                    found = false --true
216✔
1115
                                    append_capture(res,tbl)
216✔
1116
                                end
1117
                            until not next_elem() or (found and not ret)
304✔
1118
                            i = i + 1
60✔
1119
                        else
1120
                            ret = match(d[j],p,res,false)
704✔
1121
                            if ret then i = i + 1 end
528✔
1122
                        end
1123
                    until not next_elem() or i > #pat -- run out of elements or patterns to match
784✔
1124
                    -- if every element in our pattern matched ok, then it's been a successful match
1125
                    if i > #pat then return true end
390✔
1126
                end
1127
                if ret then return true end
234✔
1128
            else
1129
                ret = false
84✔
1130
            end
1131
            -- keep going anyway - look at the children!
1132
            if keep_going then
150✔
1133
                for child in d:childtags() do
20✔
1134
                    ret = match(child,pat,res,keep_going)
16✔
1135
                    if ret then break end
12✔
1136
                end
1137
            end
1138
        end
1139
        return ret
150✔
1140
    end
1141
  end
1142

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

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

1163

1164
return _M
12✔
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