【发布时间】:2011-04-30 19:58:09
【问题描述】:
我希望我的 :default 任务在 Rakefile 中成为有用的消息,其中还包括可用任务列表(rake -T 的输出),供不熟悉 rake 的人使用。
如何从任务内部调用 rake -T?
【问题讨论】:
-
查看 rake.rb 的源代码,看起来我应该能够在 Rake.application 上调用 display_tasks_and_cmets,但它没有输出任何内容。
我希望我的 :default 任务在 Rakefile 中成为有用的消息,其中还包括可用任务列表(rake -T 的输出),供不熟悉 rake 的人使用。
如何从任务内部调用 rake -T?
【问题讨论】:
在新版本的 rake 中,从任务中调用 rake -T 有点复杂。需要设置的选项可以从方法standard_rake_options中的rake/lib/application.rb导出。基本上这归结为
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
注意record_task_metadata不能在默认任务中设置,因为当任务执行时已经太晚了(描述不会被收集,因此那些是零,因此没有任务匹配模式) .尝试从任务中重新加载 Rakefile 将导致闭环。我认为在总是收集元数据时会有性能折衷。如果这是一个问题
task :default do
system("rake -sT") # s for silent
end
可能更合适。
两者都适用于我使用 rake 0.9.2.2。
【讨论】:
Rake::TaskManager.record_task_metadata = true 必须在Rakefile 中定义任何任务之前发生。
Rake::TaskManager.record_task_metadata = true 放在我的 Rakefile 的顶部,并将默认任务放在我所有常规任务之后的底部。注意:您可以传入:describe 或:lines 而不是:tasks 以获得不同的输出。就个人而言,我更喜欢:tasks。
没关系。一旦我找到了正确的方法,我就找到了答案。
除了调用 display_tasks_and_cmets 之外,您还必须设置正则表达式来过滤您想要显示的任务,或者默认情况下它会将它们全部过滤掉。
要将默认任务设为 rake -T 的输出,请使用以下命令:
task :default do
Rake.application.options.show_task_pattern = //
Rake.application.display_tasks_and_comments()
end
【讨论】:
这比很多人需要的要复杂,但是这个程序会从其他 rake 文件中提取 rake 任务,而不包括那些其他 rakefile。我将它用作需要验证其他 rakefile 的 rake 任务的一部分。
class RakeBrowser
attr_reader :tasks
attr_reader :variables
attr_reader :loads
@last_description = ''
@namespace = ''
include Rake::DSL
def desc(description)
@last_description = description
end
def namespace(name=nil, &block) # :doc:
old = @namespace
@namespace = "#{name}:#{@namespace}"
yield(block)
@namespace = old
end
def task(*args, &block)
if args.first.respond_to?(:id2name)
@tasks << "#{@namespace}" + args.first.id2name
elsif args.first.keys.first.respond_to?(:id2name)
@tasks << "#{@namespace}" + args.first.keys.first.id2name
end
end
def load(filename)
@loads << filename
end
def initialize(file)
@tasks = []
@loads = []
Dir.chdir(File.dirname(file)) do
eval(File.read(File.basename(file)))
end
@variables = Hash.new
instance_variables.each do |name|
@variables[name] = instance_variable_get(name)
end
end
end
desc "Show all the tasks"
task :default do
browser = RakeBrowser.new('common.rake')
browser.tasks.each do |task|
puts " " + task
end
end
完整的代码在
【讨论】: