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