Skip to content

Commit

Permalink
enhancement(fs): Cache loaded files like require
Browse files Browse the repository at this point in the history
  • Loading branch information
dabrady committed Aug 30, 2020
1 parent 102ea78 commit fc9bbb4
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions hammerspoon/fs.lua
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,25 @@ function module.dirs(path)
end

-- Load each file in a given directory with the given extension, with any arguments given.
function module.loadAllFiles(rootDir, ext, ...)
function module.loadAllFiles(rootDir, ext, prefix, ...)
-- Make sure our root ends with a directory marker.
rootDir = rootDir:endsWith('/') and rootDir or rootDir..'/'
prefix = prefix or ''

local loadedScripts = {}
local _,scripts = hs.fs.dir(rootDir)
repeat
local filename = scripts:next()
if filename and filename ~= '.' and filename ~= '..' and filename:endsWith(ext) then
print('\t\tloading script: '..filename)
print('\t\tloading script: '..prefix..filename)
-- Load the script, passing the given arguments as parameters to the Lua chunk.
-- Using `assert(loadfile(...))` instead of `require` to be compatible with Spoons.
local script = assert(loadfile(rootDir..filename))(...)
local basename = filename:match("^(.+)%.") -- Matches everything up to the first '.'

-- Cache it like `require` does
package.loaded[prefix..basename] = script

loadedScripts[basename] = script
end
until filename == nil
Expand Down

0 comments on commit fc9bbb4

Please sign in to comment.