Skip to content

Instantly share code, notes, and snippets.

@inem
Created May 4, 2010 07:36
Show Gist options
  • Save inem/389095 to your computer and use it in GitHub Desktop.
Save inem/389095 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# encoding: utf-8
require "find"
require "eventmachine"
# === Usage ===
# project-watcher.rb --no-daemon -- run
# project-watcher.rb -- run as a daemon
# project-watcher.rb --debug -- run in debug mode
# http://eventmachine.rubyforge.org/EventMachine/FileWatch.html
module FileWatcher
def file_modified
rsync path
end
end
$DEBUG = ARGV.include?("--debug")
def debug(*args)
puts *args if $DEBUG
end
def reload_files
debug "Reloading files ..."
old_files, @files = (@files || Array.new), Array.new
Find.find(".") do |file|
if File.file?(file)
@files << file
EM.watch_file(file, FileWatcher)
end
end
# create
newly_created_files = @files - old_files
newly_created_files.each(&method(:rsync))
# remove
removed_files = old_files - @files
removed_files.each(&method(:un_rsync))
rescue Errno::EMFILE
# WTF?
end
def rsync(path)
debug "Pretending to rsync #{path}"
end
def un_rsync(path)
debug "Pretending to un-rsynch #{path}"
end
#
def main
trap(:HUP) do
reload_files
end
trap(:KILL) do
debug "Ending ..."
EM.stop
end
EM.run do
reload_files
EventMachine::PeriodicTimer.new(5) do
reload_files
end
end
end
EM.kqueue if EM.kqueue?
#
if __FILE__ == $0 && ! ARGV.include?("--no-daemon")
pid = fork do
main
end
puts "Starting project watching deamon with PID #{pid}. Send it HUP signal to reload."
else
main
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment