Strange Symphonies Don’t worry, be happy

11Dec/070

Automatically Restart script/server For Easier Plugin Development with FSEvents

When developing a Rails plugin, you are required to restart the server so that your plugin will be reloaded. You'll notice that after a while this becomes a rather tedious process, especially if you are working on a hot-off-the-press new plugin.

Following suit on my autotest with FSEvents, I opted to listen for any changes to the vendor/plugins and lib directories to restart the server as required. Thus freeing me of the horrible grunt work of restarting the server.

Note: This is Mac OS X 10.5 Leopard specific.

The Incantation

Create the required file script/autorestart_server, and put this beauty in it.

For an easy to copy dump, click "view plain".

Note: Don't forget to make it executable! chmod u+x script/autorestart_server Terminal

#!/usr/bin/env ruby

PATHS_TO_OBSERVE = /^(lib|vendor\/plugins)/

require 'osx/foundation'
OSX.require_framework '/System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework'
include OSX

def start_server
  IO.popen("script/server #{ARGV.join(' ')}")
end

def stop_server(io)
  return if io.nil?
  Process.kill("INT", io.pid)
end

io = start_server

callback = proc do |stream, ctx, numEvents, paths, marks, eventIDs|
  paths.regard_as('*')
  rpaths = []
  length = Dir.pwd.length + 1

  numEvents.times { |i| rpaths << paths[i][length..-1] }

  next if rpaths.select { |path| path =~ PATHS_TO_OBSERVE }.empty?
  stop_server(io)
  puts "Restarting server"
  io = start_server
end

stream = FSEventStreamCreate(KCFAllocatorDefault, callback, nil, [Dir.pwd], KFSEventStreamEventIdSinceNow, 1.0, 0)
unless stream
  puts "Failed to create stream"
  exit
end

FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), KCFRunLoopDefaultMode)
unless FSEventStreamStart(stream)
  puts "Failed to start stream"
  exit
end

begin
  CFRunLoopRun()
rescue Interrupt
  stop_server(io)
  FSEventStreamStop(stream)
  FSEventStreamInvalidate(stream)
  FSEventStreamRelease(stream)
end

Automatically Restarting script/server

Now feel free to execute script/autorestart_server

Wondering where else I can inject FSEvents into, its quite a handy little tool...

Related posts

Tags

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.