helpers: improved i/o functions

This commit is contained in:
Luca CPZ 2018-02-23 13:24:10 +01:00
parent e81f46950b
commit 92d17d289c

View file

@ -33,51 +33,47 @@ end
-- {{{ File operations -- {{{ File operations
-- see if the file exists and is readable -- check if the file exists and is readable
function helpers.file_exists(file) function helpers.file_exists(path)
local f = io.open(file) local file = io.open(path, "rb")
if f then if file then file:close() end
local s = f:read() return file ~= nil
f:close()
f = s
end
return f ~= nil
end end
-- get all lines from a file, returns an empty -- get a table with all lines from a file
-- list/table if the file does not exist function helpers.lines_from(path)
function helpers.lines_from(file)
if not helpers.file_exists(file) then return {} end
local lines = {} local lines = {}
for line in io.lines(file) do for line in io.lines(path) do
lines[#lines + 1] = line lines[#lines + 1] = line
end end
return lines return lines
end end
-- match all lines from a file, returns an empty -- get a table with all lines from a file matching regexp
-- list/table if the file or match does not exist function helpers.lines_match(regexp, path)
function helpers.lines_match(regexp, file)
local lines = {} local lines = {}
for index,line in pairs(helpers.lines_from(file)) do for line in io.lines(path) do
if string.match(line, regexp) then if string.match(line, regexp) then
lines[index] = line lines[#lines + 1] = line
end end
end end
return lines return lines
end end
-- get first line of a file, return nil if -- get first line of a file
-- the file does not exist function helpers.first_line(path)
function helpers.first_line(file) local file, first = io.open(path, "rb"), nil
return helpers.lines_from(file)[1] if file then
first = file:read("*l")
file:close()
end
return first
end end
-- get first non empty line from a file, -- get first non empty line from a file
-- returns nil otherwise function helpers.first_nonempty_line(path)
function helpers.first_nonempty_line(file) for line in io.lines(path) do
for k,v in pairs(helpers.lines_from(file)) do if #line then return line end
if #v then return v end
end end
return nil return nil
end end