The Listen gem listens to file modifications and notifies you about the changes.
The
listengem listens to file modifications and notifies you about the changes.
listen3.0.0 (#319, #218). There are plans to extract this feature to separate gems (#258), until this is finished, you can use by locking the
listengem to version
'~> 2.10'.
Pull requests or help is very welcome for these.
The simplest way to install
listenis to use Bundler.
gem 'listen'
Here is a complete example of using the
listengem: ```ruby require 'listen'
listener = Listen.to('/srv/app') do |modified, added, removed| puts(modified: modified, added: added, removed: removed) end listener.start sleep
Running the above in the background, you can see the callback block being called in response to each command:$ cd /srv/app $ touch a.txt {:modified=>[], :added=>["/srv/app/a.txt"], :removed=>[]}
$ echo more >> a.txt {:modified=>["/srv/app/a.txt"], :added=>[], :removed=>[]}
$ mv a.txt b.txt {:modified=>[], :added=>["/srv/app/b.txt"], :removed=>["/srv/app/a.txt"]}
$ vi b.txt
{:modified=>["/srv/app/b.txt"], :added=>[], :removed=>[]}
$ vi c.txt
{:modified=>[], :added=>["/srv/app/c.txt"], :removed=>[]}
$ rm b.txt c.txt {:modified=>[], :added=>[], :removed=>["/srv/app/b.txt", "/srv/app/c.txt"]} ```
Call
Listen.towith one or more directories and the "changes" callback passed as a block.
listener = Listen.to('dir/to/listen', 'dir/to/listen2') do |modified, added, removed| puts "modified absolute path array: #{modified}" puts "added absolute path array: #{added}" puts "removed absolute path array: #{removed}" end listener.start # starts a listener thread--does not blockdo whatever you want here...just don't exit the process :)
sleep
Changes to the listened-to directories are reported by the listener thread in a callback. The callback receives three array parameters:
modified,
addedand
removed, in that order. Each of these three is always an array with 0 or more entries. Each array entry is an absolute path.
Listeners can also be easily paused/unpaused:
listener = Listen.to('dir/path/to/listen') { |modified, added, removed| puts 'handle changes here...' }listener.start listener.paused? # => false listener.processing? # => true
listener.pause # stops processing changes (but keeps on collecting them) listener.paused? # => true listener.processing? # => false
listener.unpause # resumes processing changes ("start" would do the same) listener.stop # stop both listening to changes and processing them
Note: While paused,
listenkeeps on collecting changes in the background - to clear them, call
stop.
Note: You should keep track of all started listeners and
stopthem properly on finish.
Listenignores some directories and extensions by default (See DEFAULTIGNOREDDIRECTORIES and DEFAULTIGNOREDEXTENSIONS in Listen::Silencer). You can add ignoring patterns with the
ignoreoption/method or overwrite default with
ignore!option/method.
listener = Listen.to('dir/path/to/listen', ignore: /\.txt/) { |modified, added, removed| # ... } listener.start listener.ignore! /\.pkg/ # overwrite all patterns and only ignore pkg extension. listener.ignore /\.rb/ # ignore rb extension in addition of pkg. sleep
Note:
:ignoreregexp patterns are evaluated against relative paths.
Note: Ignoring paths does not improve performance, except when Polling (#274).
Listenwatches all files (less the ignored ones) by default. If you want to only listen to a specific type of file (i.e., just
.rbextension), you should use the
onlyoption/method.
listener = Listen.to('dir/path/to/listen', only: /\.rb$/) { |modified, added, removed| # ... } listener.start listener.only /_spec\.rb$/ # overwrite all existing only patterns. sleep
Note:
:onlyregexp patterns are evaluated only against relative file paths.
All the following options can be set through the
Listen.toafter the directory path(s) params.
ignore: [%r{/foo/bar}, /\.pid$/, /\.coffee$/] # Ignore a list of paths # default: See DEFAULT_IGNORED_DIRECTORIES and DEFAULT_IGNORED_EXTENSIONS in Listen::Silencerignore!: %r{/foo/bar} # Same as ignore options, but overwrite default ignored paths.
only: %r{.rb$} # Only listen to specific files # default: none
latency: 0.5 # Set the delay (in seconds) between checking for changes # default: 0.25 sec (1.0 sec for polling)
wait_for_delay: 4 # Set the delay (in seconds) between calls to the callback when changes exist # default: 0.10 sec
force_polling: true # Force the use of the polling adapter # default: none
relative: false # Whether changes should be relative to current dir or not # default: false
polling_fallback_message: 'custom message' # Set a custom polling fallback message (or disable it with false) # default: "Listen will be polling for changes. Learn more at https://github.com/guard/listen#listen-adapters."
Listenlogs its activity to
Listen.logger. This is the primary method of debugging.
You can call
Listen.logger =to set a custom
listenlogger for the process. For example:
Listen.logger = Rails.logger
If no custom logger is set, a default
listenlogger which logs to to
STDERRwill be created and assigned to
Listen.logger.
The default logger defaults to the
errorlogging level (severity). You can override the logging level by setting the environment variable
LISTEN_GEM_DEBUGGING=. For , all standard
::Loggerlevels are supported, with any mix of upper-/lower-case:
export LISTEN_GEM_DEBUGGING=debug # or 2 [deprecated] export LISTEN_GEM_DEBUGGING=info # or 1 or true or yes [deprecated] export LISTEN_GEM_DEBUGGING=warn export LISTEN_GEM_DEBUGGING=fatal export LISTEN_GEM_DEBUGGING=errorThe default of
errorwill be used if an unsupported value is set.
Note: The alternate values
1,
2,
trueand
yesshown above are deprecated and will be removed from
listenv4.0.
If you want to disable
listenlogging, set
Listen.logger = ::Logger.new('/dev/null')
The
Listengem has a set of adapters to notify it when there are changes.
There are 4 OS-specific adapters to support Darwin, Linux, *BSD and Windows. These adapters are fast as they use some system-calls to implement the notifying function.
There is also a polling adapter - although it's much slower than other adapters, it works on every platform/system and scenario (including network filesystems such as VM shared folders).
The Darwin and Linux adapters are dependencies of the
listengem so they work out of the box. For other adapters a specific gem will have to be added to your Gemfile, please read below.
The
listengem will choose the best adapter automatically, if present. If you want to force the use of the polling adapter, use the
:force_pollingoption while initializing the listener.
If you are on Windows, it's recommended to use the
wdmadapter instead of polling.
Please add the following to your Gemfile:
gem 'wdm', '>= 0.1.0', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
If you are on *BSD you can try to use the
rb-kqueueadapter instead of polling.
Please add the following to your Gemfile:
require 'rbconfig' if RbConfig::CONFIG['target_os'] =~ /bsd|dragonfly/i gem 'rb-kqueue', '>= 0.2' end
If you see:
Listen will be polling for changes.
This means the Listen gem can’t find an optimized adapter. Typically this is caused by:
Possible solutions:
Create a Gemfile with these lines:
source 'https://rubygems.org' gem 'listen' gem 'sass'Next, use Bundler to update gems:
$ bundle update $ bundle exec sass --watch # ... or whatever app is using Listen.
If you are running Debian, RedHat, or another similar Linux distribution, run the following in a terminal:
$ sudo sh -c "echo fs.inotify.max_user_watches=524288 >> /etc/sysctl.conf" $ sudo sysctl -pIf you are running ArchLinux, search the
/etc/sysctl.d/directory for config files with the setting:
$ grep -H -s "fs.inotify.max_user_watches" /etc/sysctl.d/* /etc/sysctl.d/40-max_user_watches.conf:fs.inotify.max_user_watches=100000Then change the setting in the file you found above to a higher value (see here for why):
$ sudo sh -c "echo fs.inotify.max_user_watches=524288 > /etc/sysctl.d/40-max-user-watches.conf" $ sudo sysctl --system
Listen uses
inotifyby default on Linux to monitor directories for changes. It's not uncommon to encounter a system limit on the number of files you can monitor. For example, Ubuntu Lucid's (64bit)
inotifylimit is set to 8192.
You can get your current inotify file watch limit by executing:
$ cat /proc/sys/fs/inotify/max_user_watchesWhen this limit is not enough to monitor all files inside a directory, the limit must be increased for Listen to work properly.
You can set a new limit temporarily with:
$ sudo sysctl fs.inotify.max_user_watches=524288 $ sudo sysctl -pIf you like to make your limit permanent, use:
$ sudo sh -c "echo fs.inotify.max_user_watches=524288 >> /etc/sysctl.conf" $ sudo sysctl -pYou may also need to pay attention to the values of
max_queued_eventsand
max_user_instancesif Listen keeps on complaining.
Man page for inotify(7). Blog post: limit of inotify.
If the gem doesn't work as expected, start by setting
LISTEN_GEM_DEBUGGING=debugor
LISTEN_GEM_DEBUGGING=infoas described above in Logging and Debugging.
NOTE: without providing the output after setting the
LISTEN_GEM_DEBUGGING=debugenvironment variable, it is usually impossible to guess why
listenis not working as expected.
These 3 steps will:
Step 1 - The most important option in Listen For effective troubleshooting set the
LISTEN_GEM_DEBUGGING=infovariable before starting
listen.
Step 2 - Verify polling works Polling has to work ... or something is really wrong (and we need to know that before anything else).
(see force_polling option).
After starting
listen, you should see something like:
INFO -- : Record.build(): 0.06773114204406738 secondsStep 3 - Trigger some changes directly without using editors or apps Make changes e.g. touch foo or echo "a" >> foo (for troubleshooting, avoid using an editor which could generate too many misleading events).
You should see something like:
INFO -- : listen: raw changes: [[:added, "/home/me/foo"]] INFO -- : listen: final changes: {:modified=>[], :added=>["/home/me/foo"], :removed=>[]}"raw changes" contains changes collected during the :waitfordelay and :latency intervals, while "final changes" is what listen decided are relevant changes (for better editor support).
If
listenseems slow or unresponsive, make sure you're not using the Polling adapter (you should see a warning upon startup if you are).
Also, if the directories you're watching contain many files, make sure you're:
:ignoreand
:onlyoptions to avoid tracking directories you don't care about (important with Polling and on MacOS)
listenwith the
:latencyand
:wait_for_delayoptions not too small or too big (depends on needs)
listenprior to 2.7.7
listen(see
LISTEN_GEM_DEBUGGING=debug)
listenin the background
When in doubt,
LISTEN_GEM_DEBUGGING=debugcan help discover the actual events and time they happened.
:latencyand
:wait_for_delayoptions until you get good results (see options).
:ignorerules to silence all events you don't care about (reduces a lot of noise, especially if you use it on directories)
Pull requests are very welcome! Please try to follow these simple rules if applicable:
For questions please join us in our Google group or on
#guard(irc.freenode.net).
bundle installto make sure that you have all the gems necessary for testing and releasing.
bundle exec rake.
./lib/listen/version.rb.
./README.md(
gem 'listen', '~> X.Y').
bundle exec rake release:full; this will tag, push to GitHub, and publish to rubygems.org.
Thibaud Guillaume-Gentil (@thibaudgg)