Skip to content

Watcher: if we're already stale, no need to keep listening for changes #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions lib/spring/watcher/listen.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ class Listen < Abstract

attr_reader :listener

def initialize(*)
super
@listener = nil
end

def start
unless @listener
@listener = ::Listen.to(*base_directories, latency: latency, &method(:changed))
Expand All @@ -35,6 +40,10 @@ def stop
end
end

def running?
@listener && @listener.processing?
end

def subjects_changed
return unless @listener
return unless @listener.respond_to?(:directories)
Expand All @@ -54,6 +63,14 @@ def changed(modified, added, removed)
end
end

def mark_stale
super

# May be called from listen thread which won't be happy
# about stopping itself, so stop from another thread.
Thread.new { stop }.join
end

def base_directories
([root] +
files.reject { |f| f.start_with? "#{root}/" }.map { |f| File.expand_path("#{f}/..") } +
Expand Down
18 changes: 18 additions & 0 deletions test/unit_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,22 @@ def watcher_class
FileUtils.rmdir other_dir_2
end
end

test "stops listening when already stale" do
# Track when we're marked as stale.
on_stale_count = 0
watcher.on_stale { on_stale_count += 1 }

# Add a file to watch and start listening.
file = "#{@dir}/omg"
touch file, Time.now - 2.seconds
watcher.add file
watcher.start
assert watcher.running?

# Touch bumps mtime and marks as stale which stops listener.
touch file, Time.now - 1.second
Timeout.timeout(1) { sleep 0.1 while watcher.running? }
assert_equal 1, on_stale_count
end
end