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,162 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ class Style
6
+ # The colors a terminal can show, and how to find the closest one.
7
+ #
8
+ # A style holds 24-bit colors. When we apply it, we swap each color for the nearest one the
9
+ # terminal can show. This module holds the palettes we swap in, and the search that picks from
10
+ # them.
11
+ #
12
+ # @api private
13
+ module Palette
14
+ # The 16 ANSI colors, with the values xterm gives them.
15
+ #
16
+ # Codes 0-7 are the base colors, 8-15 the bright ones. Users can change these in their
17
+ # terminal settings, so we use the values to find the closest match, not to say what the
18
+ # screen will show.
19
+ ANSI = [
20
+ [0, 0, 0], # black
21
+ [128, 0, 0], # red
22
+ [0, 128, 0], # green
23
+ [128, 128, 0], # yellow
24
+ [0, 0, 128], # blue
25
+ [128, 0, 128], # magenta
26
+ [0, 128, 128], # cyan
27
+ [192, 192, 192], # white
28
+ [128, 128, 128], # bright_black
29
+ [255, 0, 0], # bright_red
30
+ [0, 255, 0], # bright_green
31
+ [255, 255, 0], # bright_yellow
32
+ [0, 0, 255], # bright_blue
33
+ [255, 0, 255], # bright_magenta
34
+ [0, 255, 255], # bright_cyan
35
+ [255, 255, 255] # bright_white
36
+ ].freeze
37
+
38
+ # The six levels each of red, green and blue takes in the 6x6x6 color cube.
39
+ CUBE_STEPS = [0, 95, 135, 175, 215, 255].freeze
40
+
41
+ # The 256 color palette, as red, green and blue values by color code.
42
+ #
43
+ # Codes 0-15 are {ANSI}, 16-231 a 6x6x6 color cube, and 232-255 24 shades of gray.
44
+ XTERM = [
45
+ *ANSI,
46
+ *CUBE_STEPS.product(CUBE_STEPS, CUBE_STEPS),
47
+ *(0...24).map { |step| Array.new(3, 8 + (step * 10)) }
48
+ ].map(&:freeze).freeze
49
+
50
+ # The first color code we search when we degrade a 24-bit color.
51
+ #
52
+ # Users can change codes 0-15 in their terminal settings. If someone has set their "red" to
53
+ # a pastel, we should not answer `rgb(255, 0, 0)` with that pastel, so we search from 16 up,
54
+ # where the codes have fixed values.
55
+ FIXED_RANGE = (16..255)
56
+
57
+ # The ANSI colors that have a hue, and the ones that are only gray.
58
+ CHROMATIC = [*1..6, *9..14].freeze
59
+ GRAYS = [0, 7, 8, 15].freeze
60
+ BASE_CHROMATIC = [*1..6].freeze
61
+ BASE_GREYS = [0, 7].freeze
62
+
63
+ # How much color a shade needs before we match its hue instead of its brightness.
64
+ #
65
+ # With 16 colors to pick from, often none is close to the one you asked for, and the closest
66
+ # by distance is a gray. A mid violet is nearer to gray than to any purple in the palette.
67
+ # Gray is the right answer by the sums and the wrong one on screen: a style says "this is an
68
+ # error" or "this is a warning", and it says it with hue. So we first ask whether the color
69
+ # has a hue worth keeping, then match it only against colors that keep it.
70
+ #
71
+ # We measure that as chroma, the gap between the highest and lowest of red, green and blue.
72
+ # Saturation would be wrong here. It runs high for any dark color, so it would turn near
73
+ # blacks into whatever hue their few stray levels tilt toward.
74
+ CHROMA_THRESHOLD = 48
75
+
76
+ class << self
77
+ # Returns the RGB triplet for a 256 color code.
78
+ #
79
+ # @param code [Integer] a color code, 0-255
80
+ #
81
+ # @return [Array<Integer>] the red, green and blue components
82
+ def rgb(code)
83
+ XTERM.fetch(code)
84
+ end
85
+
86
+ # Returns the closest 256 color code to the given color.
87
+ #
88
+ # @param red [Integer]
89
+ # @param green [Integer]
90
+ # @param blue [Integer]
91
+ #
92
+ # @return [Integer] a color code, 16-255
93
+ def nearest_xterm(red, green, blue)
94
+ nearest(FIXED_RANGE, red, green, blue)
95
+ end
96
+
97
+ # Returns the closest of the 16 ANSI colors to the given color.
98
+ #
99
+ # @param red [Integer]
100
+ # @param green [Integer]
101
+ # @param blue [Integer]
102
+ #
103
+ # @return [Integer] a color code, 0-15
104
+ def nearest_ansi(red, green, blue)
105
+ candidates = chromatic?(red, green, blue) ? CHROMATIC : GRAYS
106
+
107
+ nearest(candidates, red, green, blue)
108
+ end
109
+
110
+ # Returns the closest of the 8 base ANSI colors to the given color.
111
+ #
112
+ # @param red [Integer]
113
+ # @param green [Integer]
114
+ # @param blue [Integer]
115
+ #
116
+ # @return [Integer] a color code, 0-7
117
+ def nearest_base_ansi(red, green, blue)
118
+ candidates = chromatic?(red, green, blue) ? BASE_CHROMATIC : BASE_GREYS
119
+
120
+ nearest(candidates, red, green, blue)
121
+ end
122
+
123
+ private
124
+
125
+ # Returns whether the color has a hue worth keeping.
126
+ def chromatic?(red, green, blue)
127
+ components = [red, green, blue]
128
+
129
+ (components.max - components.min) >= CHROMA_THRESHOLD
130
+ end
131
+
132
+ # Returns the code within the range whose color is closest to the given one.
133
+ def nearest(range, red, green, blue)
134
+ range.min_by { |code| distance(XTERM[code], red, green, blue) }
135
+ end
136
+
137
+ # Returns how far apart two colors look, squared.
138
+ #
139
+ # Plain distance in red, green and blue treats all three as equal. The eye does not. It
140
+ # sees a shift in green more than one in blue, and it sees red differently in dark colors
141
+ # than in light ones. This is the "redmean" formula, which weights the three to match. It
142
+ # is close enough to pick good matches, and it costs almost nothing.
143
+ #
144
+ # We compare squared distances, since sorting by a distance and by its square gives the
145
+ # same order.
146
+ #
147
+ # @see https://www.compuphase.com/cmetric.htm
148
+ def distance(reference, red, green, blue)
149
+ mean = (reference[0] + red) / 2
150
+ delta_red = reference[0] - red
151
+ delta_green = reference[1] - green
152
+ delta_blue = reference[2] - blue
153
+
154
+ (((512 + mean) * delta_red * delta_red) >> 8) +
155
+ (4 * delta_green * delta_green) +
156
+ (((767 - mean) * delta_blue * delta_blue) >> 8)
157
+ end
158
+ end
159
+ end
160
+ end
161
+ end
162
+ end
@@ -0,0 +1,232 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ class CLI
5
+ class Style
6
+ # Text with styles attached, rendered when it is written to a {Dry::CLI::Stream}.
7
+ #
8
+ # Applying a style gives you one of these rather than a `String`. It holds the text and the
9
+ # styles, and turns them into escape sequences at the last moment: when it reaches a stream,
10
+ # which knows what it can show.
11
+ #
12
+ # This structure is what allows for writing colored text to a terminal but plain text to a
13
+ # file it is redirected to. It also means the text knows how long it is without its escape
14
+ # sequences, so padding lines up.
15
+ #
16
+ # @example
17
+ # ERROR = Dry::CLI::Style.bold.red
18
+ # ERROR["Boom"].length # => 4
19
+ #
20
+ # Anywhere a `String` is wanted, this renders itself for Ruby's own `$stdout`, so
21
+ # interpolation, `format`, and `puts` all still work.
22
+ #
23
+ # @api public
24
+ # @since x.y.z
25
+ class Text
26
+ # The runs of text this is made of, each with the style to render it in.
27
+ #
28
+ # Each part is a `[style, text]` pair, and they render in order and join together. A `nil`
29
+ # style means that run is plain: joining styled text to a plain `String` keeps both, rather
30
+ # than rendering early to make one `String` of them.
31
+ #
32
+ # @example
33
+ # (ERROR["failed"] + ": " + reason).parts
34
+ # # => [[#<Dry::CLI::Style bold.red>, "failed"],
35
+ # # [nil, ": "],
36
+ # # [nil, "no such file"]]
37
+ #
38
+ # A part's text can be another {Dry::CLI::Style::Text}, which is how a style wraps text that
39
+ # is already styled. It renders from the inside out, so the outer style picks up again where
40
+ # the inner one left off.
41
+ #
42
+ # @example
43
+ # Dry::CLI::Style.red[Dry::CLI::Style.bold["config.yml"]].parts
44
+ # # => [[#<Dry::CLI::Style red>, #<Dry::CLI::Style::Text "config.yml">]]
45
+ #
46
+ # @return [Array<Array(Dry::CLI::Style,String)>]
47
+ #
48
+ # @api private
49
+ attr_reader :parts
50
+
51
+ # @param parts [Array<Array(Dry::CLI::Style,String)>] the runs of text and their styles, in
52
+ # the order they render
53
+ #
54
+ # @api private
55
+ def initialize(parts)
56
+ @parts = parts.freeze
57
+ freeze
58
+ end
59
+
60
+ # Returns the text rendered with styles for the given color level.
61
+ #
62
+ # @param color_level [Symbol, nil] a color level, or `nil` for no styling at all
63
+ #
64
+ # @return [String]
65
+ #
66
+ # @api private
67
+ def render(color_level)
68
+ return plain if color_level.nil?
69
+ return render_part(*parts.first, color_level) if parts.one?
70
+
71
+ parts.map { |style, text| render_part(style, text, color_level) }.join
72
+ end
73
+
74
+ # Returns the text on its own, with no styles applied.
75
+ #
76
+ # Use this as the fast path to render text when styling has been disabled.
77
+ #
78
+ # @return [String]
79
+ #
80
+ # @api private
81
+ def plain
82
+ return plain_text(parts.first.last) if parts.one?
83
+
84
+ parts.map { |_style, text| plain_text(text) }.join
85
+ end
86
+
87
+ # Renders the text for Ruby's own `$stdout`.
88
+ #
89
+ # @return [String]
90
+ #
91
+ # @api public
92
+ # @since x.y.z
93
+ def to_s
94
+ render(Style.default_stdout_color_level)
95
+ end
96
+ alias_method :to_str, :to_s
97
+
98
+ # Joins this text to other text, keeping both sides unrendered.
99
+ #
100
+ # Only works this way around. With a `String` on the left, Ruby asks us for a `String` in
101
+ # return, so `"read " + styled` renders there and then, for Ruby's own `$stdout` rather than
102
+ # the stream it ends up on. Put the styled text first, or style the whole of it, and it
103
+ # stays unrendered until it is written.
104
+ #
105
+ # @example
106
+ # ERROR["failed"] + ": " + reason # stays unrendered
107
+ # "failed: " + ERROR[reason] # renders ERROR[reason] now
108
+ #
109
+ # @param other [Dry::CLI::Style::Text,String]
110
+ #
111
+ # @return [Dry::CLI::Style::Text]
112
+ #
113
+ # @api public
114
+ # @since x.y.z
115
+ def +(other)
116
+ other.is_a?(Text) ? Text.new(parts + other.parts) : Text.new(parts + [[nil, other]])
117
+ end
118
+
119
+ # Apply arguments as a formatting string.
120
+ #
121
+ # @see String#%
122
+ #
123
+ # @example
124
+ # format = dim["Waiting for "] + bold["%d"] + dim[" seconds"]
125
+ # format % 5 # => "\e[2mWaiting for \e[0m\e[1m5\e[0m\e[2m seconds\e[0m"
126
+ #
127
+ # @param args [Object]
128
+ #
129
+ # @return [Dry::CLI::Style::Text]
130
+ #
131
+ # @api public
132
+ # @since x.y.z
133
+ def %(args) = Formatter.call(self, args)
134
+
135
+ # The length of the text without any styling.
136
+ #
137
+ # @return [Integer]
138
+ #
139
+ # @api public
140
+ # @since x.y.z
141
+ def length
142
+ parts.sum { |_, text| text.is_a?(Text) ? text.length : text.to_s.length }
143
+ end
144
+ alias_method :size, :length
145
+
146
+ # @api public
147
+ # @since x.y.z
148
+ def empty?
149
+ length.zero?
150
+ end
151
+
152
+ # Pads the text to the given width, counting only what will be seen.
153
+ #
154
+ # @param width [Integer]
155
+ # @param padding [String]
156
+ #
157
+ # @return [Dry::CLI::Style::Text]
158
+ #
159
+ # @api public
160
+ # @since x.y.z
161
+ def ljust(width, padding = " ")
162
+ self + pad(width, padding)
163
+ end
164
+
165
+ # @see #ljust
166
+ #
167
+ # @api public
168
+ # @since x.y.z
169
+ def rjust(width, padding = " ")
170
+ Text.new([[nil, pad(width, padding)]] + parts)
171
+ end
172
+
173
+ # Returns true if the `other` is equal to self, either another {Text} consisting of the same
174
+ # style and text parts, or a `String` with the same content.
175
+ #
176
+ # @api private
177
+ def ==(other)
178
+ case other
179
+ when Text then other.parts == parts
180
+ when String then to_s == other
181
+ else false
182
+ end
183
+ end
184
+
185
+ # Returns true only if the `other` is another {Text} with the same style and text parts.
186
+ #
187
+ # @api private
188
+ def eql?(other)
189
+ other.is_a?(Text) && other.parts == parts
190
+ end
191
+
192
+ # @api private
193
+ def hash
194
+ [self.class, parts].hash
195
+ end
196
+
197
+ # @api private
198
+ def inspect
199
+ "#<#{self.class.name}#{style_names} #{plain.inspect}>"
200
+ end
201
+
202
+ private
203
+
204
+ # Returns the unique set of styles this text renders with, for including in {#inspect}.
205
+ #
206
+ # Returns `"(bold.red, dim)"`, or `""` when it has none.
207
+ def style_names
208
+ names = parts.map(&:first).compact.map(&:to_s).reject(&:empty?).uniq
209
+ return "" if names.empty?
210
+
211
+ "(#{names.join(", ")})"
212
+ end
213
+
214
+ def plain_text(text)
215
+ text.is_a?(Text) ? text.plain : text.to_s
216
+ end
217
+
218
+ def render_part(style, text, color_level)
219
+ rendered = text.is_a?(Text) ? text.render(color_level) : text.to_s
220
+ style.nil? ? rendered : style.render(rendered, color_level)
221
+ end
222
+
223
+ def pad(width, padding)
224
+ missing = width - length
225
+ return "" if missing <= 0
226
+
227
+ (padding * missing)[0, missing]
228
+ end
229
+ end
230
+ end
231
+ end
232
+ end