Class: Pocketbook::CLI::Watcher::ChangeBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/pocketbook/cli/watch_command.rb

Instance Method Summary collapse

Constructor Details

#initialize(debounce_seconds:, poll_interval:, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }) ⇒ ChangeBuffer

Returns a new instance of ChangeBuffer.



16
17
18
19
20
21
22
23
24
25
# File 'lib/pocketbook/cli/watch_command.rb', line 16

def initialize(debounce_seconds:, poll_interval:, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
  @debounce_seconds = debounce_seconds
  @poll_interval = poll_interval
  @clock = clock
  @pending_paths = Set.new
  @stopped = false
  @last_change_at = nil
  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Method Details

#add(paths) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/pocketbook/cli/watch_command.rb', line 27

def add(paths)
  normalized = paths.map { |path| File.expand_path(path) }.uniq
  return if normalized.empty?

  @mutex.synchronize do
    normalized.each { |path| @pending_paths << path }
    @last_change_at = @clock.call
    @condition.broadcast
  end
end

#next_batchObject



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
# File 'lib/pocketbook/cli/watch_command.rb', line 38

def next_batch
  @mutex.synchronize do
    while !@stopped && @pending_paths.empty?
      @condition.wait(@mutex, @poll_interval)
    end

    return nil if @stopped

    loop do
      break if @stopped

      elapsed = @clock.call - @last_change_at
      remaining = @debounce_seconds - elapsed
      break if remaining <= 0

      @condition.wait(@mutex, [remaining, @poll_interval].min)
    end

    return nil if @stopped

    paths = @pending_paths.to_a.sort
    @pending_paths.clear
    paths
  end
end

#stop!Object



64
65
66
67
68
69
70
71
# File 'lib/pocketbook/cli/watch_command.rb', line 64

def stop!
  @mutex.synchronize do
    return if @stopped

    @stopped = true
    @condition.broadcast
  end
end

#wait_until_stoppedObject



73
74
75
76
77
# File 'lib/pocketbook/cli/watch_command.rb', line 73

def wait_until_stopped
  @mutex.synchronize do
    @condition.wait(@mutex, @poll_interval) until @stopped
  end
end