dry-cli 1.4.0 → 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,620 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ansi"
4
+
5
+ module Dry
6
+ class CLI
7
+ # A text style you can build up and reuse.
8
+ #
9
+ # A style is a value. Build one by chaining style names, give it a name that means something,
10
+ # then apply it to text as often as you like.
11
+ #
12
+ # @example
13
+ # ERROR = Dry::CLI::Style.bold.red
14
+ #
15
+ # ERROR.call("Boom") # => "\e[1;31mBoom\e[0m"
16
+ #
17
+ # Building a style and applying it are always separate steps. For a one-off, apply it straight
18
+ # away with `#[]`.
19
+ #
20
+ # @example
21
+ # Dry::CLI::Style.bold.red["Boom"] # => "\e[1;31mBoom\e[0m"
22
+ #
23
+ # ## Color
24
+ #
25
+ # Choose whichever color you want, and it will automatically degrade to whatever the terminal
26
+ # supports.
27
+ #
28
+ # @example
29
+ # ERROR = Dry::CLI::Style.bold.rgb(255, 0, 0)
30
+ #
31
+ # ERROR.call("Boom")
32
+ # # on a 24-bit terminal => "\e[1;38;2;255;0;0mBoom\e[0m"
33
+ # # on a 256 color one => "\e[1;38;5;196mBoom\e[0m"
34
+ # # on a 16 color one => "\e[1;91mBoom\e[0m"
35
+ # # on an 8 color one => "\e[1;31mBoom\e[0m"
36
+ # # with no color at all => "\e[1mBoom\e[0m"
37
+ #
38
+ # @api public
39
+ # @since x.y.z
40
+ class Style
41
+ require_relative "style/palette"
42
+ require_relative "style/attribute"
43
+ require_relative "style/color"
44
+ require_relative "style/color_level"
45
+ require_relative "style/text"
46
+
47
+ autoload :Formatter, "dry/cli/style/formatter"
48
+
49
+ # ANSI escape sequence resetting all styles.
50
+ #
51
+ # @api private
52
+ RESET = ANSI::SGR0
53
+
54
+ # The character every escape sequence we emit begins with.
55
+ #
56
+ # @api private
57
+ ESCAPE = "\e"
58
+
59
+ # Regexp matching the ANSI escape sequences we emit.
60
+ #
61
+ # @api private
62
+ SGR_PATTERN = /\e\[[0-9;]*m/
63
+
64
+ # Non-color style names mapped to their ANSI code.
65
+ #
66
+ # @api private
67
+ ATTRIBUTES = {
68
+ bold: 1,
69
+ dim: 2,
70
+ italic: 3,
71
+ underline: 4,
72
+ blink: 5,
73
+ reverse: 7,
74
+ invisible: 8
75
+ }.freeze
76
+
77
+ # Color names, and where they sit in the ANSI palette.
78
+ #
79
+ # Each has a `bright_` version too, eight places along.
80
+ #
81
+ # @api private
82
+ COLORS = {
83
+ black: 0,
84
+ red: 1,
85
+ green: 2,
86
+ yellow: 3,
87
+ blue: 4,
88
+ magenta: 5,
89
+ cyan: 6,
90
+ white: 7
91
+ }.freeze
92
+
93
+ # Regexp matching a hex color, with or without its leading `#`.
94
+ #
95
+ # @api private
96
+ HEX_PATTERN = /\A#?(?<digits>\h{3}|\h{6})\z/
97
+
98
+ # The values an RGB component can take.
99
+ #
100
+ # @api private
101
+ COMPONENT_RANGE = (0..255)
102
+
103
+ # @api private
104
+ Unchecked = Object.new.freeze
105
+ private_constant :Unchecked
106
+
107
+ @enabled = nil
108
+ @color_level = nil
109
+
110
+ # Memoized values
111
+ @env_enabled = Unchecked
112
+ @detected_color_level = nil
113
+ @color_levels = nil
114
+ @default_stdout_object = nil
115
+ @default_stdout_terminal = nil
116
+
117
+ class << self
118
+ # Enable or disable styling for the whole program.
119
+ #
120
+ # Set to `nil` (the default) to decide automatically: styling is on when the stream being
121
+ # written to is a terminal and `NO_COLOR` is unset. `FORCE_COLOR` overrides both.
122
+ #
123
+ # @param enabled [Boolean, nil]
124
+ #
125
+ # @example
126
+ # Dry::CLI::Style.enabled = false if args[:no_color]
127
+ #
128
+ # @api public
129
+ # @since x.y.z
130
+ def enabled=(enabled)
131
+ @enabled = enabled
132
+ forget_environment
133
+ end
134
+
135
+ # Set how much color styles should render with.
136
+ #
137
+ # Set to `nil` (the default) to decide automatically from the environment.
138
+ #
139
+ # @param color_level [Symbol, nil] `:truecolor`, `:ansi256`, `:ansi16`, `:ansi8`, `:none`
140
+ #
141
+ # @raise [ArgumentError] if the color level isn't one we know
142
+ #
143
+ # @example
144
+ # Dry::CLI::Style.color_level = :truecolor
145
+ #
146
+ # @api public
147
+ # @since x.y.z
148
+ def color_level=(color_level)
149
+ unless color_level.nil? || ColorLevel.valid?(color_level)
150
+ raise ArgumentError,
151
+ "unknown color level #{color_level.inspect}; " \
152
+ "expected one of #{ColorLevel::ALL.map(&:inspect).join(', ')}, or nil"
153
+ end
154
+
155
+ @color_level = color_level
156
+ forget_environment
157
+ end
158
+
159
+ # How much color to render for the given stream, or `nil` for no styling at all.
160
+ #
161
+ # @param stream [IO]
162
+ #
163
+ # @return [Symbol, nil] `:truecolor`, `:ansi256`, `:ansi16`, `:ansi8`, `:none`
164
+ #
165
+ # @api private
166
+ def color_level_for(stream)
167
+ color_levels[stream.tty?]
168
+ end
169
+
170
+ # How much color to render for text that hasn't reached a stream.
171
+ #
172
+ # Returns the color level supported by Ruby's own `$stdout`.
173
+ #
174
+ # @return [Symbol, nil]
175
+ #
176
+ # @api private
177
+ def default_stdout_color_level
178
+ color_levels[default_stdout_terminal?]
179
+ end
180
+
181
+ # Removes all style escape sequences from the given text.
182
+ #
183
+ # @param text [String] the text to strip
184
+ #
185
+ # @return [String] the text without styling
186
+ #
187
+ # @example
188
+ # Dry::CLI::Style.unstyle("\e[31mBoom\e[0m") # => "Boom"
189
+ #
190
+ # @api public
191
+ # @since x.y.z
192
+ def unstyle(text)
193
+ text.to_s.gsub(SGR_PATTERN, "")
194
+ end
195
+
196
+ private
197
+
198
+ # Returns whether an explicit env var has turned styling on or off.
199
+ def env_enabled
200
+ return @env_enabled unless @env_enabled.eql?(Unchecked)
201
+
202
+ @env_enabled = detect_env_enabled
203
+ end
204
+
205
+ def detect_env_enabled
206
+ return false unless ENV.fetch("NO_COLOR", "").empty?
207
+
208
+ forced = ENV["FORCE_COLOR"]
209
+ return !%w[0 false].include?(forced.downcase) unless forced.nil?
210
+
211
+ nil
212
+ end
213
+
214
+ # Returns the color level a terminal can support, based on the environment.
215
+ def detected_color_level
216
+ @detected_color_level ||= ColorLevel.detect
217
+ end
218
+
219
+ # Returns a hash with the color levels to render at, keyed true for a terminal, and false
220
+ # for anything else.
221
+ def color_levels
222
+ @color_levels ||= {
223
+ true => color_level_when(terminal: true),
224
+ false => color_level_when(terminal: false)
225
+ }.freeze
226
+ end
227
+
228
+ # Returns the color level for a terminal or non-terminal stream.
229
+ def color_level_when(terminal:)
230
+ # Check for enabled/disabled styling, in order of precedence:
231
+ #
232
+ # 1. `Style.enabled`
233
+ # 2. `NO_COLOR`/`FORCE_COLOR` from the env
234
+ # 3. Whether we're writing to a terminal
235
+ #
236
+ # Only `nil` here means "nothing to say". `false` is an explicit disable, so
237
+ # chaining these checks via `||` would skip straight past it.
238
+ enabled = [@enabled, env_enabled, terminal].compact.first
239
+
240
+ @color_level || detected_color_level if enabled
241
+ end
242
+
243
+ def terminal?(stream)
244
+ stream.respond_to?(:tty?) && stream.tty?
245
+ end
246
+
247
+ # Returns whether Ruby's own `$stdout` is a terminal.
248
+ #
249
+ # Checking this costs a system call, so we keep the answer against the stream we asked. A
250
+ # swapped `$stdout`, as capturing output in a test does, gets a fresh one.
251
+ def default_stdout_terminal?
252
+ out = $stdout
253
+ return @default_stdout_terminal if @default_stdout_object.equal?(out)
254
+
255
+ @default_stdout_object = out
256
+ @default_stdout_terminal = terminal?(out)
257
+ end
258
+
259
+ def forget_environment
260
+ @env_enabled = Unchecked
261
+ @detected_color_level = nil
262
+ @color_levels = nil
263
+ @default_stdout_object = nil
264
+ end
265
+ end
266
+
267
+ # @api private
268
+ attr_reader :steps
269
+
270
+ # Returns a new style.
271
+ #
272
+ # A style with no steps returns text unchanged. It's useful as a neutral value.
273
+ #
274
+ # @param steps [Array] the attributes and colors to apply
275
+ #
276
+ # @api private
277
+ def initialize(steps = [])
278
+ @steps = steps.freeze
279
+ # Rendering a color means searching a palette for the closest match, so we keep the sequence
280
+ # for each color level once we have worked it out. Most programs ask for one.
281
+ @sequences = {}
282
+ freeze
283
+ end
284
+
285
+ # The style builder methods.
286
+ #
287
+ # This module is both included and extended on {Style}, which makes its builder methods
288
+ # available to both begin and extend chains of styles.
289
+ #
290
+ # @api public
291
+ module Builders
292
+ # @!method bold
293
+ # @!method dim
294
+ # @!method italic
295
+ # @!method underline
296
+ # @!method blink
297
+ # @!method reverse
298
+ # @!method invisible
299
+ # @!method black
300
+ # @!method red
301
+ # @!method green
302
+ # @!method yellow
303
+ # @!method blue
304
+ # @!method magenta
305
+ # @!method cyan
306
+ # @!method white
307
+ # @!method bright_black
308
+ # @!method bright_red
309
+ # @!method bright_green
310
+ # @!method bright_yellow
311
+ # @!method bright_blue
312
+ # @!method bright_magenta
313
+ # @!method bright_cyan
314
+ # @!method bright_white
315
+ # @!method on_black
316
+ # @!method on_red
317
+ # @!method on_green
318
+ # @!method on_yellow
319
+ # @!method on_blue
320
+ # @!method on_magenta
321
+ # @!method on_cyan
322
+ # @!method on_white
323
+ # @!method on_bright_black
324
+ # @!method on_bright_red
325
+ # @!method on_bright_green
326
+ # @!method on_bright_yellow
327
+ # @!method on_bright_blue
328
+ # @!method on_bright_magenta
329
+ # @!method on_bright_cyan
330
+ # @!method on_bright_white
331
+ #
332
+ # Adds this style to the chain.
333
+ #
334
+ # Returns a new {Dry::CLI::Style}, to keep chaining or to apply with {#call} or {#[]}.
335
+ #
336
+ # @return [Dry::CLI::Style]
337
+ #
338
+ # @api public
339
+ # @since x.y.z
340
+
341
+ ATTRIBUTES.each do |name, code|
342
+ attribute = Attribute.new(name, code)
343
+
344
+ define_method(name) do
345
+ add(attribute)
346
+ end
347
+ end
348
+
349
+ COLORS.each do |name, index|
350
+ {name => index, :"bright_#{name}" => index + 8}.each do |color_name, color_index|
351
+ {foreground: color_name, background: :"on_#{color_name}"}.each do |layer, method_name|
352
+ color = Color::ANSI.new(layer, color_index, color_name)
353
+
354
+ define_method(method_name) do
355
+ add(color)
356
+ end
357
+ end
358
+ end
359
+ end
360
+
361
+ # Adds a 24-bit color to the chain.
362
+ #
363
+ # @param red [Integer] 0-255
364
+ # @param green [Integer] 0-255
365
+ # @param blue [Integer] 0-255
366
+ #
367
+ # @return [Dry::CLI::Style]
368
+ #
369
+ # @raise [Dry::CLI::InvalidColorError] if a component is out of range
370
+ #
371
+ # @example
372
+ # Dry::CLI::Style.rgb(255, 0, 0).call("Boom")
373
+ #
374
+ # @api public
375
+ # @since x.y.z
376
+ def rgb(red, green, blue)
377
+ add(Color::RGB.new(:foreground, *validate_components(red, green, blue)))
378
+ end
379
+
380
+ # Adds a 24-bit background color to the chain.
381
+ #
382
+ # @param (see #rgb)
383
+ #
384
+ # @return (see #rgb)
385
+ #
386
+ # @raise (see #rgb)
387
+ #
388
+ # @example
389
+ # Dry::CLI::Style.on_rgb(255, 0, 0).call("Boom")
390
+ #
391
+ # @api public
392
+ # @since x.y.z
393
+ def on_rgb(red, green, blue)
394
+ add(Color::RGB.new(:background, *validate_components(red, green, blue)))
395
+ end
396
+
397
+ # Adds a 24-bit color written as hex to the chain.
398
+ #
399
+ # @param value [String] a hex color, with or without its leading `#`, in three or six digits
400
+ #
401
+ # @return [Dry::CLI::Style]
402
+ #
403
+ # @raise [Dry::CLI::InvalidColorError] if the value isn't a hex color
404
+ #
405
+ # @example
406
+ # Dry::CLI::Style.hex("#ff0000").call("Boom")
407
+ # Dry::CLI::Style.hex("f00").call("Boom")
408
+ #
409
+ # @api public
410
+ # @since x.y.z
411
+ def hex(value)
412
+ add(Color::RGB.new(:foreground, *parse_hex(value)))
413
+ end
414
+
415
+ # Adds a 24-bit background color written as hex to the chain.
416
+ #
417
+ # @param (see #hex)
418
+ #
419
+ # @return (see #hex)
420
+ #
421
+ # @raise (see #hex)
422
+ #
423
+ # @example
424
+ # Dry::CLI::Style.on_hex("#ff0000").call("Boom")
425
+ #
426
+ # @api public
427
+ # @since x.y.z
428
+ def on_hex(value)
429
+ add(Color::RGB.new(:background, *parse_hex(value)))
430
+ end
431
+
432
+ # Adds a color from the 256 color palette to the chain.
433
+ #
434
+ # @param index [Integer] a color code, 0-255
435
+ #
436
+ # @return [Dry::CLI::Style]
437
+ #
438
+ # @raise [Dry::CLI::InvalidColorError] if the code is out of range
439
+ #
440
+ # @example
441
+ # Dry::CLI::Style.ansi256(196).call("Boom")
442
+ #
443
+ # @api public
444
+ # @since x.y.z
445
+ def ansi256(index)
446
+ add(Color::Xterm.new(:foreground, validate_index(index)))
447
+ end
448
+
449
+ # Adds a background color from the 256 color palette to the chain.
450
+ #
451
+ # @param (see #ansi256)
452
+ #
453
+ # @return (see #ansi256)
454
+ #
455
+ # @raise (see #ansi256)
456
+ #
457
+ # @example
458
+ # Dry::CLI::Style.on_ansi256(196).call("Boom")
459
+ #
460
+ # @api public
461
+ # @since x.y.z
462
+ def on_ansi256(index)
463
+ add(Color::Xterm.new(:background, validate_index(index)))
464
+ end
465
+
466
+ private
467
+
468
+ def validate_components(*components)
469
+ components.each do |component|
470
+ next if component.is_a?(Integer) && COMPONENT_RANGE.cover?(component)
471
+
472
+ raise InvalidColorError.new(
473
+ value: component,
474
+ expected: "an integer between 0 and 255"
475
+ )
476
+ end
477
+ end
478
+
479
+ def validate_index(index)
480
+ unless index.is_a?(Integer) && COMPONENT_RANGE.cover?(index)
481
+ raise InvalidColorError.new(
482
+ value: index,
483
+ expected: "a color code between 0 and 255"
484
+ )
485
+ end
486
+
487
+ index
488
+ end
489
+
490
+ def parse_hex(value)
491
+ digits = HEX_PATTERN.match(value.to_s)&.[](:digits)
492
+
493
+ if digits.nil?
494
+ raise InvalidColorError.new(value: value, expected: %(a hex color, like "#ff0000"))
495
+ end
496
+
497
+ digits = digits.chars.flat_map { |digit| [digit, digit] }.join if digits.length == 3
498
+ digits.scan(/\h{2}/).map { |pair| pair.to_i(16) }
499
+ end
500
+ end
501
+
502
+ include Builders
503
+ extend Builders
504
+
505
+ # Starts a chain from a class-level style method.
506
+ #
507
+ # This is the class-level counterpart of the private `#add` below, and the only piece
508
+ # {Builders} needs to serve both the class and its instances.
509
+ #
510
+ # @api private
511
+ private_class_method def self.add(step)
512
+ new([step])
513
+ end
514
+
515
+ # Applies the style to the given text.
516
+ #
517
+ # @param text [String] the text to style
518
+ #
519
+ # @return [Dry::CLI::Style::Text] the styled text
520
+ #
521
+ # @api public
522
+ # @since x.y.z
523
+ def call(text)
524
+ Text.new([[self, text]])
525
+ end
526
+
527
+ alias_method :[], :call
528
+
529
+ # Returns the style as a proc, for use with `&`.
530
+ #
531
+ # @return [Proc]
532
+ #
533
+ # @example
534
+ # names.map(&Dry::CLI::Style.bold)
535
+ #
536
+ # @api public
537
+ # @since x.y.z
538
+ def to_proc
539
+ method(:call).to_proc
540
+ end
541
+
542
+ # Renders the given text at the given color level.
543
+ #
544
+ # @param text [String] the text to style
545
+ # @param color_level [Symbol] a color level
546
+ #
547
+ # @return [String]
548
+ #
549
+ # @api private
550
+ def render(text, color_level)
551
+ text = text.to_s
552
+ opening = sequence_for(color_level)
553
+ return text if opening.empty?
554
+
555
+ # Text that arrived with styling in it has resets of its own, and each would end ours
556
+ # early. Reopen after them, so styled text can be nested.
557
+ return "#{opening}#{text.gsub(RESET, RESET + opening)}#{RESET}" if text.include?(RESET)
558
+
559
+ "#{opening}#{text}#{RESET}"
560
+ end
561
+
562
+ # Returns the ANSI codes this style renders as at the given color level.
563
+ #
564
+ # @param color_level [Symbol] a color level
565
+ #
566
+ # @return [Array<Integer>]
567
+ #
568
+ # @api private
569
+ def codes(color_level)
570
+ steps.flat_map { |step| step.codes(color_level) }
571
+ end
572
+
573
+ # @api private
574
+ def ==(other)
575
+ other.is_a?(self.class) && other.steps == steps
576
+ end
577
+ alias_method :eql?, :==
578
+
579
+ # @api private
580
+ def hash
581
+ [self.class, steps].hash
582
+ end
583
+
584
+ # Returns the style's names, chained as they were built.
585
+ #
586
+ # A style with no steps has no names, and returns an empty string.
587
+ #
588
+ # @return [String]
589
+ #
590
+ # @example
591
+ # Dry::CLI::Style.bold.red.to_s # => "bold.red"
592
+ #
593
+ # @api public
594
+ # @since x.y.z
595
+ def to_s
596
+ steps.map(&:to_s).join(".")
597
+ end
598
+
599
+ # @api private
600
+ def inspect
601
+ return "#<#{self.class.name}>" if steps.empty?
602
+
603
+ "#<#{self.class.name} #{self}>"
604
+ end
605
+
606
+ private
607
+
608
+ def add(step)
609
+ self.class.new(steps + [step])
610
+ end
611
+
612
+ def sequence_for(color_level)
613
+ @sequences[color_level] ||= begin
614
+ codes = codes(color_level)
615
+ codes.empty? ? "" : "\e[#{codes.join(";")}m"
616
+ end
617
+ end
618
+ end
619
+ end
620
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/cli/style"
4
+
5
+ module Dry
6
+ class CLI
7
+ # Convenience access to {Dry::CLI::Style}
8
+ #
9
+ # Included in {Dry::CLI::Command} at both class and instance level. Extend it to build a
10
+ # palette of your own.
11
+ #
12
+ # @example
13
+ # module MyCLI
14
+ # module Styles
15
+ # extend Dry::CLI::StyleMixin
16
+ #
17
+ # ERROR = style.bold.red
18
+ # MUTED = style.dim
19
+ # end
20
+ # end
21
+ #
22
+ # @api public
23
+ # @since x.x.x
24
+ module StyleMixin
25
+ # Returns a neutral style to chain from.
26
+ #
27
+ # @return [Dry::CLI::Style]
28
+ #
29
+ # @example
30
+ # style.bold.red["Boom"] # => "\e[1;31mBoom\e[0m"
31
+ #
32
+ # @api public
33
+ # @since x.x.x
34
+ def style
35
+ Style.new
36
+ end
37
+
38
+ # Removes all style escape sequences from the given text.
39
+ #
40
+ # @param text [String] the text to strip
41
+ #
42
+ # @return [String] the text without styling
43
+ #
44
+ # @example
45
+ # unstyle(`git status --porcelain`)
46
+ #
47
+ # @api public
48
+ # @since x.x.x
49
+ def unstyle(text)
50
+ Style.unstyle(text)
51
+ end
52
+ end
53
+ end
54
+ end