Skip to content

Commit 121cd9a

Browse files
committed
utils: watcher
1 parent c4b50f2 commit 121cd9a

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

src/utils/watcher.cr

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,46 @@
1818
# -----------------------------------------------------------------------
1919

2020
module MoonScript
21-
class Watcher
22-
@patterns = Array(String) = [] of String
23-
@state = Set(Tuple(String, Time)).new
21+
class Watcher
22+
@patterns : Array(String) = [] of String
23+
@state = Set(Tuple(String, Time)).new
2424

25-
def initialize(&@listener: Proc(Array(String), Symbol, Nil))
26-
end
25+
def initialize(&@listener : Proc(Array(String), Symbol, Nil))
26+
end
27+
28+
def patterns=(@patterns : Array(String))
29+
@state.clear
30+
scan :reset
31+
end
32+
33+
def scan(reason : Symbol)
34+
current =
35+
Dir.glob(@patterns)
36+
.map(&->info(String))
37+
.sort_by!(&.last)
38+
.to_set
39+
40+
diff = @state ^ current
2741

28-
def patterns=(@patterns: Array(String))
29-
@state.clear
30-
scan: reset
31-
end
42+
@listener.call(diff.map(&.first).uniq!, reason) unless diff.empty?
43+
44+
@state = current
45+
end
46+
47+
def info(file : String)
48+
path =
49+
Path[file].normalize.expand.to_s
50+
51+
{path, File.info(path).modification_time}
52+
end
3253

33-
def scan(reason: Symbol)
34-
current = Dir.glob(@patterns).map(&->info(String)).sort_by!(&.last).to_set
35-
end
54+
def watch
55+
spawn do
56+
loop do
57+
sleep 0.1.seconds
58+
scan :modified
59+
end
60+
end
3661
end
37-
end
62+
end
63+
end

0 commit comments

Comments
 (0)