Module: CemAcpt::Utils::Shell
- Defined in:
- lib/cem_acpt/utils/shell.rb
Overview
Generic utilities for running local shell commands
Class Method Summary collapse
-
.run_cmd(cmd, env = {}, output: $stdout, raise_on_fail: true) ⇒ String
Runs a command in a subshell and returns the Process::Status and the string output of the command.
-
.which(cmd) ⇒ String?
Mimics the behavior of the ‘which` command.
Class Method Details
.run_cmd(cmd, env = {}, output: $stdout, raise_on_fail: true) ⇒ String
Runs a command in a subshell and returns the Process::Status and the string output of the command.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/cem_acpt/utils/shell.rb', line 22 def self.run_cmd(cmd, env = {}, output: $stdout, raise_on_fail: true) io_outerr = StringIO.new if output.respond_to?(:debug) output.debug('CemAcpt::Utils::Shell') { "Running command:\n\t#{cmd}\nWith environment:\n\t#{env}" } else output << "Running command:\n\t#{cmd}\nWith environment:\n\t#{env}\n" end val = Open3.popen2e(env, cmd) do |stdin, outerr, wait_thr| stdin.close outerr.sync = true output_thread = Thread.new do while (line = outerr.readline_nonblock) output << line if output io_outerr.write(line) unless line.chomp.empty? end rescue IO::WaitReadable begin IO.select([outerr]) retry rescue IOError # outerr closed, won't retry end rescue EOFError # outerr closed, won't retry end wait_thr.join output_thread.exit wait_thr.value end io_string = io_outerr.string raise CemAcpt::ShellCommandError, "Error running command: #{cmd}\n#{io_string}" if raise_on_fail && !val.success? io_string end |
.which(cmd) ⇒ String?
Mimics the behavior of the ‘which` command.
61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/cem_acpt/utils/shell.rb', line 61 def self.which(cmd) return cmd if File.executable?(cmd) && !File.directory?(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each do |ext| exe = File.join(path, "#{cmd}#{ext}") return exe if File.executable?(exe) && !File.directory?(exe) end end nil end |