dry-cli-ui 0.4.0 → 0.5.1

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.
data/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  Runtime terminal UI for [dry-cli](https://github.com/dry-rb/dry-cli) commands: spinners, progress bars, boxes, status lines, task trees, tables and prompts.
6
6
 
7
7
  > [!NOTE]
8
- > The design, and the reasons behind it, are in [SPECIFICATION](SPECIFICATION.md).
8
+ > The design, and the reasons behind it, are in [SPECIFICATION](docs/SPECIFICATION.md).
9
9
 
10
10
  A long-running command has more to say than `puts` can show well: what it is doing now, how far along it is, what went wrong. Include one module and the command gets a `ui` that says it, in colour and in place on a terminal, and as plain lines when the output is piped to a file or a CI log.
11
11
 
@@ -15,7 +15,14 @@ A long-running command has more to say than `puts` can show well: what it is doi
15
15
  gem "dry-cli-ui"
16
16
  ```
17
17
 
18
- Requires Ruby 4.0 or later.
18
+ Requires Ruby 4.0 or later and `dry-cli` 1.0 or later. The rendering comes from the [TTY toolkit](https://ttytoolkit.org) (`tty-box`, `tty-spinner`, `tty-progressbar`, `tty-table`, `tty-prompt`, `tty-cursor`, `tty-screen`), `pastel`, `strings` and `concurrent-ruby`, which Bundler installs with the gem.
19
+
20
+ Either require works, and both load the same file:
21
+
22
+ ```ruby
23
+ require "dry-cli-ui" # matches the gem name
24
+ require "dry/cli/ui" # matches the constant Dry::CLI::UI
25
+ ```
19
26
 
20
27
  ## Usage
21
28
 
@@ -52,20 +59,47 @@ Loading tax rules...
52
59
  āœ“ Loading tax rules (0.3s)
53
60
  Importing rules...
54
61
  š˜… Importing rules 1482/1900 (4.1s)
55
- ā”Œā”€ Error ──────────────────────────────────────────────────┐
56
- │ │
57
- │ Import failed │
58
- │ │
59
- │ Could not validate rule US.2026.IRC.199A: missing │
60
- │ dependency taxable_income │
61
- │ │
62
- ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
62
+
63
+ ā”Œā”€ Error ────────────────────────────────────────────────────────────────────┐
64
+ │ │
65
+ │ Import failed │
66
+ │ │
67
+ │ Could not validate rule US.2026.IRC.199A: missing dependency │
68
+ │ taxable_income │
69
+ │ │
70
+ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
63
71
  ```
64
72
 
73
+ A stream that is not a terminal is taken to be 80 columns wide, so a piped box is 78.
74
+
65
75
  On a terminal the spinner turns and the bar fills in place, with percent, count and ETA, and each is replaced by the same `āœ“` or `š˜…` line when its block ends.
66
76
 
67
77
  Include the module once in a base class and every command has `ui`. Including it loads nothing: the TTY gems load the first time `ui` is used.
68
78
 
79
+ ```ruby
80
+ class ApplicationCommand < Dry::CLI::Command
81
+ include Dry::CLI::UI
82
+ end
83
+
84
+ class Import < ApplicationCommand
85
+ def call(**) = ui.success("Nothing to import")
86
+ end
87
+ ```
88
+
89
+ `ui` writes to the command's `out` and `err` when dry-cli has set them, and to `$stdout` and `$stderr` otherwise.
90
+
91
+ ### Without dry-cli
92
+
93
+ `Dry::CLI::UI::Console` needs nothing from dry-cli, so a Rake task or a plain script can use it directly:
94
+
95
+ ```ruby
96
+ require "dry-cli-ui"
97
+
98
+ ui = Dry::CLI::UI::Console.new
99
+ ui.spinner("Compacting the database") { compact! }
100
+ ui.success "Done"
101
+ ```
102
+
69
103
  ## API
70
104
 
71
105
  ### Messages
@@ -79,28 +113,95 @@ ui.error "Import failed", e.message
79
113
  ui.fatal "Database unreachable"
80
114
  ```
81
115
 
82
- Each draws a box with a single white border and the level's name as a coloured title. Every argument is a paragraph, wrapped to fit. The box fills the terminal less a two-column margin, or takes a fixed width:
116
+ Each prints a blank line, then a box with a single white border and the level's name as a coloured title, and returns `nil`. Every argument is a paragraph, wrapped to fit, with a blank line between paragraphs. The box fills the terminal less a two-column margin, or takes a fixed width:
83
117
 
84
118
  ```ruby
85
119
  ui.info "Short and narrow", width: 40
86
- ui.box "Name: Alan Turing", "Role: Cryptanalyst", title: "Profile" # untitled without title:
87
120
  ```
88
121
 
122
+ ```text
123
+
124
+ ā”Œā”€ Info ───────────────────────────────┐
125
+ │ │
126
+ │ Short and narrow │
127
+ │ │
128
+ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
129
+ ```
130
+
131
+ A `width:` is never wider than the terminal less its margin, and never narrower than 20 columns.
132
+
133
+ | Method | Title | Colour | Stream |
134
+ | --------- | ------- | ------- | ------ |
135
+ | `debug` | Debug | gray | `err` |
136
+ | `info` | Info | cyan | `out` |
137
+ | `success` | Success | green | `out` |
138
+ | `warn` | Warning | yellow | `err` |
139
+ | `error` | Error | red | `err` |
140
+ | `fatal` | Fatal | magenta | `err` |
141
+
142
+ `ui.box` is the general form. Without `level:` it is untitled unless given a `title:`, uncoloured, and goes to `out`:
143
+
144
+ ```ruby
145
+ ui.box "Name: Alan Turing", "Role: Cryptanalyst", title: "Profile", width: 40
146
+ ```
147
+
148
+ ```text
149
+
150
+ ā”Œā”€ Profile ────────────────────────────┐
151
+ │ │
152
+ │ Name: Alan Turing │
153
+ │ │
154
+ │ Role: Cryptanalyst │
155
+ │ │
156
+ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
157
+ ```
158
+
159
+ With `level:` it takes that level's colour and stream, and its title unless `title:` replaces it:
160
+
161
+ ```ruby
162
+ ui.box "Disk is 91% full", level: :warn, title: "Disk" # a yellow "Disk" box on err
163
+ ui.box "Plain and untitled" # no title, on out
164
+ ```
165
+
166
+ An unknown level raises `ArgumentError`.
167
+
89
168
  ### Popups
90
169
 
91
170
  ```ruby
92
171
  ui.popup "h help", "q quit", title: "Keys"
93
172
  ```
94
173
 
95
- On a terminal, a box drawn over whatever is on the screen: only as wide as its text, centred, and leaving the cursor where it was, so a spinner or a redrawn screen carries on underneath. Piped, it is the same box `ui.box` draws, on `err`.
174
+ On a terminal, a box drawn over whatever is on the screen: only as wide as its text (at least 20 columns, at most `width:` or the box width), centred, and leaving the cursor where it was, so a spinner or a redrawn screen carries on underneath. Piped, it is the same box `ui.box` draws, on `err`:
175
+
176
+ ```text
177
+ ā”Œā”€ Keys ─────────────────────┐
178
+ │ │
179
+ │ h help │
180
+ │ │
181
+ │ q quit │
182
+ │ │
183
+ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
184
+ ```
96
185
 
97
186
  ### Status lines
98
187
 
188
+ One line with a coloured glyph, on the level's stream. The level defaults to `:info`, and every argument is joined with a space:
189
+
99
190
  ```ruby
100
191
  ui.status "Connected to the database", level: :success # āœ“ Connected to the database
101
192
  ui.status "Disk nearly full", level: :warn # ⚠ Disk nearly full
193
+ ui.status "Loaded", rules.size, "rules" # ℹ Loaded 1900 rules
102
194
  ```
103
195
 
196
+ | Level | Glyph | Stream |
197
+ | ---------- | ----- | ------ |
198
+ | `:debug` | `Ā·` | `err` |
199
+ | `:info` | `ℹ` | `out` |
200
+ | `:success` | `āœ“` | `out` |
201
+ | `:warn` | `⚠` | `err` |
202
+ | `:error` | `āœ—` | `err` |
203
+ | `:fatal` | `āœ–` | `err` |
204
+
104
205
  ### Spinners
105
206
 
106
207
  ```ruby
@@ -118,7 +219,27 @@ ui.spinner("Importing rules") do |line|
118
219
  end
119
220
  ```
120
221
 
121
- `line.detail = "..."` shows text after the label, redrawn in place as it changes. Piped, the detail is kept and never printed, since it can change many times a second. `line.fail(reason)` ends the spinner as `š˜… Importing rules: 3 rules skipped (4.1s)` without raising, and the block's value is still returned. `line.failed?` and `line.reason` read it back. Every `Line` method is safe to call from any thread.
222
+ `line.detail = "..."` shows text after the label, redrawn in place as it changes. Piped, the detail is kept and never printed, since it can change many times a second. `line.fail(reason)` ends the spinner as `š˜… Importing rules: 3 rules skipped (4.1s)` without raising, and the block's value is still returned. `line.failed?`, `line.reason` and `line.detail` read it back. Every `Line` method is safe to call from any thread.
223
+
224
+ Piped, each of these prints its label with `...` when it starts, then its outcome:
225
+
226
+ ```text
227
+ Loading tax rules...
228
+ āœ“ Loading tax rules (0.3s)
229
+ Importing rules...
230
+ š˜… Importing rules: 3 rules skipped (4.1s)
231
+ ```
232
+
233
+ A block that raises leaves `š˜… Loading tax rules (0.3s)` and the error propagates, so `rescue` it around the call. A lambda that takes no arguments is called without a `Line`, so a method object or a stored lambda can be passed as it is:
234
+
235
+ ```ruby
236
+ load = -> { YAML.load_file("rules.yml") }
237
+ rules = ui.spinner("Loading tax rules", &load)
238
+ ```
239
+
240
+ Without a block, `spinner` raises `ArgumentError`. The same is true of `progress`, `multi_spinner`, `multi_progress`, `tasks` and `status_bar`.
241
+
242
+ Elapsed times read `0.4s` under a minute, `1m 02s` under an hour, and `1h 02m` after that.
122
243
 
123
244
  ### Progress bars
124
245
 
@@ -131,7 +252,28 @@ ui.progress("Importing rules", total: rules.size) do |bar|
131
252
  end
132
253
  ```
133
254
 
134
- The bar shows percent, `current/total` and ETA, `Importing rules [◼◼◼◼◼◼ ] 61% 1159/1900 ETA 2.7s`, and ends with `āœ“ Importing rules 1900/1900 (4.2s)`. On a terminal the `ā—¼`s are green and the whole bar sits on a gray background; see [Configuration](#configuration) to change either.
255
+ The bar shows percent, `current/total` and ETA, `Importing rules [◼◼◼◼◼◼ ] 61% 1159/1900 ETA 2.7s`, and ends with `āœ“ Importing rules 1900/1900 (4.2s)`. On a terminal the `ā—¼`s are green, between brackets, on no background; see [Configuration](#configuration) to change either.
256
+
257
+ The block is given a `Dry::CLI::UI::Widgets::Progress::Handle`, never the underlying `TTY::ProgressBar`:
258
+
259
+ ```ruby
260
+ ui.progress("Copying", total: files.sum(&:size)) do |bar|
261
+ files.each do |file|
262
+ copy(file) { |bytes| bar.advance(bytes) }
263
+ ui.status "#{bar.current} of #{bar.total} bytes" if bar.current == bar.total
264
+ end
265
+ :copied # progress returns the block's value
266
+ end
267
+ ```
268
+
269
+ - `advance(step = 1)` adds to `current` and returns the handle; `current` never passes `total`.
270
+ - `total = n` sets the total once the work finds out, such as a download learning its size, and lowers `current` to fit. Anything but a non-negative Integer raises `ArgumentError`.
271
+ - `total:` must be a non-negative Integer, or `progress` raises `ArgumentError`.
272
+ - `total: 0` draws no bar, and ends `āœ“ Copying 0/0`.
273
+ - `color:` paints this bar's finished part in any Pastel style, such as `color: :red`, instead of the configured `bar_color`. A style Pastel does not know raises `ArgumentError` before the block runs.
274
+ - The outcome is `āœ“` whenever the block returns, even short of the total (`āœ“ Copying 12/20`), and `š˜…` when it raises.
275
+
276
+ Piped, it prints `Importing rules...` when it starts and the outcome line when it ends, with no bar in between.
135
277
 
136
278
  ### Several spinners at once
137
279
 
@@ -163,7 +305,37 @@ Once they finish, the headline ends `āœ“`, or `š˜…` when any job failed:
163
305
  └─ [āœ“] video (0.2s)
164
306
  ```
165
307
 
166
- Each job is given a `Line`, as a single spinner's block is. When a job raises, jobs already running finish, jobs not yet started are marked skipped (`[—]`), and the error is re-raised. Piped, it prints `Fetching...`, then each job's outcome as it ends, then the headline's.
308
+ Each job is given a `Line`, as a single spinner's block is. When a job raises, jobs already running finish, jobs not yet started are marked skipped (`[—]`), and the first error is re-raised. A job that never ran has `nil` in the returned array, which matters only when you rescue the error.
309
+
310
+ `concurrent:` takes `true` (all at once, the default), `false` (one at a time, in order), or a positive Integer. Anything else, `0` included, raises `ArgumentError` before any job runs.
311
+
312
+ Piped, it prints `Fetching...`, then each job's outcome as it ends, then the headline's:
313
+
314
+ ```text
315
+ Fetching...
316
+ [āœ“] fonts (0.3s)
317
+ [š˜…] images: 2 timed out (0.3s)
318
+ [āœ“] video (0.2s)
319
+ š˜… Fetching (0.5s)
320
+ ```
321
+
322
+ When a job raises under `concurrent: 1`:
323
+
324
+ ```text
325
+ Fetching...
326
+ [š˜…] fonts (0.1s)
327
+ [—] images
328
+ [—] video
329
+ š˜… Fetching (0.1s)
330
+ ```
331
+
332
+ On a terminal with fewer rows than the widget needs, the cursor cannot reach them all, so only the jobs running are shown under the headline, as many as fit. Jobs leave the screen as they end, and the headline is all that remains:
333
+
334
+ ```text
335
+ [ā ‹] Fetching
336
+ ā”œā”€ [ā ‹] video
337
+ └─ [ā ‹] audio
338
+ ```
167
339
 
168
340
  ### Several progress bars at once
169
341
 
@@ -186,7 +358,56 @@ The same shape as `multi_spinner`, with a bar per job and a headline bar that co
186
358
  └─ [ ] video.mp4
187
359
  ```
188
360
 
189
- Each job is given the same handle as `ui.progress`, with `advance(step = 1)`, `current` and `total`. A finished job's row reads `[āœ“] fonts.zip 40/40 (0.1s)`, and the headline's `[āœ“] Downloading 240/240 (0.3s)`.
361
+ Each job is given the same handle as `ui.progress`, with `advance(step = 1)`, `current` and `total`. `m.progress` takes `color:` as `ui.progress` does, so bars side by side can differ:
362
+
363
+ ```ruby
364
+ ui.multi_progress("Probing #{hosts.size} hosts", total: hosts.size) do |m|
365
+ m.progress("Answered", total: hosts.size, color: :green) { |bar| ... }
366
+ m.progress("No answer", total: hosts.size, color: :red) { |bar| ... }
367
+ end
368
+ ```
369
+
370
+ The headline bar keeps the configured colour. A finished job's row reads `[āœ“] fonts.zip 40/40 (0.1s)`, and the headline's `[āœ“] Downloading 240/240 (0.3s)`. It returns what each job returned, in declaration order, and takes `concurrent:` as `multi_spinner` does. Every `m.progress` needs a block, and a `total:` that is nil or a non-negative Integer, or raises `ArgumentError`.
371
+
372
+ A job that learns its size only as it runs declares `total: nil` and sets `bar.total =` once it knows. Until then its bar is empty and its count reads `12/?`.
373
+
374
+ The headline bar adds up every job's bar. Two options change that:
375
+
376
+ - `count: :jobs` counts the jobs that have ended, out of all of them, whatever each bar measures.
377
+ - `total: n` sets the headline's total, for bars that overlap, such as two bars that each count some of the same hosts.
378
+
379
+ ```ruby
380
+ ui.multi_progress("Downloading", concurrent: 2, count: :jobs) do |m|
381
+ files.each do |file|
382
+ m.progress(file.name, total: nil) do |bar|
383
+ bar.total = size_of(file)
384
+ download(file) { |bytes| bar.advance(bytes) }
385
+ end
386
+ end
387
+ end
388
+ ```
389
+
390
+ Piped, where `images.tar.gz` never learned its size:
391
+
392
+ ```text
393
+ Downloading...
394
+ [āœ“] fonts.zip 40/40 (0.1s)
395
+ [āœ“] images.tar.gz 120/? (0.1s)
396
+ [āœ“] video.mp4 80/80 (0.1s)
397
+ āœ“ Downloading 3/3 (0.1s)
398
+ ```
399
+
400
+ Any other `count:`, or a `total:` that is not a non-negative Integer, raises `ArgumentError`.
401
+
402
+ Piped:
403
+
404
+ ```text
405
+ Downloading...
406
+ [āœ“] fonts.zip 40/40 (0.1s)
407
+ [āœ“] images.tar.gz 120/120 (0.2s)
408
+ [āœ“] video.mp4 80/80 (0.3s)
409
+ āœ“ Downloading 240/240 (0.3s)
410
+ ```
190
411
 
191
412
  ### Example: fetching many URLs
192
413
 
@@ -200,21 +421,16 @@ end
200
421
  File.write("urls.txt", bodies.join("\n"))
201
422
  ```
202
423
 
203
- With `multi_progress`, each URL gets a bar that fills one byte at a time as the body arrives. A bar's `total` is fixed when it is declared, so a `HEAD` request asks each URL for its size first:
424
+ With `multi_progress`, each URL gets a bar that fills as the body arrives, and the headline counts URLs. When a URL's turn comes, a `HEAD` request asks for its size, which becomes the bar's total:
204
425
 
205
426
  ```ruby
206
- found = urls.filter_map do |url|
207
- [url, content_length(url)]
208
- rescue StandardError => e
209
- ui.status "#{url}: #{e.message}", level: :warn
210
- nil
211
- end
212
-
213
- bodies = ui.multi_progress("Fetching #{found.size} URLs", concurrent: 8) do |m|
214
- found.each do |url, size|
215
- m.progress(url, total: size || 1) do |bar|
216
- body = download(url) { |bytes| bytes.times { bar.advance } if size }
217
- bar.advance unless size # no Content-Length: done in one step
427
+ bodies = ui.multi_progress("Fetching #{urls.size} URLs", concurrent: 8, count: :jobs) do |m|
428
+ urls.each do |url|
429
+ m.progress(url, total: nil) do |bar|
430
+ size = content_length(url)
431
+ bar.total = size if size
432
+ body = download(url) { |bytes| bar.advance(bytes) }
433
+ bar.total = bar.current unless size # no Content-Length: full once done
218
434
  body
219
435
  end
220
436
  end
@@ -250,7 +466,34 @@ def download(url)
250
466
  end
251
467
  ```
252
468
 
253
- In both, at most eight requests run at once and the rest wait as `[ ]` rows. The headline counts every URL, and in `multi_progress` every byte. A server that sends no `Content-Length` gets a bar of one unit, which sits at 0% and fills when its download ends. These helpers are kept short: a real one follows redirects, and sends `Accept-Encoding: identity` so the bytes counted match `Content-Length`. With more URLs than the screen has rows, each finished URL prints one line instead.
469
+ In both, at most eight requests run at once, in the order of `urls`, and the rest wait as `[ ]` rows. A server that sends no `Content-Length` leaves its bar empty, counting `12/?`, until its download ends. These helpers are kept short: a real one follows redirects, sends `Accept-Encoding: identity` so the bytes counted match `Content-Length`, and writes each body to its file as it arrives rather than holding it in memory; `examples/bin/mycli download-urls` does all three. With more URLs than the screen has rows, only the URLs downloading are shown.
470
+
471
+ ### Stopping on Ctrl-C
472
+
473
+ `ui.stoppable` runs its block with Ctrl-C asking for a stop instead of killing the command. Hand the `stop` it yields to `multi_spinner` or `multi_progress` as `stop:`: once Ctrl-C is pressed, the jobs running finish, no more start, and the command carries on to report what it did. A second Ctrl-C interrupts as usual.
474
+
475
+ ```ruby
476
+ ui.stoppable do |stop|
477
+ files = ui.multi_spinner("Downloading #{urls.size} URLs", concurrent: 10, stop: stop) do |m|
478
+ urls.each { |url| m.spinner(url) { download(url) } }
479
+ end
480
+ next ui.success("Downloaded #{files.size} URLs") unless stop.stopped?
481
+
482
+ ui.info "Stopped", "Downloaded #{files.compact.size} of #{urls.size} URLs"
483
+ end
484
+ ```
485
+
486
+ While the running jobs finish, the headline reads `[ā ‹] Downloading 1628 URLs stopping`. Jobs that never started are marked skipped and return `nil`, and the headline ends skipped too, unless a job failed. Piped:
487
+
488
+ ```text
489
+ Fetching...
490
+ [āœ“] fonts (0.1s)
491
+ [—] images
492
+ [—] video
493
+ — Fetching (0.1s)
494
+ ```
495
+
496
+ `stop.stopped?` says whether a stop was asked for, and `stop.stop!` asks for one from code, from any thread. `Dry::CLI::UI::Stop.new.trap(signal)` traps a signal other than `INT`. Your own worker threads can check `stop.stopped?` before taking the next item, as `examples/bin/mycli find-hosts` does. With `concurrent: true` every job has started already, so there is nothing left to skip.
254
497
 
255
498
  ### Task trees
256
499
 
@@ -285,7 +528,37 @@ Deploy
285
528
  └─ [āœ“] Restart (0.3s)
286
529
  ```
287
530
 
288
- While it runs, the tree redraws in place and every running task has its own spinner. Every row is marked in brackets, in bold yellow while it waits, `[ ]`, and while it runs, a turning `[ā ]`; then a green `[āœ“]` when it is done, a red `[š˜…]` when it failed, or a yellow `[—]` when it was skipped. Piped, each line is printed once it is final, and a group's line appears as `[ā–ø]` when it starts. `concurrent: true` runs a group's tasks at the same time, on a group or on `ui.tasks` itself, and `concurrent: 3` runs at most three at once. When a task raises, it is marked `[š˜…]`, tasks already running finish, the rest are marked skipped (`[—]`), and the error is re-raised.
531
+ While it runs, the tree redraws in place and every running task has its own spinner. Every row is marked in brackets, in bold yellow while it waits, `[ ]`, and while it runs, a turning `[ā ]`; then a green `[āœ“]` when it is done, a red `[š˜…]` when it failed, or a yellow `[—]` when it was skipped. Piped, each line is printed once it is final, and a group's line appears as `[ā–ø]` when it starts. `concurrent: true` runs a group's tasks at the same time, on a group or on `ui.tasks` itself, and `concurrent: 3` runs at most three at once. Without it, tasks run one after another. When a task raises, it is marked `[š˜…]`, tasks already running finish, the rest are marked skipped (`[—]`), and the error is re-raised. `ui.tasks` returns `nil`, and its title is optional: `ui.tasks { |t| ... }` draws the tree without a heading.
532
+
533
+ Piped, the same tree as the example above, with one migration failing:
534
+
535
+ ```text
536
+ Deploy
537
+ ā”œā”€ [āœ“] Build assets (0.4s)
538
+ ā”œā”€ [ā–ø] Migrate
539
+ │ ā”œā”€ [āœ“] users (0.1s)
540
+ │ └─ [š˜…] orders: table locked (0.2s)
541
+ ā”œā”€ [ā–ø] Warm caches
542
+ │ ā”œā”€ [āœ“] fonts (0.5s)
543
+ │ └─ [āœ“] images (0.3s)
544
+ └─ [āœ“] Restart (0.3s)
545
+ ```
546
+
547
+ And when `Build assets` raises instead:
548
+
549
+ ```text
550
+ Deploy
551
+ ā”œā”€ [š˜…] Build assets (0.4s)
552
+ ā”œā”€ [—] Migrate
553
+ │ ā”œā”€ [—] users
554
+ │ └─ [—] orders
555
+ ā”œā”€ [—] Warm caches
556
+ │ ā”œā”€ [—] fonts
557
+ │ └─ [—] images
558
+ └─ [—] Restart
559
+ ```
560
+
561
+ `task` and `group` each need a block, and `concurrent:` takes the same values as on the multi widgets; either mistake raises `ArgumentError` while the tree is being declared, before anything runs.
289
562
 
290
563
  Each task is given a `Line`, as a spinner's block is. Its detail is drawn after the task's name while it runs, and `line.fail(reason)` marks the task `š˜… name: reason` and its groups `š˜…`, while the rest of the tree runs on:
291
564
 
@@ -325,7 +598,15 @@ While the block runs, the bottom of the screen shows how the whole command is do
325
598
 
326
599
  Nothing reports to it by hand: every `spinner`, `progress`, `multi_spinner`, `multi_progress` and task started inside the block does so on its own. Hints that do not fit are left out, and a status that does not fit is cut short with `…`.
327
600
 
328
- It sets no scroll region, so the scrollback keeps everything, and an interrupted command leaves nothing behind. Piped, or without animation, it just runs the block. Write through `ui` while it runs: a bare `puts` lands where the bar is, until the next `ui` call draws the bar again.
601
+ It sets no scroll region, so the scrollback keeps everything, and an interrupted command leaves nothing behind. Piped, or without animation, it just runs the block, and a `status_bar` inside another one does the same. Either way it returns the block's value. Write through `ui` while it runs: a bare `puts` lands where the bar is, until the next `ui` call draws the bar again.
602
+
603
+ Both arguments are optional, and `hints:` takes one string or several:
604
+
605
+ ```ruby
606
+ report = ui.status_bar { build_report } # no title, no hints
607
+ ui.status_bar("sync", hints: "q quit") { sync }
608
+ ui.status_bar("sync", hints: ["^C cancel", "? help"]) { sync }
609
+ ```
329
610
 
330
611
  ### Putting it together
331
612
 
@@ -376,7 +657,11 @@ ui.table([["Alan Turing", 41], ["Ada Lovelace", 36]], header: %w[Name Age])
376
657
  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”˜
377
658
  ```
378
659
 
379
- Tables are never truncated or rotated to fit the screen.
660
+ Tables go to `out` and return `nil`. Cells are converted with `to_s`, the header is bold on a colour terminal, `header:` is optional, and an empty `rows` prints nothing. Tables are never truncated or rotated to fit the screen: a table wider than the terminal wraps like any long line.
661
+
662
+ ```ruby
663
+ ui.table(User.limit(10).pluck(:email, :created_at)) # no header
664
+ ```
380
665
 
381
666
  ### Prompts
382
667
 
@@ -387,13 +672,52 @@ tier = ui.prompt("Tier?", choices: { "Free" => :free, "Pro" => :pro })
387
672
  ui.confirm("Deploy to #{env}?", default: false)
388
673
  ```
389
674
 
390
- On a terminal these use arrow-key menus and line editing. Otherwise they read lines from standard input, so answers can be piped:
675
+ - `prompt` returns the answer as a String, or the default for an empty answer.
676
+ - With an Array of `choices:`, it returns the chosen name; with a Hash, the value the chosen name maps to (`:pro` above). `default:` is the name of a choice.
677
+ - `confirm` returns `true` or `false`, and `default:` is `false` unless given.
678
+
679
+ When both standard input and `err` are terminals, these use arrow-key menus and line editing (TTY::Prompt). Otherwise they print the question to `err` and read lines from standard input, so answers can be piped:
391
680
 
392
681
  ```bash
393
682
  printf 'production\ny\n' | mycli deploy
394
683
  ```
395
684
 
396
- When the input runs out, a prompt returns its default, or raises `Dry::CLI::UI::NonInteractiveError` if it has none.
685
+ In that mode a list of choices is numbered, and an answer may be the number or the name:
686
+
687
+ ```text
688
+ Name? [Alan Turing]
689
+ Environment?
690
+ 1) staging
691
+ 2) production
692
+ Choose 1-2 [staging]: 2
693
+ Tier?
694
+ 1) Free
695
+ 2) Pro
696
+ Choose 1-2: Pro
697
+ Deploy to production? (y/N) maybe
698
+ Please answer y or n.
699
+ Deploy to production? (y/N) yes
700
+ ```
701
+
702
+ An answer that matches no choice asks again, and `confirm` accepts `y`, `yes`, `n` and `no` in any case. When the input runs out, a prompt returns its default, or raises `Dry::CLI::UI::NonInteractiveError` if it has none:
703
+
704
+ ```ruby
705
+ token = begin
706
+ ui.prompt("API token?")
707
+ rescue Dry::CLI::UI::NonInteractiveError
708
+ ENV.fetch("API_TOKEN")
709
+ end
710
+ ```
711
+
712
+ ## Errors
713
+
714
+ | Error | Raised when |
715
+ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
716
+ | `Dry::CLI::UI::NonInteractiveError` | a prompt has no answer left to read and no default |
717
+ | `Dry::CLI::UI::Error` | never directly: the base class of the gem's own errors, for `rescue Dry::CLI::UI::Error` |
718
+ | `ArgumentError` | a widget has no block, `total:` is not a non-negative Integer, `concurrent:` is invalid, a level or configuration is unknown |
719
+
720
+ Errors raised inside a block are never swallowed: the widget marks itself failed and re-raises them.
397
721
 
398
722
  ## Where output goes
399
723
 
@@ -414,11 +738,11 @@ Dry::CLI::UI.configure do
414
738
  spinner_format :dots # any TTY::Spinner format name
415
739
  bar_format(complete: "ā—¼", incomplete: " ") # or any TTY::ProgressBar bar format name, such as :box
416
740
  bar_color :green # the finished part: any Pastel style, or nil
417
- bar_background :on_bright_black # the whole bar: any Pastel style, or nil
741
+ bar_background nil # the whole bar: any Pastel style, or nil
418
742
  end
419
743
  ```
420
744
 
421
- Those are the defaults: spinners turn through `ā ‹ ā ™ ā ¹ ā ø ā ¼ ā “ ā ¦ ā § ā ‡ ā ` ten times a second, and bars draw a green `ā—¼` for each finished part on a gray track. Without colour the track is blank, and the brackets still show where the bar ends. Every spinner reads the same format, including `multi_spinner`, task trees and the status bar, and every bar reads the same characters and colours. The formats also take a definition of your own:
745
+ Those are the defaults: spinners turn through `ā ‹ ā ™ ā ¹ ā ø ā ¼ ā “ ā ¦ ā § ā ‡ ā ` ten times a second, and bars draw a green `ā—¼` for each finished part, with nothing behind them, and brackets show where the bar begins and ends. Every spinner reads the same format, including `multi_spinner`, task trees and the status bar, and every bar reads the same characters and colours, except a bar given its own `color:`. The formats also take a definition of your own:
422
746
 
423
747
  ```ruby
424
748
  Dry::CLI::UI.configure do |config|
@@ -427,7 +751,34 @@ Dry::CLI::UI.configure do |config|
427
751
  end
428
752
  ```
429
753
 
430
- An unknown name or a malformed definition raises `ArgumentError` when it is set.
754
+ An unknown name or a malformed definition raises `ArgumentError` when it is set, as does a colour Pastel does not know:
755
+
756
+ ```ruby
757
+ Dry::CLI::UI.configure { bar_color :nope }
758
+ # => ArgumentError: bar_color must be a Pastel style or nil, got :nope
759
+ ```
760
+
761
+ Called without a value, each setting reads it back, and `Dry::CLI::UI.config` returns the configuration itself. `Dry::CLI::UI.reset!` restores every default, which is useful between specs:
762
+
763
+ ```ruby
764
+ Dry::CLI::UI.config.bar_color # => :green
765
+ Dry::CLI::UI.config.spinner_frames # => ["ā ‹", "ā ™", "ā ¹", ...]
766
+
767
+ RSpec.configure { |c| c.after { Dry::CLI::UI.reset! } }
768
+ ```
769
+
770
+ Some more looks, all from names the TTY gems already know:
771
+
772
+ ```ruby
773
+ Dry::CLI::UI.configure do
774
+ spinner_format :classic # | / - \
775
+ bar_format :block # ā–ˆ and ā–‘
776
+ bar_color :cyan
777
+ bar_background :on_blue # a blue track the whole bar's width
778
+ end
779
+ ```
780
+
781
+ ### Console options
431
782
 
432
783
  Override `ui` to configure the console:
433
784
 
@@ -447,6 +798,47 @@ class ApplicationCommand < Dry::CLI::Command
447
798
  end
448
799
  ```
449
800
 
801
+ Every option `Console.new` takes:
802
+
803
+ | Option | Default | What it does |
804
+ | ------------ | --------------------- | -------------------------------------------------------------------- |
805
+ | `out:` | `$stdout` | where results go |
806
+ | `err:` | `$stderr` | where diagnostics, progress and prompts go |
807
+ | `input:` | `$stdin` | where prompt answers are read from |
808
+ | `env:` | `ENV` | read for `NO_COLOR` and `TERM` |
809
+ | `color:` | `nil` | `true` or `false` forces colour on both streams; `nil` detects it |
810
+ | `animate:` | `nil` | `true` or `false` forces animation on both streams; `nil` detects it |
811
+ | `width:` | `nil` | forces the terminal width in columns; `nil` asks the terminal, or 80 |
812
+ | `box_width:` | `nil` | the width of every box; `nil` fills the terminal less two columns |
813
+ | `clock:` | monotonic clock | any object whose `call` returns seconds, for elapsed times |
814
+ | `config:` | `Dry::CLI::UI.config` | a `Dry::CLI::UI::Configuration` for this console alone |
815
+
816
+ `config:` gives one console a look of its own without changing the process-wide one:
817
+
818
+ ```ruby
819
+ classic = Dry::CLI::UI::Configuration.new.tap { |c| c.spinner_format = :classic }
820
+ ui = Dry::CLI::UI::Console.new(config: classic)
821
+ ```
822
+
823
+ ### Testing a command
824
+
825
+ Pass `StringIO`s and assert on what was written. A `StringIO` is not a terminal, so the output is the plain form shown throughout this README, with no escape codes:
826
+
827
+ ```ruby
828
+ out = StringIO.new
829
+ err = StringIO.new
830
+ ui = Dry::CLI::UI::Console.new(out: out, err: err, input: StringIO.new("y\n"))
831
+
832
+ ui.spinner("Loading") { :ok }
833
+ ui.success "Imported"
834
+ ui.confirm("Continue?") # => true
835
+
836
+ err.string # => "Loading...\nāœ“ Loading (0.0s)\nContinue? (y/N) "
837
+ out.string # => the Success box
838
+ ```
839
+
840
+ Through dry-cli, `Dry::CLI.new(registry).call(arguments: %w[import], out: out, err: err)` gives every command's `ui` those streams.
841
+
450
842
  ## Relationship to dry-cli-help
451
843
 
452
844
  `dry-cli-help` is static presentation: what does this command do? `dry-cli-ui` is runtime presentation: what is this command doing? Use either, or both.
@@ -457,6 +849,19 @@ gem "dry-cli-help"
457
849
  gem "dry-cli-ui"
458
850
  ```
459
851
 
852
+ ## Examples
853
+
854
+ [`examples/`](examples/README.md) holds a small dry-cli application that uses the gem:
855
+
856
+ ```bash
857
+ cd examples
858
+ bundle install
859
+ bundle exec bin/mycli primes --max 200000
860
+ bundle exec bin/mycli urls_spinner https://www.ruby-lang.org https://dry-rb.org
861
+ bundle exec bin/mycli urls_progress https://www.ruby-lang.org https://dry-rb.org
862
+ bundle exec bin/mycli urls_progress https://www.ruby-lang.org | cat # the plain form
863
+ ```
864
+
460
865
  ## Development
461
866
 
462
867
  ```bash
@@ -465,10 +870,11 @@ just test # the suite, with 100% line and branch coverage enforced
465
870
  just lint # rubocop
466
871
  just ci # both
467
872
  just format # rubocop -a, then mdformat
873
+ just doc # YARD documentation
468
874
  bin/console # IRB with the gem loaded
469
875
  ```
470
876
 
471
- Specs render into a `StringIO`. The animated code paths run against `FakeTTY`, a `StringIO` that answers `tty?` with true, and elapsed times come from a fake clock.
877
+ Specs render into a `StringIO`. The animated code paths run against `FakeTTY`, a `StringIO` that answers `tty?` with true, and elapsed times come from a fake clock. RBS signatures for the public API are in [`sig/dry/cli/ui.rbs`](sig/dry/cli/ui.rbs).
472
878
 
473
879
  ## Contributing
474
880
 
@@ -477,6 +883,18 @@ Bug reports and pull requests are welcome at <https://github.com/kigster/dry-cli
477
883
  > [!WARNING]
478
884
  > The `dry-` prefix and the `Dry::CLI::UI` namespace do not imply endorsement by `dry-rb`. This is an independent gem that extends theirs.
479
885
 
886
+ ## Note to Dry-Rb Maintainers
887
+
888
+ First — hats off to all of you who tirelessly built out one of the most valuable collections of libraries in the Ruby ecosystem.
889
+
890
+ While I admire and would be willing to contribute any or all of the extension gem's code to the original gem, I feel that creating plugins and extensions allows the author to fully express their needs and wants, and then, if the authors of `dry-cli` become interested in any of them, I would be honored to submit a PR to `dry-cli` itself.
891
+
892
+ This method offered a very open road to extensibility and experimentation. If the code quality or design is not up to the level required for direct contributions to `dry-rb`, then let it be known that:
893
+
894
+ 1. We would be very happy to receive any feedback and improve, refactor, and update the gem assuming it improves it
895
+ 1. Roll any part of the codebase as a PR to the `dry-cli` core.
896
+ 1. We hold the authors of `dry-rb` in high regard, and generally would love to collaborate, as long as the feedback loop/cycle is not so long that the context of the changes gets lost in time, as with so many contributions made to other gems in the past.
897
+
480
898
  ## License
481
899
 
482
900
  MIT. See [LICENSE.txt](LICENSE.txt).