103 lines
2.5 KiB
Lua
103 lines
2.5 KiB
Lua
local h = require('dep.helpers')
|
|
|
|
local logger = {}
|
|
|
|
logger.stage_colors = {
|
|
skip = "Comment",
|
|
clean = "Boolean",
|
|
install = "MoreMsg",
|
|
update = "WarningMsg",
|
|
delete = "Directory",
|
|
error = "ErrorMsg",
|
|
}
|
|
|
|
--- create the default logging path
|
|
---@return string path to the logfile
|
|
local function default_log_path()
|
|
-- create cache directory and chmod it if it doesn't already exist
|
|
local path = vim.fn.stdpath("cache")
|
|
if not h.uv.fs_stat(path) then
|
|
h.uv.fs_mkdir(path, 0x1ff) -- 0777
|
|
end
|
|
|
|
return vim.fs.normalize(path).."/dep.log"
|
|
end
|
|
|
|
--- attempt to format a string
|
|
---@vararg string formating args
|
|
local function try_format(...)
|
|
local ok, s = pcall(string.format, ...)
|
|
if ok then
|
|
return s
|
|
end
|
|
end
|
|
|
|
--- setup all logging stuff
|
|
---@param path string|nil optional alternative path for the log file
|
|
---@return table
|
|
function logger:setup(path)
|
|
logger.path = path or default_log_path()
|
|
local pipe
|
|
|
|
logger.handle = assert(h.uv.fs_open(logger.path, "w", 0x1a4)) -- 0644
|
|
pipe = h.uv.new_pipe()
|
|
pipe:open(logger.handle)
|
|
|
|
return pipe
|
|
end
|
|
|
|
--- log a message
|
|
---@param level string error level
|
|
---@param message any string message to send
|
|
---@vararg any options to go into the message
|
|
function logger:log(level, message, ...)
|
|
-- make sure the message string is actually a string, and formatted
|
|
-- appropriately
|
|
if type(message) == "string" then
|
|
message = try_format(message, ...) or message
|
|
else
|
|
message = vim.inspect(message)
|
|
end
|
|
|
|
-- get debug info about the current function
|
|
local source = debug.getinfo(2, "Sl")
|
|
|
|
-- schedule a log message to be sent to vim, and the log file
|
|
vim.schedule(function()
|
|
if not logger.silent then
|
|
if level == "error" then
|
|
vim.api.nvim_echo({ { string.format("[dep] %s", message) } }, true,
|
|
{ err = true })
|
|
elseif logger.stage_colors[level] then
|
|
vim.api.nvim_echo({
|
|
{ "[dep]", "Identifier" },
|
|
{ " " },
|
|
{ message, logger.stage_colors[level] },
|
|
}, true, {})
|
|
end
|
|
end
|
|
|
|
-- write to the pipe if it's open
|
|
if logger.pipe then
|
|
logger.pipe:write(string.format("[%s] %s:%s:(%s) %s\n", os.date("%T"),
|
|
source.short_src:gsub('.*%/', ''), source.currentline, level, message))
|
|
end
|
|
end)
|
|
end
|
|
|
|
--- cleanup all logging stuff
|
|
---@param pipe table? pipe
|
|
---@param handle table? handle
|
|
function logger:cleanup(pipe, handle)
|
|
if pipe then
|
|
pipe:close()
|
|
pipe = nil
|
|
end
|
|
if handle then
|
|
h.uv.fs_close(logger.handle)
|
|
handle = nil
|
|
end
|
|
end
|
|
|
|
return logger
|