Thursday, March 9, 2006

Fast Rake Task Completion for Zsh

Posted by nicholas

Those of you who love running Rake tasks but don’t like typing are in for a treat. Although there’s been task completion for Rake for a while now, most of the scripts for it are painfully slow, especially with Rails’ Rakefile.

Below is a small zsh completion script that uses a cache file (named .rake_tasks) to improve the performance of your tab keystrokes.

To use, throw it in your home folder somewhere and add source $HOME/.rake_completion.zsh to your .zshrc file.

A few disclaimers: Yes, it doesn’t work with lowercase named rakefile‘s. Only barbarians use such names though, so hopefully you won’t have a problem there. And no, it doesn’t complete the other assorted arguments that the rake command can accept, frankly because I rarely use them.

Without further ado, here’s the bytes.

_rake_does_task_list_need_generating () {
  if [ ! -f .rake_tasks ]; then return 0;
  else
    accurate=$(stat -f%m .rake_tasks)
    changed=$(stat -f%m Rakefile)
    return $(expr $accurate '>=' $changed)
  fi
}

_rake () {
  if [ -f Rakefile ]; then
    if _rake_does_task_list_need_generating; then
      echo "\nGenerating .rake_tasks..." > /dev/stderr
      rake --silent --tasks | cut -d " " -f 2 > .rake_tasks
    fi
    compadd `cat .rake_tasks`
  fi
}

compdef _rake rake

(Use at your own risk. Comments and improvements welcome.)