Module: SmilyCli::Color

Defined in:
lib/smily_cli/color.rb

Overview

Minimal, dependency-free ANSI coloring. Coloring is a process-wide setting (driven by --no-color, the NO_COLOR/SMILY_NO_COLOR env vars, and whether stdout is a TTY) so formatters can call Color.bold etc. without threading a flag everywhere.

Constant Summary collapse

CODES =
{
  reset: 0, bold: 1, dim: 2, red: 31, green: 32, yellow: 33,
  blue: 34, magenta: 35, cyan: 36, gray: 90
}.freeze

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.enabledBoolean

Returns whether ANSI codes are currently emitted.

Returns:

  • (Boolean)

    whether ANSI codes are currently emitted



16
17
18
# File 'lib/smily_cli/color.rb', line 16

def enabled
  @enabled
end

Class Method Details

.default_enabled?(stream: $stdout) ⇒ Boolean

Decide the default enabled state from the environment. Honors the informal NO_COLOR standard and requires an interactive stdout.

Parameters:

  • stream (IO) (defaults to: $stdout)

    stream that output is written to (defaults to $stdout)

Returns:

  • (Boolean)


24
25
26
27
28
29
# File 'lib/smily_cli/color.rb', line 24

def self.default_enabled?(stream: $stdout)
  return false if ENV["NO_COLOR"] && !ENV["NO_COLOR"].empty?
  return false if ENV["SMILY_NO_COLOR"] && !ENV["SMILY_NO_COLOR"].empty?

  stream.respond_to?(:tty?) && stream.tty?
end

.paint(text, *styles) ⇒ String

Wrap text in the given ANSI styles when coloring is enabled.

Parameters:

  • text (String)
  • styles (Array<Symbol>)

    any of CODES' keys

Returns:

  • (String)


36
37
38
39
40
41
42
43
# File 'lib/smily_cli/color.rb', line 36

def self.paint(text, *styles)
  return text.to_s unless enabled

  codes = styles.flatten.filter_map { |s| CODES[s] }
  return text.to_s if codes.empty?

  "\e[#{codes.join(';')}m#{text}\e[0m"
end