# Redefine Rake::Task to chdir(@curpath) to whatever @@curpath was at the time of Task *creation*
module Rake
  class Task
    alias old_initialize initialize
    alias old_needed? needed?
    alias old_invoke  invoke
    alias old_execute execute
    @@curpath = nil

    class << self
      def curpath
	@@curpath
      end

      def curpath= (what)
	@@curpath = what if what.nil? or File.directory?(what)
      end
    end

    def initialize(*args)
      @curpath=@@curpath
      old_initialize(*args)
    end

    def pathchdir(&block)
      if @curpath.nil?
	yield block
      else
	FileUtils.chdir(@curpath, &block)
      end
    end

    def needed?(*args)
      retval=nil
      pathchdir do
	retval=old_needed?(*args)
      end
      retval
    end

    def invoke(*args)
      retval=nil
      pathchdir do
	retval=old_invoke(*args)
      end
      retval
    end

    def execute(*args)
      retval=nil
      pathchdir do
	retval=old_execute(*args)
      end
      retval
    end
  end

  class FileTask
    alias old_needed? needed?

    def needed?(*args)
      retval=nil
      pathchdir do
	retval=old_needed?(*args)
      end
      retval
    end
  end
end

# Defines a block wherein all defined Rake Tasks will invoke and execute in the directory given
def dirspace(path=nil, &block)
  if not path.nil? and File.directory?(path=File.expand_path(path))
    old_path=Dir.pwd
    Rake::Task.curpath=path
    begin
      yield block
    ensure
      Rake::Task.curpath=old_path
    end
  else
    yield block
  end
end

