libs/core: Add Pythonic string formatting syntax
[project/luci.git] / libs / core / luasrc / util.lua
index 638bb05..cc15d3a 100644 (file)
@@ -28,6 +28,20 @@ limitations under the License.
 module("luci.util", package.seeall)
 
 --
+-- Pythonic string formatting extension
+--
+getmetatable("").__mod = function(a, b)
+       if not b then
+               return a
+       elseif type(b) == "table" then
+               return a:format(unpack(b))
+       else
+               return a:format(b)
+       end
+end
+
+
+--
 -- Class helper routines
 --
 
@@ -199,6 +213,8 @@ end
 -- @param value        String value containing the data to escape
 -- @return             String value containing the escaped data
 function pcdata(value)
+       if not value then return end
+       value = tostring(value)
        value = value:gsub("&", "&")
        value = value:gsub('"', """)
        value = value:gsub("'", "'")
@@ -206,6 +222,13 @@ function pcdata(value)
        return value:gsub(">", ">")
 end
 
+--- Strip HTML tags from given string.
+-- @param value        String containing the HTML text
+-- @return     String with HTML tags stripped of
+function striptags(s)
+       return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
+end
+
 --- Splits given string on a defined separator sequence and return a table
 -- containing the resulting substrings. The optional max parameter specifies
 -- the number of bytes to process, regardless of the actual length of the given
@@ -356,6 +379,19 @@ function update(t, updates)
        end
 end
 
+--- Retrieve all keys of given associative table.
+-- @param t    Table to extract keys from
+-- @return     Sorted table containing the keys
+function keys(t)
+       local keys = { }
+       if t then
+               for k, _ in kspairs(t) do
+                       table.insert( keys, k )
+               end
+       end
+       return keys
+end
+
 --- Clones the given object and return it's copy.
 -- @param object       Table value to clone
 -- @param deep         Boolean indicating whether to do recursive cloning
@@ -594,9 +630,24 @@ function exec(command)
        return data
 end
 
---- Execute given commandline and gather stdout.
+--- Return a line-buffered iterator over the output of given command.
 -- @param command      String containing the command to execute
--- @return                     Table containing the command's stdout splitted up in lines
+-- @return                     Iterator
+function execi(command)
+       local pp = io.popen(command)
+
+       return pp and function()
+               local line = pp:read()
+               
+               if not line then
+                       pp:close()
+               end
+               
+               return line
+       end
+end
+
+-- Deprecated
 function execl(command)
        local pp   = io.popen(command)
        local line = ""