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"
34 local cutil = require "luci.cutil"
36 local getmetatable, setmetatable = getmetatable, setmetatable
37 local rawget, rawset, unpack = rawget, rawset, unpack
38 local tostring, type, assert = tostring, type, assert
39 local ipairs, pairs, loadstring = ipairs, pairs, loadstring
40 local require, pcall, xpcall = require, pcall, xpcall
42 --- LuCI utility functions.
46 -- Pythonic string formatting extension
49 getmetatable("").__mod = function(a, b)
52 elseif type(b) == "table" then
53 return a:format(unpack(b))
62 -- Class helper routines
65 -- Instantiates a class
67 local function _instantiate(class, ...)
68 local inst = setmetatable({}, {__index = class})
78 --- Create a Class object (Python-style object model).
79 -- The class object can be instantiated by calling itself.
80 -- Any class functions or shared parameters can be attached to this object.
81 -- Attaching a table to the class object makes this table shared between
82 -- all instances of this class. For object parameters use the __init__ function.
83 -- Classes can inherit member functions and values from a base class.
84 -- Class can be instantiated by calling them. All parameters will be passed
85 -- to the __init__ function of this class - if such a function exists.
86 -- The __init__ function must be used to set any object parameters that are not shared
87 -- with other objects of this class. Any return values will be ignored.
88 -- @param base The base class to inherit from (optional)
89 -- @return A class object
94 return setmetatable({}, {
95 __call = _instantiate,
102 --- Test whether the given object is an instance of the given class.
103 -- @param object Object instance
104 -- @param class Class object to test against
105 -- @return Boolean indicating whether the object is an instance
109 function instanceof(object, class)
110 local meta = getmetatable(object)
111 while meta and meta.__index do
112 if meta.__index == class then
115 meta = getmetatable(meta.__index)
120 instanceof = cutil.instanceof
124 -- Scope manipulation routines
127 --- Create a new or get an already existing thread local store associated with
128 -- the current active coroutine. A thread local store is private a table object
129 -- whose values can't be accessed from outside of the running coroutine.
130 -- @return Table value representing the corresponding thread local store
131 function threadlocal()
134 local function get(self, key)
135 local c = coroutine.running()
136 local thread = coxpt[c] or c or 0
137 if not rawget(self, thread) then
140 return rawget(self, thread)[key]
143 local function set(self, key, value)
144 local c = coroutine.running()
145 local thread = coxpt[c] or c or 0
146 if not rawget(self, thread) then
147 rawset(self, thread, {})
149 rawget(self, thread)[key] = value
152 setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
159 -- Debugging routines
162 --- Write given object to stderr.
163 -- @param obj Value to write to stderr
164 -- @return Boolean indicating whether the write operation was successful
166 return io.stderr:write(tostring(obj) .. "\n")
169 --- Recursively dumps a table to stdout, useful for testing and debugging.
170 -- @param t Table value to dump
171 -- @param maxdepth Maximum depth
172 -- @return Always nil
173 function dumptable(t, maxdepth, i, seen)
175 seen = seen or setmetatable({}, {__mode="k"})
177 for k,v in pairs(t) do
178 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
179 if type(v) == "table" and (not maxdepth or i < maxdepth) then
182 dumptable(v, maxdepth, i+1, seen)
184 perror(string.rep("\t", i) .. "*** RECURSION ***")
192 -- String and data manipulation routines
195 --- Escapes all occurrences of the given character in given string.
196 -- @param s String value containing unescaped characters
197 -- @param c String value with character to escape (optional, defaults to "\")
198 -- @return String value with each occurrence of character escaped with "\"
199 function escape(s, c)
201 return s:gsub(c, "\\" .. c)
204 --- Create valid XML PCDATA from given string.
205 -- @param value String value containing the data to escape
206 -- @return String value containing the escaped data
208 function pcdata(value)
209 return value and tostring(value):gsub("[&\"'<>]", {
218 pcdata = cutil.pcdata
220 --- Strip HTML tags from given string.
221 -- @param value String containing the HTML text
222 -- @return String with HTML tags stripped of
223 function striptags(s)
224 return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
227 --- Splits given string on a defined separator sequence and return a table
228 -- containing the resulting substrings. The optional max parameter specifies
229 -- the number of bytes to process, regardless of the actual length of the given
230 -- string. The optional last parameter, regex, specifies whether the separator
231 -- sequence is interpreted as regular expression.
232 -- @param str String value containing the data to split up
233 -- @param pat String with separator pattern (optional, defaults to "\n")
234 -- @param max Maximum times to split (optional)
235 -- @param regex Boolean indicating whether to interpret the separator
236 -- pattern as regular expression (optional, default is false)
237 -- @return Table containing the resulting substrings
238 function split(str, pat, max, regex)
258 local s, e = str:find(pat, c, not regex)
260 if s and max < 0 then
263 t[#t+1] = str:sub(c, s and s - 1)
265 c = e and e + 1 or #str + 1
266 until not s or max < 0
271 --- Remove leading and trailing whitespace from given string value.
272 -- @param str String value containing whitespace padded data
273 -- @return String value with leading and trailing space removed
276 return (str:gsub("^%s*(.-)%s*$", "%1"))
281 --- Count the occurences of given substring in given string.
282 -- @param str String to search in
283 -- @param pattern String containing pattern to find
284 -- @return Number of found occurences
285 function cmatch(str, pat)
287 for _ in str:gmatch(pat) do count = count + 1 end
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)
315 y = 60 * 60 * 24 * 366,
316 m = 60 * 60 * 24 * 31,
317 w = 60 * 60 * 24 * 7,
325 gb = 1024 * 1024 * 1024,
327 -- storage sizes (si)
330 gib = 1000 * 1000 * 1000
333 -- parse input string
334 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
336 local num = spec:gsub("[^0-9%.]+$","")
337 local spn = spec:gsub("^[0-9%.]+", "")
339 if map[spn] or map[spn:sub(1,1)] then
340 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
350 -- also register functions above in the central string class for convenience
351 string.escape = escape
352 string.pcdata = pcdata
353 string.striptags = striptags
356 string.cmatch = cmatch
357 string.parse_units = parse_units
360 --- Appends numerically indexed tables or single objects to a given table.
361 -- @param src Target table
362 -- @param ... Objects to insert
363 -- @return Target table
364 function append(src, ...)
365 for i, a in ipairs({...}) do
366 if type(a) == "table" then
367 for j, v in ipairs(a) do
377 --- Combines two or more numerically indexed tables and single objects into one table.
378 -- @param tbl1 Table value to combine
379 -- @param tbl2 Table value to combine
380 -- @param ... More tables to combine
381 -- @return Table value containing all values of given tables
382 function combine(...)
383 return append({}, ...)
386 --- Checks whether the given table contains the given value.
387 -- @param table Table value
388 -- @param value Value to search within the given table
389 -- @return Boolean indicating whether the given value occurs within table
390 function contains(table, value)
391 for k, v in pairs(table) do
399 --- Update values in given table with the values from the second given table.
400 -- Both table are - in fact - merged together.
401 -- @param t Table which should be updated
402 -- @param updates Table containing the values to update
403 -- @return Always nil
404 function update(t, updates)
405 for k, v in pairs(updates) do
410 --- Retrieve all keys of given associative table.
411 -- @param t Table to extract keys from
412 -- @return Sorted table containing the keys
416 for k, _ in kspairs(t) do
423 --- Clones the given object and return it's copy.
424 -- @param object Table value to clone
425 -- @param deep Boolean indicating whether to do recursive cloning
426 -- @return Cloned table value
427 function clone(object, deep)
430 for k, v in pairs(object) do
431 if deep and type(v) == "table" then
437 return setmetatable(copy, getmetatable(object))
441 --- Create a dynamic table which automatically creates subtables.
442 -- @return Dynamic Table
444 return setmetatable({}, { __index =
446 return rawget(tbl, key)
447 or rawget(rawset(tbl, key, dtable()), key)
453 -- Serialize the contents of a table value.
454 function _serialize_table(t, seen)
455 assert(not seen[t], "Recursion detected.")
462 for k, v in pairs(t) do
463 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
464 k = serialize_data(k, seen)
465 v = serialize_data(v, seen)
466 data = data .. ( #data > 0 and ", " or "" ) ..
467 '[' .. k .. '] = ' .. v
474 local v = serialize_data(t[i], seen)
475 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
478 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
481 --- Recursively serialize given data to lua code, suitable for restoring
482 -- with loadstring().
483 -- @param val Value containing the data to serialize
484 -- @return String value containing the serialized code
487 function serialize_data(val, seen)
488 seen = seen or setmetatable({}, {__mode="k"})
492 elseif type(val) == "number" then
494 elseif type(val) == "string" then
496 elseif type(val) == "boolean" then
497 return val and "true" or "false"
498 elseif type(val) == "function" then
499 return "loadstring(%q)" % get_bytecode(val)
500 elseif type(val) == "table" then
501 return "{ " .. _serialize_table(val, seen) .. " }"
503 return '"[unhandled data type:' .. type(val) .. ']"'
507 --- Restore data previously serialized with serialize_data().
508 -- @param str String containing the data to restore
509 -- @return Value containing the restored data structure
510 -- @see serialize_data
512 function restore_data(str)
513 return loadstring("return " .. str)()
518 -- Byte code manipulation routines
521 --- Return the current runtime bytecode of the given data. The byte code
522 -- will be stripped before it is returned.
523 -- @param val Value to return as bytecode
524 -- @return String value containing the bytecode of the given data
525 function get_bytecode(val)
528 if type(val) == "function" then
529 code = string.dump(val)
531 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
534 return code and strip_bytecode(code)
537 --- Strips unnescessary lua bytecode from given string. Information like line
538 -- numbers and debugging numbers will be discarded. Original version by
539 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
540 -- @param code String value containing the original lua byte code
541 -- @return String value containing the stripped lua byte code
542 function strip_bytecode(code)
543 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
546 subint = function(code, i, l)
549 val = val * 256 + code:byte(i + n - 1)
554 subint = function(code, i, l)
557 val = val * 256 + code:byte(i + n - 1)
564 strip_function = function(code)
565 local count, offset = subint(code, 1, size)
566 local stripped, dirty = string.rep("\0", size), offset + count
567 offset = offset + count + int * 2 + 4
568 offset = offset + int + subint(code, offset, int) * ins
569 count, offset = subint(code, offset, int)
572 t, offset = subint(code, offset, 1)
576 offset = offset + size + subint(code, offset, size)
578 offset = offset + num
579 elseif t == 254 or t == 9 then
580 offset = offset + lnum
583 count, offset = subint(code, offset, int)
584 stripped = stripped .. code:sub(dirty, offset - 1)
586 local proto, off = strip_function(code:sub(offset, -1))
587 stripped, offset = stripped .. proto, offset + off - 1
589 offset = offset + subint(code, offset, int) * int + int
590 count, offset = subint(code, offset, int)
592 offset = offset + subint(code, offset, size) + size + int * 2
594 count, offset = subint(code, offset, int)
596 offset = offset + subint(code, offset, size) + size
598 stripped = stripped .. string.rep("\0", int * 3)
599 return stripped, offset
602 return code:sub(1,12) .. strip_function(code:sub(13,-1))
607 -- Sorting iterator functions
610 function _sortiter( t, f )
613 for k, v in pairs(t) do
619 table.sort( keys, f )
623 if _pos <= #keys then
624 return keys[_pos], t[keys[_pos]]
629 --- Return a key, value iterator which returns the values sorted according to
630 -- the provided callback function.
631 -- @param t The table to iterate
632 -- @param f A callback function to decide the order of elements
633 -- @return Function value containing the corresponding iterator
635 return _sortiter( t, f )
638 --- Return a key, value iterator for the given table.
639 -- The table pairs are sorted by key.
640 -- @param t The table to iterate
641 -- @return Function value containing the corresponding iterator
643 return _sortiter( t )
646 --- Return a key, value iterator for the given table.
647 -- The table pairs are sorted by value.
648 -- @param t The table to iterate
649 -- @return Function value containing the corresponding iterator
651 return _sortiter( t, function (a,b) return t[a] < t[b] end )
656 -- System utility functions
659 --- Test whether the current system is operating in big endian mode.
660 -- @return Boolean value indicating whether system is big endian
662 return string.byte(string.dump(function() end), 7) == 0
665 --- Execute given commandline and gather stdout.
666 -- @param command String containing command to execute
667 -- @return String containing the command's stdout
668 function exec(command)
669 local pp = io.popen(command)
670 local data = pp:read("*a")
676 --- Return a line-buffered iterator over the output of given command.
677 -- @param command String containing the command to execute
679 function execi(command)
680 local pp = io.popen(command)
682 return pp and function()
683 local line = pp:read()
694 function execl(command)
695 local pp = io.popen(command)
701 if (line == nil) then break end
709 --- Returns the absolute path to LuCI base directory.
710 -- @return String containing the directory path
712 return require "luci.fs".dirname(ldebug.__file__)
717 -- Coroutine safe xpcall and pcall versions modified for Luci
719 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
721 -- Copyright © 2005 Kepler Project.
722 -- Permission is hereby granted, free of charge, to any person obtaining a
723 -- copy of this software and associated documentation files (the "Software"),
724 -- to deal in the Software without restriction, including without limitation
725 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
726 -- and/or sell copies of the Software, and to permit persons to whom the
727 -- Software is furnished to do so, subject to the following conditions:
729 -- The above copyright notice and this permission notice shall be
730 -- included in all copies or substantial portions of the Software.
732 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
733 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
734 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
735 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
736 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
737 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
738 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
740 local performResume, handleReturnValue
741 local oldpcall, oldxpcall = pcall, xpcall
743 setmetatable(coxpt, {__mode = "kv"})
745 -- Identity function for copcall
746 local function copcall_id(trace, ...)
750 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
751 -- @param f Lua function to be called protected
752 -- @param err Custom error handler
753 -- @param ... Parameters passed to the function
754 -- @return A boolean whether the function call succeeded and the return
755 -- values of either the function or the error handler
756 function coxpcall(f, err, ...)
757 local res, co = oldpcall(coroutine.create, f)
760 local newf = function() return f(unpack(params)) end
761 co = coroutine.create(newf)
763 local c = coroutine.running()
764 coxpt[co] = coxpt[c] or c or 0
766 return performResume(err, co, ...)
769 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
770 -- @param f Lua function to be called protected
771 -- @param ... Parameters passed to the function
772 -- @return A boolean whether the function call succeeded and the returns
773 -- values of the function or the error object
774 function copcall(f, ...)
775 return coxpcall(f, copcall_id, ...)
778 -- Handle return value of protected call
779 function handleReturnValue(err, co, status, ...)
781 return false, err(debug.traceback(co, (...)), ...)
783 if coroutine.status(co) == 'suspended' then
784 return performResume(err, co, coroutine.yield(...))
790 -- Resume execution of protected function call
791 function performResume(err, co, ...)
792 return handleReturnValue(err, co, coroutine.resume(co, ...))