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 --- LuCI utility functions.
28 module("luci.util", package.seeall)
31 -- Class helper routines
34 --- Create a Class object (Python-style object model).
35 -- The class object can be instantiated by calling itself.
36 -- Any class functions or shared parameters can be attached to this object.
37 -- Attaching a table to the class object makes this table shared between
38 -- all instances of this class. For object parameters use the __init__ function.
39 -- Classes can inherit member functions and values from a base class.
40 -- Class can be instantiated by calling them. All parameters will be passed
41 -- to the __init__ function of this class - if such a function exists.
42 -- The __init__ function must be used to set any object parameters that are not shared
43 -- with other objects of this class. Any return values will be ignored.
44 -- @param base The base class to inherit from (optional)
45 -- @return A class object
51 local create = function(class, ...)
53 setmetatable(inst, {__index = class})
56 local stat, err = copcall(inst.__init__, inst, ...)
65 local classmeta = {__call = create}
68 classmeta.__index = base
71 setmetatable(class, classmeta)
75 --- Test whether the given object is an instance of the given class.
76 -- @param object Object instance
77 -- @param class Class object to test against
78 -- @return Boolean indicating whether the object is an instance
81 function instanceof(object, class)
82 local meta = getmetatable(object)
83 while meta and meta.__index do
84 if meta.__index == class then
87 meta = getmetatable(meta.__index)
94 -- Scope manipulation routines
97 --- Replace a function scope with a shallow copy of itself.
98 -- This is useful if you want to get rid of several unwanted side effects
99 -- while changing the scope of a certain Lua function.
100 -- @param f Lua function
102 setfenv(f, clone(getfenv(f)))
105 --- Store given object associated with given key in the scope of a function.
106 -- @param f Lua function
107 -- @param key String value containg the key of the object to store
108 -- @param obj Object to store in the scope
109 -- @return Always nil
112 function extfenv(f, key, obj)
113 local scope = getfenv(f)
117 --- Extend the scope of a function with the contents of a table
118 -- @param f Lua function
119 -- @param key String value containg the key of the object to store
120 -- @param obj Object to store in the scope
121 -- @return Always nil
124 function updfenv(f, extscope)
125 update(getfenv(f), extscope)
128 --- Create a new or get an already existing thread local store associated with
129 -- the current active coroutine. A thread local store is private a table object
130 -- whose values can't be accessed from outside of the running coroutine.
131 -- @return Table value representing the corresponding thread local store
132 function threadlocal()
135 local function get(self, key)
136 local c = coroutine.running()
137 local thread = coxpt[c] or c or 0
138 if not rawget(self, thread) then
141 return rawget(self, thread)[key]
144 local function set(self, key, value)
145 local c = coroutine.running()
146 local thread = coxpt[c] or c or 0
147 if not rawget(self, thread) then
148 rawset(self, thread, {})
150 rawget(self, thread)[key] = value
153 setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
160 -- Debugging routines
163 --- Write given object to stderr.
164 -- @param obj Value to write to stderr
165 -- @return Boolean indicating whether the write operation was successful
167 return io.stderr:write(tostring(obj) .. "\n")
170 --- Recursively dumps a table to stdout, useful for testing and debugging.
171 -- @param t Table value to dump
172 -- @param i Number of tabs to prepend to each line
173 -- @return Always nil
174 function dumptable(t, i)
176 for k,v in pairs(t) do
177 print(string.rep("\t", i) .. tostring(k), tostring(v))
178 if type(v) == "table" then
186 -- String and data manipulation routines
189 --- Escapes all occurrences of the given character in given string.
190 -- @param s String value containing unescaped characters
191 -- @param c String value with character to escape (optional, defaults to "\")
192 -- @return String value with each occurrence of character escaped with "\"
193 function escape(s, c)
195 return s:gsub(c, "\\" .. c)
198 --- Create valid XML PCDATA from given string.
199 -- @param value String value containing the data to escape
200 -- @return String value containing the escaped data
201 function pcdata(value)
202 if not value then return end
203 value = tostring(value)
204 value = value:gsub("&", "&")
205 value = value:gsub('"', """)
206 value = value:gsub("'", "'")
207 value = value:gsub("<", "<")
208 return value:gsub(">", ">")
211 --- Splits given string on a defined separator sequence and return a table
212 -- containing the resulting substrings. The optional max parameter specifies
213 -- the number of bytes to process, regardless of the actual length of the given
214 -- string. The optional last parameter, regex, specifies whether the separator
215 -- sequence is interpreted as regular expression.
216 -- @param str String value containing the data to split up
217 -- @param pat String with separator pattern (optional, defaults to "\n")
218 -- @param max Maximum times to split (optional)
219 -- @param regex Boolean indicating whether to interpret the separator
220 -- pattern as regular expression (optional, default is false)
221 -- @return Table containing the resulting substrings
222 function split(str, pat, max, regex)
242 local s, e = str:find(pat, c, not regex)
244 if s and max < 0 then
245 table.insert(t, str:sub(c))
247 table.insert(t, str:sub(c, s and s - 1))
249 c = e and e + 1 or #str + 1
250 until not s or max < 0
255 --- Remove leading and trailing whitespace from given string value.
256 -- @param str String value containing whitespace padded data
257 -- @return String value with leading and trailing space removed
259 local s = str:gsub("^%s*(.-)%s*$", "%1")
263 --- Parse certain units from the given string and return the canonical integer
264 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
265 -- Recognized units are:
266 -- o "y" - one year (60*60*24*366)
267 -- o "m" - one month (60*60*24*31)
268 -- o "w" - one week (60*60*24*7)
269 -- o "d" - one day (60*60*24)
270 -- o "h" - one hour (60*60)
271 -- o "min" - one minute (60)
272 -- o "kb" - one kilobyte (1024)
273 -- o "mb" - one megabyte (1024*1024)
274 -- o "gb" - one gigabyte (1024*1024*1024)
275 -- o "kib" - one si kilobyte (1000)
276 -- o "mib" - one si megabyte (1000*1000)
277 -- o "gib" - one si gigabyte (1000*1000*1000)
278 -- @param ustr String containing a numerical value with trailing unit
279 -- @return Number containing the canonical value
280 function parse_units(ustr)
287 y = 60 * 60 * 24 * 366,
288 m = 60 * 60 * 24 * 31,
289 w = 60 * 60 * 24 * 7,
297 gb = 1024 * 1024 * 1024,
299 -- storage sizes (si)
302 gib = 1000 * 1000 * 1000
305 -- parse input string
306 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
308 local num = spec:gsub("[^0-9%.]+$","")
309 local spn = spec:gsub("^[0-9%.]+", "")
311 if map[spn] or map[spn:sub(1,1)] then
312 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
322 --- Combines two or more numerically indexed tables into one.
323 -- @param tbl1 Table value to combine
324 -- @param tbl2 Table value to combine
325 -- @param ... More tables to combine
326 -- @return Table value containing all values of given tables
327 function combine(...)
329 for i, a in ipairs(arg) do
330 for j, v in ipairs(a) do
331 table.insert(result, v)
337 --- Checks whether the given table contains the given value.
338 -- @param table Table value
339 -- @param value Value to search within the given table
340 -- @return Boolean indicating whether the given value occurs within table
341 function contains(table, value)
342 for k, v in pairs(table) do
350 --- Update values in given table with the values from the second given table.
351 -- Both table are - in fact - merged together.
352 -- @param t Table which should be updated
353 -- @param updates Table containing the values to update
354 -- @return Always nil
355 function update(t, updates)
356 for k, v in pairs(updates) do
361 --- Clones the given object and return it's copy.
362 -- @param object Table value to clone
363 -- @param deep Boolean indicating whether to do recursive cloning
364 -- @return Cloned table value
365 function clone(object, deep)
368 for k, v in pairs(object) do
369 if deep and type(v) == "table" then
375 setmetatable(copy, getmetatable(object))
381 --- Create a dynamic table which automatically creates subtables.
382 -- @return Dynamic Table
384 return setmetatable({}, { __index =
386 return rawget(tbl, key)
387 or rawget(rawset(tbl, key, dtable()), key)
393 -- Serialize the contents of a table value.
394 function _serialize_table(t)
396 for k, v in pairs(t) do
397 k = serialize_data(k)
398 v = serialize_data(v)
399 data = data .. ( #data > 0 and ", " or "" ) ..
400 '[' .. k .. '] = ' .. v
405 --- Recursively serialize given data to lua code, suitable for restoring
406 -- with loadstring().
407 -- @param val Value containing the data to serialize
408 -- @return String value containing the serialized code
411 function serialize_data(val)
414 elseif type(val) == "number" then
416 elseif type(val) == "string" then
417 return string.format("%q", val)
418 elseif type(val) == "boolean" then
419 return val and "true" or "false"
420 elseif type(val) == "function" then
421 return string.format("loadstring(%q)", get_bytecode(val))
422 elseif type(val) == "table" then
423 return "{ " .. _serialize_table(val) .. " }"
425 return '"[unhandled data type:' .. type(val) .. ']"'
429 --- Restore data previously serialized with serialize_data().
430 -- @param str String containing the data to restore
431 -- @return Value containing the restored data structure
432 -- @see serialize_data
434 function restore_data(str)
435 return loadstring("return " .. str)()
440 -- Byte code manipulation routines
443 --- Return the current runtime bytecode of the given data. The byte code
444 -- will be stripped before it is returned.
445 -- @param val Value to return as bytecode
446 -- @return String value containing the bytecode of the given data
447 function get_bytecode(val)
450 if type(val) == "function" then
451 code = string.dump(val)
453 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
456 return code and strip_bytecode(code)
459 --- Strips unnescessary lua bytecode from given string. Information like line
460 -- numbers and debugging numbers will be discarded. Original version by
461 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
462 -- @param code String value containing the original lua byte code
463 -- @return String value containing the stripped lua byte code
464 function strip_bytecode(code)
465 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
468 subint = function(code, i, l)
471 val = val * 256 + code:byte(i + n - 1)
476 subint = function(code, i, l)
479 val = val * 256 + code:byte(i + n - 1)
486 strip_function = function(code)
487 local count, offset = subint(code, 1, size)
488 local stripped, dirty = string.rep("\0", size), offset + count
489 offset = offset + count + int * 2 + 4
490 offset = offset + int + subint(code, offset, int) * ins
491 count, offset = subint(code, offset, int)
494 t, offset = subint(code, offset, 1)
498 offset = offset + size + subint(code, offset, size)
500 offset = offset + num
501 elseif t == 254 or t == 9 then
502 offset = offset + lnum
505 count, offset = subint(code, offset, int)
506 stripped = stripped .. code:sub(dirty, offset - 1)
508 local proto, off = strip_function(code:sub(offset, -1))
509 stripped, offset = stripped .. proto, offset + off - 1
511 offset = offset + subint(code, offset, int) * int + int
512 count, offset = subint(code, offset, int)
514 offset = offset + subint(code, offset, size) + size + int * 2
516 count, offset = subint(code, offset, int)
518 offset = offset + subint(code, offset, size) + size
520 stripped = stripped .. string.rep("\0", int * 3)
521 return stripped, offset
524 return code:sub(1,12) .. strip_function(code:sub(13,-1))
529 -- Sorting iterator functions
532 function _sortiter( t, f )
535 for k, v in pairs(t) do
536 table.insert( keys, k )
540 local _len = table.getn( keys )
542 table.sort( keys, f )
547 return keys[_pos], t[keys[_pos]]
552 --- Return a key, value iterator which returns the values sorted according to
553 -- the provided callback function.
554 -- @param t The table to iterate
555 -- @param f A callback function to decide the order of elements
556 -- @return Function value containing the corresponding iterator
558 return _sortiter( t, f )
561 --- Return a key, value iterator for the given table.
562 -- The table pairs are sorted by key.
563 -- @param t The table to iterate
564 -- @return Function value containing the corresponding iterator
566 return _sortiter( t )
569 --- Return a key, value iterator for the given table.
570 -- The table pairs are sorted by value.
571 -- @param t The table to iterate
572 -- @return Function value containing the corresponding iterator
574 return _sortiter( t, function (a,b) return t[a] < t[b] end )
579 -- System utility functions
582 --- Test whether the current system is operating in big endian mode.
583 -- @return Boolean value indicating whether system is big endian
585 return string.byte(string.dump(function() end), 7) == 0
588 --- Execute given commandline and gather stdout.
589 -- @param command String containing command to execute
590 -- @return String containing the command's stdout
591 function exec(command)
592 local pp = io.popen(command)
593 local data = pp:read("*a")
599 --- Return a line-buffered iterator over the output of given command.
600 -- @param command String containing the command to execute
602 function execi(command)
603 local pp = io.popen(command)
605 return pp and function()
606 local line = pp:read()
617 function execl(command)
618 local pp = io.popen(command)
624 if (line == nil) then break end
625 table.insert(data, line)
632 --- Returns the absolute path to LuCI base directory.
633 -- @return String containing the directory path
635 return luci.fs.dirname(require("luci.debug").__file__)
640 -- Coroutine safe xpcall and pcall versions modified for Luci
642 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
644 -- Copyright © 2005 Kepler Project.
645 -- Permission is hereby granted, free of charge, to any person obtaining a
646 -- copy of this software and associated documentation files (the "Software"),
647 -- to deal in the Software without restriction, including without limitation
648 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
649 -- and/or sell copies of the Software, and to permit persons to whom the
650 -- Software is furnished to do so, subject to the following conditions:
652 -- The above copyright notice and this permission notice shall be
653 -- included in all copies or substantial portions of the Software.
655 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
656 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
657 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
658 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
659 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
660 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
661 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
663 local performResume, handleReturnValue
664 local oldpcall, oldxpcall = pcall, xpcall
666 setmetatable(coxpt, {__mode = "kv"})
668 -- Identity function for copcall
669 local function copcall_id(trace, ...)
673 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
674 -- @param f Lua function to be called protected
675 -- @param err Custom error handler
676 -- @param ... Parameters passed to the function
677 -- @return A boolean whether the function call succeeded and the return
678 -- values of either the function or the error handler
679 function coxpcall(f, err, ...)
680 local res, co = oldpcall(coroutine.create, f)
683 local newf = function() return f(unpack(params)) end
684 co = coroutine.create(newf)
686 local c = coroutine.running()
687 coxpt[co] = coxpt[c] or c or 0
689 return performResume(err, co, ...)
692 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
693 -- @param f Lua function to be called protected
694 -- @param ... Parameters passed to the function
695 -- @return A boolean whether the function call succeeded and the returns
696 -- values of the function or the error object
697 function copcall(f, ...)
698 return coxpcall(f, copcall_id, ...)
701 -- Handle return value of protected call
702 function handleReturnValue(err, co, status, ...)
704 return false, err(debug.traceback(co, (...)), ...)
706 if coroutine.status(co) == 'suspended' then
707 return performResume(err, co, coroutine.yield(...))
713 -- Resume execution of protected function call
714 function performResume(err, co, ...)
715 return handleReturnValue(err, co, coroutine.resume(co, ...))