diff options
author | 最萌小汐 <sumneko@hotmail.com> | 2021-08-18 19:55:04 +0800 |
---|---|---|
committer | 最萌小汐 <sumneko@hotmail.com> | 2021-08-18 19:55:04 +0800 |
commit | 38d46faae20bbdbc3578452f020276766aed67e0 (patch) | |
tree | 6ff276e89459b4d7098a5d1e50789a82ab2c6449 /script/filewatch.lua | |
parent | 1d0dc164b84fffdfe281615013278013baf9aae7 (diff) | |
download | lua-language-server-38d46faae20bbdbc3578452f020276766aed67e0.zip |
watching library changes
Diffstat (limited to 'script/filewatch.lua')
-rw-r--r-- | script/filewatch.lua | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/script/filewatch.lua b/script/filewatch.lua new file mode 100644 index 00000000..fd3b8686 --- /dev/null +++ b/script/filewatch.lua @@ -0,0 +1,78 @@ +local fw = require 'bee.filewatch' +local fs = require 'bee.filesystem' +local await = require 'await' + +local MODIFY = 1 << 0 +local RENAME = 1 << 1 + +---@class filewatch +local m = {} + +m._eventList = {} + +function m.watch(path) + local id = fw.add(path) + return function () + fw.remove(id) + end +end + +function m.event(callback) + m._eventList[#m._eventList+1] = callback +end + +function m._callEvent(changes) + for _, callback in ipairs(m._eventList) do + await.call(function () + callback(changes) + end) + end +end + +function m.update() + local collect + while true do + local ev, path = fw.select() + if not ev then + break + end + if not collect then + collect = {} + end + if ev == 'modify' then + collect[path] = (collect[path] or 0) | MODIFY + elseif ev == 'rename' then + collect[path] = (collect[path] or 0) | RENAME + end + end + + if not collect or not next(collect) then + return + end + + local changes = {} + for path, flag in pairs(collect) do + if flag & RENAME ~= 0 then + if fs.exists(fs.path(path)) then + changes[#changes+1] = { + type = 'create', + path = path, + } + else + changes[#changes+1] = { + type = 'delete', + path = path, + } + end + elseif flag & MODIFY ~= 0 then + changes[#changes+1] = { + type = 'change', + path = path, + } + end + end + + m._callEvent(changes) +end + +return m |