Sha256: c79de481a1ee5cddbab9c70ad60780a64d95f48a40ee954bf73e70bf5a20b2a1

Contents?: true

Size: 1.84 KB

Versions: 42

Compression:

Stored size: 1.84 KB

Contents

module SSHKit
  # Very basic support for ANSI color, so that we don't have to rely on
  # any external dependencies. This class handles colorizing strings, and
  # automatically disabling color if the underlying output is not a tty.
  #
  class Color
    COLOR_CODES = {
      :black   => 30,
      :red     => 31,
      :green   => 32,
      :yellow  => 33,
      :blue    => 34,
      :magenta => 35,
      :cyan    => 36,
      :white   => 37,
      :light_black   => 90,
      :light_red     => 91,
      :light_green   => 92,
      :light_yellow  => 93,
      :light_blue    => 94,
      :light_magenta => 95,
      :light_cyan    => 96,
      :light_white   => 97
    }.freeze

    def initialize(output, env=ENV)
      @output, @env = output, env
    end

    # Converts the given obj to string and surrounds in the appropriate ANSI
    # color escape sequence, based on the specified color and mode. The color
    # must be a symbol (see COLOR_CODES for a complete list).
    #
    # If the underlying output does not support ANSI color (see `colorize?),
    # the string will be not be colorized. Likewise if the specified color
    # symbol is unrecognized, the string will not be colorized.
    #
    # Note that the only mode currently support is :bold. All other values
    # will be silently ignored (i.e. treated the same as mode=nil).
    #
    def colorize(obj, color, mode=nil)
      string = obj.to_s
      return string unless colorize?
      return string unless COLOR_CODES.key?(color)

      result = mode == :bold ? "\e[1;" : "\e[0;"
      result << COLOR_CODES.fetch(color).to_s
      result << ";49m#{string}\e[0m"
    end

    # Returns `true` if the underlying output is a tty, or if the SSHKIT_COLOR
    # environment variable is set.
    #
    def colorize?
      @env['SSHKIT_COLOR'] || (@output.respond_to?(:tty?) && @output.tty?)
    end
  end
end

Version data entries

42 entries across 42 versions & 2 rubygems

Version Path
sshkit-1.23.1 lib/sshkit/color.rb
sshkit-1.23.0 lib/sshkit/color.rb
sshkit-1.22.2 lib/sshkit/color.rb
sshkit-1.22.1 lib/sshkit/color.rb
sshkit-1.22.0 lib/sshkit/color.rb
sshkit-1.21.7 lib/sshkit/color.rb
honeybadger-5.4.0 vendor/bundle/ruby/3.2.0/gems/sshkit-1.21.6/lib/sshkit/color.rb
sshkit-1.21.6 lib/sshkit/color.rb
honeybadger-5.3.0 vendor/bundle/ruby/3.2.0/gems/sshkit-1.21.5/lib/sshkit/color.rb
sshkit-1.21.5 lib/sshkit/color.rb
sshkit-1.21.4 lib/sshkit/color.rb
sshkit-1.21.3 lib/sshkit/color.rb
sshkit-1.21.2 lib/sshkit/color.rb
sshkit-1.21.1 lib/sshkit/color.rb
sshkit-1.21.0 lib/sshkit/color.rb
honeybadger-4.5.3 vendor/bundle/ruby/2.6.0/gems/sshkit-1.18.2/lib/sshkit/color.rb
sshkit-1.20.0 lib/sshkit/color.rb
sshkit-1.19.1 lib/sshkit/color.rb
sshkit-1.19.0 lib/sshkit/color.rb
sshkit-1.18.2 lib/sshkit/color.rb