Skip to content

Commit

Permalink
Merge pull request #20 from jeremy/stop-listening-when-stale
Browse files Browse the repository at this point in the history
Watcher: if we're already stale, no need to keep listening for changes
  • Loading branch information
rafaelfranca authored Sep 22, 2022
2 parents 229ff1e + 4cb49f2 commit 18c4d12
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/spring/watcher/listen.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ class Listen < Abstract

attr_reader :listener

def initialize(*)
super
@listener = nil
end

def start
return if defined?(@listener) && @listener

Expand All @@ -37,6 +42,10 @@ def stop
end
end

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

def subjects_changed
return unless defined?(@listener)
return unless @listener.respond_to?(:directories)
Expand All @@ -56,6 +65,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.keys.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 @@ -55,4 +55,22 @@ def watcher_class
FileUtils.rm_rf 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

0 comments on commit 18c4d12

Please sign in to comment.