Luke Melia


March 10, 2008

capistrano task autocompletion for bash

Remembering all those capistrano tasks can be tough for the sleep-impaired startup employee…. Help yourself out with this autocomplete script:

#!/usr/bin/env ruby

# Save this somewhere, chmod 755 it, then add
#   complete -C path/to/this/script -o default cap
# to your ~/.bashrc
# If you update your tasks, just $ rm ~/.captabs*

exit 0 unless /^cap\b/ =~ ENV["COMP_LINE"]

def cap_silent_tasks
  if File.exists?(dotcache = File.join(File.expand_path('~'), ".captabs-#{Dir.pwd.hash}"))
    tasks = `cap -qT`
    tasks ={|task| task =~ /^cap/ }.join, 'w') { |f| f.puts tasks }

after_match = $'
task_match = (after_match.empty? || after_match =~ /\s$/) ? nil : after_match.split.last
tasks = cap_silent_tasks.split("\n")[1..-1].map { |line| line.split[1] }
tasks = { |t| /^#{Regexp.escape task_match}/ =~ t } if task_match

# handle namespaces
if task_match =~ /^([-\w:]+:)/
  upto_last_colon = $1
  after_match = $'
  tasks = { |t| (t =~ /^#{Regexp.escape upto_last_colon}([-\w:]+)$/) ? "#{$1}" : t }

puts tasks
exit 0

4 Responses to “capistrano task autocompletion for bash”

  1. Unnsse Khan chimed in:

    Can you give us an example of what this Ruby script does?

    Unix already supports tab completions…

    What is an “auto completion”, per se’?

    Happy programming!

  2. d. chimed in:

    Hi Luke. Congrats on the launch of weplay. Wow, the site rocks way harder than Exile on Mainstreet!!! I think you are really onto something big. Congrats on your new endeavor, and get some sleep.

  3. silkcom chimed in:

    any updates to this? There are a few little bugs, it works awesome though :) thank you very much, our team will love this.

  4. Roman chimed in:

    Here’s a simpler version which works fine for me and there’s some Ruby in it as well :-)


    _cap_complete ()
    local cur=${COMP_WORDS[$COMP_CWORD]}
    local opt_regex=


    # Options that need no completion and the cursor position to start
    # expansion from for different programs

    # We expand either straight from the cursor if it is at the position to expand
    # or check for the preceding options whether to expand or not
    if ! [[ “${COMP_WORDS[$((COMP_CWORD-1))]}” =~ $opt_regex ]]
    COMPREPLY=(`compgen -W “$(command cap -qT | ruby -ne ‘puts $_[/^cap (\S+) .*$/,1] if $_ =~ /^cap/’)” $cur`)

    } # ———- end of function _pminfo_complete ———-

    complete -F _cap_complete -o default cap

Leave a Reply created 1999. ··· Luke Melia created 1976. ··· Live With Passion!