How to Abort a Chain of Rake Tasks on Error

I use nanoc as my static site creator for this blog. It’s written in Ruby, my favorite scripting language. And so I use a Rakefile to automate most things, like generating a fresh copy of the site and deploying it to my server.

Only last week did I find out how to make Rake not continue when a part of its tasks failed. Most of the stuff I use is wrappers around shell commands with a few system notifications sprinkled in. $? does capture the latest shell call’s return value (kudos

task :generate do
  out = system "nanoc co" # compile site
  # abort on error
  if $?.to_i == 0
    puts  "Compilation succeeded"
    abort "Compilation failed: #{$?.to_i}\n#{out}\n"

In the past, when I changed something and was to lazy to preview changes, the task chain of cleaning + compilation + deployment sometimes resulted in compilation errors; then a lot of files would be missing in the compilation result’s folder; and then the folder would still get rsynced to my server, deleting most of the stuff there. Oh my. I’m glad these times are gone. Astonishingly, total data loss on the server never bugged me enough to look this simple thing up.

Browse the blog archive