Added maxdepth to luci.util.dumptable
[project/luci.git] / libs / core / luasrc / util.lua
1 --[[
2 LuCI - Utility library
3
4 Description:
5 Several common useful Lua functions
6
7 FileId:
8 $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
16
17         http://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26
27 --- LuCI utility functions.
28 module("luci.util", package.seeall)
29
30 --
31 -- Pythonic string formatting extension
32 --
33 getmetatable("").__mod = function(a, b)
34         if not b then
35                 return a
36         elseif type(b) == "table" then
37                 return a:format(unpack(b))
38         else
39                 return a:format(b)
40         end
41 end
42
43
44 --
45 -- Class helper routines
46 --
47
48 --- Create a Class object (Python-style object model).
49 -- The class object can be instantiated by calling itself.
50 -- Any class functions or shared parameters can be attached to this object.
51 -- Attaching a table to the class object makes this table shared between
52 -- all instances of this class. For object parameters use the __init__ function.
53 -- Classes can inherit member functions and values from a base class.
54 -- Class can be instantiated by calling them. All parameters will be passed
55 -- to the __init__ function of this class - if such a function exists.
56 -- The __init__ function must be used to set any object parameters that are not shared
57 -- with other objects of this class. Any return values will be ignored.
58 -- @param base  The base class to inherit from (optional)
59 -- @return              A class object
60 -- @see                 instanceof
61 -- @see                 clone
62 function class(base)
63         local class = {}
64
65         local create = function(class, ...)
66                 local inst = {}
67                 setmetatable(inst, {__index = class})
68
69                 if inst.__init__ then
70                         local stat, err = copcall(inst.__init__, inst, ...)
71                         if not stat then
72                                 error(err)
73                         end
74                 end
75
76                 return inst
77         end
78
79         local classmeta = {__call = create}
80
81         if base then
82                 classmeta.__index = base
83         end
84
85         setmetatable(class, classmeta)
86         return class
87 end
88
89 --- Test whether the given object is an instance of the given class.
90 -- @param object        Object instance
91 -- @param class         Class object to test against
92 -- @return                      Boolean indicating whether the object is an instance
93 -- @see                         class
94 -- @see                         clone
95 function instanceof(object, class)
96         local meta = getmetatable(object)
97         while meta and meta.__index do
98                 if meta.__index == class then
99                         return true
100                 end
101                 meta = getmetatable(meta.__index)
102         end
103         return false
104 end
105
106
107 --
108 -- Scope manipulation routines
109 --
110
111 --- Replace a function scope with a shallow copy of itself.
112 -- This is useful if you want to get rid of several unwanted side effects
113 -- while changing the scope of a certain Lua function.
114 -- @param f             Lua function
115 function resfenv(f)
116         setfenv(f, clone(getfenv(f)))
117 end
118
119 --- Store given object associated with given key in the scope of a function.
120 -- @param f             Lua function
121 -- @param key   String value containg the key of the object to store
122 -- @param obj   Object to store in the scope
123 -- @return              Always nil
124 -- @see updfenv
125 -- @see resfenv
126 function extfenv(f, key, obj)
127         local scope = getfenv(f)
128         scope[key] = obj
129 end
130
131 --- Extend the scope of a function with the contents of a table
132 -- @param f             Lua function
133 -- @param key   String value containg the key of the object to store
134 -- @param obj   Object to store in the scope
135 -- @return              Always nil
136 -- @see extfenv
137 -- @see resfenv
138 function updfenv(f, extscope)
139         update(getfenv(f), extscope)
140 end
141
142 --- Create a new or get an already existing thread local store associated with
143 -- the current active coroutine. A thread local store is private a table object
144 -- whose values can't be accessed from outside of the running coroutine.
145 -- @return      Table value representing the corresponding thread local store
146 function threadlocal()
147         local tbl = {}
148
149         local function get(self, key)
150                 local c = coroutine.running()
151                 local thread = coxpt[c] or c or 0
152                 if not rawget(self, thread) then
153                         return nil
154                 end
155                 return rawget(self, thread)[key]
156         end
157
158         local function set(self, key, value)
159                 local c = coroutine.running()
160                 local thread = coxpt[c] or c or 0
161                 if not rawget(self, thread) then
162                         rawset(self, thread, {})
163                 end
164                 rawget(self, thread)[key] = value
165         end
166
167         setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
168
169         return tbl
170 end
171
172
173 --
174 -- Debugging routines
175 --
176
177 --- Write given object to stderr.
178 -- @param obj   Value to write to stderr
179 -- @return              Boolean indicating whether the write operation was successful
180 function perror(obj)
181         return io.stderr:write(tostring(obj) .. "\n")
182 end
183
184 --- Recursively dumps a table to stdout, useful for testing and debugging.
185 -- @param t     Table value to dump
186 -- @param maxdepth      Maximum depth
187 -- @return      Always nil
188 function dumptable(t, maxdepth, i, seen)
189         i = i or 0
190         seen = seen or setmetatable({}, {__mode="k"})
191         
192         for k,v in pairs(t) do
193                 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
194                 if type(v) == "table" and i < maxdepth then
195                         if not seen[v] then
196                                 seen[v] = true
197                                 dumptable(v, maxdepth, i+1, seen)
198                         else
199                                 perror(string.rep("\t", i) .. "*** RECURSION ***")
200                         end
201                 end
202         end
203 end
204
205
206 --
207 -- String and data manipulation routines
208 --
209
210 --- Escapes all occurrences of the given character in given string.
211 -- @param s     String value containing unescaped characters
212 -- @param c     String value with character to escape (optional, defaults to "\")
213 -- @return      String value with each occurrence of character escaped with "\"
214 function escape(s, c)
215         c = c or "\\"
216         return s:gsub(c, "\\" .. c)
217 end
218
219 --- Create valid XML PCDATA from given string.
220 -- @param value String value containing the data to escape
221 -- @return              String value containing the escaped data
222 function pcdata(value)
223         if not value then return end
224         value = tostring(value)
225         value = value:gsub("&", "&amp;")
226         value = value:gsub('"', "&quot;")
227         value = value:gsub("'", "&apos;")
228         value = value:gsub("<", "&lt;")
229         return value:gsub(">", "&gt;")
230 end
231
232 --- Strip HTML tags from given string.
233 -- @param value String containing the HTML text
234 -- @return      String with HTML tags stripped of
235 function striptags(s)
236         return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
237 end
238
239 --- Splits given string on a defined separator sequence and return a table
240 -- containing the resulting substrings. The optional max parameter specifies
241 -- the number of bytes to process, regardless of the actual length of the given
242 -- string. The optional last parameter, regex, specifies whether the separator
243 -- sequence is interpreted as regular expression.
244 -- @param str           String value containing the data to split up
245 -- @param pat           String with separator pattern (optional, defaults to "\n")
246 -- @param max           Maximum times to split (optional)
247 -- @param regex         Boolean indicating whether to interpret the separator
248 --                                      pattern as regular expression (optional, default is false)
249 -- @return                      Table containing the resulting substrings
250 function split(str, pat, max, regex)
251         pat = pat or "\n"
252         max = max or #str
253
254         local t = {}
255         local c = 1
256
257         if #str == 0 then
258                 return {""}
259         end
260
261         if #pat == 0 then
262                 return nil
263         end
264
265         if max == 0 then
266                 return str
267         end
268
269         repeat
270                 local s, e = str:find(pat, c, not regex)
271                 max = max - 1
272                 if s and max < 0 then
273                         table.insert(t, str:sub(c))
274                 else
275                         table.insert(t, str:sub(c, s and s - 1))
276                 end
277                 c = e and e + 1 or #str + 1
278         until not s or max < 0
279
280         return t
281 end
282
283 --- Remove leading and trailing whitespace from given string value.
284 -- @param str   String value containing whitespace padded data
285 -- @return              String value with leading and trailing space removed
286 function trim(str)
287         local s = str:gsub("^%s*(.-)%s*$", "%1")
288         return s
289 end
290
291 --- Parse certain units from the given string and return the canonical integer
292 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
293 -- Recognized units are:
294 --      o "y"   - one year   (60*60*24*366)
295 --  o "m"       - one month  (60*60*24*31)
296 --  o "w"       - one week   (60*60*24*7)
297 --  o "d"       - one day    (60*60*24)
298 --  o "h"       - one hour       (60*60)
299 --  o "min"     - one minute (60)
300 --  o "kb"  - one kilobyte (1024)
301 --  o "mb"      - one megabyte (1024*1024)
302 --  o "gb"      - one gigabyte (1024*1024*1024)
303 --  o "kib" - one si kilobyte (1000)
304 --  o "mib"     - one si megabyte (1000*1000)
305 --  o "gib"     - one si gigabyte (1000*1000*1000)
306 -- @param ustr  String containing a numerical value with trailing unit
307 -- @return              Number containing the canonical value
308 function parse_units(ustr)
309
310         local val = 0
311
312         -- unit map
313         local map = {
314                 -- date stuff
315                 y   = 60 * 60 * 24 * 366,
316                 m   = 60 * 60 * 24 * 31,
317                 w   = 60 * 60 * 24 * 7,
318                 d   = 60 * 60 * 24,
319                 h   = 60 * 60,
320                 min = 60,
321
322                 -- storage sizes
323                 kb  = 1024,
324                 mb  = 1024 * 1024,
325                 gb  = 1024 * 1024 * 1024,
326
327                 -- storage sizes (si)
328                 kib = 1000,
329                 mib = 1000 * 1000,
330                 gib = 1000 * 1000 * 1000
331         }
332
333         -- parse input string
334         for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
335
336                 local num = spec:gsub("[^0-9%.]+$","")
337                 local spn = spec:gsub("^[0-9%.]+", "")
338
339                 if map[spn] or map[spn:sub(1,1)] then
340                         val = val + num * ( map[spn] or map[spn:sub(1,1)] )
341                 else
342                         val = val + num
343                 end
344         end
345
346
347         return val
348 end
349
350 --- Combines two or more numerically indexed tables into one.
351 -- @param tbl1  Table value to combine
352 -- @param tbl2  Table value to combine
353 -- @param ...   More tables to combine
354 -- @return              Table value containing all values of given tables
355 function combine(...)
356         local result = {}
357         for i, a in ipairs(arg) do
358                 for j, v in ipairs(a) do
359                         table.insert(result, v)
360                 end
361         end
362         return result
363 end
364
365 --- Checks whether the given table contains the given value.
366 -- @param table Table value
367 -- @param value Value to search within the given table
368 -- @return              Boolean indicating whether the given value occurs within table
369 function contains(table, value)
370         for k, v in pairs(table) do
371                 if value == v then
372                         return k
373                 end
374         end
375         return false
376 end
377
378 --- Update values in given table with the values from the second given table.
379 -- Both table are - in fact - merged together.
380 -- @param t                     Table which should be updated
381 -- @param updates       Table containing the values to update
382 -- @return                      Always nil
383 function update(t, updates)
384         for k, v in pairs(updates) do
385                 t[k] = v
386         end
387 end
388
389 --- Retrieve all keys of given associative table.
390 -- @param t     Table to extract keys from
391 -- @return      Sorted table containing the keys
392 function keys(t)
393         local keys = { }
394         if t then
395                 for k, _ in kspairs(t) do
396                         table.insert( keys, k )
397                 end
398         end
399         return keys
400 end
401
402 --- Clones the given object and return it's copy.
403 -- @param object        Table value to clone
404 -- @param deep          Boolean indicating whether to do recursive cloning
405 -- @return                      Cloned table value
406 function clone(object, deep)
407         local copy = {}
408
409         for k, v in pairs(object) do
410                 if deep and type(v) == "table" then
411                         v = clone(v, deep)
412                 end
413                 copy[k] = v
414         end
415
416         setmetatable(copy, getmetatable(object))
417
418         return copy
419 end
420
421
422 --- Create a dynamic table which automatically creates subtables.
423 -- @return      Dynamic Table
424 function dtable()
425         return setmetatable({}, { __index =
426                 function(tbl, key)
427                         return rawget(tbl, key)
428                          or rawget(rawset(tbl, key, dtable()), key)
429                 end
430         })
431 end
432
433
434 -- Serialize the contents of a table value.
435 function _serialize_table(t, seen)
436         assert(not seen[t], "Recursion detected.")
437         seen[t] = true
438         
439         local data  = ""
440         local idata = ""
441         local ilen  = 0
442
443         for k, v in pairs(t) do
444                 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
445                         k = serialize_data(k, seen)
446                         v = serialize_data(v, seen)
447                         data = data .. ( #data > 0 and ", " or "" ) ..
448                                 '[' .. k .. '] = ' .. v
449                 elseif k > ilen then
450                         ilen = k
451                 end
452         end
453
454         for i = 1, ilen do
455                 local v = serialize_data(t[i], seen)
456                 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
457         end             
458
459         return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
460 end
461
462 --- Recursively serialize given data to lua code, suitable for restoring
463 -- with loadstring().
464 -- @param val   Value containing the data to serialize
465 -- @return              String value containing the serialized code
466 -- @see                 restore_data
467 -- @see                 get_bytecode
468 function serialize_data(val, seen)
469         seen = seen or setmetatable({}, {__mode="k"})
470         
471         if val == nil then
472                 return "nil"
473         elseif type(val) == "number" then
474                 return val
475         elseif type(val) == "string" then
476                 return string.format("%q", val)
477         elseif type(val) == "boolean" then
478                 return val and "true" or "false"
479         elseif type(val) == "function" then
480                 return string.format("loadstring(%q)", get_bytecode(val))
481         elseif type(val) == "table" then
482                 return "{ " .. _serialize_table(val, seen) .. " }"
483         else
484                 return '"[unhandled data type:' .. type(val) .. ']"'
485         end
486 end
487
488 --- Restore data previously serialized with serialize_data().
489 -- @param str   String containing the data to restore
490 -- @return              Value containing the restored data structure
491 -- @see                 serialize_data
492 -- @see                 get_bytecode
493 function restore_data(str)
494         return loadstring("return " .. str)()
495 end
496
497
498 --
499 -- Byte code manipulation routines
500 --
501
502 --- Return the current runtime bytecode of the given data. The byte code
503 -- will be stripped before it is returned.
504 -- @param val   Value to return as bytecode
505 -- @return              String value containing the bytecode of the given data
506 function get_bytecode(val)
507         local code
508
509         if type(val) == "function" then
510                 code = string.dump(val)
511         else
512                 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
513         end
514
515         return code and strip_bytecode(code)
516 end
517
518 --- Strips unnescessary lua bytecode from given string. Information like line
519 -- numbers and debugging numbers will be discarded. Original version by
520 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
521 -- @param code  String value containing the original lua byte code
522 -- @return              String value containing the stripped lua byte code
523 function strip_bytecode(code)
524         local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
525         local subint
526         if endian == 1 then
527                 subint = function(code, i, l)
528                         local val = 0
529                         for n = l, 1, -1 do
530                                 val = val * 256 + code:byte(i + n - 1)
531                         end
532                         return val, i + l
533                 end
534         else
535                 subint = function(code, i, l)
536                         local val = 0
537                         for n = 1, l, 1 do
538                                 val = val * 256 + code:byte(i + n - 1)
539                         end
540                         return val, i + l
541                 end
542         end
543
544         local strip_function
545         strip_function = function(code)
546                 local count, offset = subint(code, 1, size)
547                 local stripped, dirty = string.rep("\0", size), offset + count
548                 offset = offset + count + int * 2 + 4
549                 offset = offset + int + subint(code, offset, int) * ins
550                 count, offset = subint(code, offset, int)
551                 for n = 1, count do
552                         local t
553                         t, offset = subint(code, offset, 1)
554                         if t == 1 then
555                                 offset = offset + 1
556                         elseif t == 4 then
557                                 offset = offset + size + subint(code, offset, size)
558                         elseif t == 3 then
559                                 offset = offset + num
560                         elseif t == 254 or t == 9 then
561                                 offset = offset + lnum
562                         end
563                 end
564                 count, offset = subint(code, offset, int)
565                 stripped = stripped .. code:sub(dirty, offset - 1)
566                 for n = 1, count do
567                         local proto, off = strip_function(code:sub(offset, -1))
568                         stripped, offset = stripped .. proto, offset + off - 1
569                 end
570                 offset = offset + subint(code, offset, int) * int + int
571                 count, offset = subint(code, offset, int)
572                 for n = 1, count do
573                         offset = offset + subint(code, offset, size) + size + int * 2
574                 end
575                 count, offset = subint(code, offset, int)
576                 for n = 1, count do
577                         offset = offset + subint(code, offset, size) + size
578                 end
579                 stripped = stripped .. string.rep("\0", int * 3)
580                 return stripped, offset
581         end
582
583         return code:sub(1,12) .. strip_function(code:sub(13,-1))
584 end
585
586
587 --
588 -- Sorting iterator functions
589 --
590
591 function _sortiter( t, f )
592         local keys = { }
593
594         for k, v in pairs(t) do
595                 table.insert( keys, k )
596         end
597
598         local _pos = 0
599         local _len = table.getn( keys )
600
601         table.sort( keys, f )
602
603         return function()
604                 _pos = _pos + 1
605                 if _pos <= _len then
606                         return keys[_pos], t[keys[_pos]]
607                 end
608         end
609 end
610
611 --- Return a key, value iterator which returns the values sorted according to
612 -- the provided callback function.
613 -- @param t     The table to iterate
614 -- @param f A callback function to decide the order of elements
615 -- @return      Function value containing the corresponding iterator
616 function spairs(t,f)
617         return _sortiter( t, f )
618 end
619
620 --- Return a key, value iterator for the given table.
621 -- The table pairs are sorted by key.
622 -- @param t     The table to iterate
623 -- @return      Function value containing the corresponding iterator
624 function kspairs(t)
625         return _sortiter( t )
626 end
627
628 --- Return a key, value iterator for the given table.
629 -- The table pairs are sorted by value.
630 -- @param t     The table to iterate
631 -- @return      Function value containing the corresponding iterator
632 function vspairs(t)
633         return _sortiter( t, function (a,b) return t[a] < t[b] end )
634 end
635
636
637 --
638 -- System utility functions
639 --
640
641 --- Test whether the current system is operating in big endian mode.
642 -- @return      Boolean value indicating whether system is big endian
643 function bigendian()
644         return string.byte(string.dump(function() end), 7) == 0
645 end
646
647 --- Execute given commandline and gather stdout.
648 -- @param command       String containing command to execute
649 -- @return                      String containing the command's stdout
650 function exec(command)
651         local pp   = io.popen(command)
652         local data = pp:read("*a")
653         pp:close()
654
655         return data
656 end
657
658 --- Return a line-buffered iterator over the output of given command.
659 -- @param command       String containing the command to execute
660 -- @return                      Iterator
661 function execi(command)
662         local pp = io.popen(command)
663
664         return pp and function()
665                 local line = pp:read()
666                 
667                 if not line then
668                         pp:close()
669                 end
670                 
671                 return line
672         end
673 end
674
675 -- Deprecated
676 function execl(command)
677         local pp   = io.popen(command)
678         local line = ""
679         local data = {}
680
681         while true do
682                 line = pp:read()
683                 if (line == nil) then break end
684                 table.insert(data, line)
685         end
686         pp:close()
687
688         return data
689 end
690
691 --- Returns the absolute path to LuCI base directory.
692 -- @return              String containing the directory path
693 function libpath()
694         return luci.fs.dirname(require("luci.debug").__file__)
695 end
696
697
698 --
699 -- Coroutine safe xpcall and pcall versions modified for Luci
700 -- original version:
701 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
702 --
703 -- Copyright © 2005 Kepler Project.
704 -- Permission is hereby granted, free of charge, to any person obtaining a
705 -- copy of this software and associated documentation files (the "Software"),
706 -- to deal in the Software without restriction, including without limitation
707 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
708 -- and/or sell copies of the Software, and to permit persons to whom the
709 -- Software is furnished to do so, subject to the following conditions:
710 --
711 -- The above copyright notice and this permission notice shall be
712 -- included in all copies or substantial portions of the Software.
713 --
714 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
715 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
716 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
717 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
718 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
719 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
720 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
721
722 local performResume, handleReturnValue
723 local oldpcall, oldxpcall = pcall, xpcall
724 coxpt = {}
725 setmetatable(coxpt, {__mode = "kv"})
726
727 -- Identity function for copcall
728 local function copcall_id(trace, ...)
729   return ...
730 end
731
732 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
733 -- @param f             Lua function to be called protected
734 -- @param err   Custom error handler
735 -- @param ...   Parameters passed to the function
736 -- @return              A boolean whether the function call succeeded and the return
737 --                              values of either the function or the error handler
738 function coxpcall(f, err, ...)
739         local res, co = oldpcall(coroutine.create, f)
740         if not res then
741                 local params = {...}
742                 local newf = function() return f(unpack(params)) end
743                 co = coroutine.create(newf)
744         end
745         local c = coroutine.running()
746         coxpt[co] = coxpt[c] or c or 0
747
748         return performResume(err, co, ...)
749 end
750
751 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
752 -- @param f             Lua function to be called protected
753 -- @param ...   Parameters passed to the function
754 -- @return              A boolean whether the function call succeeded and the returns
755 --                              values of the function or the error object
756 function copcall(f, ...)
757         return coxpcall(f, copcall_id, ...)
758 end
759
760 -- Handle return value of protected call
761 function handleReturnValue(err, co, status, ...)
762         if not status then
763                 return false, err(debug.traceback(co, (...)), ...)
764         end
765         if coroutine.status(co) == 'suspended' then
766                 return performResume(err, co, coroutine.yield(...))
767         else
768                 return true, ...
769         end
770 end
771
772 -- Resume execution of protected function call
773 function performResume(err, co, ...)
774         return handleReturnValue(err, co, coroutine.resume(co, ...))
775 end