Sha256: f10ed61a373e2de205ecbceb9f166f97ee6c94daf9c820a190a2299de31d502c

Contents?: true

Size: 1.5 KB

Versions: 12

Compression:

Stored size: 1.5 KB

Contents

require 'shellwords'
require 'open3'
require 'dragonfly'

module Dragonfly
  class Shell

    # Exceptions
    class CommandFailed < RuntimeError; end

    def run(command, opts={})
      command = escape_args(command) unless opts[:escape] == false
      Dragonfly.debug("shell command: #{command}")
      run_command(command)
    end

    def escape_args(args)
      args.shellsplit.map do |arg|
        quote arg.gsub(/\\?'/, %q('\\\\''))
      end.join(' ')
    end

    def quote(string)
      q = Dragonfly.running_on_windows? ? '"' : "'"
      q + string + q
    end

    private

    # Annoyingly, Open3 seems buggy on jruby/1.8.7:
    # Some versions don't yield a wait_thread in the block and
    # you can't run sub-shells (if explicitly turning shell-escaping off)
    if RUBY_PLATFORM == 'java' || RUBY_VERSION < '1.9'

      # Unfortunately we have no control over stderr this way
      def run_command(command)
        result = `#{command}`
        status = $?
        raise CommandFailed, "Command failed (#{command}) with exit status #{status.exitstatus}" unless status.success?
        result
      end

    else

      def run_command(command)
        Open3.popen3 command do |stdin, stdout, stderr, wait_thread|
          stdin.close_write # make sure it doesn't hang
          status = wait_thread.value
          raise CommandFailed, "Command failed (#{command}) with exit status #{status.exitstatus} and stderr #{stderr.read}" unless status.success?
          stdout.read
        end
      end

    end

  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
dragonfly-1.1.0 lib/dragonfly/shell.rb
dragonfly-1.0.12 lib/dragonfly/shell.rb
dragonfly-1.0.11 lib/dragonfly/shell.rb
dragonfly-1.0.10 lib/dragonfly/shell.rb
dragonfly-1.0.9 lib/dragonfly/shell.rb
dragonfly-1.0.8 lib/dragonfly/shell.rb
dragonfly-1.0.7 lib/dragonfly/shell.rb
dragonfly-1.0.6 lib/dragonfly/shell.rb
dragonfly-1.0.5 lib/dragonfly/shell.rb
dragonfly-1.0.4 lib/dragonfly/shell.rb
dragonfly-1.0.3 lib/dragonfly/shell.rb
dragonfly-1.0.2 lib/dragonfly/shell.rb