Search code examples
rubyrake

Rake: how to output a list of tasks from inside a task?


I'd like my :default task in a Rakefile to be a helpful message that also includes the list of available tasks (the output of rake -T) for people who are not as familiar with rake.

How do you invoke rake -T from inside a task?


Solution

  • Invoking rake -T from within tasks is a bit more complicated in newer versions of rake. The options that need to be set may be derived from rake/lib/application.rb in method standard_rake_options. Basically this boils down to

    Rake::TaskManager.record_task_metadata = true
    
    task :default do
      Rake::application.options.show_tasks = :tasks  # this solves sidewaysmilk problem
      Rake::application.options.show_task_pattern = //
      Rake::application.display_tasks_and_comments
    end
    

    Note that record_task_metadata cannot be set from within the default task, as it will already be too late when the task is executed (descriptions won’t have been collected, thus those are nil and therefore no task matches the pattern). Trying to reload the Rakefile from within a task will lead to a closed loop. I assume there are performance trade ofs when always collecting metadata. If that’s an issue

    task :default do
      system("rake -sT")  # s for silent
    end
    

    might be more suitable.

    Both work for me using rake 0.9.2.2.