Skip to content

Commit

Permalink
chore(packages): Protect existing instances of packages
Browse files Browse the repository at this point in the history
This re-runs the _init() function to potentially force a reload or
change options, but it avoids re-instantiating a new instance from the
package class.
  • Loading branch information
alerque committed Jan 31, 2024
1 parent ec6ed65 commit 3c3fada
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
27 changes: 22 additions & 5 deletions classes/base.lua
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,31 @@ end

function class:loadPackage (packname, options, reload)
local pack
-- Allow loading by injecting whole packages as-is, otherwise try to load it with the usual packages path.
if type(packname) == "table" then
pack = packname
pack, packname = packname, packname._name
else
pack = require(("packages.%s"):format(packname))
pack = require(("packages.%s"):format(packname))
if pack._name ~= packname then
SU.error(("Loaded module name '%s' does not match requested name '%s'"):format(pack._name, packname))
end
end
if type(pack) == "table" and pack.type == "package" then -- new package
local name = pack._name
self.packages[name] = pack(options, reload)
SILE.packages[packname] = pack
if type(pack) == "table" and pack.type == "package" then -- current package api
if self.packages[packname] then
-- If the same package name has been loaded before, we might be loading a modified version of the same package or
-- we might be re-loading the same package, or we might just be doubling up work because somebody called us twice.
-- The package itself should take care of the difference between load and reload based on the reload flag here,
-- but in addition to that we also want to avoid creating a new instance. We want to run the intitializer from the
-- (possibly different) new module, but not create a new instance ID and loose any connections it made.
-- To do this we add a create function that returns the current instance. This brings along the _initialized flag
-- and of course anything else already setup and running.
local current_instance = self.packages[packname]
pack._create = function () return current_instance end
pack(options, true)
else
self.packages[packname] = pack(options, reload)
end
else -- legacy package
self:initPackage(pack, options)
end
Expand Down
1 change: 1 addition & 0 deletions core/sile.lua
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ SILE.use = function (module, options, reload)
SILE.pagebuilders[name] = pack
SILE.pagebuilder = pack(options)
elseif pack.type == "package" then
SILE.packages[pack._name] = pack
if class then
class:loadPackage(pack, options, reload)
else
Expand Down

0 comments on commit 3c3fada

Please sign in to comment.