Module: TFWrapper::Helpers

Defined in:
lib/tfwrapper/helpers.rb

Overview

generic helper functions for TFWrapper

Class Method Summary collapse

Class Method Details

.check_env_vars(required) ⇒ Object

Ensure that a given list of environment variables are present and non-empty. Raise StandardError if any aren’t.

Parameters:

  • required (Array)

    list of required environment variables



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/tfwrapper/helpers.rb', line 62

def self.check_env_vars(required)
  missing = []
  required.each do |name|
    if !ENV.include?(name)
      puts "ERROR: Environment variable '#{name}' must be set."
      missing << name
    elsif ENV[name].to_s.strip.empty?
      puts "ERROR: Environment variable '#{name}' must not be empty."
      missing << name
    end
  end
  # rubocop:disable Style/GuardClause
  unless missing.empty?
    raise StandardError, 'Missing or empty environment variables: ' \
      "#{missing}"
  end
  # rubocop:enable Style/GuardClause
end

.run_cmd(cmd) ⇒ Object

Run a system command, print the command before running it. If it exits with a non-zero status, print the exit status and output and then fail.

Parameters:

  • cmd (String)

    the command to run

Raises:

  • (StandardError)


15
16
17
18
19
20
21
22
23
# File 'lib/tfwrapper/helpers.rb', line 15

def self.run_cmd(cmd)
  puts "Running command: #{cmd}"
  out = `#{cmd}`
  status = $CHILD_STATUS.exitstatus
  return if status.zero?
  puts "Command exited #{status}:"
  puts out
  raise StandardError, "ERROR: Command failed: #{cmd}"
end

.run_cmd_stream_output(cmd, pwd) ⇒ Array

popen2e wrapper to simultaneously stream command output and capture it.

STDOUT and STDERR will be combined to the same stream, and returned as one string. This is because there doesn’t seem to be a safe, cross-platform way to both capture and stream STDOUT and STDERR separately that isn’t prone to deadlocking if large chunks of data are written to the pipes.

Parameters:

  • cmd (String)

    command to run

  • pwd (String)

    directory/path to run command in

Returns:

  • (Array)
    • out_err [String], exit code [Fixnum]



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tfwrapper/helpers.rb', line 35

def self.run_cmd_stream_output(cmd, pwd)
  old_sync = $stdout.sync
  $stdout.sync = true
  all_out_err = ''.dup
  exit_status = nil
  Open3.popen2e(cmd, chdir: pwd) do |stdin, stdout_and_err, wait_thread|
    stdin.close_write
    begin
      while (line = stdout_and_err.gets)
        puts line
        all_out_err << line
      end
    rescue IOError => e
      STDERR.puts "IOError: #{e}"
    end
    exit_status = wait_thread.value.exitstatus
  end
  # rubocop:disable Style/RedundantReturn
  $stdout.sync = old_sync
  return all_out_err, exit_status
  # rubocop:enable Style/RedundantReturn
end