Class: Listen::Listener

Inherits:
Object
  • Object
show all
Includes:
Celluloid::FSM, QueueOptimizer
Defined in:
lib/listen/listener.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from QueueOptimizer

#_calculate_add_remove_difference, #_detect_possible_editor_save, #_logical_action_for, #_reinterpret_related_changes, #_smoosh_changes, #_squash_changes

Constructor Details

#initialize(*args) {|modified, added, removed| ... } ⇒ Listener

Initializes the directories listener.

Parameters:

  • directory (String)

    the directories to listen to

  • options (Hash)

    the listen options (see Listen::Listener::Options)

Yields:

  • (modified, added, removed)

    the changed files

Yield Parameters:

  • modified (Array<String>)

    the list of modified files

  • added (Array<String>)

    the list of added files

  • removed (Array<String>)

    the list of removed files



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/listen/listener.rb', line 36

def initialize(*args, &block)
  @options = _init_options(args.last.is_a?(Hash) ? args.pop : {})

  # Setup logging first
  if Celluloid.logger
    Celluloid.logger.level = _debug_level
    _log :info, "Celluloid loglevel set to: #{Celluloid.logger.level}"
  end

  @silencer = Silencer.new
  _reconfigure_silencer({})

  @tcp_mode = nil
  if [:recipient, :broadcaster].include? args[1]
    target = args.shift
    @tcp_mode = args.shift
    _init_tcp_options(target)
  end

  @directories = args.flatten.map { |path| Pathname.new(path).realpath }
  @queue = Queue.new
  @block = block
  @registry = Celluloid::Registry.new

  transition :stopped
end

Instance Attribute Details

#blockObject

Returns the value of attribute block.



14
15
16
# File 'lib/listen/listener.rb', line 14

def block
  @block
end

#directoriesObject (readonly)

TODO: deprecate



19
20
21
# File 'lib/listen/listener.rb', line 19

def directories
  @directories
end

#hostObject (readonly)

TODO: deprecate NOTE: these are VERY confusing (broadcast + recipient modes)



24
25
26
# File 'lib/listen/listener.rb', line 24

def host
  @host
end

#optionsObject (readonly)

TODO: deprecate



19
20
21
# File 'lib/listen/listener.rb', line 19

def options
  @options
end

#portObject (readonly)

TODO: deprecate NOTE: these are VERY confusing (broadcast + recipient modes)



24
25
26
# File 'lib/listen/listener.rb', line 24

def port
  @port
end

#registryObject (readonly)

Returns the value of attribute registry.



20
21
22
# File 'lib/listen/listener.rb', line 20

def registry
  @registry
end

#silencerObject (readonly)

Returns the value of attribute silencer.



16
17
18
# File 'lib/listen/listener.rb', line 16

def silencer
  @silencer
end

#supervisorObject (readonly)

Returns the value of attribute supervisor.



20
21
22
# File 'lib/listen/listener.rb', line 20

def supervisor
  @supervisor
end

#wait_threadObject (readonly, private)

Returns the value of attribute wait_thread.



286
287
288
# File 'lib/listen/listener.rb', line 286

def wait_thread
  @wait_thread
end

Instance Method Details

#_adapter_classObject (private)



260
261
262
# File 'lib/listen/listener.rb', line 260

def _adapter_class
  @adapter_class ||= Adapter.select(options)
end

#_debug_levelObject (private)



183
184
185
186
187
188
189
190
191
192
193
# File 'lib/listen/listener.rb', line 183

def _debug_level
  debugging = ENV['LISTEN_GEM_DEBUGGING'] || options[:debug]
  case debugging.to_s
  when /2/
    Logger::DEBUG
  when /true|yes|1/i
    Logger::INFO
  else
    Logger::ERROR
  end
end

#_init_actorsObject (private)



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/listen/listener.rb', line 195

