feat(plugin): improve error handling and show better error message

This commit is contained in:
Folke Lemaitre 2024-07-23 17:24:33 +02:00
parent d5686efbd0
commit c02268ac6e
No known key found for this signature in database
GPG Key ID: 41F8B1FBACAE2040
1 changed files with 25 additions and 16 deletions

View File

@ -146,33 +146,43 @@ function Spec:import(spec)
local imported = 0 local imported = 0
---@type (string|(fun():LazyPluginSpec))[] ---@type {modname: string, load: fun():(LazyPluginSpec?, string?)}[]
local modspecs = {} local modspecs = {}
if type(import) == "string" then if type(import) == "string" then
Util.lsmod(import, function(modname, modpath) Util.lsmod(import, function(modname, modpath)
modspecs[#modspecs + 1] = modname modspecs[#modspecs + 1] = {
package.preload[modname] = function() modname = modname,
return loadfile(modpath)() load = function()
end local mod, err = loadfile(modpath)
end) if mod then
table.sort(modspecs) return mod()
else else
modspecs = { spec.import } return nil, err
end
end,
}
end)
table.sort(modspecs, function(a, b)
return a.modname < b.modname
end)
else
modspecs = { modname = import_name, load = spec.import }
end end
for _, modspec in ipairs(modspecs) do for _, modspec in ipairs(modspecs) do
imported = imported + 1 imported = imported + 1
local modname = type(modspec) == "string" and modspec or import_name local modname = modspec.modname
Util.track({ import = modname }) Util.track({ import = modname })
self.importing = modname self.importing = modname
-- unload the module so we get a clean slate -- unload the module so we get a clean slate
---@diagnostic disable-next-line: no-unknown ---@diagnostic disable-next-line: no-unknown
package.loaded[modname] = nil package.loaded[modname] = nil
Util.try(function() Util.try(function()
local mod = type(modspec) == "function" and modspec() or require(modspec) local mod, err = modspec.load()
if type(mod) ~= "table" then if err then
self.importing = nil self:error("Failed to load `" .. modname .. "`:\n" .. err)
elseif type(mod) ~= "table" then
return self:error( return self:error(
"Invalid spec module: `" "Invalid spec module: `"
.. modname .. modname
@ -180,18 +190,17 @@ function Spec:import(spec)
.. type(mod) .. type(mod)
.. "` was returned instead" .. "` was returned instead"
) )
end else
self:normalize(mod) self:normalize(mod)
self.importing = nil end
Util.track()
end, { end, {
msg = "Failed to load `" .. modname .. "`", msg = "Failed to load `" .. modname .. "`",
on_error = function(msg) on_error = function(msg)
self:error(msg) self:error(msg)
self.importing = nil
Util.track()
end, end,
}) })
self.importing = nil
Util.track()
end end
if imported == 0 then if imported == 0 then
self:error("No specs found for module " .. spec.import) self:error("No specs found for module " .. spec.import)