mini_progress 0.1.0

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,543 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/console"
4
+ require "unicode/display_width"
5
+
6
+ module MiniProgress
7
+ class Tui
8
+ # The drawing half. It owns the step model and paints each frame. Only the
9
+ # render thread touches it. All time comes from `clock` and all output goes
10
+ # to `output`; both can be injected in tests.
11
+ class Renderer
12
+ include Formatting
13
+
14
+ SPINNER = %w[⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏].freeze
15
+ SPINNER_RATE = 6 # spinner steps per second, separate from the draw rate
16
+ TITLE_WIDTH = 16 # smallest width; grows to the longest title, up to MAX_TITLE_WIDTH
17
+ MAX_TITLE_WIDTH = 40 # upper limit, so a long title can't push the columns off-screen
18
+ TIME_WIDTH = 7 # fits "9:59:59"; the column grows for longer runs
19
+ PERCENT_WIDTH = 4 # "100%"
20
+ COUNT_WIDTH = 10 # fits "99,999,999" (8 digits with commas); larger counts grow it
21
+ RATE_SMOOTHING = 0.1 # EMA weight for each throughput sample; lower = smoother
22
+ RATE_AFTER_SECONDS = 0.5 # don't show a rate until the step has run this long
23
+ ETA_AFTER_SECONDS = 1 # don't show an ETA until the step has run this long
24
+ SHORT_STEP_SECONDS = 2 # skip the rate/ETA for steps expected to finish within this
25
+ # Columns of a live row. ETA is left-aligned (it has its own "ETA " label);
26
+ # the rest are right-aligned. A bold percent takes the place of a progress
27
+ # bar: it lines up in columns, works for several steps at once, and avoids
28
+ # block characters that don't look the same on every terminal. Concurrency
29
+ # sits last so it can't shift the columns the collapsed (finished) rows share.
30
+ COLUMNS = %i[percent count elapsed eta rate concurrency].freeze
31
+ LEFT_ALIGNED = %i[eta].freeze
32
+
33
+ Step =
34
+ Struct.new(
35
+ :title,
36
+ :total,
37
+ :current,
38
+ :skip_count,
39
+ :warning_count,
40
+ :error_count,
41
+ :state,
42
+ :started_at,
43
+ :finished_at,
44
+ :rate,
45
+ :rate_sampled_at,
46
+ :rate_sampled_current,
47
+ :concurrency,
48
+ keyword_init: true,
49
+ )
50
+
51
+ def initialize(output: $stdout, width: nil, clock: nil, titles: [])
52
+ @output = output
53
+ @forced_width = width
54
+ @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
55
+ @terminal_columns = terminal_columns
56
+ # NO_COLOR disables color only when set to a non-empty value.
57
+ @color = ENV["NO_COLOR"].to_s.empty?
58
+ # Translated once here, not every frame.
59
+ @counting_label = I18n.t("mini_progress.counting")
60
+ @eta_label = I18n.t("mini_progress.eta")
61
+ @steps = {}
62
+ @pending_permanent = []
63
+ @live_count = 0
64
+ @last_live = nil
65
+ @resize_pending = false
66
+ @finalizing = false
67
+ @frame_buffer = +"" # reused on each repaint instead of making a new one
68
+ # Reserve the column widths up front: a finished row scrolls into the
69
+ # history and can't be realigned, so every column has to start at the
70
+ # same place from the first row on. Percent is reserved on every row
71
+ # (blank when finished) so finished and running totals share a column.
72
+ @title_width = [
73
+ [TITLE_WIDTH, *titles.map { |title| Ansi.width(title) }].max,
74
+ MAX_TITLE_WIDTH,
75
+ ].min
76
+ @column_widths = {
77
+ percent: PERCENT_WIDTH,
78
+ count: COUNT_WIDTH,
79
+ elapsed: TIME_WIDTH,
80
+ eta: 0,
81
+ rate: 0,
82
+ concurrency: 0,
83
+ }
84
+ end
85
+
86
+ # --- lifecycle (called by the render thread) ---
87
+
88
+ def on_start
89
+ emit(Ansi::HIDE_CURSOR)
90
+ @output.flush
91
+ end
92
+
93
+ # Writes to the terminal. When NO_COLOR is set, it removes the color codes
94
+ # (SGR) but keeps the cursor and erase codes.
95
+ def emit(string)
96
+ @output.write(@color ? string : string.gsub(Ansi::SGR, ""))
97
+ end
98
+
99
+ def mark_resize
100
+ @resize_pending = true
101
+ end
102
+
103
+ def consume_resize
104
+ return unless @resize_pending
105
+ @resize_pending = false
106
+ @terminal_columns = terminal_columns
107
+ @last_live = nil # force a repaint at the new width
108
+ return if @live_count == 0
109
+
110
+ # After a resize the old region is still at least `@live_count` rows
111
+ # tall (a rewrap can only make it taller, never shorter), so moving up
112
+ # `@live_count - 1` rows keeps us inside our own rows. Erase to the end
113
+ # of the screen and let the next repaint draw again at the new width.
114
+ out = +""
115
+ out << Ansi.cursor_up(@live_count - 1) if @live_count > 1
116
+ out << "\r" << Ansi::ERASE_BELOW
117
+ emit(out)
118
+ @live_count = 0
119
+ end
120
+
121
+ # Mark any step that is still running as interrupted, remove the live
122
+ # region, and restore the terminal. Safe to call more than once.
123
+ def finalize
124
+ return if @finalized
125
+ @finalized = true
126
+ @steps.each_value do |step|
127
+ next unless running?(step)
128
+ step.finished_at = now
129
+ step.state = :interrupted
130
+ @pending_permanent << collapsed_line(step)
131
+ end
132
+ repaint(final: true)
133
+ emit(Ansi::SHOW_CURSOR)
134
+ @output.flush
135
+ end
136
+
137
+ # --- model updates ---
138
+
139
+ def apply(event)
140
+ case event[0]
141
+ when :start
142
+ _, id, title = event
143
+ @steps[id] = Step.new(
144
+ title:,
145
+ total: nil,
146
+ current: 0,
147
+ skip_count: 0,
148
+ warning_count: 0,
149
+ error_count: 0,
150
+ state: :starting,
151
+ started_at: now,
152
+ finished_at: nil,
153
+ rate: nil,
154
+ rate_sampled_at: nil,
155
+ rate_sampled_current: 0,
156
+ concurrency: 1,
157
+ )
158
+ when :concurrency
159
+ _, id, count = event
160
+ step = @steps[id]
161
+ step.concurrency = count if step
162
+ when :progress_begin
163
+ _, id, max_progress = event
164
+ step = @steps[id]
165
+ return unless step && running?(step)
166
+ step.total = max_progress
167
+ step.state = :running
168
+ # The step clock keeps running from :start — the planning/counting
169
+ # seconds belong to the step's elapsed and final duration (the plain
170
+ # reporter counts them too). Only the rate anchors reset here, so
171
+ # items/s and the ETA measure the work window, not the counting.
172
+ step.rate_sampled_at = now
173
+ step.rate_sampled_current = step.current
174
+ when :progress
175
+ _, id, current, skip_count, warning_count, error_count = event
176
+ step = @steps[id]
177
+ return unless step && step.state == :running
178
+ step.current = current
179
+ step.skip_count = skip_count
180
+ step.warning_count = warning_count
181
+ step.error_count = error_count
182
+ when :notice
183
+ _, id, message = event
184
+ step = @steps[id]
185
+ notice_lines(step && step.title, message).each { |line| @pending_permanent << line }
186
+ when :finish
187
+ _, id, outcome = event
188
+ step = @steps.delete(id) # no longer needed; its line is permanent now
189
+ return unless step
190
+ step.finished_at = now
191
+ step.state = outcome # :done, :interrupted, or :failed
192
+ @pending_permanent << collapsed_line(step)
193
+ when :finalizing_begin
194
+ @finalizing = true
195
+ when :finalizing_end
196
+ @finalizing = false
197
+ when :summary
198
+ _, runtime, total, failed, skipped = event
199
+ @pending_permanent << summary_line(runtime, total, failed, skipped)
200
+ end
201
+ end
202
+
203
+ # --- rendering ---
204
+
205
+ # Between frames the cursor rests at column 0 of the last live line. Each
206
+ # frame: move up to the top of the region, print any new permanent lines
207
+ # (these push the region down and scroll into the history), redraw the live
208
+ # lines, then erase leftover lines if the region got shorter. Erasing the
209
+ # whole line on every redraw removes old characters and clears wrap flags. A
210
+ # frame that is the same as the last one is skipped.
211
+ def repaint(final: false)
212
+ permanent = @pending_permanent
213
+ @pending_permanent = []
214
+ live = final ? [] : format_live(running_steps)
215
+ live += [finalizing_line] if @finalizing && !final
216
+
217
+ return if permanent.empty? && live.empty? && @live_count == 0
218
+ return if !final && permanent.empty? && live == @last_live
219
+
220
+ out = @frame_buffer.clear
221
+ out << Ansi.cursor_up(@live_count - 1) if @live_count > 1
222
+ out << "\r"
223
+
224
+ permanent.each { |line| out << Ansi::ERASE_LINE << fit_to_width(line) << "\r\n" }
225
+
226
+ live.each_with_index do |line, index|
227
+ out << Ansi::ERASE_LINE << fit_to_width(line)
228
+ out << "\r\n" if index < live.size - 1
229
+ end
230
+
231
+ # This frame wrote `permanent.size + live.size` rows over the old live
232
+ # region, so only the old rows beyond that are stale and need erasing.
233
+ leftover = [@live_count - permanent.size - live.size, 0].max
234
+ if leftover > 0
235
+ leftover.times { out << "\r\n" << Ansi::ERASE_LINE }
236
+ out << Ansi.cursor_up(leftover) unless final
237
+ end
238
+ out << "\r"
239
+
240
+ emit(out)
241
+ @output.flush
242
+ @live_count = live.size
243
+ @last_live = live
244
+ end
245
+
246
+ private
247
+
248
+ def now
249
+ @clock.call
250
+ end
251
+
252
+ def running?(step)
253
+ %i[starting running].include?(step.state)
254
+ end
255
+
256
+ def running_steps
257
+ @steps.values.select { |step| running?(step) }
258
+ end
259
+
260
+ # Keep lines two columns short of the window width. While the window is
261
+ # being dragged, WINCH arrives in small steps; lines that never reach the
262
+ # new width never wrap, so the resize cleanup stays exact. Staying under the
263
+ # width also avoids the wrap glitch in the last column.
264
+ def fit_to_width(line)
265
+ Ansi.truncate(line, [@terminal_columns - 2, 8].max)
266
+ end
267
+
268
+ def format_live(steps)
269
+ return [] if steps.empty?
270
+ rows = steps.map { |step| row_fields(step) }
271
+ widths = reserve_column_widths(rows)
272
+ glyph = spinner # animated; same frame for every live row
273
+ rows.zip(widths).map { |row, row_widths| build_live_line(row, row_widths, glyph) }
274
+ end
275
+
276
+ # Measure each cell once and grow the reserved column widths to fit.
277
+ # Returns the per-cell widths so the padding can reuse them instead of
278
+ # stripping SGR a second time.
279
+ def reserve_column_widths(rows)
280
+ widths = rows.map { |row| COLUMNS.map { |column| Ansi.width(row[column]) } }
281
+ COLUMNS.each_with_index do |column, i|
282
+ @column_widths[column] = [
283
+ @column_widths[column],
284
+ *widths.map { |row_widths| row_widths[i] },
285
+ ].max
286
+ end
287
+ widths
288
+ end
289
+
290
+ def build_live_line(row, row_widths, glyph)
291
+ cells =
292
+ COLUMNS.each_with_index.filter_map do |column, i|
293
+ next if @column_widths[column] == 0
294
+ align = LEFT_ALIGNED.include?(column) ? :left : :right
295
+ Ansi.pad_to(row[column], row_widths[i], @column_widths[column], align)
296
+ end
297
+ line = +"#{glyph} #{title_field(row[:title])} "
298
+ line << cells.join(" ")
299
+ line << row[:annot] unless row[:annot].empty?
300
+ line
301
+ end
302
+
303
+ # Builds one running step as a hash of column strings (blank where a
304
+ # column doesn't apply). The spinner in front shows it's alive (added in
305
+ # format_live). The bold percent and the total stand in for a progress bar;
306
+ # the count column shows the total (not current/max), because the percent
307
+ # already shows how far along it is. The extra numbers (elapsed, ETA, rate)
308
+ # are dimmed.
309
+ def row_fields(step)
310
+ elapsed = now - step.started_at
311
+ fields = {
312
+ title: step.title,
313
+ percent: "",
314
+ count: "",
315
+ elapsed: "",
316
+ eta: "",
317
+ rate: "",
318
+ concurrency: concurrency_cell(step.concurrency),
319
+ annot: "",
320
+ }
321
+
322
+ if step.state == :starting # work hasn't started: no total yet
323
+ fields[:count] = "#{Ansi::DIM}#{@counting_label}#{Ansi::RESET}"
324
+ fields[:elapsed] = "#{Ansi::DIM}#{format_duration(elapsed)}#{Ansi::RESET}"
325
+ return fields
326
+ end
327
+
328
+ sample_rate(step)
329
+ remaining = remaining_seconds(step)
330
+ # Skip the rate and ETA for a step that's about to finish anyway — noise.
331
+ short = remaining && elapsed + remaining < SHORT_STEP_SECONDS
332
+
333
+ if step.total&.positive?
334
+ # Floor, don't round: rounding would show "100%" from 99.5% on, which
335
+ # on a large step can mean many seconds of a bar that reads done but
336
+ # isn't. The plain reporter floors too.
337
+ percent = [step.current * 100 / step.total, 100].min
338
+ fields[:percent] = "#{Ansi::BOLD}#{format("%3d%%", percent)}#{Ansi::RESET}"
339
+ fields[:count] = format_count(step.total)
340
+ if remaining && elapsed > ETA_AFTER_SECONDS && !short
341
+ fields[:eta] = "#{Ansi::DIM}#{@eta_label} #{format_duration(remaining)}#{Ansi::RESET}"
342
+ end
343
+ else # unknown or empty total: no percent, just the running count
344
+ fields[:count] = format_count(step.current)
345
+ end
346
+
347
+ fields[:elapsed] = "#{Ansi::DIM}#{format_duration(elapsed)}#{Ansi::RESET}"
348
+ if step.rate && elapsed > RATE_AFTER_SECONDS && !short
349
+ rate = step.rate < 1 ? "<1" : format_count(step.rate.round)
350
+ fields[:rate] = "#{Ansi::DIM}#{rate}/s#{Ansi::RESET}"
351
+ end
352
+ fields[:annot] = annotations(step)
353
+ fields
354
+ end
355
+
356
+ # Smoothed items/s, sampled each frame the count advances and folded into
357
+ # an EMA, so the rate (and ETA) track recent throughput, not the run-long
358
+ # average.
359
+ def sample_rate(step)
360
+ t = now
361
+ window = t - step.rate_sampled_at
362
+ return if window <= 0 || step.current == step.rate_sampled_current
363
+
364
+ per_second = (step.current - step.rate_sampled_current) / window
365
+ step.rate =
366
+ if step.rate
367
+ per_second * RATE_SMOOTHING + step.rate * (1 - RATE_SMOOTHING)
368
+ else
369
+ per_second
370
+ end
371
+ step.rate_sampled_at = t
372
+ step.rate_sampled_current = step.current
373
+ end
374
+
375
+ # Estimated seconds until the step finishes, or nil if we can't tell yet
376
+ # (no total, or no rate sampled).
377
+ def remaining_seconds(step)
378
+ return unless step.total&.positive? && step.rate
379
+ [(step.total - step.current) / step.rate, 0].max
380
+ end
381
+
382
+ # Builds the permanent line for a finished, interrupted, or failed step: a
383
+ # status glyph, a blank percent column (so the count lines up with the live
384
+ # rows' totals), the count, the duration, and a short note at the end for
385
+ # the outcomes that aren't clean.
386
+ def collapsed_line(step)
387
+ duration = (step.finished_at || now) - step.started_at
388
+ count = step.state == :done ? (step.total || step.current) : step.current
389
+
390
+ line = +"#{status_glyph(step)} #{title_field(step.title)} "
391
+ line << padded_columns(format_count(count), duration, dim: true)
392
+ line << outcome_note(step)
393
+ line << annotations(step)
394
+ line
395
+ end
396
+
397
+ # The transient live line shown while the run finishes background work
398
+ # after every step is done. The spinner animates it.
399
+ def finalizing_line
400
+ "#{spinner} #{Ansi::DIM}#{I18n.t("mini_progress.finishing_up")}#{Ansi::RESET}"
401
+ end
402
+
403
+ # The permanent end-of-run line: a Σ, the total runtime in the elapsed
404
+ # column (so it lines up under the per-step durations), and the step tally.
405
+ def summary_line(runtime, total, failed, skipped)
406
+ columns = padded_columns("", runtime, dim: false)
407
+ line = +"#{Ansi::BOLD}Σ#{Ansi::RESET} #{title_field(I18n.t("mini_progress.total"))} "
408
+ line << columns << summary_tally(total, failed, skipped)
409
+ line
410
+ end
411
+
412
+ def summary_tally(total, failed, skipped)
413
+ note = +" #{I18n.t("mini_progress.steps", count: total, number: total)}"
414
+ if failed > 0
415
+ note << " #{Ansi::RED}#{I18n.t("mini_progress.steps_failed", number: failed)}#{Ansi::RESET}"
416
+ end
417
+ if skipped > 0
418
+ note << " #{Ansi::YELLOW}#{I18n.t("mini_progress.steps_skipped", number: skipped)}#{Ansi::RESET}"
419
+ end
420
+ note
421
+ end
422
+
423
+ def status_glyph(step)
424
+ case step.state
425
+ when :done
426
+ "#{Ansi::GREEN}✓#{Ansi::RESET}"
427
+ when :failed
428
+ "#{Ansi::RED}✗#{Ansi::RESET}"
429
+ else # :interrupted — no glyph; the note says what happened
430
+ " "
431
+ end
432
+ end
433
+
434
+ def outcome_note(step)
435
+ case step.state
436
+ when :failed
437
+ " #{Ansi::RED}#{I18n.t("mini_progress.failed")}#{Ansi::RESET}"
438
+ when :interrupted
439
+ if step.total&.positive?
440
+ percent = [(step.current.to_f / step.total * 100).round, 100].min
441
+ " #{Ansi::YELLOW}#{I18n.t("mini_progress.interrupted_at", percent:)}#{Ansi::RESET}"
442
+ else
443
+ " #{Ansi::YELLOW}#{I18n.t("mini_progress.interrupted")}#{Ansi::RESET}"
444
+ end
445
+ else
446
+ ""
447
+ end
448
+ end
449
+
450
+ # The blank-percent, count, and time triple shared by the finished rows
451
+ # and the run summary. It uses the same widths as the live rows, so every
452
+ # count and duration lines up down the whole display. The percent is
453
+ # always blank here; a finished row dims its duration, the summary doesn't.
454
+ def padded_columns(count_text, duration, dim:)
455
+ time = Ansi.pad(format_duration(duration), @column_widths[:elapsed], :right)
456
+ time = "#{Ansi::DIM}#{time}#{Ansi::RESET}" if dim
457
+ [
458
+ Ansi.pad("", @column_widths[:percent]),
459
+ Ansi.pad(count_text, @column_widths[:count], :right),
460
+ time,
461
+ ].join(" ")
462
+ end
463
+
464
+ # A notice becomes one permanent line per line of its message. Messages
465
+ # can carry newlines (exception messages often do), and an embedded "\n"
466
+ # has zero display width — it would slip through `fit_to_width` and move
467
+ # the cursor a row the live-region math doesn't account for. The title is
468
+ # deliberately not padded to the table's title column (unlike the step
469
+ # rows): a notice is prose, not a table row.
470
+ def notice_lines(title, message)
471
+ lines = message.to_s.split("\n").map(&:rstrip).reject(&:empty?)
472
+ # `[""]` keeps a title-only line when the message is empty.
473
+ lines = [""] if lines.empty?
474
+ prefix = title ? "#{title} " : ""
475
+
476
+ lines.each_with_index.map do |text, index|
477
+ # Continuation lines get a two-space indent instead of the title.
478
+ lead = index == 0 ? prefix : " "
479
+ "#{lead}#{Ansi::DIM}#{text}#{Ansi::RESET}"
480
+ end
481
+ end
482
+
483
+ # The skip, warning, and error labels, shown only when the count is above
484
+ # 0, using the shared `mini_progress.*` translations. Each one has its own
485
+ # glyph, not just a color, so it can be read without seeing color. The
486
+ # error glyph is ⊗, not the status ✗, so the two don't look alike.
487
+ def annotations(step)
488
+ return "" if step.skip_count == 0 && step.warning_count == 0 && step.error_count == 0
489
+
490
+ out = +""
491
+ if step.skip_count > 0
492
+ out << " #{Ansi::CYAN}⊘ #{count_label(:skips, step.skip_count)}#{Ansi::RESET}"
493
+ end
494
+ if step.warning_count > 0
495
+ out << " #{Ansi::YELLOW}⚠ #{count_label(:warnings, step.warning_count)}#{Ansi::RESET}"
496
+ end
497
+ if step.error_count > 0
498
+ out << " #{Ansi::RED}⊗ #{count_label(:errors, step.error_count)}#{Ansi::RESET}"
499
+ end
500
+ out
501
+ end
502
+
503
+ # The title comes after the status glyph, padded to the reserved width so
504
+ # the columns after it line up across rows (each caller adds a " "
505
+ # separator).
506
+ def title_field(title)
507
+ Ansi.pad(ellipsize(title, @title_width), @title_width, :left)
508
+ end
509
+
510
+ # Shortens a title to fit `max` display columns, ending it with "…". Titles
511
+ # are plain text, so we can step through them character by character.
512
+ def ellipsize(title, max)
513
+ return title if Ansi.width(title) <= max
514
+
515
+ out = +""
516
+ used = 0
517
+ title.each_grapheme_cluster do |cluster|
518
+ w = Unicode::DisplayWidth.of(cluster)
519
+ break if used + w > max - 1 # leave a cell for the ellipsis
520
+ out << cluster
521
+ used += w
522
+ end
523
+ "#{out}…"
524
+ end
525
+
526
+ def spinner
527
+ SPINNER[(now * SPINNER_RATE).to_i % SPINNER.size]
528
+ end
529
+
530
+ def concurrency_cell(count)
531
+ return "" if count <= 1
532
+
533
+ "#{Ansi::MAGENTA}#{count}×#{Ansi::RESET}"
534
+ end
535
+
536
+ def terminal_columns
537
+ @forced_width || @output.winsize[1]
538
+ rescue StandardError
539
+ 80
540
+ end
541
+ end
542
+ end
543
+ end