kawaii_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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5e9c1bc600fc3b46f036b6f1f96962c4882eebcb71d976f0a8bb635dbf431560
4
+ data.tar.gz: b3a07e8399e5f450ab3dcf523c156b9ff25a6c5140dec80bfb6c3be3d5bc466e
5
+ SHA512:
6
+ metadata.gz: 25b15248176b06a0b445a8a1cfe9f14f0d7b97c43d44147978d820fe4ba8643f2cda64fbafc5f4601ee1d9363759bca4b972b4d4b99adc85689dadc3f4137ac8
7
+ data.tar.gz: a89c4d7d591e8ef15edb55369264b97799ab9bf2058f70792f0c552dfe3c061929e56277a36b15c27ca7473d09fe2165bb2c1e3cfa342c3ed1c7170963aa6db7
data/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Elijah S. Krukowski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,386 @@
1
+ # KawaiiProgress (˶ᵔ ᵕ ᵔ˶)
2
+
3
+ ![CI](https://github.com/bodrovis/kawaii_progress/actions/workflows/ci.yml/badge.svg)
4
+ [![Code Coverage](https://qlty.sh/gh/bodrovis/projects/kawaii_progress/coverage.svg)](https://qlty.sh/gh/bodrovis/projects/kawaii_progress)
5
+ [![Maintainability](https://qlty.sh/gh/bodrovis/projects/kawaii_progress/maintainability.svg)](https://qlty.sh/gh/bodrovis/projects/kawaii_progress)
6
+
7
+ A little Ruby gem for making long-running tasks a little less boring.
8
+
9
+ KawaiiProgress gives you customizable terminal progress bars, estimated completion times, and thread-safe updates without pulling in a pile of dependencies. Feed some cats, process a million records, or watch your background workers do their thing. At least now you know how far they've got.
10
+
11
+ ```text
12
+ Processing [████████████░░░░░░░░░░░░░░░░░░] 40/100 40% ETA 15s
13
+ Downloading [========------------] 40% | 12.5 items/s
14
+ Feeding cats ♥♥♥♥♥♥♡♡♡♡ 6/10 | ETA 2s
15
+ ```
16
+
17
+ Small gem. Big kawaii energy. ♡
18
+
19
+ ## Features
20
+
21
+ - Zero third-party runtime dependencies and Ruby 3.4+ support.
22
+ - Thread-safe updates to a single progress bar, even from multiple workers.
23
+ - Configurable refresh intervals to avoid overwhelming the terminal.
24
+ - Custom symbols and format templates with progress, speed, elapsed time, and ETA.
25
+ - Automatic terminal width detection and resizing (optional).
26
+ - Automatic TTY detection and final-only output when redirected to a file or CI log.
27
+ - An enumerable helper that takes care of updating and finishing the bar for you.
28
+ - Immutable progress snapshots, injectable monotonic clocks, and custom renderers.
29
+
30
+ ## Installation
31
+
32
+ Add the gem to your project:
33
+
34
+ ```sh
35
+ bundle add kawaii_progress
36
+ ```
37
+
38
+ Or install it directly:
39
+
40
+ ```sh
41
+ gem install kawaii_progress
42
+ ```
43
+
44
+ KawaiiProgress requires Ruby 3.4 or newer.
45
+
46
+ ## Quick start
47
+
48
+ The easiest way to track a collection is with `KawaiiProgress.each`:
49
+
50
+ ```ruby
51
+ require 'kawaii_progress'
52
+
53
+ KawaiiProgress.each(1..50, title: 'Feeding cats') do |_cat|
54
+ sleep 0.05 # Pretend we're doing something useful.
55
+ end
56
+ ```
57
+
58
+ That's it. KawaiiProgress determines the total, advances the bar after each completed iteration, and finishes it when the loop exits.
59
+
60
+ ### Manual progress updates
61
+
62
+ For more control, create a `KawaiiProgress::Bar` yourself:
63
+
64
+ ```ruby
65
+ require 'kawaii_progress'
66
+
67
+ bar = KawaiiProgress::Bar.new('Processing', total: 100)
68
+
69
+ begin
70
+ 100.times do
71
+ sleep 0.03
72
+ bar.advance
73
+ end
74
+ ensure
75
+ bar.finish
76
+ end
77
+ ```
78
+
79
+ `advance` increments the counter by one by default. Pass a non-negative integer to advance by a different amount:
80
+
81
+ ```ruby
82
+ bar.advance(5)
83
+ ```
84
+
85
+ The counter never exceeds the specified total. Reaching the total redraws the bar but does not automatically finish it. Call `finish` to finalize the output and freeze the elapsed time.
86
+
87
+ You can finish a bar early, too. If your task stops at 42%, the bar will still say 42%. No fake achievements here.
88
+
89
+ Calling `finish` more than once has no effect, and valid progress updates after finishing are ignored.
90
+
91
+ ## Make it kawaii
92
+
93
+ The default block characters are nice, but why stop there?
94
+
95
+ ```ruby
96
+ KawaiiProgress.each(
97
+ 1..50,
98
+ title: 'Feeding cats',
99
+ width: 10,
100
+ filled: '♥',
101
+ empty: '♡',
102
+ format: '%{title} %{bar} %{percentage}%% | ETA %{eta}'
103
+ ) do |_cat|
104
+ sleep 0.05
105
+ end
106
+ ```
107
+
108
+ ```text
109
+ Feeding cats ♥♥♥♥♥♥♡♡♡♡ 60% | ETA 1s
110
+ ```
111
+
112
+ Prefer ASCII? We have you covered:
113
+
114
+ ```ruby
115
+ bar = KawaiiProgress::Bar.new(
116
+ 'Downloading',
117
+ total: 100,
118
+ width: 20,
119
+ filled: '=',
120
+ empty: '-',
121
+ format: '%{title} [%{bar}] %{percentage}%% | %{rate} items/s'
122
+ )
123
+ ```
124
+
125
+ ```text
126
+ Downloading [========------------] 40% | 12.5 items/s
127
+ ```
128
+
129
+ You don't even have to include the graphical bar in your template. A plain counter, a timer, or a line full of hearts is perfectly fine.
130
+
131
+ ### Format placeholders
132
+
133
+ Templates use Ruby's named format tokens. The default template is:
134
+
135
+ ```ruby
136
+ '%{title} [%{bar}] %{current}/%{total} %{percentage}%% ETA %{eta}'
137
+ ```
138
+
139
+ | Placeholder | Description | Example |
140
+ | --- | --- | --- |
141
+ | `%{title}` | Task title | `Feeding cats` |
142
+ | `%{bar}` | Graphical progress bar | `♥♥♥♡♡` |
143
+ | `%{current}` | Number of completed items | `60` |
144
+ | `%{total}` | Total number of items | `100` |
145
+ | `%{percentage}` | Rounded completion percentage | `60` |
146
+ | `%{eta}` | Estimated remaining time | `20s` |
147
+ | `%{elapsed}` | Elapsed time | `30s` |
148
+ | `%{rate}` | Average items processed per second | `2.0` |
149
+ | `%%` | Literal percent sign | `%` |
150
+
151
+ Remember to use `%%` if you want a literal percent sign in the output. Unknown named placeholders raise a `KeyError` when the template is rendered.
152
+
153
+ ## Configuration
154
+
155
+ Pass these options to `Bar.new` or, where applicable, to `KawaiiProgress.each`:
156
+
157
+ | Option | Default | Description |
158
+ | --- | --- | --- |
159
+ | `total` | Required for `Bar` | Non-negative integer representing the expected work. In `.each`, inferred from the collection when possible. |
160
+ | `enabled` | `true` | Enables rendering. When `false`, progress is still tracked. |
161
+ | `width` | `30` | Positive number of bar segments, or `:auto`. |
162
+ | `filled` | `'█'` | Non-empty string representing a completed segment. |
163
+ | `empty` | `'░'` | Non-empty string representing an incomplete segment. |
164
+ | `format` | Default template above | Template used to build the progress line. |
165
+ | `output` | `$stderr` | Output stream supporting `print`, `puts`, and `flush`. |
166
+ | `interactive` | `nil` | Automatically detects TTY when `nil`; override with `true` or `false`. |
167
+ | `refresh_interval` | `0.1` | Minimum time between regular redraws, in seconds. Use `0` to disable throttling. |
168
+ | `clock` | `KawaiiProgress::Clock` | Custom monotonic clock exposing a `now` method returning seconds. |
169
+ | `renderer` | Default renderer | Custom object implementing `render(snapshot)` and `finish(snapshot)`. |
170
+
171
+ `Bar.new` takes the title as its first positional argument. `KawaiiProgress.each` accepts `title:` as a keyword argument, defaulting to `'Processing'`.
172
+
173
+ ### Automatic width
174
+
175
+ Use `width: :auto` to let the bar adapt to the terminal and the rest of your format template:
176
+
177
+ ```ruby
178
+ KawaiiProgress.each(1..100, width: :auto) do
179
+ sleep 0.05
180
+ end
181
+ ```
182
+
183
+ The width is recalculated when the bar is redrawn. If the terminal dimensions are unavailable or output is non-interactive, KawaiiProgress falls back to 30 segments.
184
+
185
+ Display width is estimated using Unicode grapheme clusters and ignores ANSI styling sequences. Wide characters and emoji may take up more than one terminal column, so automatic sizing is approximate. A very long title or template can still wrap even when the bar itself has no segments. ASCII symbols are the safest option when exact alignment matters.
186
+
187
+ ### Refresh intervals
188
+
189
+ Updating a counter is cheap. Redrawing a terminal thousands of times per second? Not so much.
190
+
191
+ KawaiiProgress updates the counter on every valid `advance` call while the task is running, but normally redraws the bar no more than once per refresh interval. The initial and final states, as well as the transition to the specified total, bypass throttling.
192
+
193
+ ```ruby
194
+ bar = KawaiiProgress::Bar.new(
195
+ 'Crunching numbers',
196
+ total: 100_000,
197
+ refresh_interval: 0.25
198
+ )
199
+
200
+ 100_000.times { bar.advance }
201
+ bar.finish
202
+ ```
203
+
204
+ There are no background refresh threads. Redraws happen in response to progress updates, so the display will not update itself while your task is idle.
205
+
206
+ ### Output and interactive mode
207
+
208
+ By default, progress is written to standard error (`$stderr`), leaving standard output available for your application's actual results.
209
+
210
+ | `interactive` | Behavior |
211
+ | --- | --- |
212
+ | `nil` | Detect whether the output is a TTY. |
213
+ | `true` | Redraw the current line using ANSI escape sequences. |
214
+ | `false` | Suppress intermediate output and write a single final line. |
215
+
216
+ For example, capture the final progress line in memory:
217
+
218
+ ```ruby
219
+ require 'stringio'
220
+ require 'kawaii_progress'
221
+
222
+ output = StringIO.new
223
+
224
+ KawaiiProgress.each(1..10, output: output) do
225
+ sleep 0.01
226
+ end
227
+
228
+ puts output.string
229
+ ```
230
+
231
+ Or set `enabled: false` to suppress rendering entirely without losing progress tracking. A task with `total: 0` also produces no progress output.
232
+
233
+ ## Working with collections
234
+
235
+ `KawaiiProgress.each` works with arrays, hashes, ranges, and other objects that implement `each`.
236
+
237
+ If the collection exposes a non-negative integer `size`, KawaiiProgress uses it as the total. Otherwise, supply `total:` explicitly:
238
+
239
+ ```ruby
240
+ KawaiiProgress.each(
241
+ File.foreach('records.txt'),
242
+ title: 'Reading records',
243
+ total: 1_000
244
+ ) do |line|
245
+ process(line) # Your own processing method.
246
+ end
247
+ ```
248
+
249
+ KawaiiProgress does not traverse a collection in advance to count its items. Tasks with an unknown total require an explicit estimate; the total does not limit how many items are actually iterated over.
250
+
251
+ Without a block, `.each` returns an `Enumerator`, so you can chain standard Ruby enumerable methods:
252
+
253
+ ```ruby
254
+ squares = KawaiiProgress.each(1..10, title: 'Doing maths').map do |number|
255
+ number**2
256
+ end
257
+ ```
258
+
259
+ The progress bar is created when iteration begins. During block-based iteration, exceptions propagate normally and the bar is finalized when the loop exits, including on `break`. Only iterations that return normally are counted as completed.
260
+
261
+ ## Concurrent updates
262
+
263
+ Got a bunch of workers? Let them share one progress bar:
264
+
265
+ ```ruby
266
+ bar = KawaiiProgress::Bar.new('Parallel workers', total: 100)
267
+
268
+ begin
269
+ threads = Array.new(4) do
270
+ Thread.new do
271
+ 25.times do
272
+ sleep 0.04
273
+ bar.advance
274
+ end
275
+ end
276
+ end
277
+
278
+ threads.each(&:value)
279
+ ensure
280
+ bar.finish
281
+ end
282
+ ```
283
+
284
+ Updates and rendering are synchronized within each bar to prevent lost increments and interleaved redraws from its workers. Independent bars writing to the same stream are not coordinated; multi-line progress displays are not supported at present.
285
+
286
+ ## Inspecting progress
287
+
288
+ You can read the current state through the bar's public methods:
289
+
290
+ ```ruby
291
+ bar.current # Completed items
292
+ bar.total # Expected items
293
+ bar.progress # Completion ratio, e.g. 0.4
294
+ bar.percentage # Rounded percentage, e.g. 40
295
+ bar.elapsed # Elapsed seconds
296
+ bar.rate # Average items per second
297
+ bar.eta # Estimated remaining seconds, or nil
298
+ bar.enabled? # Whether rendering is enabled
299
+ bar.finished? # Whether finish has been called
300
+ ```
301
+
302
+ If you need several consistent metrics at once, capture an immutable snapshot:
303
+
304
+ ```ruby
305
+ state = bar.snapshot
306
+
307
+ puts "Processed #{state.current}/#{state.total}"
308
+ puts "Average speed: #{state.rate.round(2)} items/s"
309
+ puts "Elapsed: #{state.elapsed.round(2)}s"
310
+ ```
311
+
312
+ All timing metrics in a snapshot are based on the same captured timestamp. Later updates do not change an existing snapshot. The default clock is monotonic, so system clock adjustments do not affect elapsed time calculations.
313
+
314
+ ETA is estimated using the average processing rate since the task began. It is unknown until a positive rate can be calculated. When a task is finished early, its actual progress and timing metrics are preserved.
315
+
316
+ ### Custom renderers
317
+
318
+ Want to send progress somewhere other than a terminal? Implement your own renderer:
319
+
320
+ ```ruby
321
+ class PlainRenderer
322
+ def render(snapshot)
323
+ puts "#{snapshot.title}: #{snapshot.percentage}%"
324
+ end
325
+
326
+ def finish(snapshot)
327
+ render(snapshot)
328
+ end
329
+ end
330
+
331
+ bar = KawaiiProgress::Bar.new(
332
+ 'Processing',
333
+ total: 10,
334
+ renderer: PlainRenderer.new
335
+ )
336
+
337
+ 10.times { bar.advance }
338
+ bar.finish
339
+ ```
340
+
341
+ A renderer receives a `KawaiiProgress::Snapshot`, not the mutable bar itself. Configure custom renderers directly rather than combining `renderer:` with built-in rendering options such as `width:` or `format:`.
342
+
343
+ Renderer callbacks run synchronously under the bar's lock during updates and finalization. Do not call synchronized methods on the same bar from inside a renderer callback.
344
+
345
+ ## Samples
346
+
347
+ Want to see the little thing in action before using it in your own project? Run any of the scripts in [`samples/`](samples/) from the repository root:
348
+
349
+ ```sh
350
+ ruby samples/basic.rb
351
+ ruby samples/custom_format.rb
352
+ ruby samples/auto_width.rb
353
+ ruby samples/threads.rb
354
+ ```
355
+
356
+ | Sample | What it demonstrates |
357
+ | --- | --- |
358
+ | [`basic.rb`](samples/basic.rb) | Manual updates and finalization. |
359
+ | [`custom_format.rb`](samples/custom_format.rb) | ASCII bars, hearts, custom templates, and variable delays. |
360
+ | [`auto_width.rb`](samples/auto_width.rb) | Resize your terminal while the task runs. |
361
+ | [`enumerable.rb`](samples/enumerable.rb) | Enumerable integration, `map`, and explicitly sized sources. |
362
+ | [`threads.rb`](samples/threads.rb) | Multiple workers sharing a single bar. |
363
+ | [`throttling.rb`](samples/throttling.rb) | 100,000 updates without 100,000 redraws. |
364
+ | [`early_finish.rb`](samples/early_finish.rb) | Exceptions and interrupted iteration. |
365
+ | [`non_interactive.rb`](samples/non_interactive.rb) | Final-only output, captured output, and disabled rendering. |
366
+
367
+ The samples load the local library directly. No gem installation, network requests, or actual cats are required. Sadly.
368
+
369
+ ## Development and contributing
370
+
371
+ Bug reports, ideas, and pull requests are welcome! To get started, clone the repository and install its development dependencies:
372
+
373
+ ```sh
374
+ bundle install
375
+ bundle exec rspec
376
+ bundle exec rubocop
377
+ bundle exec reek
378
+ ```
379
+
380
+ If you're reporting a terminal rendering issue, please include your Ruby version, operating system, terminal, and a small reproducible example. Terminal quirks can be surprisingly un-kawaii.
381
+
382
+ ## License
383
+
384
+ KawaiiProgress is available under the [MIT License](LICENSE.md).
385
+
386
+ Made with Ruby, a little patience, and a whole lot of ♡.
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ module KawaiiProgress
6
+ # Tracks task progress, synchronizes state changes, and coordinates
7
+ # rendering using immutable snapshots and configurable refresh intervals.
8
+ class Bar
9
+ extend Forwardable
10
+
11
+ DEFAULT_REFRESH_INTERVAL = 0.1
12
+
13
+ attr_reader :title, :total
14
+
15
+ def_delegators :snapshot, :progress, :percentage, :elapsed, :rate, :eta
16
+
17
+ def initialize(
18
+ title,
19
+ total:,
20
+ enabled: true,
21
+ clock: Clock,
22
+ refresh_interval: DEFAULT_REFRESH_INTERVAL,
23
+ renderer: nil,
24
+ **render_options
25
+ )
26
+ validate_total!(total)
27
+
28
+ @title = title.to_s.dup.freeze
29
+ @total = total
30
+ @enabled = enabled
31
+ @clock = clock
32
+ @throttle = RefreshThrottle.new(interval: refresh_interval)
33
+ @renderer = resolve_renderer(renderer, render_options)
34
+
35
+ @current = 0
36
+ @started_at = clock.now
37
+ @finished_at = nil
38
+ @mutex = Mutex.new
39
+
40
+ render(now: started_at)
41
+ end
42
+
43
+ def advance(step = 1)
44
+ validate_step!(step)
45
+
46
+ mutex.synchronize do
47
+ return if finished_at
48
+
49
+ previous = @current
50
+ @current = [@current + step, total].min
51
+
52
+ render(force: previous < total && @current == total)
53
+ end
54
+ end
55
+
56
+ def finish
57
+ mutex.synchronize do
58
+ return if finished_at
59
+
60
+ @finished_at = clock.now
61
+
62
+ renderer.finish(build_snapshot(finished_at)) if renderable?
63
+ end
64
+ end
65
+
66
+ def current
67
+ mutex.synchronize { @current }
68
+ end
69
+
70
+ def enabled?
71
+ @enabled
72
+ end
73
+
74
+ def finished?
75
+ mutex.synchronize { !finished_at.nil? }
76
+ end
77
+
78
+ def snapshot
79
+ mutex.synchronize do
80
+ build_snapshot(finished_at || clock.now)
81
+ end
82
+ end
83
+
84
+ private
85
+
86
+ attr_reader :started_at, :finished_at, :mutex, :clock, :renderer, :throttle
87
+
88
+ def resolve_renderer(renderer, options)
89
+ return Renderer.new(**options) if renderer.nil?
90
+ return renderer if options.empty?
91
+
92
+ raise ArgumentError, 'Cannot combine a custom renderer with rendering options'
93
+ end
94
+
95
+ def renderable?
96
+ enabled? && total.positive?
97
+ end
98
+
99
+ def render(force: false, now: nil)
100
+ return unless renderable?
101
+
102
+ now ||= clock.now
103
+
104
+ return unless force || throttle.due?(now)
105
+
106
+ renderer.render(build_snapshot(now))
107
+ throttle.mark_rendered(now)
108
+ end
109
+
110
+ # Called under the mutex or during initialization, before the bar
111
+ # is exposed to other threads.
112
+ def build_snapshot(now)
113
+ Snapshot.new(
114
+ title: title,
115
+ total: total,
116
+ current: @current,
117
+ elapsed: now - started_at,
118
+ finished: !finished_at.nil?
119
+ )
120
+ end
121
+
122
+ def validate_total!(total)
123
+ return if total.is_a?(Integer) && total >= 0
124
+
125
+ raise ArgumentError, 'Total must be a non-negative integer'
126
+ end
127
+
128
+ def validate_step!(step)
129
+ return if step.is_a?(Integer) && step >= 0
130
+
131
+ raise ArgumentError, 'Step must be a non-negative integer'
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KawaiiProgress
4
+ # Provides monotonic timestamps for elapsed time calculations.
5
+ # Can be replaced with a custom clock for deterministic testing.
6
+ module Clock
7
+ def self.now
8
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KawaiiProgress
4
+ # Builds a formatted progress line using the current progress state,
5
+ # customizable symbols, and an optional terminal width.
6
+ # Does not perform any I/O operations.
7
+ class Formatter
8
+ DEFAULT_WIDTH = 30
9
+ DEFAULT_FILLED = '█'
10
+ DEFAULT_EMPTY = '░'
11
+ DEFAULT_FORMAT = '%{title} [%{bar}] %{current}/%{total} %{percentage}%% ETA %{eta}'
12
+
13
+ attr_reader :width, :filled, :empty, :template
14
+
15
+ def initialize(
16
+ width: DEFAULT_WIDTH,
17
+ filled: DEFAULT_FILLED,
18
+ empty: DEFAULT_EMPTY,
19
+ format: DEFAULT_FORMAT
20
+ )
21
+ validate_width!(width)
22
+ validate_symbol!(filled)
23
+ validate_symbol!(empty)
24
+ validate_format!(format)
25
+
26
+ @width = width
27
+ @filled = filled
28
+ @empty = empty
29
+ @template = format
30
+ end
31
+
32
+ def format(snapshot, columns: nil)
33
+ values = format_values(snapshot)
34
+ progress = snapshot.progress
35
+
36
+ build_line = lambda do |segments|
37
+ format_with_width(values, progress, segments)
38
+ end
39
+
40
+ build_line.call(resolve_width(columns, &build_line))
41
+ end
42
+
43
+ private
44
+
45
+ def format_values(snapshot)
46
+ {
47
+ title: snapshot.title,
48
+ current: snapshot.current,
49
+ total: snapshot.total,
50
+ percentage: snapshot.percentage,
51
+ eta: format_duration(snapshot.eta),
52
+ elapsed: format_duration(snapshot.elapsed.round),
53
+ rate: Kernel.format('%.1f', snapshot.rate)
54
+ }
55
+ end
56
+
57
+ def format_with_width(values, progress, segments)
58
+ Kernel.format(
59
+ template,
60
+ **values, bar: progress_bar(progress, segments)
61
+ )
62
+ end
63
+
64
+ def resolve_width(columns, &)
65
+ return width unless width == :auto
66
+ return DEFAULT_WIDTH unless columns.is_a?(Integer) && columns.positive?
67
+
68
+ # Reserve one column to reduce the risk of terminal line wrapping.
69
+ fit_width(columns - 1, &)
70
+ end
71
+
72
+ def fit_width(available)
73
+ # Find the largest segment count that fits within the available
74
+ # space, accounting for the entire formatted line.
75
+ overflow = (0..available).bsearch do |segments|
76
+ Terminal.display_width(yield(segments)) > available
77
+ end
78
+
79
+ overflow ? [overflow - 1, 0].max : available
80
+ end
81
+
82
+ def progress_bar(progress, segments)
83
+ completed = (segments * progress).round
84
+ remaining = segments - completed
85
+
86
+ (filled * completed) + (empty * remaining)
87
+ end
88
+
89
+ def format_duration(seconds)
90
+ return '--' if seconds.nil?
91
+ return "#{seconds}s" if seconds < 60
92
+
93
+ minutes, seconds = seconds.divmod(60)
94
+ return "#{minutes}m #{seconds.to_s.rjust(2, '0')}s" if minutes < 60
95
+
96
+ hours, minutes = minutes.divmod(60)
97
+
98
+ "#{hours}h #{minutes.to_s.rjust(2, '0')}m"
99
+ end
100
+
101
+ def validate_width!(width)
102
+ return if width == :auto
103
+ return if width.is_a?(Integer) && width.positive?
104
+
105
+ raise ArgumentError, 'Width must be a positive integer or :auto'
106
+ end
107
+
108
+ def validate_symbol!(symbol)
109
+ return if symbol.is_a?(String) && !symbol.empty?
110
+
111
+ raise ArgumentError, 'Progress bar symbols must be non-empty strings'
112
+ end
113
+
114
+ def validate_format!(format)
115
+ return if format.is_a?(String) && !format.empty?
116
+
117
+ raise ArgumentError, 'Format must be a non-empty string'
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KawaiiProgress
4
+ # Controls rendering frequency using a configurable refresh interval.
5
+ # Accepts externally supplied monotonic timestamps and does not
6
+ # perform its own synchronization or clock access.
7
+ class RefreshThrottle
8
+ DEFAULT_INTERVAL = 0.1
9
+
10
+ attr_reader :interval
11
+
12
+ def initialize(interval: DEFAULT_INTERVAL)
13
+ validate_interval!(interval)
14
+
15
+ @interval = interval
16
+ @last_rendered_at = nil
17
+ end
18
+
19
+ def due?(now)
20
+ last_rendered_at.nil? ||
21
+ now - last_rendered_at >= interval
22
+ end
23
+
24
+ def mark_rendered(now)
25
+ @last_rendered_at = now
26
+ end
27
+
28
+ private
29
+
30
+ attr_reader :last_rendered_at
31
+
32
+ def validate_interval!(interval)
33
+ return if interval.is_a?(Numeric) &&
34
+ interval.real? &&
35
+ interval.finite? &&
36
+ interval >= 0
37
+
38
+ raise ArgumentError, 'Refresh interval must be a non-negative finite number'
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ module KawaiiProgress
6
+ # Writes formatted progress lines to an output stream.
7
+ # Interactive streams are updated in place, while non-interactive
8
+ # streams receive only the final progress line.
9
+ class Renderer
10
+ extend Forwardable
11
+
12
+ DEFAULT_WIDTH = Formatter::DEFAULT_WIDTH
13
+ DEFAULT_FILLED = Formatter::DEFAULT_FILLED
14
+ DEFAULT_EMPTY = Formatter::DEFAULT_EMPTY
15
+ DEFAULT_FORMAT = Formatter::DEFAULT_FORMAT
16
+
17
+ CLEAR_LINE = "\r\e[2K"
18
+
19
+ attr_reader :output
20
+
21
+ def_delegators :formatter, :width, :filled, :empty, :template
22
+
23
+ def initialize(
24
+ width: DEFAULT_WIDTH,
25
+ output: $stderr,
26
+ interactive: nil,
27
+ filled: DEFAULT_FILLED,
28
+ empty: DEFAULT_EMPTY,
29
+ format: DEFAULT_FORMAT
30
+ )
31
+ @formatter = Formatter.new(
32
+ width: width,
33
+ filled: filled,
34
+ empty: empty,
35
+ format: format
36
+ )
37
+
38
+ @output = output
39
+ @interactive = interactive.nil? ? detect_interactive? : interactive
40
+ end
41
+
42
+ def interactive?
43
+ @interactive
44
+ end
45
+
46
+ def render(snapshot)
47
+ return unless interactive?
48
+
49
+ output.print("#{CLEAR_LINE}#{format_line(snapshot)}")
50
+ output.flush
51
+ end
52
+
53
+ def finish(snapshot)
54
+ prefix = interactive? ? CLEAR_LINE : ''
55
+
56
+ output.puts("#{prefix}#{format_line(snapshot)}")
57
+ output.flush
58
+ end
59
+
60
+ private
61
+
62
+ attr_reader :formatter
63
+
64
+ def detect_interactive?
65
+ output.respond_to?(:tty?) && output.tty?
66
+ end
67
+
68
+ def format_line(snapshot)
69
+ formatter.format(snapshot, columns: terminal_columns)
70
+ end
71
+
72
+ def terminal_columns
73
+ return unless interactive? && width == :auto
74
+
75
+ Terminal.columns(output)
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KawaiiProgress
4
+ # An immutable snapshot of a progress bar at a specific point in time.
5
+ # All derived metrics are calculated from the same captured state
6
+ # without accessing the clock or the original progress bar.
7
+ Snapshot = Data.define(:title, :total, :current, :elapsed, :finished) do
8
+ def finished?
9
+ finished
10
+ end
11
+
12
+ def progress
13
+ return 0.0 if total.zero?
14
+
15
+ current.fdiv(total)
16
+ end
17
+
18
+ def percentage
19
+ (progress * 100).round
20
+ end
21
+
22
+ def rate
23
+ return 0.0 unless elapsed.positive?
24
+
25
+ current.fdiv(elapsed)
26
+ end
27
+
28
+ def eta
29
+ current_rate = rate
30
+ return unless current_rate.positive?
31
+
32
+ ((total - current) / current_rate).round
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'io/console'
4
+
5
+ module KawaiiProgress
6
+ # Provides terminal dimension detection and approximate display width
7
+ # calculations for formatted text.
8
+ module Terminal
9
+ def self.columns(output)
10
+ return unless output.respond_to?(:winsize)
11
+
12
+ _, columns = output.winsize
13
+
14
+ columns if columns.is_a?(Integer) && columns.positive?
15
+ rescue IOError, SystemCallError, NotImplementedError
16
+ nil
17
+ end
18
+
19
+ def self.display_width(text)
20
+ # Strip ANSI styling sequences and count grapheme clusters.
21
+ # Wide Unicode characters may occupy more than one terminal column,
22
+ # so the resulting width is an approximation.
23
+ text.gsub(/\e\[[0-9;:]*m/, '').each_grapheme_cluster.count
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KawaiiProgress
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'zeitwerk'
4
+
5
+ loader = Zeitwerk::Loader.for_gem
6
+ loader.setup
7
+
8
+ # A lightweight, thread-safe progress bar for Ruby.
9
+ module KawaiiProgress
10
+ class << self
11
+ # Iterates over a collection while tracking its progress.
12
+ # Returns an enumerator when called without a block.
13
+ def each(enumerable, title: 'Processing', total: nil, **)
14
+ return enum_for(__method__, enumerable, title: title, total: total, **) unless block_given?
15
+
16
+ bar = Bar.new(title, total: resolve_total(enumerable, total), **)
17
+
18
+ enumerable.each do |*items|
19
+ yield(*items)
20
+ bar.advance
21
+ end
22
+ ensure
23
+ bar&.finish
24
+ end
25
+
26
+ private
27
+
28
+ # An explicit total takes precedence over the collection size.
29
+ # Not all enumerable objects provide a size method.
30
+ # :reek:NilCheck
31
+ # :reek:ManualDispatch
32
+ def resolve_total(enumerable, total)
33
+ return total unless total.nil?
34
+
35
+ size = enumerable.size if enumerable.respond_to?(:size)
36
+
37
+ return size if size.is_a?(Integer) && size >= 0
38
+
39
+ raise ArgumentError, 'Cannot determine collection size; provide total explicitly'
40
+ end
41
+ end
42
+ end
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kawaii_progress
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Elijah S. Krukowski
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: zeitwerk
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ -
17
+ - ~>
18
+ - !ruby/object:Gem::Version
19
+ version: "2.6"
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ -
25
+ - ~>
26
+ - !ruby/object:Gem::Version
27
+ version: "2.6"
28
+ description: |
29
+ KawaiiProgress provides customizable terminal progress bars with
30
+ thread-safe updates, automatic refresh throttling, and ETA estimation.
31
+ Built for modern Ruby with zero runtime dependencies and maximum kawaii.
32
+ email:
33
+ - elskruk@proton.me
34
+ executables: []
35
+ extensions: []
36
+ extra_rdoc_files: []
37
+ files:
38
+ - LICENSE.md
39
+ - README.md
40
+ - lib/kawaii_progress.rb
41
+ - lib/kawaii_progress/bar.rb
42
+ - lib/kawaii_progress/clock.rb
43
+ - lib/kawaii_progress/formatter.rb
44
+ - lib/kawaii_progress/refresh_throttle.rb
45
+ - lib/kawaii_progress/renderer.rb
46
+ - lib/kawaii_progress/snapshot.rb
47
+ - lib/kawaii_progress/terminal.rb
48
+ - lib/kawaii_progress/version.rb
49
+ homepage: "https://github.com/bodrovis/kawaii_progress"
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ rubygems_mfa_required: "true"
54
+ bug_tracker_uri: "https://github.com/bodrovis/kawaii_progress/issues"
55
+ documentation_uri: "https://github.com/bodrovis/kawaii_progress/blob/master/README.md"
56
+ changelog_uri: "https://github.com/bodrovis/kawaii_progress/blob/master/CHANGELOG.md"
57
+ homepage_uri: "https://github.com/bodrovis/kawaii_progress"
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ -
64
+ - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: "3.4"
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ -
70
+ - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: "0"
73
+ requirements: []
74
+ rubygems_version: 4.1.1
75
+ specification_version: 4
76
+ summary: "A lightweight, thread-safe progress bar for Ruby"
77
+ test_files: []