Skip to content

Commit 4cb49f2

Browse files
committed
Watcher: if we're already stale, no need to keep listening for changes
1 parent c4bfe15 commit 4cb49f2

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/spring/watcher/listen.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ class Listen < Abstract
2121

2222
attr_reader :listener
2323

24+
def initialize(*)
25+
super
26+
@listener = nil
27+
end
28+
2429
def start
2530
unless @listener
2631
@listener = ::Listen.to(*base_directories, latency: latency, &method(:changed))
@@ -35,6 +40,10 @@ def stop
3540
end
3641
end
3742

43+
def running?
44+
@listener && @listener.processing?
45+
end
46+
3847
def subjects_changed
3948
return unless @listener
4049
return unless @listener.respond_to?(:directories)
@@ -54,6 +63,14 @@ def changed(modified, added, removed)
5463
end
5564
end
5665

66+
def mark_stale
67+
super
68+
69+
# May be called from listen thread which won't be happy
70+
# about stopping itself, so stop from another thread.
71+
Thread.new { stop }.join
72+
end
73+
5774
def base_directories
5875
([root] +
5976
files.reject { |f| f.start_with? "#{root}/" }.map { |f| File.expand_path("#{f}/..") } +

test/unit_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,22 @@ def watcher_class
5353
FileUtils.rmdir other_dir_2
5454
end
5555
end
56+
57+
test "stops listening when already stale" do
58+
# Track when we're marked as stale.
59+
on_stale_count = 0
60+
watcher.on_stale { on_stale_count += 1 }
61+
62+
# Add a file to watch and start listening.
63+
file = "#{@dir}/omg"
64+
touch file, Time.now - 2.seconds
65+
watcher.add file
66+
watcher.start
67+
assert watcher.running?
68+
69+
# Touch bumps mtime and marks as stale which stops listener.
70+
touch file, Time.now - 1.second
71+
Timeout.timeout(1) { sleep 0.1 while watcher.running? }
72+
assert_equal 1, on_stale_count
73+
end
5674
end

0 commit comments

Comments
 (0)