2019-04-19 15:38:03 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-08-26 16:04:47 +02:00
|
|
|
module Tty
|
|
|
|
module_function
|
|
|
|
|
|
|
|
def strip_ansi(string)
|
|
|
|
string.gsub(/\033\[\d+(;\d+)*m/, "")
|
|
|
|
end
|
|
|
|
|
|
|
|
def width
|
2018-06-14 22:14:46 +02:00
|
|
|
@width ||= begin
|
2018-09-17 19:44:12 +02:00
|
|
|
_, width = `/bin/stty size 2>/dev/null`.split
|
|
|
|
width, = `/usr/bin/tput cols 2>/dev/null`.split if width.to_i.zero?
|
2018-06-14 22:14:46 +02:00
|
|
|
width ||= 80
|
|
|
|
width.to_i
|
|
|
|
end
|
2016-08-26 16:04:47 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def truncate(string)
|
|
|
|
(w = width).zero? ? string.to_s : string.to_s[0, w - 4]
|
|
|
|
end
|
|
|
|
|
|
|
|
COLOR_CODES = {
|
2018-11-02 17:18:07 +00:00
|
|
|
red: 31,
|
|
|
|
green: 32,
|
|
|
|
yellow: 33,
|
|
|
|
blue: 34,
|
2016-08-26 16:04:47 +02:00
|
|
|
magenta: 35,
|
2018-11-02 17:18:07 +00:00
|
|
|
cyan: 36,
|
2016-08-26 16:04:47 +02:00
|
|
|
default: 39,
|
|
|
|
}.freeze
|
|
|
|
|
|
|
|
STYLE_CODES = {
|
2018-11-02 17:18:07 +00:00
|
|
|
reset: 0,
|
|
|
|
bold: 1,
|
|
|
|
italic: 3,
|
|
|
|
underline: 4,
|
2016-08-26 16:04:47 +02:00
|
|
|
strikethrough: 9,
|
2018-11-02 17:18:07 +00:00
|
|
|
no_underline: 24,
|
2016-08-26 16:04:47 +02:00
|
|
|
}.freeze
|
|
|
|
|
|
|
|
CODES = COLOR_CODES.merge(STYLE_CODES).freeze
|
|
|
|
|
|
|
|
def append_to_escape_sequence(code)
|
|
|
|
@escape_sequence ||= []
|
|
|
|
@escape_sequence << code
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def current_escape_sequence
|
|
|
|
return "" if @escape_sequence.nil?
|
2018-09-17 02:45:00 +02:00
|
|
|
|
2016-08-26 16:04:47 +02:00
|
|
|
"\033[#{@escape_sequence.join(";")}m"
|
|
|
|
end
|
|
|
|
|
|
|
|
def reset_escape_sequence!
|
|
|
|
@escape_sequence = nil
|
|
|
|
end
|
|
|
|
|
|
|
|
CODES.each do |name, code|
|
|
|
|
define_singleton_method(name) do
|
|
|
|
append_to_escape_sequence(code)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
2019-10-04 09:17:44 +02:00
|
|
|
return "" unless color?
|
2018-09-17 02:45:00 +02:00
|
|
|
|
2016-08-26 16:04:47 +02:00
|
|
|
current_escape_sequence
|
|
|
|
ensure
|
|
|
|
reset_escape_sequence!
|
|
|
|
end
|
2019-10-04 09:17:44 +02:00
|
|
|
|
|
|
|
def color?
|
|
|
|
return false if ENV["HOMEBREW_NO_COLOR"]
|
|
|
|
return true if ENV["HOMEBREW_COLOR"]
|
|
|
|
|
|
|
|
$stdout.tty?
|
|
|
|
end
|
2016-08-26 16:04:47 +02:00
|
|
|
end
|