rubycapistrano3

Capistrano 3 execute arbitrary command on remote server


Capistrano 3 does not use command cap env shell anymore.

Now we should use cap env console

But it is not interactive and we can not use for example arrow keys for history or autocompletion on tab button

And what should I do?


Solution

  • I suggest to write your own little rake task to do it. Use readline gem First of all thanks to follow materials:

    1. https://thoughtbot.com/blog/tab-completion-in-gnu-readline-ruby-edition

    2. How to write a Ruby command line app that supports tab completion?

    
    desc "Remote console" 
    task :console do
      require 'readline'
      # https://thoughtbot.com/blog/tab-completion-in-gnu-readline-ruby-edition
    
      host_args = (ENV['HOSTS'] || '').split(',').map { |r| r.to_sym }
      role_args = (ENV['ROLES'] || '').split(',').map { |r| r.to_sym }
    
      LIST = `ls /usr/bin`.split("\n").sort + `ls /bin`.split("\n").sort
    
      comp = proc { |s| LIST.grep(/^#{Regexp.escape(s)}/) }
    
      Readline.completion_append_character = " "
      Readline.completion_proc = comp
    
      while line = Readline.readline('cap> ', true)
        begin
          next if line.strip.empty?
          exec_cmd(line, host_args, role_args)
        rescue StandardError => e
          puts e
          puts e.backtrace
        end
      end
    end
    
    def exec_cmd(line, host_args, role_args)
      line = "RAILS_ENV=#{fetch(:stage)} #{line}" if fetch(:stage)
      cmd = "bash -lc '#{line}'"
      puts "Final command: #{cmd}"
      if host_args.any?
        on hosts host_args do
          execute cmd
        end
      elsif role_args.any?
        on roles role_args do
          execute cmd
        end
      else
        on roles :all do
          execute cmd
        end
      end
    end
    
    
    

    And do what you want with it, cheers! =))