* luci/libs/core: added inline documentation to luci.util, reordered and renamed...
[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 -- Class helper routines
32 --
33
34 --- Creates a Class object (Python-style object model)
35 -- Creates a new class object which 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 paramters 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
46 -- @see                 instanceof
47 -- @see                 clone
48 function class(base)
49         local class = {}
50
51         local create = function(class, ...)
52                 local inst = {}
53                 setmetatable(inst, {__index = class})
54
55                 if inst.__init__ then
56                         local stat, err = copcall(inst.__init__, inst, ...)
57                         if not stat then
58                                 error(err)
59                         end
60                 end
61
62                 return inst
63         end
64
65         local classmeta = {__call = create}
66
67         if base then
68                 classmeta.__index = base
69         end
70
71         setmetatable(class, classmeta)
72         return class
73 end
74
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 wheather the object is an instance
79 -- @see                         class
80 -- @see                         clone
81 function instanceof(object, class)
82         local meta = getmetatable(object)
83         while meta and meta.__index do
84                 if meta.__index == class then
85                         return true
86                 end
87                 meta = getmetatable(meta.__index)
88         end
89         return false
90 end
91
92
93 --
94 -- Scope manipulation routines
95 --
96
97 --- Resets the scope of f doing a shallow copy of its scope into a new table
98 -- (ToDo: @param and @return)
99 function resfenv(f)
100         setfenv(f, clone(getfenv(f)))
101 end
102
103 --- Store given object associated with given key in the scope associated with
104 -- the given identifier.
105 -- @param f             Value containing the scope identifier
106 -- @param key   String value containg the key of the object to store
107 -- @param obj   Object to store in the scope
108 -- @return              Always nil
109 function extfenv(f, key, obj)
110         local scope = getfenv(f)
111         scope[key] = obj
112 end
113
114 --- Updates the scope of f with "extscope" (ToDo: docu)
115 function updfenv(f, extscope)
116         update(getfenv(f), extscope)
117 end
118
119 --- Create a new or get an already existing thread local store associated with
120 -- the current active coroutine. A thread local store is private a table object
121 -- whose values can't be accessed from outside of the running coroutine.
122 -- @return      Table value representing the corresponding thread local store
123 function threadlocal()
124         local tbl = {}
125
126         local function get(self, key)
127                 local c = coroutine.running()
128                 local thread = coxpt[c] or c or 0
129                 if not rawget(self, thread) then
130                         return nil
131                 end
132                 return rawget(self, thread)[key]
133         end
134
135         local function set(self, key, value)
136                 local c = coroutine.running()
137                 local thread = coxpt[c] or c or 0
138                 if not rawget(self, thread) then
139                         rawset(self, thread, {})
140                 end
141                 rawget(self, thread)[key] = value
142         end
143
144         setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
145
146         return tbl
147 end
148
149
150 --
151 -- Debugging routines
152 --
153
154 --- Write given object to stderr.
155 -- @param obj   Value to write to stderr
156 -- @return              Boolean indicating wheather the write operation was successful
157 function perror(obj)
158         io.stderr:write(tostring(obj) .. "\n")
159 end
160
161 --- Recursively dumps a table to stdout, useful for testing and debugging.
162 -- @param t     Table value to dump
163 -- @param i     Number of tabs to prepend to each line
164 -- @return      Always nil
165 function dumptable(t, i)
166         i = i or 0
167         for k,v in pairs(t) do
168                 print(string.rep("\t", i) .. tostring(k), tostring(v))
169                 if type(v) == "table" then
170                         dumptable(v, i+1)
171                 end
172         end
173 end
174
175
176 --
177 -- String and data manipulation routines
178 --
179
180 --- Escapes all occurences of the given character in given string.
181 -- @param s     String value containing unescaped characters
182 -- @param c     String value with character to escape (optional, defaults to "\")
183 -- @return      String value with each occurence of character escaped with "\"
184 function escape(s, c)
185         c = c or "\\"
186         return s:gsub(c, "\\" .. c)
187 end
188
189 --- Create valid XML PCDATA from given string.
190 -- @param value String value containing the data to escape
191 -- @return              String value containing the escaped data
192 function pcdata(value)
193         value = value:gsub("&", "&amp;")
194         value = value:gsub('"', "&quot;")
195         value = value:gsub("'", "&apos;")
196         value = value:gsub("<", "&lt;")
197         return value:gsub(">", "&gt;")
198 end
199
200 --- Splits given string on a defined seperator sequence and return a table
201 -- containing the resulting substrings. The optional max parameter specifies
202 -- the number of bytes to process, regardless of the actual length of the given
203 -- string. The optional last parameter, regex, sepcifies wheather the separator
204 -- sequence is interpreted as regular expression.
205 -- @param str           String value containing the data to split up
206 -- @param pat           String with separator pattern (optional, defaults to "\n")
207 -- @param max           Num of bytes to process (optional, default is string length)
208 -- @param regexp        Boolean indicating wheather to interprete the separator
209 --                                      pattern as regular expression (optional, default is false)
210 -- @return                      Table containing the resulting substrings
211 function split(str, pat, max, regex)
212         pat = pat or "\n"
213         max = max or #str
214
215         local t = {}
216         local c = 1
217
218         if #str == 0 then
219                 return {""}
220         end
221
222         if #pat == 0 then
223                 return nil
224         end
225
226         if max == 0 then
227                 return str
228         end
229
230         repeat
231                 local s, e = str:find(pat, c, not regex)
232                 max = max - 1
233                 if s and max < 0 then
234                         table.insert(t, str:sub(c))
235                 else
236                         table.insert(t, str:sub(c, s and s - 1))
237                 end
238                 c = e and e + 1 or #str + 1
239         until not s or max < 0
240
241         return t
242 end
243
244 --- Remove leading and trailing whitespace from given string value.
245 -- @param str   String value containing whitespace padded data
246 -- @return              String value with leading and trailing space removed
247 function trim(str)
248         local s = str:gsub("^%s*(.-)%s*$", "%1")
249         return s
250 end
251
252 --- Parse certain units from the given string and return the canonical integer
253 -- value or 0 if the unit is unknown. Upper- or lowercase is irrelevant.
254 -- Recognized units are:
255 --      o "y"   - one year   (60*60*24*366)
256 --  o "m"       - one month  (60*60*24*31)
257 --  o "w"       - one week   (60*60*24*7)
258 --  o "d"       - one day    (60*60*24)
259 --  o "h"       - one hour       (60*60)
260 --  o "min"     - one minute (60)
261 --  o "kb"  - one kilobyte (1024)
262 --  o "mb"      - one megabyte (1024*1024)
263 --  o "gb"      - one gigabyte (1024*1024*1024)
264 --  o "kib" - one si kilobyte (1000)
265 --  o "mib"     - one si megabyte (1000*1000)
266 --  o "gib"     - one si gigabyte (1000*1000*1000)
267 -- @param ustr  String containing a numerical value with trailing unit
268 -- @return              Number containing the canonical value
269 function parse_units(ustr)
270
271         local val = 0
272
273         -- unit map
274         local map = {
275                 -- date stuff
276                 y   = 60 * 60 * 24 * 366,
277                 m   = 60 * 60 * 24 * 31,
278                 w   = 60 * 60 * 24 * 7,
279                 d   = 60 * 60 * 24,
280                 h   = 60 * 60,
281                 min = 60,
282
283                 -- storage sizes
284                 kb  = 1024,
285                 mb  = 1024 * 1024,
286                 gb  = 1024 * 1024 * 1024,
287
288                 -- storage sizes (si)
289                 kib = 1000,
290                 mib = 1000 * 1000,
291                 gib = 1000 * 1000 * 1000
292         }
293
294         -- parse input string
295         for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
296
297                 local num = spec:gsub("[^0-9%.]+$","")
298                 local spn = spec:gsub("^[0-9%.]+", "")
299
300                 if map[spn] or map[spn:sub(1,1)] then
301                         val = val + num * ( map[spn] or map[spn:sub(1,1)] )
302                 else
303                         val = val + num
304                 end
305         end
306
307
308         return val
309 end
310
311 --- Combines two or more numerically indexed tables into one.
312 -- @param tbl1  Table value to combine
313 -- @param tbl2  Table value to combine
314 -- @param tblN  More values to combine
315 -- @return              Table value containing all values of given tables
316 function combine(...)
317         local result = {}
318         for i, a in ipairs(arg) do
319                 for j, v in ipairs(a) do
320                         table.insert(result, v)
321                 end
322         end
323         return result
324 end
325
326 --- Checks whether the given table contains the given value.
327 -- @param table Table value
328 -- @param value Value to search within the given table
329 -- @return              Boolean indicating wheather the given value occurs within table
330 function contains(table, value)
331         for k, v in pairs(table) do
332                 if value == v then
333                         return k
334                 end
335         end
336         return false
337 end
338
339 --- Update values in given table with the values from the second given table.
340 -- Both table are - in fact - merged together.
341 -- @param t                     Table which should be updated
342 -- @param updates       Table containing the values to update
343 -- @return                      Always nil
344 function update(t, updates)
345         for k, v in pairs(updates) do
346                 t[k] = v
347         end
348 end
349
350 --- Clones the given object and return it's copy.
351 -- @param object        Table value to clone
352 -- @param deep          Boolean indicating wheather to do recursive cloning
353 -- @return                      Cloned table value
354 function clone(object, deep)
355         local copy = {}
356
357         for k, v in pairs(object) do
358                 if deep and type(v) == "table" then
359                         v = clone(v, deep)
360                 end
361                 copy[k] = v
362         end
363
364         setmetatable(copy, getmetatable(object))
365
366         return copy
367 end
368
369
370 --
371 -- Byte code manipulation routines
372 --
373
374 --- Return the current runtime bytecode of the given function. The byte code
375 -- will be stripped before it is returned.
376 -- @param f     Function value to return as bytecode
377 -- @return      String value containing the bytecode of the given function
378 function get_bytecode(f)
379         local d = string.dump(f)
380         return d and strip_bytecode(d)
381 end
382
383 --- Strips unnescessary lua bytecode from given string. Information like line
384 -- numbers and debugging numbers will be discarded. Original version by
385 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
386 -- @param code  String value containing the original lua byte code
387 -- @return              String value containing the stripped lua byte code
388 function strip_bytecode(code)
389         local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
390         local subint
391         if endian == 1 then
392                 subint = function(code, i, l)
393                         local val = 0
394                         for n = l, 1, -1 do
395                                 val = val * 256 + code:byte(i + n - 1)
396                         end
397                         return val, i + l
398                 end
399         else
400                 subint = function(code, i, l)
401                         local val = 0
402                         for n = 1, l, 1 do
403                                 val = val * 256 + code:byte(i + n - 1)
404                         end
405                         return val, i + l
406                 end
407         end
408
409         local strip_function
410         strip_function = function(code)
411                 local count, offset = subint(code, 1, size)
412                 local stripped, dirty = string.rep("\0", size), offset + count
413                 offset = offset + count + int * 2 + 4
414                 offset = offset + int + subint(code, offset, int) * ins
415                 count, offset = subint(code, offset, int)
416                 for n = 1, count do
417                         local t
418                         t, offset = subint(code, offset, 1)
419                         if t == 1 then
420                                 offset = offset + 1
421                         elseif t == 4 then
422                                 offset = offset + size + subint(code, offset, size)
423                         elseif t == 3 then
424                                 offset = offset + num
425                         elseif t == 254 or t == 9 then
426                                 offset = offset + lnum
427                         end
428                 end
429                 count, offset = subint(code, offset, int)
430                 stripped = stripped .. code:sub(dirty, offset - 1)
431                 for n = 1, count do
432                         local proto, off = strip_function(code:sub(offset, -1))
433                         stripped, offset = stripped .. proto, offset + off - 1
434                 end
435                 offset = offset + subint(code, offset, int) * int + int
436                 count, offset = subint(code, offset, int)
437                 for n = 1, count do
438                         offset = offset + subint(code, offset, size) + size + int * 2
439                 end
440                 count, offset = subint(code, offset, int)
441                 for n = 1, count do
442                         offset = offset + subint(code, offset, size) + size
443                 end
444                 stripped = stripped .. string.rep("\0", int * 3)
445                 return stripped, offset
446         end
447
448         return code:sub(1,12) .. strip_function(code:sub(13,-1))
449 end
450
451
452 --
453 -- Sorting iterator functions
454 --
455
456 function _sortiter( t, f )
457         local keys = { }
458
459         for k, v in pairs(t) do
460                 table.insert( keys, k )
461         end
462
463         local _pos = 0
464         local _len = table.getn( keys )
465
466         table.sort( keys, f )
467
468         return function()
469                 _pos = _pos + 1
470                 if _pos <= _len then
471                         return keys[_pos], t[keys[_pos]]
472                 end
473         end
474 end
475
476 --- Return a key, value iterator which returns the values sorted according to
477 -- the provided callback function.
478 -- @param t     The table to iterate
479 -- @param f A callback function to decide the order of elements
480 -- @return      Function value containing the corresponding iterator
481 function spairs(t,f)
482         return _sortiter( t, f )
483 end
484
485 --- Return a key, value iterator for the given table.
486 -- The table pairs are sorted by key.
487 -- @param t     The table to iterate
488 -- @return      Function value containing the corresponding iterator
489 function kspairs(t)
490         return _sortiter( t )
491 end
492
493 --- Return a key, value iterator for the given table.
494 -- The table pairs are sorted by value.
495 -- @param t     The table to iterate
496 -- @return      Function value containing the corresponding iterator
497 function vspairs(t)
498         return _sortiter( t, function (a,b) return t[a] < t[b] end )
499 end
500
501
502 --
503 -- Coroutine safe xpcall and pcall versions modified for Luci
504 -- original version:
505 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
506 --
507
508 local performResume, handleReturnValue
509 local oldpcall, oldxpcall = pcall, xpcall
510 coxpt = {}
511 setmetatable(coxpt, {__mode = "kv"})
512
513 --- (ToDo: docu)
514 function coxpcall(f, err, ...)
515         local res, co = oldpcall(coroutine.create, f)
516         if not res then
517                 local params = {...}
518                 local newf = function() return f(unpack(params)) end
519                 co = coroutine.create(newf)
520         end
521         local c = coroutine.running()
522         coxpt[co] = coxpt[c] or c or 0
523
524         return performResume(err, co, ...)
525 end
526
527 --- (ToDo: docu)
528 function copcall(f, ...)
529         return coxpcall(f, id, ...)
530 end
531
532 --- (ToDo: docu)
533 local function id(trace, ...)
534   return ...
535 end
536
537 --- (ToDo: docu)
538 function handleReturnValue(err, co, status, ...)
539         if not status then
540                 return false, err(debug.traceback(co, (...)), ...)
541         end
542         if coroutine.status(co) == 'suspended' then
543                 return performResume(err, co, coroutine.yield(...))
544         else
545                 return true, ...
546         end
547 end
548
549 --- (ToDo: docu)
550 function performResume(err, co, ...)
551         return handleReturnValue(err, co, coroutine.resume(co, ...))
552 end