Sha256: 932221b2f69a37cdb417215d64d5166ac28bbd729902b68f5bb4ecbbb61a6eef

Contents?: true

Size: 1.34 KB

Versions: 12

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

class Helmsnap::Command < Helmsnap::Service
  Result = Struct.new(:success, :output)

  def initialize(cmd, stdout: $stdout, stderr: $stderr, allow_failure: false)
    super()
    self.cmd = cmd
    self.output = +""
    self.stdout = stdout || null_file
    self.stderr = stderr || null_file
    self.allow_failure = allow_failure
  end

  def call
    Helmsnap::Console.info(stdout, "> #{cmd}")
    run_command
  end

  private

  attr_accessor :cmd, :output, :stdout, :stderr, :allow_failure

  def null_file
    File.open(File::NULL, "w")
  end

  def run_command
    Open3.popen3(cmd) do |_in, out, err, wait_thr|
      while (chunk = out.gets)
        Helmsnap::Console.print(stdout, chunk)
        output << chunk
      end

      exit_status = wait_thr.value
      success = exit_status.success?
      handle_error!(exit_status, err.read) unless success

      Helmsnap::Console.print(stdout, "\n")
      Result.new(success, output)
    end
  rescue SystemCallError => error
    handle_error!(error.errno, error.message)
    Result.new(false, error.message)
  end

  def handle_error!(exit_status, err_output)
    Helmsnap::Console.error(stderr, err_output)

    if allow_failure
      output << err_output
    else
      Helmsnap::Console.error(stderr, "Command failed with status #{exit_status.to_i}")
      exit 1
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
helmsnap-1.2.2 lib/helmsnap/command.rb
helmsnap-1.2.1 lib/helmsnap/command.rb
helmsnap-1.2.0 lib/helmsnap/command.rb
helmsnap-1.1.0 lib/helmsnap/command.rb
helmsnap-1.0.2 lib/helmsnap/command.rb
helmsnap-1.0.1 lib/helmsnap/command.rb
helmsnap-1.0.0 lib/helmsnap/command.rb
helmsnap-0.9.0 lib/helmsnap/command.rb
helmsnap-0.8.1 lib/helmsnap/command.rb
helmsnap-0.8.0 lib/helmsnap/command.rb
helmsnap-0.7.5 lib/helmsnap/command.rb
helmsnap-0.7.4 lib/helmsnap/command.rb