computable-pandoc/src/extensions.lua

99 lines
2.2 KiB
Lua

------------------------------------ MODS ------------------------------------
-- Tries popen
-- @param ... string: Chunks for popen
-- @return boolean, string: Status and output of popen
function io.try(...)
local cmd = table.concat({...}, " ") .. " 2>&1"
local handle = io.popen(cmd)
local output = handle:read("*a")
local status = (handle:close() ~= nil and true or false)
return status, output
end
-- Gets OS short name
-- It is just intented to know if it is Linux, macOS or Windows.
-- @return string: "linux" or "macos" or "windows"
function os.uname()
local status, output = io.try("uname")
if status then
output = output:gsub(" .*", ""):lower()
if output ~= "linux" then
return "macos"
end
return "linux"
end
return "windows"
end
-- Checks if OS is windows
-- @return boolean: Windows or not
function os.iswin()
return os.uname() == "windows"
end
-- Checks if OS is Unix
-- @return boolean: Unix or not
function os.isunix()
return os.uname() ~= "windows"
end
-- Changes newlines so everything is in one line
-- @return string: String with formatted newlines as literal "\n"
function string:linearize()
return self:gsub("\n", "\\\\n")
end
-- Checks if string is empty
-- @return boolean: Empty or not
function string:isempty()
return self == ''
end
function string:lstrip()
return self:gsub("^%s+", "")
end
function string:rstrip()
return self:gsub("%s+$", "")
end
function string:strip()
return self:lstrip():rstrip()
end
-- The following are heavily influenced by Python pathlib
-- Check: https://docs.python.org/3/library/pathlib.html
-- Checks if string is a file or directory
-- @return boolean: Exists or not
function string:exists()
return os.rename(self, self) ~= nil
end
-- Checks if string is a file
-- @return boolean: File or not
function string:isfile()
if self:exists() then
return io.open(self, "a+") ~= nil
end
return false
end
-- Checks if string is a directory
-- @return boolean: Directory or not
function string:isdir()
if self:exists() then
return io.open(self, "a+") == nil
end
return false
end
-- Reads file content
-- @return string or nil: File content or nil
function string:read_text()
if self:exists() then
return io.open(self):read("*a")
end
end