5 Several common useful Lua functions
11 Copyright 2008 Steven Barth <steven@midlink.org>
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
17 http://www.apache.org/licenses/LICENSE-2.0
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.
27 local io = require "io"
28 local math = require "math"
29 local table = require "table"
30 local debug = require "debug"
31 local ldebug = require "luci.debug"
32 local string = require "string"
33 local coroutine = require "coroutine"
35 local getmetatable, setmetatable = getmetatable, setmetatable
36 local rawget, rawset, unpack = rawget, rawset, unpack
37 local tostring, type, assert = tostring, type, assert
38 local ipairs, pairs, loadstring = ipairs, pairs, loadstring
39 local require, pcall, xpcall = require, pcall, xpcall
41 --- LuCI utility functions.
45 -- Pythonic string formatting extension
47 getmetatable("").__mod = function(a, b)
50 elseif type(b) == "table" then
51 return a:format(unpack(b))
59 -- Class helper routines
62 -- Instantiates a class
63 local function _instantiate(class, ...)
64 local inst = setmetatable({}, {__index = class})
73 --- Create a Class object (Python-style object model).
74 -- The class object can be instantiated by calling itself.
75 -- Any class functions or shared parameters can be attached to this object.
76 -- Attaching a table to the class object makes this table shared between
77 -- all instances of this class. For object parameters use the __init__ function.
78 -- Classes can inherit member functions and values from a base class.
79 -- Class can be instantiated by calling them. All parameters will be passed
80 -- to the __init__ function of this class - if such a function exists.
81 -- The __init__ function must be used to set any object parameters that are not shared
82 -- with other objects of this class. Any return values will be ignored.
83 -- @param base The base class to inherit from (optional)
84 -- @return A class object
88 return setmetatable({}, {
89 __call = _instantiate,
94 --- Test whether the given object is an instance of the given class.
95 -- @param object Object instance
96 -- @param class Class object to test against
97 -- @return Boolean indicating whether the object is an instance
100 function instanceof(object, class)
101 local meta = getmetatable(object)
102 while meta and meta.__index do
103 if meta.__index == class then
106 meta = getmetatable(meta.__index)
113 -- Scope manipulation routines
116 --- Create a new or get an already existing thread local store associated with
117 -- the current active coroutine. A thread local store is private a table object
118 -- whose values can't be accessed from outside of the running coroutine.
119 -- @return Table value representing the corresponding thread local store
120 function threadlocal()
123 local function get(self, key)
124 local c = coroutine.running()
125 local thread = coxpt[c] or c or 0
126 if not rawget(self, thread) then
129 return rawget(self, thread)[key]
132 local function set(self, key, value)
133 local c = coroutine.running()
134 local thread = coxpt[c] or c or 0
135 if not rawget(self, thread) then
136 rawset(self, thread, {})
138 rawget(self, thread)[key] = value
141 setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
148 -- Debugging routines
151 --- Write given object to stderr.
152 -- @param obj Value to write to stderr
153 -- @return Boolean indicating whether the write operation was successful
155 return io.stderr:write(tostring(obj) .. "\n")
158 --- Recursively dumps a table to stdout, useful for testing and debugging.
159 -- @param t Table value to dump
160 -- @param maxdepth Maximum depth
161 -- @return Always nil
162 function dumptable(t, maxdepth, i, seen)
164 seen = seen or setmetatable({}, {__mode="k"})
166 for k,v in pairs(t) do
167 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
168 if type(v) == "table" and (not maxdepth or i < maxdepth) then
171 dumptable(v, maxdepth, i+1, seen)
173 perror(string.rep("\t", i) .. "*** RECURSION ***")
181 -- String and data manipulation routines
184 --- Escapes all occurrences of the given character in given string.
185 -- @param s String value containing unescaped characters
186 -- @param c String value with character to escape (optional, defaults to "\")
187 -- @return String value with each occurrence of character escaped with "\"
188 function escape(s, c)
190 return s:gsub(c, "\\" .. c)
193 --- Create valid XML PCDATA from given string.
194 -- @param value String value containing the data to escape
195 -- @return String value containing the escaped data
196 function pcdata(value)
197 return value and tostring(value):gsub("[&\"'<>]", {
206 --- Strip HTML tags from given string.
207 -- @param value String containing the HTML text
208 -- @return String with HTML tags stripped of
209 function striptags(s)
210 return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
213 --- Splits given string on a defined separator sequence and return a table
214 -- containing the resulting substrings. The optional max parameter specifies
215 -- the number of bytes to process, regardless of the actual length of the given
216 -- string. The optional last parameter, regex, specifies whether the separator
217 -- sequence is interpreted as regular expression.
218 -- @param str String value containing the data to split up
219 -- @param pat String with separator pattern (optional, defaults to "\n")
220 -- @param max Maximum times to split (optional)
221 -- @param regex Boolean indicating whether to interpret the separator
222 -- pattern as regular expression (optional, default is false)
223 -- @return Table containing the resulting substrings
224 function split(str, pat, max, regex)
244 local s, e = str:find(pat, c, not regex)
246 if s and max < 0 then
249 t[#t+1] = str:sub(c, s and s - 1)
251 c = e and e + 1 or #str + 1
252 until not s or max < 0
257 --- Remove leading and trailing whitespace from given string value.
258 -- @param str String value containing whitespace padded data
259 -- @return String value with leading and trailing space removed
261 return (str:gsub("^%s*(.-)%s*$", "%1"))
264 --- Count the occurences of given substring in given string.
265 -- @param str String to search in
266 -- @param pattern String containing pattern to find
267 -- @return Number of found occurences
268 function cmatch(str, pat)
270 for _ in str:gmatch(pat) do count = count + 1 end
274 --- Parse certain units from the given string and return the canonical integer
275 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
276 -- Recognized units are:
277 -- o "y" - one year (60*60*24*366)
278 -- o "m" - one month (60*60*24*31)
279 -- o "w" - one week (60*60*24*7)
280 -- o "d" - one day (60*60*24)
281 -- o "h" - one hour (60*60)
282 -- o "min" - one minute (60)
283 -- o "kb" - one kilobyte (1024)
284 -- o "mb" - one megabyte (1024*1024)
285 -- o "gb" - one gigabyte (1024*1024*1024)
286 -- o "kib" - one si kilobyte (1000)
287 -- o "mib" - one si megabyte (1000*1000)
288 -- o "gib" - one si gigabyte (1000*1000*1000)
289 -- @param ustr String containing a numerical value with trailing unit
290 -- @return Number containing the canonical value
291 function parse_units(ustr)
298 y = 60 * 60 * 24 * 366,
299 m = 60 * 60 * 24 * 31,
300 w = 60 * 60 * 24 * 7,
308 gb = 1024 * 1024 * 1024,
310 -- storage sizes (si)
313 gib = 1000 * 1000 * 1000
316 -- parse input string
317 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
319 local num = spec:gsub("[^0-9%.]+$","")
320 local spn = spec:gsub("^[0-9%.]+", "")
322 if map[spn] or map[spn:sub(1,1)] then
323 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
333 -- also register functions above in the central string class for convenience
334 string.escape = escape
335 string.pcdata = pcdata
336 string.striptags = striptags
339 string.cmatch = cmatch
340 string.parse_units = parse_units
343 --- Appends numerically indexed tables or single objects to a given table.
344 -- @param src Target table
345 -- @param ... Objects to insert
346 -- @return Target table
347 function append(src, ...)
348 for i, a in ipairs({...}) do
349 if type(a) == "table" then
350 for j, v in ipairs(a) do
360 --- Combines two or more numerically indexed tables and single objects into one table.
361 -- @param tbl1 Table value to combine
362 -- @param tbl2 Table value to combine
363 -- @param ... More tables to combine
364 -- @return Table value containing all values of given tables
365 function combine(...)
366 return append({}, ...)
369 --- Checks whether the given table contains the given value.
370 -- @param table Table value
371 -- @param value Value to search within the given table
372 -- @return Boolean indicating whether the given value occurs within table
373 function contains(table, value)
374 for k, v in pairs(table) do
382 --- Update values in given table with the values from the second given table.
383 -- Both table are - in fact - merged together.
384 -- @param t Table which should be updated
385 -- @param updates Table containing the values to update
386 -- @return Always nil
387 function update(t, updates)
388 for k, v in pairs(updates) do
393 --- Retrieve all keys of given associative table.
394 -- @param t Table to extract keys from
395 -- @return Sorted table containing the keys
399 for k, _ in kspairs(t) do
406 --- Clones the given object and return it's copy.
407 -- @param object Table value to clone
408 -- @param deep Boolean indicating whether to do recursive cloning
409 -- @return Cloned table value
410 function clone(object, deep)
413 for k, v in pairs(object) do
414 if deep and type(v) == "table" then
420 return setmetatable(copy, getmetatable(object))
424 --- Create a dynamic table which automatically creates subtables.
425 -- @return Dynamic Table
427 return setmetatable({}, { __index =
429 return rawget(tbl, key)
430 or rawget(rawset(tbl, key, dtable()), key)
436 -- Serialize the contents of a table value.
437 function _serialize_table(t, seen)
438 assert(not seen[t], "Recursion detected.")
445 for k, v in pairs(t) do
446 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
447 k = serialize_data(k, seen)
448 v = serialize_data(v, seen)
449 data = data .. ( #data > 0 and ", " or "" ) ..
450 '[' .. k .. '] = ' .. v
457 local v = serialize_data(t[i], seen)
458 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
461 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
464 --- Recursively serialize given data to lua code, suitable for restoring
465 -- with loadstring().
466 -- @param val Value containing the data to serialize
467 -- @return String value containing the serialized code
470 function serialize_data(val, seen)
471 seen = seen or setmetatable({}, {__mode="k"})
475 elseif type(val) == "number" then
477 elseif type(val) == "string" then
479 elseif type(val) == "boolean" then
480 return val and "true" or "false"
481 elseif type(val) == "function" then
482 return "loadstring(%q)" % get_bytecode(val)
483 elseif type(val) == "table" then
484 return "{ " .. _serialize_table(val, seen) .. " }"
486 return '"[unhandled data type:' .. type(val) .. ']"'
490 --- Restore data previously serialized with serialize_data().
491 -- @param str String containing the data to restore
492 -- @return Value containing the restored data structure
493 -- @see serialize_data
495 function restore_data(str)
496 return loadstring("return " .. str)()
501 -- Byte code manipulation routines
504 --- Return the current runtime bytecode of the given data. The byte code
505 -- will be stripped before it is returned.
506 -- @param val Value to return as bytecode
507 -- @return String value containing the bytecode of the given data
508 function get_bytecode(val)
511 if type(val) == "function" then
512 code = string.dump(val)
514 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
517 return code and strip_bytecode(code)
520 --- Strips unnescessary lua bytecode from given string. Information like line
521 -- numbers and debugging numbers will be discarded. Original version by
522 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
523 -- @param code String value containing the original lua byte code
524 -- @return String value containing the stripped lua byte code
525 function strip_bytecode(code)
526 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
529 subint = function(code, i, l)
532 val = val * 256 + code:byte(i + n - 1)
537 subint = function(code, i, l)
540 val = val * 256 + code:byte(i + n - 1)
547 strip_function = function(code)
548 local count, offset = subint(code, 1, size)
549 local stripped, dirty = string.rep("\0", size), offset + count
550 offset = offset + count + int * 2 + 4
551 offset = offset + int + subint(code, offset, int) * ins
552 count, offset = subint(code, offset, int)
555 t, offset = subint(code, offset, 1)
559 offset = offset + size + subint(code, offset, size)
561 offset = offset + num
562 elseif t == 254 or t == 9 then
563 offset = offset + lnum
566 count, offset = subint(code, offset, int)
567 stripped = stripped .. code:sub(dirty, offset - 1)
569 local proto, off = strip_function(code:sub(offset, -1))
570 stripped, offset = stripped .. proto, offset + off - 1
572 offset = offset + subint(code, offset, int) * int + int
573 count, offset = subint(code, offset, int)
575 offset = offset + subint(code, offset, size) + size + int * 2
577 count, offset = subint(code, offset, int)
579 offset = offset + subint(code, offset, size) + size
581 stripped = stripped .. string.rep("\0", int * 3)
582 return stripped, offset
585 return code:sub(1,12) .. strip_function(code:sub(13,-1))
590 -- Sorting iterator functions
593 function _sortiter( t, f )
596 for k, v in pairs(t) do
602 table.sort( keys, f )
606 if _pos <= #keys then
607 return keys[_pos], t[keys[_pos]]
612 --- Return a key, value iterator which returns the values sorted according to
613 -- the provided callback function.
614 -- @param t The table to iterate
615 -- @param f A callback function to decide the order of elements
616 -- @return Function value containing the corresponding iterator
618 return _sortiter( t, f )
621 --- Return a key, value iterator for the given table.
622 -- The table pairs are sorted by key.
623 -- @param t The table to iterate
624 -- @return Function value containing the corresponding iterator
626 return _sortiter( t )
629 --- Return a key, value iterator for the given table.
630 -- The table pairs are sorted by value.
631 -- @param t The table to iterate
632 -- @return Function value containing the corresponding iterator
634 return _sortiter( t, function (a,b) return t[a] < t[b] end )
639 -- System utility functions
642 --- Test whether the current system is operating in big endian mode.
643 -- @return Boolean value indicating whether system is big endian
645 return string.byte(string.dump(function() end), 7) == 0
648 --- Execute given commandline and gather stdout.
649 -- @param command String containing command to execute
650 -- @return String containing the command's stdout
651 function exec(command)
652 local pp = io.popen(command)
653 local data = pp:read("*a")
659 --- Return a line-buffered iterator over the output of given command.
660 -- @param command String containing the command to execute
662 function execi(command)
663 local pp = io.popen(command)
665 return pp and function()
666 local line = pp:read()
677 function execl(command)
678 local pp = io.popen(command)
684 if (line == nil) then break end
692 --- Returns the absolute path to LuCI base directory.
693 -- @return String containing the directory path
695 return require "luci.fs".dirname(ldebug.__file__)
700 -- Coroutine safe xpcall and pcall versions modified for Luci
702 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
704 -- Copyright © 2005 Kepler Project.
705 -- Permission is hereby granted, free of charge, to any person obtaining a
706 -- copy of this software and associated documentation files (the "Software"),
707 -- to deal in the Software without restriction, including without limitation
708 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
709 -- and/or sell copies of the Software, and to permit persons to whom the
710 -- Software is furnished to do so, subject to the following conditions:
712 -- The above copyright notice and this permission notice shall be
713 -- included in all copies or substantial portions of the Software.
715 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
716 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
717 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
718 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
719 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
720 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
721 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
723 local performResume, handleReturnValue
724 local oldpcall, oldxpcall = pcall, xpcall
726 setmetatable(coxpt, {__mode = "kv"})
728 -- Identity function for copcall
729 local function copcall_id(trace, ...)
733 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
734 -- @param f Lua function to be called protected
735 -- @param err Custom error handler
736 -- @param ... Parameters passed to the function
737 -- @return A boolean whether the function call succeeded and the return
738 -- values of either the function or the error handler
739 function coxpcall(f, err, ...)
740 local res, co = oldpcall(coroutine.create, f)
743 local newf = function() return f(unpack(params)) end
744 co = coroutine.create(newf)
746 local c = coroutine.running()
747 coxpt[co] = coxpt[c] or c or 0
749 return performResume(err, co, ...)
752 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
753 -- @param f Lua function to be called protected
754 -- @param ... Parameters passed to the function
755 -- @return A boolean whether the function call succeeded and the returns
756 -- values of the function or the error object
757 function copcall(f, ...)
758 return coxpcall(f, copcall_id, ...)
761 -- Handle return value of protected call
762 function handleReturnValue(err, co, status, ...)
764 return false, err(debug.traceback(co, (...)), ...)
766 if coroutine.status(co) == 'suspended' then
767 return performResume(err, co, coroutine.yield(...))
773 -- Resume execution of protected function call
774 function performResume(err, co, ...)
775 return handleReturnValue(err, co, coroutine.resume(co, ...))