-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch.lua
More file actions
executable file
·106 lines (87 loc) · 2.28 KB
/
watch.lua
File metadata and controls
executable file
·106 lines (87 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
local inotify = require 'inotify'
local uv = require "luv"
local ws = require "lib.ws"
local term = require "lib.utils.term"
local path = require "lib.utils.path"
local config = require "config.const"
local colors = term.colors
local git_ignore_file = io.open(".gitignore", "r")
if not git_ignore_file then
print(colors.red_bright("No .gitignore file found"))
os.exit(1)
end
local git_ignore = git_ignore_file:read "*a"
git_ignore_file:close()
local ignored = git_ignore .. "\n.git\n.gitignore"
local where = arg[1] or "."
local handle = inotify.init()
local watchers = {}
local ws_server = ws.createServer(config.HOST, config.PORT + 1)
local function is_ignored(target)
return target == ".." or target == "." or ignored:match(target) ~= nil
end
local function create_dir_watch(dir_path)
if watchers[dir_path] then
return watchers[dir_path]
end
local watcher = handle:addwatch(dir_path, inotify.IN_MODIFY)
watchers[dir_path] = watcher
return watcher
end
local function create_watchers(from)
local dir = assert(uv.fs_scandir(from))
create_dir_watch(from)
for name, type in uv.fs_scandir_next, dir do
local target = path.resolve(from, name)
if type == "directory" and not is_ignored(name) then
create_watchers(target)
end
end
end
---@param callback fun(last_modified: integer)
local function watch_where(from, callback)
create_watchers(from)
local noop = false -- trick around `IN_MODIFY` being triggered twice
for event in handle:events() do
if not noop then
if event.mask == inotify.IN_MODIFY then
callback(event.wd)
end
end
noop = not noop
end
end
---@class Dev
local Dev = {}
function Dev:new()
return self
end
function Dev:run()
os.execute("./start &")
end
function Dev:stop()
os.execute("kill $(lsof -t -i:" .. config.PORT .. ")")
end
function Dev:restart()
self:stop()
-- term.resetTerm()
self:run()
end
local function watch()
local dev = Dev:new()
local signal = uv.new_signal()
uv.signal_start(signal, "sigint", function()
print(colors.yellow_bright("Stopping server"))
dev:stop()
handle:close()
os.exit(1)
end)
ws_server:start()
dev:run()
watch_where(where, function()
print(colors.blue_bright("File changed, restarting server"))
dev:restart()
end)
end
watch()
uv.run()