Sha256: 65d4ca96da90bc766527d2c015ef7f3103780e49197dfc52ca5b63b57802fe3e

Contents?: true

Size: 1.87 KB

Versions: 12

Compression:

Stored size: 1.87 KB

Contents

module Bixby
class CommandResponse

  include Jsonify

  attr_accessor :status, :stdout, :stderr

  SUCCESS         = 0
  UNKNOWN_FAILURE = 255

  # Create a new CommandResponse from the given JsonResponse
  #
  # @param [JsonResponse] res
  #
  # @return [CommandResponse]
  def self.from_json_response(res)
    cr = CommandResponse.new(res.data)
    if res.fail? then
      if !(res.message.nil? || res.message.empty?) then
        cr.status ||= UNKNOWN_FAILURE
        cr.stderr ||= res.message
      else
        cr.status ||= UNKNOWN_FAILURE
      end
    end
    return cr
  end

  # Create a JsonResponse from this CommandResponse
  #
  # @return [JsonResponse]
  def to_json_response
    return JsonResponse.new((success?() ? "success" : "fail"), nil, self.to_hash)
  end

  def initialize(params = nil)
    if params.kind_of? Hash then
      params.each{ |k,v| self.send("#{k}=", v) if self.respond_to? "#{k}=" }

    elsif params.class.to_s == "Mixlib::ShellOut" then
      @status = params.exitstatus
      @stdout = params.stdout
      @stderr = params.stderr
    end
  end

  def success?
    @status && @status.to_i == SUCCESS
  end

  def fail?
    not success?
  end
  alias_method :error?, :fail?

  def raise!
    if fail? then
      msg = stdout || ""
      msg += "\n" if !(stdout.nil? or stdout.empty?)
      msg += stderr || ""
      raise CommandException.new(msg, msg)
    end
  end

  def decode # :nocov:
    MultiJson.load(@stdout)
  end # :nocov:

  def decode_stderr # :nocov:
    MultiJson.load(@stderr)
  end # :nocov:

  # Convert object to String, useful for debugging
  #
  # @return [String]
  def to_s # :nocov:
    s = []
    s << "CommandResponse:#{self.object_id}"
    s << "  status:   #{self.status}"
    s << "  stdout:   " + Debug.pretty_str(stdout)
    s << "  stderr:   " + Debug.pretty_str(stderr)
    s.join("\n")
  end # :nocov:

end # CommandResponse
end # Bixby

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
bixby-common-0.7.1 lib/bixby-common/command_response.rb
bixby-common-0.7.0 lib/bixby-common/command_response.rb
bixby-common-0.6.6 lib/bixby-common/command_response.rb
bixby-common-0.6.5 lib/bixby-common/command_response.rb
bixby-common-0.6.4 lib/bixby-common/command_response.rb
bixby-common-0.6.3 lib/bixby-common/command_response.rb
bixby-common-0.6.2 lib/bixby-common/command_response.rb
bixby-common-0.6.1 lib/bixby-common/command_response.rb
bixby-common-0.6.0 lib/bixby-common/command_response.rb
bixby-common-0.5.0 lib/bixby-common/command_response.rb
bixby-common-0.4.13 lib/bixby-common/command_response.rb
bixby-common-0.4.12 lib/bixby-common/command_response.rb