96 lines
2.1 KiB
Lua
96 lines
2.1 KiB
Lua
local M = {}
|
|
|
|
-- Helper functions
|
|
|
|
function M.format_time(time)
|
|
local seconds = time
|
|
local days = math.floor(seconds / 86400)
|
|
local hours = math.floor(seconds % 86400 / 3600)
|
|
local minutes = math.floor(seconds % 3600 / 60)
|
|
local result = ""
|
|
|
|
if days > 0 then
|
|
result = result .. days .. "d "
|
|
end
|
|
|
|
if hours > 0 then
|
|
result = result .. hours .. "h "
|
|
end
|
|
|
|
if minutes > 0 then
|
|
result = result .. minutes .. "m"
|
|
end
|
|
|
|
return result
|
|
end
|
|
|
|
-- Capture the first line of an invoked system process
|
|
-- (discards of error messages of the last command (the
|
|
-- one after the last pipe ('|')))
|
|
function M.process_get_one_line(proc)
|
|
local pipe = io.popen(proc .. " 2>/dev/null", "r")
|
|
if not pipe then return nil end
|
|
|
|
local data = pipe:read("*l")
|
|
pipe:close()
|
|
return data
|
|
end
|
|
|
|
-- Get the lenght of the longest info name (for padding)
|
|
function M.longest_info_name_length(modules)
|
|
local longest = 0
|
|
|
|
for _, mod in ipairs(modules) do
|
|
if type(mod.name) == "string" and #mod.name > longest then
|
|
longest = #mod.name
|
|
end
|
|
end
|
|
|
|
return longest
|
|
end
|
|
|
|
--[[
|
|
-- Loop through a file and for each line perform
|
|
-- a callback function, if it returns true, the
|
|
-- loop can end prematurely (this is wanted)
|
|
--]]
|
|
function M.for_line_in_file(filename, callback)
|
|
local file = io.open(filename, "r")
|
|
if not file then return nil end
|
|
|
|
for line in file:lines() do
|
|
if callback(line) then
|
|
file:close()
|
|
return true
|
|
end
|
|
end
|
|
|
|
file:close()
|
|
return false
|
|
end
|
|
|
|
-- filter a file line-by-line and return the given match
|
|
function M.grep(filename, regex)
|
|
local capture
|
|
|
|
M.for_line_in_file(filename, function(line)
|
|
capture = line:match(regex)
|
|
|
|
return capture ~= nil
|
|
end)
|
|
|
|
return capture
|
|
end
|
|
|
|
-- Returns the contents of the first line in a file
|
|
function M.cat_first_line(filename)
|
|
local file = io.open(filename, "r")
|
|
if not file then return nil end
|
|
|
|
local line = file:read("*l")
|
|
file:close()
|
|
return line
|
|
end
|
|
|
|
return M
|