Greg Ruhl
Greg Ruhl

Reputation: 1114

Rakefile - parameter and directory dependency on task

I want to cleanly lookup various directory paths using shell commands in a rakefile, assign that value to a variable, and then use that variable to create directories (and use in other tasks). I've put the sh code in a task and made the directory calls dependent on the task (using the file call after directory). However, I'm not able to use the variable anywhere outside of the task (even with making it global).

$my_root = String.new

task :find_path do
    sh %{git rev-parse --show-toplevel} do |pass, res|
      if ! pass
        puts "git rev-parse failed, are you in a git repo? (status = #{res.exitstatus})"
      else
        $my_root = res
      end
    end
end

$MY_DIR        = "#{$my_root}/some/sub/dir"

desc "Create MY_DIR directory"
directory $MY_DIR
file $MY_DIR  => :find_pmc_path

I get the following error:

mkdir -p /some/sub/dir
rake aborted!

When I dig further, the $MY_DIR does not get assigned correctly. If I place that variable assignment in the task I get an undefined method 'length' for nil:NilClass error.

How can I look up the information, assign the variable, and use it in multiple other tasks within the rakefile?

Upvotes: 0

Views: 186

Answers (1)

Anthony
Anthony

Reputation: 15967

This seems like a good use case for the namespace declaration:

namespace :top do
  mydir = 'my_root'
  task :find_path do
    puts mydir
  end

  task :delete do
    puts mydir
  end
end

find_task:

rake top:find_path
=> my_root

delete task:

rake top:delete
=>my_root

Upvotes: 1

Related Questions