Is it possible to get a list of all available rake

2020-02-26 04:59发布

问题:

Is it possible from within a rake task to get a list of tasks in a namespace? A sort of programatic 'rake -T db' ?

回答1:

I've found out the answer:

tasks = Rake.application.tasks

This will return an array of Rake::Task objects that can be examined. Further details at http://rake.rubyforge.org/



回答2:

As you wrote, with Rake.application.tasks you get all tasks.

But inside the namespace, you can select only the tasks of the namespace (task mytest:tasklist)

And you may restrict the tasks to a namespace (task tasklist_mytest).

require 'rake'

namespace :mytest do |ns|

  task :foo do |t|
    puts "You called task #{t}"
  end

  task :bar do |t|
    puts "You called task #{t}"
  end

  desc 'Get tasks inside actual namespace'
  task :tasklist do
    puts 'All tasks of "mytest":'
    puts ns.tasks #ns is defined as block-argument
  end

end

desc 'Get all tasks'
task :tasklist do
  puts 'All tasks:'
  puts Rake.application.tasks
end

desc 'Get tasks outside the namespace'
task :tasklist_mytest do
  puts 'All tasks of "mytest":'
  Rake.application.in_namespace(:mytest){|x|
    puts x.tasks
  }
end

if $0 == __FILE__
  Rake.application['tasklist'].invoke()  #all tasks
  Rake.application['mytest:tasklist'].invoke() #tasks of mytest
  Rake.application['tasklist_mytest'].invoke() #tasks of mytest
end


回答3:

You can use the grep command like this

desc 'Test'
task :test do
    # You can change db: by any other namespaces
    result = %x[rake -T | sed -n '/db:/{/grep/!p;}' | awk '{print$2}'] 
    result.each_line do |t|
        puts t # Where t is your task name
    end
end


标签: ruby rake