Sha256: 1678fa13e2d94ed69e4a5d9c0b72b88077a29ed836716765d5bb65c24429d3f2

Contents?: true

Size: 1.26 KB

Versions: 9

Compression:

Stored size: 1.26 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
    self.stderr = stderr
    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 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

9 entries across 9 versions & 1 rubygems

Version Path
helmsnap-0.7.3 lib/helmsnap/command.rb
helmsnap-0.7.2 lib/helmsnap/command.rb
helmsnap-0.7.1 lib/helmsnap/command.rb
helmsnap-0.7.0 lib/helmsnap/command.rb
helmsnap-0.6.2 lib/helmsnap/command.rb
helmsnap-0.6.1 lib/helmsnap/command.rb
helmsnap-0.6.0 lib/helmsnap/command.rb
helmsnap-0.5.1 lib/helmsnap/command.rb
helmsnap-0.5.0 lib/helmsnap/command.rb