dry-cli 1.4.1 → 2.0.0.rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "delegate"
4
+
5
+ module Dry
6
+ class CLI
7
+ # A stream for commands to write their output, which renders the styled text it is given.
8
+ #
9
+ # A stream is the only thing that knows both what is being written and what it can show, so it
10
+ # is the thing that turns styles into escape sequences. Two streams from the one program can
11
+ # answer differently, which is how a stream that has been redirected gets plain text while the
12
+ # terminal beside it keeps its color.
13
+ #
14
+ # Everything else is passed to the stream underneath, so this behaves as the stream you gave us
15
+ # in every other way. To write to it without any of this, see {#raw}.
16
+ #
17
+ # @api public
18
+ # @since x.y.z
19
+ class Stream < SimpleDelegator
20
+ # Returns a stream that renders what is written to it.
21
+ #
22
+ # A stream we have already wrapped is given back as it is.
23
+ #
24
+ # @param stream [IO] the stream to write to
25
+ #
26
+ # @return [Dry::CLI::Stream]
27
+ #
28
+ # @api private
29
+ def self.for(stream)
30
+ stream.is_a?(self) ? stream : new(stream)
31
+ end
32
+
33
+ # @api private
34
+ def puts(*args)
35
+ # Nearly every write is one string, and going through the general case would build an array
36
+ # to map over and another to spread back out again
37
+ return __getobj__.puts(render_value(args[0])) if args.size == 1
38
+
39
+ __getobj__.puts(*render(args))
40
+ end
41
+
42
+ # @api private
43
+ def print(*args)
44
+ return __getobj__.print(render_value(args[0])) if args.size == 1
45
+
46
+ __getobj__.print(*render(args))
47
+ end
48
+
49
+ # @api private
50
+ def write(*args)
51
+ return __getobj__.write(render_value(args[0])) if args.size == 1
52
+
53
+ __getobj__.write(*render(args))
54
+ end
55
+
56
+ # @api private
57
+ def printf(format, *args)
58
+ __getobj__.printf(render_value(format), *render(args))
59
+ end
60
+
61
+ # @api private
62
+ def <<(text)
63
+ __getobj__ << render_value(text)
64
+ self
65
+ end
66
+
67
+ # The underlying stream, to write to directly.
68
+ #
69
+ # Everything written through this stream is rendered for it. If you need to control rendering
70
+ # your self (such as displaying a progress bar), write to this raw stream.
71
+ #
72
+ # @example
73
+ # stdout.raw.print "\e[2K\r"
74
+ #
75
+ # @return [IO] the stream this one was made for
76
+ #
77
+ # @api public
78
+ # @since x.y.z
79
+ def raw
80
+ __getobj__
81
+ end
82
+
83
+ # Returns true if the stream underneath is a terminal.
84
+ #
85
+ # This result is memoized so we can avoid a syscall (the actual `tty?` check) every time we
86
+ # check {#color_level}.
87
+ #
88
+ # @return [Boolean]
89
+ #
90
+ # @api private
91
+ def tty?
92
+ # `false` is a legitimate value, so `||=` memoization would check again every time.
93
+ return @tty unless @tty.nil?
94
+
95
+ @tty = __getobj__.respond_to?(:tty?) && __getobj__.tty?
96
+ end
97
+
98
+ # How much color this stream can show, or `nil` when it should show none.
99
+ #
100
+ # @api private
101
+ def color_level
102
+ Style.color_level_for(self)
103
+ end
104
+
105
+ private
106
+
107
+ def render(args)
108
+ args.map { |arg| render_value(arg) }
109
+ end
110
+
111
+ # Styled text is rendered for this stream. A string has already been rendered by someone else,
112
+ # so the most we can do is take styling out again when this stream can't show it — which
113
+ # leaves a forced `--color=always` alone, because that gives us a color level to render at.
114
+ def render_value(value)
115
+ case value
116
+ when Style::Text then value.render(color_level)
117
+ when Array then value.map { |element| render_value(element) }
118
+ when String
119
+ # Most of what a program writes has no styling in it, so look before rewriting it:
120
+ # searching for one character beats a scan for escape sequences that aren't there.
121
+ color_level.nil? && value.include?(Style::ESCAPE) ? Style.unstyle(value) : value
122
+ else value
123
+ end
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ class Style
6
+ # A non-color style, like bold or underline.
7
+ #
8
+ # These look the same on every terminal, so unlike {Dry::CLI::Style::Color}, they ignore the
9
+ # color level.
10
+ #
11
+ # @api private
12
+ class Attribute
13
+ attr_reader :name
14
+
15
+ attr_reader :code
16
+
17
+ def initialize(name, code)
18
+ @name = name
19
+ @code = code
20
+ freeze
21
+ end
22
+
23
+ # Returns the ANSI codes for this attribute.
24
+ #
25
+ # @param _color_level [Symbol] ignored; attributes don't degrade
26
+ #
27
+ # @return [Array<Integer>]
28
+ def codes(_color_level)
29
+ [code]
30
+ end
31
+
32
+ def ==(other)
33
+ other.is_a?(self.class) && other.code == code
34
+ end
35
+ alias_method :eql?, :==
36
+
37
+ def hash
38
+ [self.class, code].hash
39
+ end
40
+
41
+ def to_s
42
+ name.to_s
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "color_level"
4
+ require_relative "palette"
5
+
6
+ module Dry
7
+ class CLI
8
+ class Style
9
+ # A color, and what it degrades to on a terminal that cannot show it.
10
+ #
11
+ # @api private
12
+ class Color
13
+ EMPTY = [].freeze
14
+
15
+ # The layer a color applies to, and the ANSI codes each layer starts from.
16
+ LAYERS = {
17
+ foreground: {base: 30, bright: 90, extended: 38},
18
+ background: {base: 40, bright: 100, extended: 48}
19
+ }.freeze
20
+
21
+ attr_reader :layer
22
+
23
+ def initialize(layer)
24
+ @layer = layer
25
+ end
26
+
27
+ # Returns the ANSI codes for this color at the given color level.
28
+ #
29
+ # @param color_level [Symbol] a {Dry::CLI::Style::ColorLevel}
30
+ #
31
+ # @return [Array<Integer>]
32
+ def codes(_color_level)
33
+ raise NoMethodError
34
+ end
35
+
36
+ def ==(other)
37
+ other.is_a?(self.class) && other.layer == layer && other.value == value
38
+ end
39
+ alias_method :eql?, :==
40
+
41
+ def hash
42
+ [self.class, layer, value].hash
43
+ end
44
+
45
+ def prefix
46
+ layer == :background ? "on_" : ""
47
+ end
48
+
49
+ protected
50
+
51
+ # The color's defining value, for comparison.
52
+ def value
53
+ raise NoMethodError
54
+ end
55
+
56
+ private
57
+
58
+ # Returns the codes for one of the 16 ANSI colors on this layer.
59
+ #
60
+ # @param index [Integer] a color code, 0-15
61
+ def ansi_codes(index)
62
+ offsets = LAYERS.fetch(layer)
63
+
64
+ if index < 8
65
+ [offsets[:base] + index]
66
+ else
67
+ [offsets[:bright] + (index - 8)]
68
+ end
69
+ end
70
+
71
+ def extended_code
72
+ LAYERS.fetch(layer)[:extended]
73
+ end
74
+
75
+ # One of the 16 ANSI colors.
76
+ #
77
+ # Every terminal that shows color at all supports these, so they never need to degrade. The
78
+ # one exception is {ColorLevel::ANSI8}, which has no bright colors: there each bright color
79
+ # drops to the base color it brightens.
80
+ class ANSI < Color
81
+ attr_reader :index, :name
82
+
83
+ def initialize(layer, index, name)
84
+ super(layer)
85
+ @index = index
86
+ @name = name
87
+ freeze
88
+ end
89
+
90
+ def codes(color_level)
91
+ case color_level
92
+ when ColorLevel::NONE then EMPTY
93
+ when ColorLevel::ANSI8 then ansi_codes(index % 8)
94
+ else ansi_codes(index)
95
+ end
96
+ end
97
+
98
+ def to_s
99
+ "#{prefix}#{name}"
100
+ end
101
+
102
+ protected
103
+
104
+ def value
105
+ index
106
+ end
107
+ end
108
+
109
+ # One of the 256 palette colors.
110
+ #
111
+ # Terminals that show 24-bit color read the 256 color escapes too, so this only degrades
112
+ # downward. To do that we look up the color's red, green and blue values, then find the
113
+ # closest match among the 16 or 8 colors left.
114
+ class Xterm < Color
115
+ attr_reader :index
116
+
117
+ def initialize(layer, index)
118
+ super(layer)
119
+ @index = index
120
+ freeze
121
+ end
122
+
123
+ def codes(color_level)
124
+ case color_level
125
+ when ColorLevel::NONE then EMPTY
126
+ when ColorLevel::TRUECOLOR, ColorLevel::ANSI256 then [extended_code, 5, index]
127
+ else ansi_codes(nearest(color_level))
128
+ end
129
+ end
130
+
131
+ def to_s
132
+ "#{prefix}ansi256(#{index})"
133
+ end
134
+
135
+ protected
136
+
137
+ def value
138
+ index
139
+ end
140
+
141
+ private
142
+
143
+ def nearest(color_level)
144
+ red, green, blue = Palette.rgb(index)
145
+
146
+ if color_level == ColorLevel::ANSI8
147
+ Palette.nearest_base_ansi(red, green, blue)
148
+ else
149
+ Palette.nearest_ansi(red, green, blue)
150
+ end
151
+ end
152
+ end
153
+
154
+ # A 24-bit color.
155
+ #
156
+ # This is the form you write most styles in, and the one that degrades furthest. Below
157
+ # 24-bit we swap it for the closest color the terminal can show, taken from whatever
158
+ # palette that color level leaves us.
159
+ #
160
+ # @api private
161
+ class RGB < Color
162
+ attr_reader :red, :green, :blue
163
+
164
+ def initialize(layer, red, green, blue)
165
+ super(layer)
166
+ @red = red
167
+ @green = green
168
+ @blue = blue
169
+ freeze
170
+ end
171
+
172
+ def codes(color_level)
173
+ case color_level
174
+ when ColorLevel::NONE then EMPTY
175
+ when ColorLevel::TRUECOLOR then [extended_code, 2, red, green, blue]
176
+ when ColorLevel::ANSI256
177
+ [extended_code, 5, Palette.nearest_xterm(red, green, blue)]
178
+ when ColorLevel::ANSI16 then ansi_codes(Palette.nearest_ansi(red, green, blue))
179
+ else ansi_codes(Palette.nearest_base_ansi(red, green, blue))
180
+ end
181
+ end
182
+
183
+ def to_s
184
+ "#{prefix}rgb(#{red}, #{green}, #{blue})"
185
+ end
186
+
187
+ protected
188
+
189
+ def value
190
+ [red, green, blue]
191
+ end
192
+ end
193
+ end
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ class Style
6
+ # How much color is supported by a terminal.
7
+ #
8
+ # There is no way to ask a terminal what it can do, so we go by what it sets in the
9
+ # environment: `COLORTERM` and the `TERM` name.
10
+ #
11
+ # When we cannot infer a terminal's color support, we degrade to basic {ANSI16}.
12
+ #
13
+ # Override the color level by setting `FORCE_COLOR` or {Dry::CLI::Style.color_level=}.
14
+ #
15
+ # @api private
16
+ module ColorLevel
17
+ # No color at all.
18
+ NONE = :none
19
+
20
+ # The 8 base ANSI colors.
21
+ ANSI8 = :ansi8
22
+
23
+ # The 8 base ANSI colors plus the bright ones.
24
+ ANSI16 = :ansi16
25
+
26
+ # The 256 color palette.
27
+ ANSI256 = :ansi256
28
+
29
+ # 24-bit color.
30
+ TRUECOLOR = :truecolor
31
+
32
+ # Every level, from least color to most.
33
+ ALL = [NONE, ANSI8, ANSI16, ANSI256, TRUECOLOR].freeze
34
+
35
+ # The levels `FORCE_COLOR` can name, by the value it holds.
36
+ #
37
+ # Follows what other tools do with `FORCE_COLOR`: any value means "yes, color", and a digit
38
+ # says how much.
39
+ FORCED = {
40
+ "0" => NONE,
41
+ "false" => NONE,
42
+ "1" => ANSI16,
43
+ "2" => ANSI256,
44
+ "3" => TRUECOLOR
45
+ }.freeze
46
+
47
+ # The `COLORTERM` values announcing 24-bit color.
48
+ TRUECOLOR_COLORTERMS = %w[truecolor 24bit].freeze
49
+
50
+ # The `TERM` fragments terminfo uses for a direct color terminal.
51
+ TRUECOLOR_TERMS = %w[direct truecolor].freeze
52
+
53
+ # The `TERM` suffixes terminfo uses for a 256 color terminal.
54
+ ANSI256_TERMS = %w[-256color -256].freeze
55
+
56
+ # The `TERM` values that rule out color.
57
+ #
58
+ # Names rather than terminals: `dumb` means a terminal that takes no escape sequences,
59
+ # `unknown` one that terminfo has no entry for.
60
+ COLORLESS_TERMS = %w[dumb unknown].freeze
61
+
62
+ # Set by Windows Terminal, which sets no `TERM`.
63
+ WINDOWS_TRUECOLOR = "WT_SESSION"
64
+
65
+ class << self
66
+ # Returns the color level of the terminal.
67
+ #
68
+ # @return [Symbol] one of {ALL}
69
+ def detect(env = ENV)
70
+ level = forced(env)
71
+ return level if level
72
+
73
+ term = env["TERM"].to_s.downcase
74
+ return NONE if COLORLESS_TERMS.include?(term)
75
+
76
+ return TRUECOLOR if truecolor?(env, term)
77
+ return ANSI256 if term.end_with?(*ANSI256_TERMS)
78
+
79
+ # If `TERM` is set to anything, assume the 16 colors every terminal has had since
80
+ # the eighties. An empty `TERM` leaves us nothing to go on.
81
+ return ANSI16 unless term.empty?
82
+
83
+ NONE
84
+ end
85
+
86
+ # Returns whether the level is valid.
87
+ def valid?(level)
88
+ ALL.include?(level)
89
+ end
90
+
91
+ private
92
+
93
+ # Returns the level `FORCE_COLOR` names, if it names one.
94
+ #
95
+ # A value we do not recognize still means "yes, color". We just have to work out how much
96
+ # on our own, so we fall through to detection.
97
+ def forced(env)
98
+ value = env["FORCE_COLOR"]
99
+ return nil if value.nil?
100
+
101
+ FORCED[value.downcase]
102
+ end
103
+
104
+ def truecolor?(env, term)
105
+ return true if TRUECOLOR_COLORTERMS.include?(env["COLORTERM"].to_s.downcase)
106
+ return true if TRUECOLOR_TERMS.any? { |fragment| term.include?(fragment) }
107
+
108
+ env.key?(WINDOWS_TRUECOLOR)
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ class Style
6
+ # Implements `%` formatting logic on behalf of Style::Text objects,
7
+ # while respecting part boundaries.
8
+ #
9
+ # @api private
10
+ module Formatter
11
+ # Formatting re-applies the full argument list while walking each part, so
12
+ # Ruby warns about this file whenever a part consumes fewer arguments than
13
+ # are supplied. Filter out that one warning rather than mutating $VERBOSE,
14
+ # which is global and cannot be made thread-safe. This intentionally
15
+ # bypasses downstream Warning handlers for this message.
16
+ ::Warning.singleton_class.prepend(Module.new do
17
+ def warn(message, category: nil, **)
18
+ if message.include?("dry/cli/style/formatter.rb") &&
19
+ message.include?("warning: too many arguments for format string")
20
+
21
+ return
22
+ end
23
+
24
+ super
25
+ end
26
+ end)
27
+
28
+ class << self
29
+ # Apply formatting to a Style::Text object.
30
+ #
31
+ # Arguments are normalized the way String#% sees them: an object that
32
+ # converts to an array is applied as positional arguments, an object
33
+ # that converts to a hash is applied as named arguments, and anything
34
+ # else is applied as a single value.
35
+ #
36
+ # @param text [Dry::CLI::Style::Text] text that may have formatting directives
37
+ # @param args [Object] formatting parameters
38
+ #
39
+ # @return [Dry::CLI::Style::Text]
40
+ def call(text, args)
41
+ args = Array.try_convert(args) || Hash.try_convert(args) || args
42
+ traverse(text.parts, args).then { Text.new(_1) }
43
+ end
44
+
45
+ private
46
+
47
+ # Partial application of format arguments is very difficult
48
+ # in the case of sequential, unnamed arguments. The only way
49
+ # to successfully apply formatting to parts is to treat them
50
+ # like slices of a larger string, and apply the formatting
51
+ # incrementally.
52
+ #
53
+ # @param parts [Array<Array(Dry::CLI::Style,String)>]
54
+ # @param args [Object]
55
+ # @param state [Dry::CLI::Style::Formatter::State]
56
+ #
57
+ # @return [Array<Array(Dry::CLI::Style,String)>]
58
+ def traverse(parts, args, state: State.new)
59
+ parts.map do |style, part|
60
+ if part.is_a?(Text)
61
+ [style, traverse(part.parts, args, state:).then { Text.new(_1) }]
62
+ else
63
+ [style, state.apply(part, args)]
64
+ end
65
+ end
66
+ end
67
+ end
68
+
69
+ # This state object appends the unformatted parts into itself
70
+ # and uses @cursor to know where the next part begins. This
71
+ # results in an applied format that retains the part boundaries,
72
+ # with the one tradeoff that the format arguments are consumed
73
+ # multiple times.
74
+ #
75
+ # @api private
76
+ class State < String
77
+ NAMED_REFERENCES = /
78
+ (?<!%) # only match at the start of a percent run
79
+ % # directive sigil
80
+ (?:%%)* # step over escaped percent pairs
81
+ [{<] # opens %{name} or %<name>s
82
+ /x
83
+
84
+ def initialize
85
+ super
86
+ @cursor = 0
87
+ end
88
+
89
+ # Incremental string format, with an internal cursor.
90
+ #
91
+ # @param text [#to_s] Text part that may contain formatting directives
92
+ # @param args [Object] formatting arguments
93
+ #
94
+ # @return [String] the formatted part
95
+ def apply(text, args)
96
+ self << text.to_s
97
+
98
+ formatted = self % jruby_normalize(args)
99
+ part = formatted[@cursor..]
100
+ @cursor = formatted.length
101
+
102
+ part
103
+ end
104
+
105
+ private
106
+
107
+ # This exists to normalize a tricky divergence in behavior between MRI and JRuby. Beware!
108
+ #
109
+ # If: 1. the formatting object is a Hash, and 2. there are no named references, we see the
110
+ # following:
111
+ #
112
+ # @example MRI
113
+ # "%s %s" % {a: 1}
114
+ # # => ArgumentError: too few arguments
115
+ #
116
+ # @example JRuby
117
+ # "%s %s" % {a: 1}
118
+ # # => "{a: 1} {a: 1}"
119
+ #
120
+ # Wrapping the Hash in an Array ensures that JRuby splats the argument correctly.
121
+ def jruby_normalize(obj)
122
+ return obj unless RUBY_ENGINE == "jruby"
123
+ return obj unless obj.is_a?(Hash)
124
+
125
+ match?(NAMED_REFERENCES) ? obj : [obj]
126
+ end
127
+ end
128
+ private_constant :State
129
+ end
130
+ end
131
+ end
132
+ end