Add bin and edit workflow
Gitea Actions Demo / Explore-Gitea-Actions (push) Failing after 9s

This commit is contained in:
2026-09-16 13:11:16 -06:00
parent c8ac4fcae5
commit 4cee170d66
17576 changed files with 895740 additions and 2 deletions
+53
View File
@@ -0,0 +1,53 @@
name: Test
on: [push, pull_request]
permissions:
contents: read
env:
CONSOLE_OUTPUT: XTerm
jobs:
test:
name: ${{matrix.ruby}} on ${{matrix.os}}
runs-on: ${{matrix.os}}-latest
continue-on-error: ${{matrix.experimental}}
strategy:
matrix:
os:
- ubuntu
ruby:
- "2.5"
- "2.6"
- "2.7"
- "3.0"
- "3.1"
- "3.2"
- "3.3"
experimental: [false]
include:
- os: ubuntu
ruby: truffleruby
experimental: true
- os: ubuntu
ruby: jruby
experimental: true
- os: ubuntu
ruby: head
experimental: true
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{matrix.ruby}}
bundler-cache: true
- name: Run tests
timeout-minutes: 10
run: bundle exec rspec
+21
View File
@@ -0,0 +1,21 @@
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
.tags*
.rspec_status
/guard/
/listen/
+4
View File
@@ -0,0 +1,4 @@
--readme README.md
--markup markdown
--markup-provider maruku
--no-private
+20
View File
@@ -0,0 +1,20 @@
source 'https://rubygems.org'
# Specify your gem's dependencies in utopia.gemspec
gemspec
group :maintenance, optional: true do
gem "bake-gem"
gem "bake-modernize"
end
group :test do
gem "rspec", "~> 3.6"
gem 'simplecov'
gem 'coveralls', require: false
gem "bundler"
gem "rake"
gem "concurrent-ruby"
end
+10
View File
@@ -0,0 +1,10 @@
# The MIT License
Copyright, 2009, by [Natalie Weizenbaum](https://github.com/nex3).
Copyright, 2017, by [Samuel G. D. Williams](http://www.codeotaku.com).
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.
+111
View File
@@ -0,0 +1,111 @@
# 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).
[![Development Status](https://github.com/guard/rb-inotify/workflows/Test/badge.svg)](https://github.com/guard/rb-inotify/actions?workflow=Test)
## 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.
### Resource Limits
If you get an error like `inotify event queue has overflowed` you might be running into system limits. You can add the following to your `/etc/sysctl.conf` to increase the number of files that can be monitored:
```
fs.inotify.max_user_watches = 100000
fs.inotify.max_queued_events = 100000
fs.inotify.max_user_instances = 100000
```
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
## License
Released under the MIT license.
Copyright, 2009, by [Natalie Weizenbaum](https://github.com/nex3).
Copyright, 2017, by [Samuel G. D. Williams](http://www.codeotaku.com/samuel-williams).
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.
@@ -0,0 +1,15 @@
require 'rb-inotify/version'
require 'rb-inotify/native'
require 'rb-inotify/native/flags'
require 'rb-inotify/notifier'
require 'rb-inotify/watcher'
require 'rb-inotify/event'
require 'rb-inotify/errors'
# 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
end
@@ -0,0 +1,3 @@
module INotify
class QueueOverflowError < RuntimeError; end
end
@@ -0,0 +1,146 @@
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 = fix_encoding(data[@native.size, @native[:len]].gsub(/\0+$/, ''))
@notifier = notifier
@watcher_id = @native[:wd]
raise QueueOverflowError.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 && 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
private
def fix_encoding(name)
name.force_encoding('filesystem') if name.respond_to?(:force_encoding)
name
end
end
end
@@ -0,0 +1,33 @@
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 FFI::Library::LIBC
begin
ffi_lib 'inotify'
rescue LoadError
end
# 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 :fpathconf, [:int, :int], :long
end
end
@@ -0,0 +1,94 @@
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
## fpathconf Macros
# returns the maximum length of a filename in the directory path or fd that the process is allowed to create. The corresponding macro is _POSIX_NAME_MAX.
PC_NAME_MAX = 3
# 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
@@ -0,0 +1,322 @@
require 'thread'
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
# * Files in `/dev/fd` sometimes register as directories, but are not enumerable.
NON_RECURSIVE = "/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]
def fd
@handle.fileno
end
# Creates a new {Notifier}.
#
# @return [Notifier]
# @raise [SystemCallError] if inotify failed to initialize for some reason
def initialize
@running = Mutex.new
@stop = false
@pipe = IO.pipe
# JRuby shutdown sometimes runs IO finalizers before all threads finish.
if RUBY_ENGINE == 'jruby'
@pipe[0].autoclose = false
@pipe[1].autoclose = false
end
@watchers = {}
fd = Native.inotify_init
unless fd < 0
@handle = IO.new(fd)
@handle.autoclose = false if RUBY_ENGINE == 'jruby'
return
end
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
@handle
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)
dont_follow = flags.include?(:dont_follow)
Dir.each_child(path) do |base|
d = File.join(path, base)
next unless File.directory?(d)
next if dont_follow && File.symlink?(d)
next if NON_RECURSIVE == d
watch(d, *flags, &callback)
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
@running.synchronize do
Thread.current[:INOTIFY_RUN_THREAD] = true
process until @stop
end
ensure
Thread.current[:INOTIFY_RUN_THREAD] = false
@stop = false
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
@pipe.last.write "."
unless Thread.current[:INOTIFY_RUN_THREAD]
@running.synchronize do
# no-op: we just needed to wait until the lock was available
end
end
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 do |event|
event.callback!
event.flags.include?(:ignored) && event.notifier.watchers.delete(event.watcher_id)
end
end
# Close the notifier.
#
# @raise [SystemCallError] if closing the underlying file descriptor fails.
def close
stop
@handle.close
@watchers.clear
end
# Blocks until there are one or more filesystem events that this notifier
# has watchers registered for. Once there are events, returns their {Event}
# objects.
#
# This can return an empty list if the watcher was closed elsewhere.
#
# {#run} or {#process} are ususally preferable to calling this directly.
def read_events
size = Native::Event.size + Native.fpathconf(fd, Native::Flags::PC_NAME_MAX) + 1
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
return [] if data.nil?
events = []
cookies = {}
while event = Event.consume(data, self)
events << event
next if event.cookie == 0
cookies[event.cookie] ||= []
cookies[event.cookie] << event
end
cookies.each {|c, evs| evs.each {|ev| ev.related.replace(evs - [ev]).freeze}}
events
end
private
# Same as IO#readpartial, or as close as we need.
def readpartial(size)
readable, = select([@handle, @pipe.first])
return nil if readable.include?(@pipe.first)
@handle.readpartial(size)
rescue Errno::EBADF
# If the IO has already been closed, reading from it will cause
# Errno::EBADF.
nil
end
end
end
@@ -0,0 +1,24 @@
# Copyright, 2012, by Natalie Weizenbaum.
# Copyright, 2017, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# 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.
module INotify
VERSION = '0.11.1'
end
@@ -0,0 +1,88 @@
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
if Native.inotify_rm_watch(@notifier.fd, @id) == 0
@notifier.watchers.delete(@id)
return
end
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
@@ -0,0 +1,23 @@
# -*- encoding: utf-8 -*-
require_relative 'lib/rb-inotify/version'
Gem::Specification.new do |spec|
spec.name = 'rb-inotify'
spec.version = INotify::VERSION
spec.platform = Gem::Platform::RUBY
spec.summary = 'A Ruby wrapper for Linux inotify, using FFI'
spec.authors = ['Natalie Weizenbaum', 'Samuel Williams']
spec.email = ['nex342@gmail.com', 'samuel.williams@oriontransfer.co.nz']
spec.homepage = 'https://github.com/guard/rb-inotify'
spec.licenses = ['MIT']
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.required_ruby_version = '>= 2.5'
spec.add_dependency "ffi", "~> 1.0"
end
@@ -0,0 +1,9 @@
require 'spec_helper'
describe INotify do
describe "version" do
it "exists" do
expect(INotify::VERSION).to be_truthy
end
end
end
@@ -0,0 +1,190 @@
require 'spec_helper'
require 'tmpdir'
require 'concurrent'
describe INotify::Notifier do
describe "instance" do
around do |block|
Dir.mktmpdir do |dir|
@root = Pathname.new(dir)
@notifier = INotify::Notifier.new
begin
block.call
ensure
@notifier.close
end
end
end
let(:dir) do
@root.join("foo").tap(&:mkdir)
end
let(:another_dir) do
@root.join("bar").tap(&:mkdir)
end
it "stops" do
@notifier.stop
end
describe :process do
it "gets events" do
events = recording(dir, :create)
dir.join("test.txt").write("hello world")
@notifier.process
expect(events.size).to eq(1)
expect(events.first.name).to eq("test.txt")
expect(events.first.absolute_name).to eq(dir.join("test.txt").to_s)
end
it "gets simultaneous events" do
events = recording(dir, :create)
dir.join("one.txt").write("hello world")
dir.join("two.txt").write("hello world")
@notifier.process
expect(events.map(&:name)).to match_array(%w(one.txt two.txt))
end
it "separates events between watches" do
bar_events = nil
foo_events = recording(dir, :create)
bar_events = recording(another_dir, :create)
dir.join("test.txt").write("hello world")
another_dir.join("test_two.txt").write("hello world")
@notifier.process
expect(foo_events.size).to eq(1)
expect(foo_events.first.name).to eq("test.txt")
expect(foo_events.first.absolute_name).to eq(dir.join("test.txt").to_s)
expect(bar_events.size).to eq(1)
expect(bar_events.first.name).to eq("test_two.txt")
expect(bar_events.first.absolute_name).to eq(another_dir.join("test_two.txt").to_s)
end
end
describe :run do
it "processes repeatedly until stopped" do
barriers = Array.new(3) { Concurrent::Event.new }
barrier_queue = barriers.dup
events = recording(dir, :create) { barrier_queue.shift.set }
run_thread = Thread.new { @notifier.run }
dir.join("one.txt").write("hello world")
barriers.shift.wait(1) or raise "timeout"
expect(events.map(&:name)).to match_array(%w(one.txt))
dir.join("two.txt").write("hello world")
barriers.shift.wait(1) or raise "timeout"
expect(events.map(&:name)).to match_array(%w(one.txt two.txt))
@notifier.stop
dir.join("three.txt").write("hello world")
run_thread.join(1) or raise "timeout"
expect(events.map(&:name)).to match_array(%w(one.txt two.txt))
end
it "can be stopped from within a callback" do
recording(dir, :create) { @notifier.stop }
run_thread = Thread.new { @notifier.run }
dir.join("one.txt").write("hello world")
run_thread.join(1) or raise "timeout"
end
it "can be stopped before it starts processing" do
barrier = Concurrent::Event.new
run_thread = Thread.new do
barrier.wait
@notifier.run
end
@notifier.stop
barrier.set
run_thread.join(1) or raise "timeout"
end
end
describe :fd do
it "returns an integer" do
expect(@notifier.fd).to be_an(Integer)
end
end
describe :to_io do
it "returns a ruby IO" do
expect(@notifier.to_io).to be_an(::IO)
end
it "matches the fd" do
expect(@notifier.to_io.fileno).to eq(@notifier.fd)
end
it "caches its result" do
expect(@notifier.to_io).to be(@notifier.to_io)
end
it "is selectable" do
events = recording(dir, :create)
expect(select([@notifier.to_io], nil, nil, 0.2)).to be_nil
dir.join("test.txt").write("hello world")
expect(select([@notifier.to_io], nil, nil, 0.2)).to eq([[@notifier.to_io], [], []])
@notifier.process
expect(select([@notifier.to_io], nil, nil, 0.2)).to be_nil
end
end
private
def recording(dir, *flags, callback: nil)
events = []
@notifier.watch(dir.to_s, *flags) do |event|
events << event
yield if block_given?
end
events
end
end
describe "mixed instances" do
it "doesn't tangle fds" do
notifiers = Array.new(30) { INotify::Notifier.new }
notifiers.each(&:to_io)
one = Array.new(10) { IO.pipe.last }
notifiers.each(&:close)
two = Array.new(10) { IO.pipe.last }
notifiers = nil
GC.start
_, writable, _ = select(nil, one, nil, 1)
expect(writable).to match_array(one)
_, writable, _ = select(nil, two, nil, 1)
expect(writable).to match_array(two)
end
end
end
@@ -0,0 +1,29 @@
if ENV['COVERAGE'] || ENV['TRAVIS']
begin
require 'simplecov'
SimpleCov.start do
add_filter "/spec/"
end
if ENV['TRAVIS']
require 'coveralls'
Coveralls.wear!
end
rescue LoadError
warn "Could not load simplecov: #{$!}"
end
end
require "bundler/setup"
require "rb-inotify"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
config.expect_with :rspec do |c|
c.syntax = :expect
end
end