def _init_actors
  options = [mq: self, directories: directories]

  @supervisor = Celluloid::SupervisionGroup.run!(registry)
  supervisor.add(Record, as: :record, args: self)
  supervisor.pool(Change, as: :change_pool, args: self)

  # TODO: broadcaster should be a separate plugin
  if @tcp_mode == :broadcaster
    require 'listen/tcp/broadcaster'
    supervisor.add(TCP::Broadcaster, as: :broadcaster, args: [@host, @port])

    # TODO: should be auto started, because if it crashes
    # a new instance is spawned by supervisor, but it's 'start' isn't
    # called
    registry[:broadcaster].start
  elsif @tcp_mode == :recipient
    # TODO: adapter options should be configured in Listen.{on/to}
    options.first.merge!(host: @host, port: @port)
  end

  supervisor.add(_adapter_class, as: :adapter, args: options)
end

#_init_options(options = {}) ⇒ Object (private)



175
176
177
178
179
180
181
# File 'lib/listen/listener.rb', line 175

def _init_options(options = {})
  { debug: false,
    latency: nil,
    wait_for_delay: 0.1,
    force_polling: false,
    polling_fallback_message: nil }.merge(options)
end

#_init_tcp_options(target) ⇒ Object (private)



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/listen/listener.rb', line 288

def _init_tcp_options(target)
  # Handle TCP options here
  require 'listen/tcp'
  fail ArgumentError, 'missing host/port for TCP' unless target

  if @tcp_mode == :recipient
    @host = 'localhost'
    @options[:force_tcp] = true
  end

  if target.is_a? Fixnum
    @port = target
  else
    @host, port = target.split(':')
    @port = port.to_i
  end
end

#_log(type, message) ⇒ Object (private)



256
257
258
# File 'lib/listen/listener.rb', line 256

def _log(type, message)
  Celluloid::Logger.send(type, message)
end

#_process_changesObject (private)

for easier testing without sleep loop



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/listen/listener.rb', line 265

def _process_changes
  return if @queue.empty?

  @last_queue_event_time = nil

  changes = []
  while !@queue.empty?
    changes << @queue.pop
  end

  return if block.nil?

  hash = _smoosh_changes(changes)
  result = [hash[:modified], hash[:added], hash[:removed]]

  block_start = Time.now.to_f
  # TODO: condition not tested, but too complex to test ATM
  block.call(*result) unless result.all?(&:empty?)
  _log :debug, "Callback took #{Time.now.to_f - block_start} seconds"
end

#_queue_raw_change(type, dir, rel_path, options) ⇒ Object (private)



334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/listen/listener.rb', line 334

def _queue_raw_change(type, dir, rel_path, options)
  _log :debug, "raw queue: #{[type, dir, rel_path, options].inspect}"

  unless (worker = async(:change_pool))
    _log :warn, 'Failed to allocate worker from change pool'
    return
  end

  worker.change(type, dir, rel_path, options)
rescue RuntimeError
  _log :error, "#{__method__} crashed: #{$!}:#{$@.join("\n")}"
  raise
end

#_reconfigure_silencer(extra_options) ⇒ Object (private)



306
307
308
309
310
311
312
313
314
315
# File 'lib/listen/listener.rb', line 306

def _reconfigure_silencer(extra_options)
  @options.merge!(extra_options)

  # TODO: this should be directory specific
  rules = [:only, :ignore, :ignore!].map do |option|
    [option, @options[option]] if @options.key? option
  end

  @silencer.configure(Hash[rules.compact])
end

#_silenced?(path, type) ⇒ Boolean (private)

Returns:

  • (Boolean)


246
247
248
# File 'lib/listen/listener.rb', line 246

def _silenced?(path, type)
  @silencer.silenced?(path, type)
end

#_start_adapterObject (private)



250
251
252
253
254
# File 'lib/listen/listener.rb', line 250

def _start_adapter
  # Don't run async, because configuration has to finish first
  adapter = sync(:adapter)
  adapter.start
end

#_start_wait_threadObject (private)



317
318
319
# File 'lib/listen/listener.rb', line 317

def _start_wait_thread
  @wait_thread = Thread.new { _wait_for_changes }
end

#_stop_wait_threadObject (private)



325
326
327
328
329
330
331
332
# File 'lib/listen/listener.rb', line 325

