Friday, January 06, 2006

I prefer Rake to NAnt (#2)

I prefer Ruby's libraries to NAnt's tasks.
Recently, I was asked to add a step to the build file that would delete all build outputs that were older than 2 weeks old. The build output is stored in a folder in the distrobution folder. I'm not even going to attempt this task in NAnt, but using Ruby's find, delete, and fileutils the code was quite easy to write. (I admit, this could probably be done even better, but this was the first thing that came to mind.)
require 'find'
require 'date'
require 'fileutils'

root_dir = "C:/Dist"
two_weeks_ago = Date.today - 14

puts "deleting files last modified before #{two_weeks_ago}"
Find.find(root_dir) do |path|
if File.dirname(path) == root_dir
file_modify_date = Date.parse(File.mtime(path).strftime("%m/%d/%Y"))
puts "#{path} last modified on #{file_modify_date}"
if file_modify_date < two_weeks_ago
puts "#{path} removed"
FileUtils.rm_rf(path)
end
end
end

2 comments:

  1. Greetings Jay,

    But you've cheated :)

    FYI, note that whilst it may be possible to conjure up a NAnt variant of your conditional delete script using existing NAnt tasks, its also possible to define custom scripting tasks containing source code in a similar manner to your Ruby script. See the following for further details:

    http://nant.sourceforge.net/release/latest/help/tasks/script.html

    Note the fourth example that shows the definition of a custom script and its invocation via custom task elements, so you could define a deletion script that is invoked as follows:

    <deleteFiles createdBefore='07-Jan-2005'/>

    Not that I'm trying to curb your enthusiasm for Ruby, just in case you need to know in future.

    Cheers,
    Matt

    ReplyDelete
  2. Hello Matt,
    I did know about creating custom scripts; however, I've never actually done it. Perhaps I'll write up the delete task and see how it compares.

    Thanks for the feedback,
    Jay

    ReplyDelete

Note: Only a member of this blog may post a comment.