Class: Listen::Listener

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Internals::Logging

#_debug, #_error_exception, #_format_error, #_info, #_log, #_warn

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



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/listen/listener.rb', line 40

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
    _info "Celluloid loglevel set to: #{Celluloid.logger.level}"
    _info "Listen version: #{Listen::VERSION}"
  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.



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

def block
  @block
end

#directoriesObject (readonly)

TODO: deprecate



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

def directories
  @directories
end

#hostObject (readonly)

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



28
29
30
# File 'lib/listen/listener.rb', line 28

def host
  @host
end

#optionsObject (readonly)

TODO: deprecate



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

def options
  @options
end

#portObject (readonly)

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



28
29
30
# File 'lib/listen/listener.rb', line 28

def port
  @port
end

#registryObject (readonly)

Returns the value of attribute registry.



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

def registry
  @registry
end

#silencerObject (readonly)

Returns the value of attribute silencer.



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

def silencer
  @silencer
end

#supervisorObject (readonly)

Returns the value of attribute supervisor.



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

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)



262
263
264
# File 'lib/listen/listener.rb', line 262

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

#_debug_levelObject (private)



190
191
192
193
194
195
196
197
198
199
200
# File 'lib/listen/listener.rb', line 190

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)



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/listen/listener.rb', line 202

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)



182
183
184
185
186
187
188
# File 'lib/listen/listener.rb', line 182

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

#_process_changesObject (private)

for easier testing without sleep loop



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

def _process_changes
  return if @queue.empty?

  @last_queue_event_time = nil

  changes = []
  changes << @queue.pop until @queue.empty?

  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?)
  _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)
  _debug "raw queue: #{[type, dir, rel_path, options].inspect}"

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

  worker.change(type, dir, rel_path, options)
rescue RuntimeError
  _error_exception "_queue_raw_change exception %s:\n%s:\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)


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

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

#_start_adapterObject (private)



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

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)



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/listen/listener.rb', line 226

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 _format_error('exception while processing events: %s %s')
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



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

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)



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

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

#ignore!(regexps) ⇒ Object

Replace default ignore patterns with provided regexp



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

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

#only(regexps) ⇒ Object

Listen only to files and dirs matching regexp



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

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

#pauseObject

Stops invoking callbacks (messages pile up)



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

def pause
  transition :paused
end

#paused=(value) ⇒ Object

TODO: deprecate



129
130
131
# File 'lib/listen/listener.rb', line 129

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

#paused?Boolean Also known as: paused

Returns:

  • (Boolean)


121
122
123
# File 'lib/listen/listener.rb', line 121

def paused?
  state == :paused
end

#processing?Boolean Also known as: listen?

processing means callbacks are called

Returns:

  • (Boolean)


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

def processing?
  state == :processing
end

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



163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/listen/listener.rb', line 163

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



99
100
101
# File 'lib/listen/listener.rb', line 99

def start
  transition :processing
end

#stopObject

Stops processing and terminates all actors



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

def stop
  transition :stopped
end

#sync(type) ⇒ Object



159
160
161
# File 'lib/listen/listener.rb', line 159

def sync(type)
  @registry[type]
end