try to use fssm with vendored darwin/linux support instead of guard

This commit is contained in:
Thomas Reynolds 2012-01-01 17:47:38 -08:00
parent c7249a63b1
commit 83de7a7e13
25 changed files with 1601 additions and 62 deletions

View file

@ -27,7 +27,7 @@ module Middleman
autoload :Base, "middleman-core/base"
autoload :Cache, "middleman-core/cache"
autoload :Templates, "middleman-core/templates"
autoload :Guard, "middleman-core/guard"
autoload :Watcher, "middleman-core/watcher"
module Cli
autoload :Base, "middleman-core/cli"

View file

@ -213,7 +213,7 @@ class Middleman::Base
# Add Builder Callbacks
register Middleman::CoreExtensions::Builder
# Add Guard Callbacks
# Add Watcher Callbacks
register Middleman::CoreExtensions::FileWatcher
# Activate Data package

View file

@ -43,7 +43,7 @@ module Middleman::Cli
}
puts "== The Middleman is loading"
Middleman::Guard.start(params)
Middleman::Watcher.start(params)
end
end

View file

@ -61,6 +61,7 @@ module Middleman::CoreExtensions::FileWatcher
# @param [String] path The file that changed
# @return [void]
def file_did_change(path)
return if ::Middleman::Watcher.ignore_list.any? { |r| path.match(r) }
file_changed.each do |callback, matcher|
next if path.match(%r{^#{build_dir}/})
next if !matcher.nil? && !path.match(matcher)
@ -73,6 +74,7 @@ module Middleman::CoreExtensions::FileWatcher
# @param [String] path The file that was deleted
# @return [void]
def file_did_delete(path)
return if ::Middleman::Watcher.ignore_list.any? { |r| path.match(r) }
file_deleted.each do |callback, matcher|
next if path.match(%r{^#{build_dir}/})
next unless matcher.nil? || path.match(matcher)

View file

@ -0,0 +1,20 @@
Copyright (c) 2011 Thibaud Guillaume-Gentil
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,254 @@
= rb-fsevent
Very simple & usable Mac OSX FSEvents API
- RubyCocoa not required!
- Signals are working (really)
- Tested on MRI 1.8.7 & 1.9.2
- Tested on JRuby 1.6.3
== Install
gem install rb-fsevent
== Usage
=== Singular path
require 'rb-fsevent'
fsevent = FSEvent.new
fsevent.watch Dir.pwd do |directories|
puts "Detected change inside: #{directories.inspect}"
end
fsevent.run
=== Multiple paths
require 'rb-fsevent'
paths = ['/tmp/path/one', '/tmp/path/two', Dir.pwd]
fsevent = FSEvent.new
fsevent.watch paths do |directories|
puts "Detected change inside: #{directories.inspect}"
end
fsevent.run
=== Multiple paths and additional options as a Hash
require 'rb-fsevent'
paths = ['/tmp/path/one', '/tmp/path/two', Dir.pwd]
options = {:latency => 1.5, :no_defer => true }
fsevent = FSEvent.new
fsevent.watch paths, options do |directories|
puts "Detected change inside: #{directories.inspect}"
end
fsevent.run
=== Multiple paths and additional options as an Array
require 'rb-fsevent'
paths = ['/tmp/path/one', '/tmp/path/two', Dir.pwd]
options = ['--latency', 1.5, '--no-defer']
fsevent = FSEvent.new
fsevent.watch paths, options do |directories|
puts "Detected change inside: #{directories.inspect}"
end
fsevent.run
== Options
When defining options using a hash or hash-like object, it gets checked for validity and converted to the appropriate fsevent_watch commandline arguments array when the FSEvent class is instantiated. This is obviously the safest and preferred method of passing in options.
You may, however, choose to pass in an array of commandline arguments as your options value and it will be passed on, unmodified, to the fsevent_watch binary when called.
So far, the following options are supported...
- :latency => 0.5 # in seconds
- :no_defer => true
- :watch_root => true
- :since_when => 18446744073709551615 # an FSEventStreamEventId
=== Latency
The :latency parameter determines how long the service should wait after the first event before passing that information along to the client. If your latency is set to 4 seconds, and 300 changes occur in the first three, then the callback will be fired only once. If latency is set to 0.1 in the exact same scenario, you will see that callback fire somewhere closer to between 25 and 30 times.
Setting a higher latency value allows for more effective temporal coalescing, resulting in fewer callbacks and greater overall efficiency... at the cost of apparent responsiveness. Setting this to a reasonably high value (and NOT setting :no_defer) is particularly well suited for background, daemon, or batch processing applications.
Implementation note: It appears that FSEvents will only coalesce events from a maximum of 32 distinct subpaths, making the above completely accurate only when events are to fewer than 32 subpaths. Creating 300 files in one directory, for example, or 30 files in 10 subdirectories, but not 300 files within 300 subdirectories. In the latter case, you may receive 31 callbacks in one go after the latency period. As this appears to be an implementation detail, the number could potentially differ across OS revisions. It is entirely possible that this number is somehow configurable, but I have not yet discovered an accepted method of doing so.
=== NoDefer
The :no_defer option changes the behavior of the latency parameter completely. Rather than waiting for $latency period of time before sending along events in an attempt to coalesce a potential deluge ahead of time, that first event is sent along to the client immediately and is followed by a $latency period of silence before sending along any additional events that occurred within that period.
This behavior is particularly useful for interactive applications where that feeling of apparent responsiveness is most important, but you still don't want to get overwhelmed by a series of events that occur in rapid succession.
=== WatchRoot
The :watch_root option allows for catching the scenario where you start watching "~/src/demo_project" and either it is later renamed to "~/src/awesome_sauce_3000" or the path changes in such a manner that the original directory is now at "~/clients/foo/iteration4/demo_project".
Unfortunately, while this behavior is somewhat supported in the fsevent_watch binary built as part of this project, support for passing across detailed metadata is not (yet). As a result, you would not receive the appropriate RootChanged event and be able to react appropriately. Also, since the C code doesn't open watched directories and retain that file descriptor as part of path-specific callback metadata, we are unable to issue an F_GETPATH fcntl() to determine the directory's new path.
Please do not use this option until proper support is added in an upcoming (planned) release.
=== SinceWhen
The FSEventStreamEventId passed in to :since_when is used as a base for reacting to historic events. Unfortunately, not only is the metadata for transitioning from historic to live events not currently passed along, but it is incorrectly passed as a change event on the root path, and only per-host event streams are currently supported. When using per-host event streams, the event IDs are not guaranteed to be unique or contiguous when shared volumes (firewire/USB/net/etc) are used on multiple macs.
Please do not use this option until proper support is added in an upcoming (planned) release, unless it's acceptable for you to receive that one fake event that's handled incorrectly when events transition from historical to live. Even in that scenario, there's no metadata available for determining the FSEventStreamEventId of the last received event.
WARNING: passing in 0 as the parameter to :since_when will return events for every directory modified since "the beginning of time".
== Debugging output
If the gem is installed with the environment variable FWDEBUG set to the string "true", then fsevent_watch will be built with its various DEBUG sections defined, and the output to STDERR is truly verbose (and hopefully helpful in debugging your application and not just fsevent_watch itself). If enough people find this to be directly useful when developing code that makes use of rb-fsevent, then it wouldn't be hard to clean this up and make it a feature enabled by a commandline argument instead. Until somebody files an issue, however, I will assume otherwise.
append_path called for: /tmp/moo/cow/
resolved path to: /private/tmp/moo/cow
config.sinceWhen 18446744073709551615
config.latency 0.300000
config.flags 00000000
config.paths
/private/tmp/moo/cow
FSEventStreamRef @ 0x100108540:
allocator = 0x7fff705a4ee0
callback = 0x10000151e
context = {0, 0x0, 0x0, 0x0, 0x0}
numPathsToWatch = 1
pathsToWatch = 0x7fff705a4ee0
pathsToWatch[0] = '/private/tmp/moo/cow'
latestEventId = -1
latency = 300000 (microseconds)
flags = 0x00000000
runLoop = 0x0
runLoopMode = 0x0
FSEventStreamCallback fired!
numEvents: 32
event path: /private/tmp/moo/cow/1/a/
event flags: 00000000
event ID: 1023767
event path: /private/tmp/moo/cow/1/b/
event flags: 00000000
event ID: 1023782
event path: /private/tmp/moo/cow/1/c/
event flags: 00000000
event ID: 1023797
event path: /private/tmp/moo/cow/1/d/
event flags: 00000000
event ID: 1023812
event path: /private/tmp/moo/cow/1/e/
event flags: 00000000
event ID: 1023827
event path: /private/tmp/moo/cow/1/f/
event flags: 00000000
event ID: 1023842
event path: /private/tmp/moo/cow/1/g/
event flags: 00000000
event ID: 1023857
event path: /private/tmp/moo/cow/1/h/
event flags: 00000000
event ID: 1023872
event path: /private/tmp/moo/cow/1/i/
event flags: 00000000
event ID: 1023887
event path: /private/tmp/moo/cow/1/j/
event flags: 00000000
event ID: 1023902
event path: /private/tmp/moo/cow/1/k/
event flags: 00000000
event ID: 1023917
event path: /private/tmp/moo/cow/1/l/
event flags: 00000000
event ID: 1023932
event path: /private/tmp/moo/cow/1/m/
event flags: 00000000
event ID: 1023947
event path: /private/tmp/moo/cow/1/n/
event flags: 00000000
event ID: 1023962
event path: /private/tmp/moo/cow/1/o/
event flags: 00000000
event ID: 1023977
event path: /private/tmp/moo/cow/1/p/
event flags: 00000000
event ID: 1023992
event path: /private/tmp/moo/cow/1/q/
event flags: 00000000
event ID: 1024007
event path: /private/tmp/moo/cow/1/r/
event flags: 00000000
event ID: 1024022
event path: /private/tmp/moo/cow/1/s/
event flags: 00000000
event ID: 1024037
event path: /private/tmp/moo/cow/1/t/
event flags: 00000000
event ID: 1024052
event path: /private/tmp/moo/cow/1/u/
event flags: 00000000
event ID: 1024067
event path: /private/tmp/moo/cow/1/v/
event flags: 00000000
event ID: 1024082
event path: /private/tmp/moo/cow/1/w/
event flags: 00000000
event ID: 1024097
event path: /private/tmp/moo/cow/1/x/
event flags: 00000000
event ID: 1024112
event path: /private/tmp/moo/cow/1/y/
event flags: 00000000
event ID: 1024127
event path: /private/tmp/moo/cow/1/z/
event flags: 00000000
event ID: 1024142
event path: /private/tmp/moo/cow/1/
event flags: 00000000
event ID: 1024145
event path: /private/tmp/moo/cow/2/a/
event flags: 00000000
event ID: 1024160
event path: /private/tmp/moo/cow/2/b/
event flags: 00000000
event ID: 1024175
event path: /private/tmp/moo/cow/2/c/
event flags: 00000000
event ID: 1024190
event path: /private/tmp/moo/cow/2/d/
event flags: 00000000
event ID: 1024205
event path: /private/tmp/moo/cow/2/e/
event flags: 00000000
event ID: 1024220
== Note about FFI
rb-fsevent doesn't use {ruby-ffi}[http://github.com/ffi/ffi] anymore because it sadly doesn't allow for catching Signals. You can still see the code in the {ffi branch}[http://github.com/thibaudgg/rb-fsevent/tree/ffi].
== Development
- Source hosted at {GitHub}[http://github.com/thibaudgg/rb-fsevent]
- Report issues/Questions/Feature requests on {GitHub Issues}[http://github.com/thibaudgg/rb-fsevent/issues]
Pull requests are quite welcome! Please ensure that your commits are in a topic branch for each individual changeset than can be reasonably isolated. It is also important to ensure that your changes are well tested... whether that means new tests, modified tests, or fixing a scenario where the existing tests currently fail. If you have rvm and the required rubies currently installed, we have a helper task for running the testsuite in all of them:
rake spec:portability
The list of tested RVM targets is currently:
%w[1.8.6 1.8.7 1.9.2 jruby-head]
== Authors
- {Thibaud Guillaume-Gentil}[http://github.com/thibaudgg]
- {Travis Tilley}[http://github.com/ttilley]

View file

@ -0,0 +1,61 @@
# Workaround to make Rubygems believe it builds a native gem
require 'mkmf'
create_makefile('none')
# TODO: determine whether we really need to be working around instead of with mkmf
if `uname -s`.chomp != 'Darwin'
puts "Warning! Only Darwin (Mac OS X) systems are supported, nothing will be compiled"
else
begin
xcode_path = %x[xcode-select -print-path].to_s.strip!
rescue Errno::ENOENT
end
raise "Could not find a suitable Xcode installation" unless xcode_path
gem_root = File.expand_path(File.join('..'))
darwin_version = `uname -r`.to_i
sdk_version = { 9 => '10.5', 10 => '10.6', 11 => '10.7' }[darwin_version]
raise "Only Darwin systems greater than 8 (Mac OS X 10.5+) are supported" unless sdk_version
core_flags = %W{
-isysroot #{xcode_path}/SDKs/MacOSX#{sdk_version}.sdk
-mmacosx-version-min=#{sdk_version} -mdynamic-no-pic -std=gnu99
}
cflags = core_flags + %w{-Os -pipe}
wflags = %w{
-Wmissing-prototypes -Wreturn-type -Wmissing-braces -Wparentheses -Wswitch
-Wunused-function -Wunused-label -Wunused-parameter -Wunused-variable
-Wunused-value -Wuninitialized -Wunknown-pragmas -Wshadow
-Wfour-char-constants -Wsign-compare -Wnewline-eof -Wconversion
-Wshorten-64-to-32 -Wglobal-constructors -pedantic
}
ldflags = %w{
-dead_strip -framework CoreServices
}
cc_opts = core_flags + ldflags
cc_opts += %w{
-D DEBUG=true
} if ENV['FWDEBUG'] == "true"
cc_bin = `which clang || which gcc`.to_s.strip!
compile_command = "CFLAGS='#{cflags.join(' ')} #{wflags.join(' ')}' #{cc_bin} #{cc_opts.join(' ')} -o '#{gem_root}/bin/fsevent_watch' fsevent/fsevent_watch.c"
STDERR.puts(compile_command)
# Compile the actual fsevent_watch binary
system "mkdir -p #{File.join(gem_root, 'bin')}"
system compile_command
unless File.executable?("#{gem_root}/bin/fsevent_watch")
raise "Compilation of fsevent_watch failed (see README)"
end
end

View file

@ -0,0 +1,226 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <CoreServices/CoreServices.h>
// Structure for storing metadata parsed from the commandline
static struct {
FSEventStreamEventId sinceWhen;
CFTimeInterval latency;
FSEventStreamCreateFlags flags;
CFMutableArrayRef paths;
} config = {
(UInt64) kFSEventStreamEventIdSinceNow,
(double) 0.3,
(UInt32) kFSEventStreamCreateFlagNone,
NULL
};
// Prototypes
static void append_path(const char *path);
static inline void parse_cli_settings(int argc, const char *argv[]);
static void callback(FSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[]);
// Resolve a path and append it to the CLI settings structure
// The FSEvents API will, internally, resolve paths using a similar scheme.
// Performing this ahead of time makes things less confusing, IMHO.
static void append_path(const char *path)
{
#ifdef DEBUG
fprintf(stderr, "\n");
fprintf(stderr, "append_path called for: %s\n", path);
#endif
char fullPath[PATH_MAX];
if (realpath(path, fullPath) == NULL) {
#ifdef DEBUG
fprintf(stderr, " realpath not directly resolvable from path\n");
#endif
if (path[0] != '/') {
#ifdef DEBUG
fprintf(stderr, " passed path is not absolute\n");
#endif
size_t len;
getcwd(fullPath, sizeof(fullPath));
#ifdef DEBUG
fprintf(stderr, " result of getcwd: %s\n", fullPath);
#endif
len = strlen(fullPath);
fullPath[len] = '/';
strlcpy(&fullPath[len + 1], path, sizeof(fullPath) - (len + 1));
} else {
#ifdef DEBUG
fprintf(stderr, " assuming path does not YET exist\n");
#endif
strlcpy(fullPath, path, sizeof(fullPath));
}
}
#ifdef DEBUG
fprintf(stderr, " resolved path to: %s\n", fullPath);
fprintf(stderr, "\n");
fflush(stderr);
#endif
CFStringRef pathRef = CFStringCreateWithCString(kCFAllocatorDefault,
fullPath,
kCFStringEncodingUTF8);
CFArrayAppendValue(config.paths, pathRef);
CFRelease(pathRef);
}
// Parse commandline settings
static inline void parse_cli_settings(int argc, const char *argv[])
{
config.paths = CFArrayCreateMutable(NULL,
(CFIndex)0,
&kCFTypeArrayCallBacks);
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--since-when") == 0) {
config.sinceWhen = strtoull(argv[++i], NULL, 0);
} else if (strcmp(argv[i], "--latency") == 0) {
config.latency = strtod(argv[++i], NULL);
} else if (strcmp(argv[i], "--no-defer") == 0) {
config.flags |= kFSEventStreamCreateFlagNoDefer;
} else if (strcmp(argv[i], "--watch-root") == 0) {
config.flags |= kFSEventStreamCreateFlagWatchRoot;
} else if (strcmp(argv[i], "--ignore-self") == 0) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
config.flags |= kFSEventStreamCreateFlagIgnoreSelf;
#else
fprintf(stderr, "MacOSX10.6.sdk is required for --ignore-self\n");
#endif
} else {
append_path(argv[i]);
}
}
if (CFArrayGetCount(config.paths) == 0) {
append_path(".");
}
#ifdef DEBUG
fprintf(stderr, "config.sinceWhen %llu\n", config.sinceWhen);
fprintf(stderr, "config.latency %f\n", config.latency);
fprintf(stderr, "config.flags %#.8x\n", config.flags);
fprintf(stderr, "config.paths\n");
long numpaths = CFArrayGetCount(config.paths);
for (long i = 0; i < numpaths; i++) {
char path[PATH_MAX];
CFStringGetCString(CFArrayGetValueAtIndex(config.paths, i),
path,
PATH_MAX,
kCFStringEncodingUTF8);
fprintf(stderr, " %s\n", path);
}
fprintf(stderr, "\n");
fflush(stderr);
#endif
}
static void callback(FSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
char **paths = eventPaths;
#ifdef DEBUG
fprintf(stderr, "\n");
fprintf(stderr, "FSEventStreamCallback fired!\n");
fprintf(stderr, " numEvents: %lu\n", numEvents);
for (size_t i = 0; i < numEvents; i++) {
fprintf(stderr, " event path: %s\n", paths[i]);
fprintf(stderr, " event flags: %#.8x\n", eventFlags[i]);
fprintf(stderr, " event ID: %llu\n", eventIds[i]);
}
fprintf(stderr, "\n");
fflush(stderr);
#endif
for (size_t i = 0; i < numEvents; i++) {
fprintf(stdout, "%s", paths[i]);
fprintf(stdout, ":");
}
fprintf(stdout, "\n");
fflush(stdout);
}
int main(int argc, const char *argv[])
{
/*
* a subprocess will initially inherit the process group of its parent. the
* process group may have a control terminal associated with it, which would
* be the first tty device opened by the group leader. typically the group
* leader is your shell and the control terminal is your login device. a
* subset of signals triggered on the control terminal are sent to all members
* of the process group, in large part to facilitate sane and consistent
* cleanup (ex: control terminal was closed).
*
* so why the overly descriptive lecture style comment?
* 1. SIGINT and SIGQUIT are among the signals with this behavior
* 2. a number of applications gank the above for their own use
* 3. ruby's insanely useful "guard" is one of these applications
* 4. despite having some level of understanding of POSIX signals and a few
* of the scenarios that might cause problems, i learned this one only
* after reading ruby 1.9's process.c
* 5. if left completely undocumented, even slightly obscure bugfixes
* may be removed as cruft by a future maintainer
*
* hindsight is 20/20 addition: if you're single-threaded and blocking on IO
* with a subprocess, then handlers for deferrable signals might not get run
* when you expect them to. In the case of Ruby 1.8, that means making use of
* IO::select, which will preserve correct signal handling behavior.
*/
if (setpgid(0,0) < 0) {
fprintf(stderr, "Unable to set new process group.\n");
return 1;
}
parse_cli_settings(argc, argv);
FSEventStreamContext context = {0, NULL, NULL, NULL, NULL};
FSEventStreamRef stream;
stream = FSEventStreamCreate(kCFAllocatorDefault,
(FSEventStreamCallback)&callback,
&context,
config.paths,
config.sinceWhen,
config.latency,
config.flags);
#ifdef DEBUG
FSEventStreamShow(stream);
fprintf(stderr, "\n");
fflush(stderr);
#endif
FSEventStreamScheduleWithRunLoop(stream,
CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
FSEventStreamStart(stream);
CFRunLoopRun();
FSEventStreamFlushSync(stream);
FSEventStreamStop(stream);
return 0;
}

View file

@ -0,0 +1,2 @@
require 'rb-fsevent/fsevent'
require 'rb-fsevent/version'

View file

@ -0,0 +1,105 @@
class FSEvent
class << self
class_eval <<-END
def root_path
"#{File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))}"
end
END
class_eval <<-END
def watcher_path
"#{File.join(FSEvent.root_path, 'bin', 'fsevent_watch')}"
end
END
end
attr_reader :paths, :callback
def watch(watch_paths, options=nil, &block)
@paths = watch_paths.kind_of?(Array) ? watch_paths : [watch_paths]
@callback = block
if options.kind_of?(Hash)
@options = parse_options(options)
elsif options.kind_of?(Array)
@options = options
else
@options = []
end
end
def run
@running = true
# please note the use of IO::select() here, as it is used specifically to
# preserve correct signal handling behavior in ruby 1.8.
while @running && IO::select([pipe], nil, nil, nil)
if line = pipe.readline
modified_dir_paths = line.split(":").select { |dir| dir != "\n" }
callback.call(modified_dir_paths)
end
end
rescue Interrupt, IOError
ensure
stop
end
def stop
if pipe
Process.kill("KILL", pipe.pid)
pipe.close
end
rescue IOError
ensure
@pipe = @running = nil
end
if RUBY_VERSION < '1.9'
def pipe
@pipe ||= IO.popen("#{self.class.watcher_path} #{options_string} #{shellescaped_paths}")
end
private
def options_string
@options.join(' ')
end
def shellescaped_paths
@paths.map {|path| shellescape(path)}.join(' ')
end
# for Ruby 1.8.6 support
def shellescape(str)
# An empty argument will be skipped, so return empty quotes.
return "''" if str.empty?
str = str.dup
# Process as a single byte sequence because not all shell
# implementations are multibyte aware.
str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")
# A LF cannot be escaped with a backslash because a backslash + LF
# combo is regarded as line continuation and simply ignored.
str.gsub!(/\n/, "'\n'")
return str
end
else
def pipe
@pipe ||= IO.popen([self.class.watcher_path] + @options + @paths)
end
end
private
def parse_options(options={})
opts = []
opts.concat(['--since-when', options[:since_when]]) if options[:since_when]
opts.concat(['--latency', options[:latency]]) if options[:latency]
opts.push('--no-defer') if options[:no_defer]
opts.push('--watch-root') if options[:watch_root]
# ruby 1.9's IO.popen(array-of-stuff) syntax requires all items to be strings
opts.map {|opt| "#{opt}"}
end
end

View file

@ -0,0 +1,3 @@
class FSEvent
VERSION = "0.4.3.1"
end

View file

@ -0,0 +1,4 @@
--readme README.md
--markup markdown
--markup-provider maruku
--no-private

View file

@ -0,0 +1,20 @@
Copyright (c) 2009 Nathan Weizenbaum
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,66 @@
# rb-inotify
This is a simple wrapper over the [inotify](http://en.wikipedia.org/wiki/Inotify) Linux kernel subsystem
for monitoring changes to files and directories.
It uses the [FFI](http://wiki.github.com/ffi/ffi) gem to avoid having to compile a C extension.
[API documentation is available on rdoc.info](http://rdoc.info/projects/nex3/rb-inotify).
## Basic Usage
The API is similar to the inotify C API, but with a more Rubyish feel.
First, create a notifier:
notifier = INotify::Notifier.new
Then, tell it to watch the paths you're interested in
for the events you care about:
notifier.watch("path/to/foo.txt", :modify) {puts "foo.txt was modified!"}
notifier.watch("path/to/bar", :moved_to, :create) do |event|
puts "#{event.name} is now in path/to/bar!"
end
Inotify can watch directories or individual files.
It can pay attention to all sorts of events;
for a full list, see [the inotify man page](http://www.tin.org/bin/man.cgi?section=7&topic=inotify).
Finally, you get at the events themselves:
notifier.run
This will loop infinitely, calling the appropriate callbacks when the files are changed.
If you don't want infinite looping,
you can also block until there are available events,
process them all at once,
and then continue on your merry way:
notifier.process
## Advanced Usage
Sometimes it's necessary to have finer control over the underlying IO operations
than is provided by the simple callback API.
The trick to this is that the \{INotify::Notifier#to_io Notifier#to_io} method
returns a fully-functional IO object,
with a file descriptor and everything.
This means, for example, that it can be passed to `IO#select`:
# Wait 10 seconds for an event then give up
if IO.select([notifier.to_io], [], [], 10)
notifier.process
end
It can even be used with EventMachine:
require 'eventmachine'
EM.run do
EM.watch notifier.to_io do
notifier.process
end
end
Unfortunately, this currently doesn't work under JRuby.
JRuby currently doesn't use native file descriptors for the IO object,
so we can't use the notifier's file descriptor as a stand-in.

View file

@ -0,0 +1,54 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "rb-inotify"
gem.summary = "A Ruby wrapper for Linux's inotify, using FFI"
gem.description = gem.summary
gem.email = "nex342@gmail.com"
gem.homepage = "http://github.com/nex3/rb-inotify"
gem.authors = ["Nathan Weizenbaum"]
gem.add_dependency "ffi", ">= 0.5.0"
gem.add_development_dependency "yard", ">= 0.4.0"
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
end
task(:permissions) {sh %{chmod -R a+r .}}
Rake::Task[:build].prerequisites.unshift('permissions')
module Jeweler::VersionHelper::PlaintextExtension
def write_with_inotify
write_without_inotify
filename = File.join(File.dirname(__FILE__), "lib/rb-inotify.rb")
text = File.read(filename)
File.open(filename, 'w') do |f|
f.write text.gsub(/^( VERSION = ).*/, '\1' + [major, minor, patch].inspect)
end
end
alias_method :write_without_inotify, :write
alias_method :write, :write_with_inotify
end
class Jeweler::Commands::Version::Base
def commit_version_with_inotify
return unless self.repo
self.repo.add(File.join(File.dirname(__FILE__), "lib/rb-inotify.rb"))
commit_version_without_inotify
end
alias_method :commit_version_without_inotify, :commit_version
alias_method :commit_version, :commit_version_with_inotify
end
begin
require 'yard'
YARD::Rake::YardocTask.new
rescue LoadError
task :yardoc do
abort "YARD is not available. In order to run yardoc, you must: sudo gem install yard"
end
end

View file

@ -0,0 +1 @@
0.8.8

View file

@ -0,0 +1,17 @@
require 'rb-inotify/native'
require 'rb-inotify/native/flags'
require 'rb-inotify/notifier'
require 'rb-inotify/watcher'
require 'rb-inotify/event'
# The root module of the library, which is laid out as so:
#
# * {Notifier} -- The main class, where the notifications are set up
# * {Watcher} -- A watcher for a single file or directory
# * {Event} -- An filesystem event notification
module INotify
# An array containing the version number of rb-inotify.
# The numbers in the array are the major, minor, and patch versions,
# respectively.
VERSION = [0, 8, 8]
end

View file

@ -0,0 +1,139 @@
module INotify
# An event caused by a change on the filesystem.
# Each {Watcher} can fire many events,
# which are passed to that watcher's callback.
class Event
# A list of other events that are related to this one.
# Currently, this is only used for files that are moved within the same directory:
# the `:moved_from` and the `:moved_to` events will be related.
#
# @return [Array<Event>]
attr_reader :related
# The name of the file that the event occurred on.
# This is only set for events that occur on files in directories;
# otherwise, it's `""`.
# Similarly, if the event is being fired for the directory itself
# the name will be `""`
#
# This pathname is relative to the enclosing directory.
# For the absolute pathname, use \{#absolute\_name}.
# Note that when the `:recursive` flag is passed to {Notifier#watch},
# events in nested subdirectories will still have a `#name` field
# relative to their immediately enclosing directory.
# For example, an event on the file `"foo/bar/baz"`
# will have name `"baz"`.
#
# @return [String]
attr_reader :name
# The {Notifier} that fired this event.
#
# @return [Notifier]
attr_reader :notifier
# An integer specifying that this event is related to some other event,
# which will have the same cookie.
#
# Currently, this is only used for files that are moved within the same directory.
# Both the `:moved_from` and the `:moved_to` events will have the same cookie.
#
# @private
# @return [Fixnum]
attr_reader :cookie
# The {Watcher#id id} of the {Watcher} that fired this event.
#
# @private
# @return [Fixnum]
attr_reader :watcher_id
# Returns the {Watcher} that fired this event.
#
# @return [Watcher]
def watcher
@watcher ||= @notifier.watchers[@watcher_id]
end
# The absolute path of the file that the event occurred on.
#
# This is actually only as absolute as the path passed to the {Watcher}
# that created this event.
# However, it is relative to the working directory,
# assuming that hasn't changed since the watcher started.
#
# @return [String]
def absolute_name
return watcher.path if name.empty?
return File.join(watcher.path, name)
end
# Returns the flags that describe this event.
# This is generally similar to the input to {Notifier#watch},
# except that it won't contain options flags nor `:all_events`,
# and it may contain one or more of the following flags:
#
# `:unmount`
# : The filesystem containing the watched file or directory was unmounted.
#
# `:ignored`
# : The \{#watcher watcher} was closed, or the watched file or directory was deleted.
#
# `:isdir`
# : The subject of this event is a directory.
#
# @return [Array<Symbol>]
def flags
@flags ||= Native::Flags.from_mask(@native[:mask])
end
# Constructs an {Event} object from a string of binary data,
# and destructively modifies the string to get rid of the initial segment
# used to construct the Event.
#
# @private
# @param data [String] The string to be modified
# @param notifier [Notifier] The {Notifier} that fired the event
# @return [Event, nil] The event, or `nil` if the string is empty
def self.consume(data, notifier)
return nil if data.empty?
ev = new(data, notifier)
data.replace data[ev.size..-1]
ev
end
# Creates an event from a string of binary data.
# Differs from {Event.consume} in that it doesn't modify the string.
#
# @private
# @param data [String] The data string
# @param notifier [Notifier] The {Notifier} that fired the event
def initialize(data, notifier)
ptr = FFI::MemoryPointer.from_string(data)
@native = Native::Event.new(ptr)
@related = []
@cookie = @native[:cookie]
@name = data[@native.size, @native[:len]].gsub(/\0+$/, '')
@notifier = notifier
@watcher_id = @native[:wd]
raise Exception.new("inotify event queue has overflowed.") if @native[:mask] & Native::Flags::IN_Q_OVERFLOW != 0
end
# Calls the callback of the watcher that fired this event,
# passing in the event itself.
#
# @private
def callback!
watcher.callback!(self)
end
# Returns the size of this event object in bytes,
# including the \{#name} string.
#
# @return [Fixnum]
def size
@native.size + @native[:len]
end
end
end

View file

@ -0,0 +1,31 @@
require 'ffi'
module INotify
# This module contains the low-level foreign-function interface code
# for dealing with the inotify C APIs.
# It's an implementation detail, and not meant for users to deal with.
#
# @private
module Native
extend FFI::Library
ffi_lib "c"
# The C struct describing an inotify event.
#
# @private
class Event < FFI::Struct
layout(
:wd, :int,
:mask, :uint32,
:cookie, :uint32,
:len, :uint32)
end
attach_function :inotify_init, [], :int
attach_function :inotify_add_watch, [:int, :string, :uint32], :int
attach_function :inotify_rm_watch, [:int, :uint32], :int
attach_function :read, [:int, :pointer, :size_t], :ssize_t
attach_function :close, [:int], :int
end
end

View file

@ -0,0 +1,89 @@
module INotify
module Native
# A module containing all the inotify flags
# to be passed to {Notifier#watch}.
#
# @private
module Flags
# File was accessed.
IN_ACCESS = 0x00000001
# Metadata changed.
IN_ATTRIB = 0x00000004
# Writtable file was closed.
IN_CLOSE_WRITE = 0x00000008
# File was modified.
IN_MODIFY = 0x00000002
# Unwrittable file closed.
IN_CLOSE_NOWRITE = 0x00000010
# File was opened.
IN_OPEN = 0x00000020
# File was moved from X.
IN_MOVED_FROM = 0x00000040
# File was moved to Y.
IN_MOVED_TO = 0x00000080
# Subfile was created.
IN_CREATE = 0x00000100
# Subfile was deleted.
IN_DELETE = 0x00000200
# Self was deleted.
IN_DELETE_SELF = 0x00000400
# Self was moved.
IN_MOVE_SELF = 0x00000800
## Helper events.
# Close.
IN_CLOSE = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
# Moves.
IN_MOVE = (IN_MOVED_FROM | IN_MOVED_TO)
# All events which a program can wait on.
IN_ALL_EVENTS = (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE |
IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE |
IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF)
## Special flags.
# Only watch the path if it is a directory.
IN_ONLYDIR = 0x01000000
# Do not follow a sym link.
IN_DONT_FOLLOW = 0x02000000
# Add to the mask of an already existing watch.
IN_MASK_ADD = 0x20000000
# Only send event once.
IN_ONESHOT = 0x80000000
## Events sent by the kernel.
# Backing fs was unmounted.
IN_UNMOUNT = 0x00002000
# Event queued overflowed.
IN_Q_OVERFLOW = 0x00004000
# File was ignored.
IN_IGNORED = 0x00008000
# Event occurred against dir.
IN_ISDIR = 0x40000000
# Converts a list of flags to the bitmask that the C API expects.
#
# @param flags [Array<Symbol>]
# @return [Fixnum]
def self.to_mask(flags)
flags.map {|flag| const_get("IN_#{flag.to_s.upcase}")}.
inject(0) {|mask, flag| mask | flag}
end
# Converts a bitmask from the C API into a list of flags.
#
# @param mask [Fixnum]
# @return [Array<Symbol>]
def self.from_mask(mask)
constants.map {|c| c.to_s}.select do |c|
next false unless c =~ /^IN_/
const_get(c) & mask != 0
end.map {|c| c.sub("IN_", "").downcase.to_sym} - [:all_events]
end
end
end
end

View file

@ -0,0 +1,308 @@
module INotify
# Notifier wraps a single instance of inotify.
# It's possible to have more than one instance,
# but usually unnecessary.
#
# @example
# # Create the notifier
# notifier = INotify::Notifier.new
#
# # Run this callback whenever the file path/to/foo.txt is read
# notifier.watch("path/to/foo.txt", :access) do
# puts "Foo.txt was accessed!"
# end
#
# # Watch for any file in the directory being deleted
# # or moved out of the directory.
# notifier.watch("path/to/directory", :delete, :moved_from) do |event|
# # The #name field of the event object contains the name of the affected file
# puts "#{event.name} is no longer in the directory!"
# end
#
# # Nothing happens until you run the notifier!
# notifier.run
class Notifier
# A list of directories that should never be recursively watched.
#
# * Files in `/dev/fd` sometimes register as directories, but are not enumerable.
RECURSIVE_BLACKLIST = %w[/dev/fd]
# A hash from {Watcher} ids to the instances themselves.
#
# @private
# @return [{Fixnum => Watcher}]
attr_reader :watchers
# The underlying file descriptor for this notifier.
# This is a valid OS file descriptor, and can be used as such
# (except under JRuby -- see \{#to\_io}).
#
# @return [Fixnum]
attr_reader :fd
# @return [Boolean] Whether or not this Ruby implementation supports
# wrapping the native file descriptor in a Ruby IO wrapper.
def self.supports_ruby_io?
RUBY_PLATFORM !~ /java/
end
# Creates a new {Notifier}.
#
# @return [Notifier]
# @raise [SystemCallError] if inotify failed to initialize for some reason
def initialize
@fd = Native.inotify_init
@watchers = {}
return unless @fd < 0
raise SystemCallError.new(
"Failed to initialize inotify" +
case FFI.errno
when Errno::EMFILE::Errno; ": the user limit on the total number of inotify instances has been reached."
when Errno::ENFILE::Errno; ": the system limit on the total number of file descriptors has been reached."
when Errno::ENOMEM::Errno; ": insufficient kernel memory is available."
else; ""
end,
FFI.errno)
end
# Returns a Ruby IO object wrapping the underlying file descriptor.
# Since this file descriptor is fully functional (except under JRuby),
# this IO object can be used in any way a Ruby-created IO object can.
# This includes passing it to functions like `#select`.
#
# Note that this always returns the same IO object.
# Creating lots of IO objects for the same file descriptor
# can cause some odd problems.
#
# **This is not supported under JRuby**.
# JRuby currently doesn't use native file descriptors for the IO object,
# so we can't use this file descriptor as a stand-in.
#
# @return [IO] An IO object wrapping the file descriptor
# @raise [NotImplementedError] if this is being called in JRuby
def to_io
unless self.class.supports_ruby_io?
raise NotImplementedError.new("INotify::Notifier#to_io is not supported under JRuby")
end
@io ||= IO.new(@fd)
end
# Watches a file or directory for changes,
# calling the callback when there are.
# This is only activated once \{#process} or \{#run} is called.
#
# **Note that by default, this does not recursively watch subdirectories
# of the watched directory**.
# To do so, use the `:recursive` flag.
#
# ## Flags
#
# `:access`
# : A file is accessed (that is, read).
#
# `:attrib`
# : A file's metadata is changed (e.g. permissions, timestamps, etc).
#
# `:close_write`
# : A file that was opened for writing is closed.
#
# `:close_nowrite`
# : A file that was not opened for writing is closed.
#
# `:modify`
# : A file is modified.
#
# `:open`
# : A file is opened.
#
# ### Directory-Specific Flags
#
# These flags only apply when a directory is being watched.
#
# `:moved_from`
# : A file is moved out of the watched directory.
#
# `:moved_to`
# : A file is moved into the watched directory.
#
# `:create`
# : A file is created in the watched directory.
#
# `:delete`
# : A file is deleted in the watched directory.
#
# `:delete_self`
# : The watched file or directory itself is deleted.
#
# `:move_self`
# : The watched file or directory itself is moved.
#
# ### Helper Flags
#
# These flags are just combinations of the flags above.
#
# `:close`
# : Either `:close_write` or `:close_nowrite` is activated.
#
# `:move`
# : Either `:moved_from` or `:moved_to` is activated.
#
# `:all_events`
# : Any event above is activated.
#
# ### Options Flags
#
# These flags don't actually specify events.
# Instead, they specify options for the watcher.
#
# `:onlydir`
# : Only watch the path if it's a directory.
#
# `:dont_follow`
# : Don't follow symlinks.
#
# `:mask_add`
# : Add these flags to the pre-existing flags for this path.
#
# `:oneshot`
# : Only send the event once, then shut down the watcher.
#
# `:recursive`
# : Recursively watch any subdirectories that are created.
# Note that this is a feature of rb-inotify,
# rather than of inotify itself, which can only watch one level of a directory.
# This means that the {Event#name} field
# will contain only the basename of the modified file.
# When using `:recursive`, {Event#absolute_name} should always be used.
#
# @param path [String] The path to the file or directory
# @param flags [Array<Symbol>] Which events to watch for
# @yield [event] A block that will be called
# whenever one of the specified events occur
# @yieldparam event [Event] The Event object containing information
# about the event that occured
# @return [Watcher] A Watcher set up to watch this path for these events
# @raise [SystemCallError] if the file or directory can't be watched,
# e.g. if the file isn't found, read access is denied,
# or the flags don't contain any events
def watch(path, *flags, &callback)
return Watcher.new(self, path, *flags, &callback) unless flags.include?(:recursive)
Dir.glob(File.join(path, '*'), File::FNM_DOTMATCH).each do |d|
binary_d = d.respond_to?(:force_encoding) ? d.dup.force_encoding('BINARY') : d
next if binary_d =~ /\/\.\.?$/ # Current or parent directory
watch(d, *flags, &callback) if !RECURSIVE_BLACKLIST.include?(d) && File.directory?(d)
end
rec_flags = [:create, :moved_to]
return watch(path, *((flags - [:recursive]) | rec_flags)) do |event|
callback.call(event) if flags.include?(:all_events) || !(flags & event.flags).empty?
next if (rec_flags & event.flags).empty? || !event.flags.include?(:isdir)
begin
watch(event.absolute_name, *flags, &callback)
rescue Errno::ENOENT
# If the file has been deleted since the glob was run, we don't want to error out.
end
end
end
# Starts the notifier watching for filesystem events.
# Blocks until \{#stop} is called.
#
# @see #process
def run
@stop = false
process until @stop
end
# Stop watching for filesystem events.
# That is, if we're in a \{#run} loop,
# exit out as soon as we finish handling the events.
def stop
@stop = true
end
# Blocks until there are one or more filesystem events
# that this notifier has watchers registered for.
# Once there are events, the appropriate callbacks are called
# and this function returns.
#
# @see #run
def process
read_events.each {|event| event.callback!}
end
# Close the notifier.
#
# @raise [SystemCallError] if closing the underlying file descriptor fails.
def close
return if Native.close(@fd) == 0
raise SystemCallError.new("Failed to properly close inotify socket" +
case FFI.errno
when Errno::EBADF::Errno; ": invalid or closed file descriptior"
when Errno::EIO::Errno; ": an I/O error occured"
end,
FFI.errno)
end
private
# Blocks until there are one or more filesystem events
# that this notifier has watchers registered for.
# Once there are events, returns their {Event} objects.
def read_events
size = 64 * Native::Event.size
tries = 1
begin
data = readpartial(size)
rescue SystemCallError => er
# EINVAL means that there's more data to be read
# than will fit in the buffer size
raise er unless er.errno == Errno::EINVAL::Errno || tries == 5
size *= 2
tries += 1
retry
end
events = []
cookies = {}
while ev = Event.consume(data, self)
events << ev
next if ev.cookie == 0
cookies[ev.cookie] ||= []
cookies[ev.cookie] << ev
end
cookies.each {|c, evs| evs.each {|ev| ev.related.replace(evs - [ev]).freeze}}
events
end
# Same as IO#readpartial, or as close as we need.
def readpartial(size)
# Use Ruby's readpartial if possible, to avoid blocking other threads.
return to_io.readpartial(size) if self.class.supports_ruby_io?
tries = 0
begin
tries += 1
buffer = FFI::MemoryPointer.new(:char, size)
size_read = Native.read(fd, buffer, size)
return buffer.read_string(size_read) if size_read >= 0
end while FFI.errno == Errno::EINTR::Errno && tries <= 5
raise SystemCallError.new("Error reading inotify events" +
case FFI.errno
when Errno::EAGAIN::Errno; ": no data available for non-blocking I/O"
when Errno::EBADF::Errno; ": invalid or closed file descriptor"
when Errno::EFAULT::Errno; ": invalid buffer"
when Errno::EINVAL::Errno; ": invalid file descriptor"
when Errno::EIO::Errno; ": I/O error"
when Errno::EISDIR::Errno; ": file descriptor is a directory"
else; ""
end,
FFI.errno)
end
end
end

View file

@ -0,0 +1,83 @@
module INotify
# Watchers monitor a single path for changes,
# specified by {INotify::Notifier#watch event flags}.
# A watcher is usually created via \{Notifier#watch}.
#
# One {Notifier} may have many {Watcher}s.
# The Notifier actually takes care of the checking for events,
# via \{Notifier#run #run} or \{Notifier#process #process}.
# The main purpose of having Watcher objects
# is to be able to disable them using \{#close}.
class Watcher
# The {Notifier} that this Watcher belongs to.
#
# @return [Notifier]
attr_reader :notifier
# The path that this Watcher is watching.
#
# @return [String]
attr_reader :path
# The {INotify::Notifier#watch flags}
# specifying the events that this Watcher is watching for,
# and potentially some options as well.
#
# @return [Array<Symbol>]
attr_reader :flags
# The id for this Watcher.
# Used to retrieve this Watcher from {Notifier#watchers}.
#
# @private
# @return [Fixnum]
attr_reader :id
# Calls this Watcher's callback with the given {Event}.
#
# @private
# @param event [Event]
def callback!(event)
@callback[event]
end
# Disables this Watcher, so that it doesn't fire any more events.
#
# @raise [SystemCallError] if the watch fails to be disabled for some reason
def close
return if Native.inotify_rm_watch(@notifier.fd, @id) == 0
raise SystemCallError.new("Failed to stop watching #{path.inspect}", FFI.errno)
end
# Creates a new {Watcher}.
#
# @private
# @see Notifier#watch
def initialize(notifier, path, *flags, &callback)
@notifier = notifier
@callback = callback || proc {}
@path = path
@flags = flags.freeze
@id = Native.inotify_add_watch(@notifier.fd, path.dup,
Native::Flags.to_mask(flags))
unless @id < 0
@notifier.watchers[@id] = self
return
end
raise SystemCallError.new(
"Failed to watch #{path.inspect}" +
case FFI.errno
when Errno::EACCES::Errno; ": read access to the given file is not permitted."
when Errno::EBADF::Errno; ": the given file descriptor is not valid."
when Errno::EFAULT::Errno; ": path points outside of the process's accessible address space."
when Errno::EINVAL::Errno; ": the given event mask contains no legal events; or fd is not an inotify file descriptor."
when Errno::ENOMEM::Errno; ": insufficient kernel memory was available."
when Errno::ENOSPC::Errno; ": The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource."
else; ""
end,
FFI.errno)
end
end
end

View file

@ -0,0 +1,53 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{rb-inotify}
s.version = "0.8.8"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Nathan Weizenbaum"]
s.date = %q{2011-09-27}
s.description = %q{A Ruby wrapper for Linux's inotify, using FFI}
s.email = %q{nex342@gmail.com}
s.extra_rdoc_files = [
"README.md"
]
s.files = [
".yardopts",
"MIT-LICENSE",
"README.md",
"Rakefile",
"VERSION",
"lib/rb-inotify.rb",
"lib/rb-inotify/event.rb",
"lib/rb-inotify/native.rb",
"lib/rb-inotify/native/flags.rb",
"lib/rb-inotify/notifier.rb",
"lib/rb-inotify/watcher.rb",
"rb-inotify.gemspec"
]
s.homepage = %q{http://github.com/nex3/rb-inotify}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{A Ruby wrapper for Linux's inotify, using FFI}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<ffi>, [">= 0.5.0"])
s.add_development_dependency(%q<yard>, [">= 0.4.0"])
else
s.add_dependency(%q<ffi>, [">= 0.5.0"])
s.add_dependency(%q<yard>, [">= 0.4.0"])
end
else
s.add_dependency(%q<ffi>, [">= 0.5.0"])
s.add_dependency(%q<yard>, [">= 0.4.0"])
end
end

View file

@ -1,55 +1,58 @@
# Guard watches the filesystem for changes
require "guard"
require "guard/guard"
# Inspect Ruby env
require "rbconfig"
# Watcher Library
require "fssm"
# File changes are forwarded to the currently running app via HTTP
require "net/http"
# Support forking on Windows
require "win32/process" if Middleman::WINDOWS
# The Guard namespace
module Middleman::Guard
# Start guard
# @param [Hash] options
# @return [void]
def self.start(options={})
# Forward CLI options to Guard
options_hash = options.map { |k,v| ", :#{k} => '#{v}'" }.join
# Watch all files in project, even hidden ones.
::Guard.start({
:guardfile_contents => %Q{
guard 'middleman'#{options_hash} do
watch(%r{(.*)})
end
},
:watch_all_modifications => true,
:no_interactions => true
})
end
end
# @private
module Guard
# Monkeypatch Guard into being quiet
module UI
module Middleman
class Watcher
class << self
def info(message, options = { }); end
attr_accessor :singleton
def start(options)
self.singleton = new(options)
self.singleton.watch!
end
# What command is sent to kill instances
# @return [Symbol, Fixnum]
def kill_command
::Middleman::WINDOWS ? 1 : :INT
end
def ignore_list
[
/\.sass-cache/,
/\.git/,
/\.DS_Store/
]
end
end
# Guards must be in the Guard module to be picked up
class Middleman < Guard
# Save the options for later
def initialize(watchers = [], options = {})
super
# Save options
def initialize(options)
@options = options
if RbConfig::CONFIG['target_os'] =~ /darwin/i
$LOAD_PATH << File.expand_path('../../middleman-core/vendor/rb-fsevent-0.4.3.1/lib', __FILE__)
require 'rb-fsevent'
elsif RbConfig::CONFIG['target_os'] =~ /linux/i
$LOAD_PATH << File.expand_path('../../middleman-core/vendor/rb-inotify-0.8.8/lib', __FILE__)
require 'rb-inotify'
end
start
end
def watch!
local = self
FSSM.monitor(Dir.pwd) do
create { |base, relative| local.run_on_change([relative]) }
update { |base, relative| local.run_on_change([relative]) }
delete { |base, relative| local.run_on_deletion([relative]) }
end
end
# Start Middleman in a fork
@ -104,7 +107,9 @@ module Guard
return reload if needs_to_reload?(paths)
# Otherwise forward to Middleman
paths.each { |path| tell_server(:change => path) }
paths.each do |path|
tell_server(:change => path) unless self.class.ignore_list.any? { |r| path.match(r) }
end
end
# What to do on file deletion
@ -115,13 +120,9 @@ module Guard
return reload if needs_to_reload?(paths)
# Otherwise forward to Middleman
paths.each { |path| tell_server(:delete => path) }
paths.each do |path|
tell_server(:delete => path) unless self.class.ignore_list.any? { |r| path.match(r) }
end
# What command is sent to kill instances
# @return [Symbol, Fixnum]
def self.kill_command
::Middleman::WINDOWS ? 1 : :INT
end
private
@ -144,8 +145,8 @@ module Guard
end
end
# Trap the interupt signal and shut down Guard (and thus the server) smoothly
trap(::Guard::Middleman.kill_command) do
::Guard.stop
exit!(0)
# Trap the interupt signal and shut down FSSM (and thus the server) smoothly
trap(::Middleman::Watcher.kill_command) do
::Middleman::Watcher.singleton.stop
exit(0)
end

View file

@ -36,6 +36,6 @@ Gem::Specification.new do |s|
s.add_dependency("activesupport", ["~> 3.1.0"])
# Watcher
s.add_dependency("guard", ["~> 0.9.4"])
s.add_dependency("fssm", ["~> 0.2.7"])
end