Skip to content

Commit

Permalink
Fix failing to report error when distant_lua lib fails to load
Browse files Browse the repository at this point in the history
  • Loading branch information
chipsenkbeil committed Nov 10, 2021
1 parent 06de9e1 commit 1d798b3
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
2 changes: 2 additions & 0 deletions doc/distant.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1293,6 +1293,8 @@ Latest ~
* Add logging initialization for distant lua shared library
* Fix `poll_interval` to be properly applied when polling futures
* Add |DistantConnect| as new command alternative to |DistantLaunch|
* Fix failing to load Rust lua module getting masked by a prompt to
install the module when an error is encountered

v0.1.1 ~

Expand Down
45 changes: 45 additions & 0 deletions lua/distant/lib.lua
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,31 @@ local function is_loaded()
return package.loaded[LIB_NAME] ~= nil
end

--- Returns object with loaded (bool) and errors (list of err strings)
--- when attempting to a load a library
---
--- From https://stackoverflow.com/a/15434737
local function try_load_lib(name)
local errors = {}

if package.loaded[name] then
return { loaded = true, errors = errors }
else
for _, searcher in ipairs(package.searchers or package.loaders) do
local success, loader = pcall(searcher, name)
if success then
if type(loader) == 'function' then
package.preload[name] = loader
return { loaded = true, errors = errors }
end
else
table.insert(errors, tostring(loader))
end
end
return { loaded = false, errors = errors }
end
end

--- Loads the library asynchronously, providing several options to install the library
--- if it is unavailable
---
Expand All @@ -536,6 +561,8 @@ end
--- @param opts table
--- @param cb function (bool, lib|err) where bool = true on success and lib would be second arg
local function load(opts, cb)
local lib_status, err_msg

if not cb then
cb = opts
opts = {}
Expand All @@ -548,6 +575,15 @@ local function load(opts, cb)

-- If not reloading the library
if not opts.reload then
lib_status = try_load_lib(LIB_NAME)
if not lib_status.loaded and not vim.tbl_isempty(lib_status.errors) then
err_msg = ''
for _, err in ipairs(lib_status.errors) do
err_msg = err_msg .. err
end
return cb(false, err_msg)
end

local success, lib = pcall(require, LIB_NAME)
if success then
return cb(success, lib)
Expand Down Expand Up @@ -580,6 +616,15 @@ local function load(opts, cb)
return cb(status, msg)
end

lib_status = try_load_lib(LIB_NAME)
if not lib_status.loaded and not vim.tbl_isempty(lib_status.errors) then
err_msg = ''
for _, err in ipairs(lib_status.errors) do
err_msg = err_msg .. err
end
return cb(false, err_msg)
end

return cb(pcall(require, LIB_NAME))
end

Expand Down

0 comments on commit 1d798b3

Please sign in to comment.