Sha256: 3efdbc4653c3ad31a810cd61936b97c14ef0ddd577511553c2d614f2f4733f06

Contents?: true

Size: 1.25 KB

Versions: 9

Compression:

Stored size: 1.25 KB

Contents

require_relative 'error'
require 'shellwords'

module Dply
  class Command

    def initialize(command, env: {}, shell: false)
      @command = command
      @env = env
      @shell = shell
      validate!
    end

    def run
      assert_success { system(@env, *command, unsetenv_others: true, 2 => 1) }
    end

    def capture
      assert_success { IO.popen(@env, command, unsetenv_others: true) { |f| f.read } }
    end

    private

    def assert_success(&block)
      ret = yield
      exitstatus = $?.exitstatus
      if exitstatus != 0
        raise Error, "non zero exit for \"#{command_str}\""
      end
      ret
    end

    def command
      @shell ? command_str : command_arr
    end

    def command_arr
      @command_arr ||= begin
        command_arr = @command.is_a?(Array) ? @command : @command.shellsplit
        raise Error, "empty command \"#{@command}\"" if command_arr.empty?
        command_arr[0] = command_arr[0].shellescape if command_arr.size == 1
        command_arr
      end
    end

    def command_str
      @command_str ||= @command.is_a?(String) ? @command : @command.join(" ")
    end

    def validate!
      if @shell && @command.is_a?(Array)
        raise Error, "command cannot be an array when shell: true"
      end
    end

  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
dply-0.3.8 lib/dply/command.rb
dply-0.3.7 lib/dply/command.rb
dply-0.3.6 lib/dply/command.rb
dply-0.3.5 lib/dply/command.rb
dply-0.3.4 lib/dply/command.rb
dply-0.3.3 lib/dply/command.rb
dply-0.3.2 lib/dply/command.rb
dply-0.3.1 lib/dply/command.rb
dply-0.3.0 lib/dply/command.rb