Skip to content

Commit 044e28b

Browse files
committed
fix(cache): check package.loaded after auto-load and return existing module if present. Fixes #224
1 parent b8c5ab5 commit 044e28b

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

lua/lazy/core/cache.lua

+23-9
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,16 @@ function M.disable()
103103
M.enabled = false
104104
end
105105

106+
function M.check_loaded(modname)
107+
---@diagnostic disable-next-line: no-unknown
108+
local mod = package.loaded[modname]
109+
if type(mod) == "table" then
110+
return function()
111+
return mod
112+
end
113+
end
114+
end
115+
106116
---@param modname string
107117
---@return any
108118
function M.loader(modname)
@@ -111,12 +121,6 @@ function M.loader(modname)
111121
local chunk, err
112122
if entry and M.check_path(modname, entry.modpath) then
113123
M.stats.find.total = M.stats.find.total + 1
114-
local mod = package.loaded[modname]
115-
if type(mod) == "table" then
116-
return function()
117-
return mod
118-
end
119-
end
120124
chunk, err = M.load(modname, entry.modpath)
121125
end
122126
if not chunk then
@@ -127,7 +131,10 @@ function M.loader(modname)
127131
if M.enabled then
128132
chunk, err = M.load(modname, modpath)
129133
else
130-
chunk, err = M._loadfile(modpath)
134+
chunk = M.check_loaded(modname)
135+
if not chunk then
136+
chunk, err = M._loadfile(modpath)
137+
end
131138
end
132139
end
133140
end
@@ -145,6 +152,11 @@ end
145152
---@param modpath string
146153
---@return function?, string? error_message
147154
function M.load(modkey, modpath)
155+
local chunk, err
156+
chunk = M.check_loaded(modkey)
157+
if chunk then
158+
return chunk
159+
end
148160
modpath = modpath:gsub("\\", "/")
149161
local hash = M.hash(modpath)
150162
if not hash then
@@ -158,7 +170,7 @@ function M.load(modkey, modpath)
158170
entry.used = os.time()
159171
if M.eq(entry.hash, hash) then
160172
-- found in cache and up to date
161-
local chunk, err = loadstring(entry.chunk --[[@as string]], "@" .. entry.modpath)
173+
chunk, err = loadstring(entry.chunk --[[@as string]], "@" .. entry.modpath)
162174
if not (err and err:find("cannot load incompatible bytecode", 1, true)) then
163175
return chunk, err
164176
end
@@ -175,7 +187,7 @@ function M.load(modkey, modpath)
175187
end)
176188
end
177189

178-
local chunk, err = M._loadfile(entry.modpath)
190+
chunk, err = M._loadfile(entry.modpath)
179191
if chunk then
180192
M.dirty = true
181193
entry.chunk = string.dump(chunk)
@@ -184,7 +196,9 @@ function M.load(modkey, modpath)
184196
end
185197

186198
function M.require(modname)
199+
---@diagnostic disable-next-line: no-unknown
187200
local mod = M.loader(modname)()
201+
---@diagnostic disable-next-line: no-unknown
188202
package.loaded[modname] = mod
189203
return mod
190204
end

0 commit comments

Comments
 (0)