def _stop_wait_thread
  return unless wait_thread
  if wait_thread.alive?
    wait_thread.wakeup
    wait_thread.join
  end
  @wait_thread = nil
end

#_wait_for_changesObject (private)



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/listen/listener.rb', line 219

def _wait_for_changes
  latency = options[:wait_for_delay]

  loop do
    break if state == :stopped

    if state == :paused || @queue.empty?
      sleep
      break if state == :stopped
    end

    # Assure there's at least latency between callbacks to allow
    # for accumulating changes
    now = Time.now.to_f
    diff = latency + (@last_queue_event_time || now) - now
    if diff > 0
      sleep diff
      next
    end

    _process_changes unless state == :paused
  end
rescue RuntimeError
  Kernel.warn "[Listen warning]: Change block raised an exception: #{$!}"
  Kernel.warn "Backtrace:\n\t#{$@.join("\n\t")}"
end

#_wakeup_wait_threadObject (private)



321
322
323
# File 'lib/listen/listener.rb', line 321

def _wakeup_wait_thread
  wait_thread.wakeup if wait_thread && wait_thread.alive?
end

#async(type) ⇒ Object



149
150
151
152
# File 'lib/listen/listener.rb', line 149

def async(type)
  proxy = sync(type)
  proxy ? proxy.async : nil
end

#ignore(regexps) ⇒ Object

Add files and dirs to ignore on top of defaults

(@see Listen::Silencer for default ignored files and dirs)



135
136
137
# File 'lib/listen/listener.rb', line 135

def ignore(regexps)
  _reconfigure_silencer(ignore: [options[:ignore], regexps])
end

#ignore!(regexps) ⇒ Object

Replace default ignore patterns with provided regexp



140
141
142
# File 'lib/listen/listener.rb', line 140

def ignore!(regexps)
  _reconfigure_silencer(ignore: [], ignore!: regexps)
end

#only(regexps) ⇒ Object

Listen only to files and dirs matching regexp



145
146
147
# File 'lib/listen/listener.rb', line 145

def only(regexps)
  _reconfigure_silencer(only: regexps)
end

#pauseObject

Stops invoking callbacks (messages pile up)



107
108
109
# File 'lib/listen/listener.rb', line 107

def pause
  transition :paused
end

#paused=(value) ⇒ Object

TODO: deprecate



124
125
126
# File 'lib/listen/listener.rb', line 124

def paused=(value)
  transition value ? :paused : :processing
end

#paused?Boolean Also known as: paused

Returns:

  • (Boolean)


116
117
118
# File 'lib/listen/listener.rb', line 116

def paused?
  state == :paused
end

#processing?Boolean Also known as: listen?

processing means callbacks are called

Returns:

  • (Boolean)


112
113
114
# File 'lib/listen/listener.rb', line 112

def processing?
  state == :processing
end

#queue(type, change, dir, path, options = {}) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/listen/listener.rb', line 158

def queue(type, change, dir, path, options = {})
  fail "Invalid type: #{type.inspect}" unless [:dir, :file].include? type
  fail "Invalid change: #{change.inspect}" unless change.is_a?(Symbol)
  fail "Invalid path: #{path.inspect}" unless path.is_a?(String)
  @queue << [type, change, dir, path, options]

  @last_queue_event_time = Time.now.to_f
  _wakeup_wait_thread unless state == :paused

  return unless @tcp_mode == :broadcaster

  message = TCP::Message.new(type, change, dir, path, options)
  registry[:broadcaster].async.broadcast(message.payload)
end

#startObject Also known as: unpause

Starts processing events and starts adapters or resumes invoking callbacks if paused



94
95
96
# File 'lib/listen/listener.rb', line 94

def start
  transition :processing
end

#stopObject

Stops processing and terminates all actors



102
103
104
# File 'lib/listen/listener.rb', line 102

def stop
  transition :stopped
end

#sync(type) ⇒ Object



154
155
156
# File 'lib/listen/listener.rb', line 154

def sync(type)
  @registry[type]
end