2011-12-22 41 views
4

我有一個Rake文件這樣耙清潔引發錯誤時,文件不存在

task :clean do 
    sh 'rm ./foo' 
end 

我想阻止它在文件「富」是不存在的錯誤報告。怎麼做?

我想我想要的是:有沒有辦法先檢查文件,然後決定下一步該做什麼。

例如:

file 'aaa' => 'bbb' do 
    sh 'cp bbb aaa' 
end 

這個任務依賴於文件 'BBB' 的存在,所以我想知道can I tell Rake that my task depends on the不存在of file 'foo'

回答

4

您可以通過擴展耙位做到這一點

require File.join(File.dirname(__FILE__), 'unfile_rake_ext') 

unfile 'target.txt' do 
    File.delete('target.txt') 
end 

unfile_rake_ext.rb:

class UnFileTask < Rake::FileTask 
    def needed? 
    File.exist?(name) 
    end 
end 

def unfile(*args, &block) 
    UnFileTask.define_task(*args, &block) 
end 

我的控制檯輸出:

D:\Projects\ZPersonal\tmp>ls 
Rakefile unfile_rake_ext.rb 

D:\Projects\ZPersonal\tmp>touch target.txt && ls 
Rakefile target.txt unfile_rake_ext.rb 

D:\Projects\ZPersonal\tmp>rake target.txt --trace 
** Invoke target.txt (first_time) 
** Execute target.txt 

D:\Projects\ZPersonal\tmp>ls 
Rakefile unfile_rake_ext.rb 

D:\Projects\ZPersonal\tmp>rake target.txt --trace 
** Invoke target.txt (first_time, not_needed) 

D:\Projects\ZPersonal\tmp>ls 
Rakefile unfile_rake_ext.rb 

希望這會有所幫助。

+1

酷!學到了很多。謝謝。 – Rocky 2011-12-22 09:31:45

1

這個怎麼樣?

Rake文件:

if File.exists? './foo/' 
    sh 'rm -f ./foo' 
end 
+0

好。這是一個解決方案。我真正想要的是檢查一些條件並決定做什麼或不做什麼。謝謝。 – Rocky 2011-12-22 05:34:06

+0

啊哈,所以,像'sh'rm ./foo'如果File.exists? 」/foo''? – buruzaemon 2011-12-22 05:37:43

+0

謝謝,看看我的新編輯。我真的想耙去處理,而不是我的代碼。 :) – Rocky 2011-12-22 05:42:13

2

在你的Rakefile:

task :clean do 
    rm 'foo' if File.exists? 'foo' 
end 

file 'aaa' => ['bbb', :clean] do |t| 
    cp t.prerequisites[0], t.name 
end 

現在在命令行:

echo 'test' > bbb 
rake aaa 
    => cp bbb aaa 

touch foo 
rake aaa 
    => rm foo 
    => cp bbb aaa