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,221 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MiniProgress
4
+ # A terminal reporter. It draws a live progress row for each running step
5
+ # (spinner, percent, count, elapsed time, ETA, and rate) at the bottom of the
6
+ # screen. Notices and finished steps print above and scroll up into the normal
7
+ # terminal history.
8
+ #
9
+ # The code that reports progress never draws anything itself. This class is a
10
+ # thread-safe front end: callers only hand off events. A separate thread
11
+ # applies them, updates the model, and redraws at a fixed rate. That lets one
12
+ # thread report progress while another started the step, without the output
13
+ # getting mixed up.
14
+ #
15
+ # The drawing itself is in {Renderer}. It runs on one thread only and has no
16
+ # side effects apart from its output and clock (both can be injected), so it
17
+ # can be tested without threads or a real terminal.
18
+ class Tui < Reporter
19
+ # How long `close` waits for the render thread to drain before killing it.
20
+ CLOSE_TIMEOUT = 5
21
+ private_constant :CLOSE_TIMEOUT
22
+
23
+ def initialize(fps: 10, output: $stdout, titles: [])
24
+ raise ArgumentError, "fps must be greater than 0" if fps <= 0
25
+
26
+ super()
27
+ @queue = Thread::Queue.new
28
+ @progress = {}
29
+ @progress_mutex = Mutex.new
30
+ @output = output
31
+ @renderer = Renderer.new(output:, titles:)
32
+ @frame = 1.0 / fps
33
+ @closed = false
34
+ @render_error = nil
35
+ @render_thread = Thread.new { render_loop }
36
+ @render_thread.name = "tui_reporter"
37
+ @render_thread.report_on_exception = false # render_loop catches it; close reports it
38
+ end
39
+
40
+ # --- The {Reporter} methods. {StepHandle} calls them from other threads. ---
41
+
42
+ def report_start(id, title)
43
+ enqueue([:start, id, title])
44
+ end
45
+
46
+ def report_notice(id, message)
47
+ enqueue([:notice, id, message])
48
+ end
49
+
50
+ def report_progress_begin(id, max_progress)
51
+ enqueue([:progress_begin, id, max_progress])
52
+ end
53
+
54
+ def report_concurrency(id, count)
55
+ enqueue([:concurrency, id, count])
56
+ end
57
+
58
+ def report_progress(id, current, skip_count, warning_count, error_count)
59
+ # Progress is coalesced, not queued: one event per row across many steps
60
+ # would keep the queue full and starve the repaint. Keep the latest only.
61
+ @progress_mutex.synchronize do
62
+ @progress[id] = [current, skip_count, warning_count, error_count]
63
+ end
64
+ end
65
+
66
+ def report_finish(id, outcome)
67
+ enqueue([:finish, id, outcome])
68
+ end
69
+
70
+ def report_finalizing_begin
71
+ enqueue([:finalizing_begin])
72
+ end
73
+
74
+ def report_finalizing_end
75
+ enqueue([:finalizing_end])
76
+ end
77
+
78
+ def report_summary(runtime:, total:, failed:, skipped:)
79
+ enqueue([:summary, runtime, total, failed, skipped])
80
+ end
81
+
82
+ def close
83
+ return if @closed
84
+ @closed = true
85
+ enqueue([:close])
86
+
87
+ if @render_thread.join(CLOSE_TIMEOUT).nil?
88
+ # The render thread is wedged (e.g. blocked in `write` on a stopped
89
+ # tty). `close` runs inside the run's `ensure`, so it must not hang.
90
+ @render_thread.kill
91
+ warn("TUI reporter did not stop in time and was killed.")
92
+ show_cursor_best_effort
93
+ end
94
+
95
+ report_render_error
96
+ end
97
+
98
+ private
99
+
100
+ # If the render thread has died, drop the event. Otherwise a crashed
101
+ # renderer would let the queue grow without limit for the rest of the run.
102
+ def enqueue(event)
103
+ @queue << event if @render_thread.nil? || @render_thread.alive?
104
+ end
105
+
106
+ def render_loop
107
+ # Redraw on a terminal resize while we run; the ensure below puts the
108
+ # previous handler back. Some platforms have no WINCH signal, where
109
+ # `Signal.trap` raises — run without resize support rather than crash.
110
+ begin
111
+ @winch_prev = Signal.trap("WINCH") { @renderer.mark_resize }
112
+ @winch_installed = true
113
+ rescue StandardError
114
+ @winch_installed = false
115
+ end
116
+
117
+ @renderer.on_start
118
+ run_frames
119
+ rescue Exception => e
120
+ # The thread boundary: nothing may escape, or `close`'s `join` would
121
+ # re-raise it inside the run's `ensure`. Fatal errors land in the render
122
+ # error report like everything else.
123
+ @render_error = e
124
+ ensure
125
+ # Two independent steps: a failure restoring the trap must not skip the
126
+ # terminal restore, and vice versa. Neither may raise out of the ensure.
127
+ restore_winch_trap
128
+ finalize_renderer
129
+ end
130
+
131
+ def restore_winch_trap
132
+ Signal.trap("WINCH", @winch_prev || "DEFAULT") if @winch_installed
133
+ rescue StandardError
134
+ nil
135
+ end
136
+
137
+ def finalize_renderer
138
+ @renderer.finalize
139
+ rescue StandardError => e
140
+ @render_error ||= e
141
+ end
142
+
143
+ # The render loop's `ensure` already restored the terminal. If the loop
144
+ # crashed, report it here so it isn't lost. Don't raise: `close` runs
145
+ # inside the run's `ensure`.
146
+ def report_render_error
147
+ return unless @render_error
148
+
149
+ warn("TUI reporter crashed: #{@render_error.class}: #{@render_error.message}")
150
+ warn(@render_error.backtrace.first(5).join("\n")) if @render_error.backtrace
151
+ end
152
+
153
+ # `write_nonblock`: the render thread was most likely killed because it was
154
+ # blocked writing to this same output, so a plain `write` here could block
155
+ # `close` all over again.
156
+ def show_cursor_best_effort
157
+ @output.write_nonblock(Ansi::SHOW_CURSOR)
158
+ rescue StandardError
159
+ nil
160
+ end
161
+
162
+ # Draws a frame at a steady rate until the close event arrives. Each frame
163
+ # drains the queued events, handles a pending resize, repaints, then sleeps
164
+ # for the rest of the frame's time.
165
+ def run_frames
166
+ loop do
167
+ frame_started_at = monotonic
168
+ break if drain_until_close
169
+ apply_coalesced_progress
170
+ @renderer.consume_resize
171
+ @renderer.repaint
172
+ sleep_rest_of_frame(frame_started_at)
173
+ end
174
+ end
175
+
176
+ # Take the whole map and leave a fresh one behind, so a progress report
177
+ # racing its step's `:finish` can't linger and be re-applied as a no-op on
178
+ # every frame for the rest of the run. A finishing step still sees its last
179
+ # value: the drain (and its `flush_progress`) runs before this swap.
180
+ def apply_coalesced_progress
181
+ snapshot =
182
+ @progress_mutex.synchronize do
183
+ current = @progress
184
+ @progress = {}
185
+ current
186
+ end
187
+ snapshot.each { |id, values| @renderer.apply([:progress, id, *values]) }
188
+ end
189
+
190
+ def flush_progress(id)
191
+ values = @progress_mutex.synchronize { @progress.delete(id) }
192
+ @renderer.apply([:progress, id, *values]) if values
193
+ end
194
+
195
+ # Sleeps for whatever is left of this frame's time, so repaints happen at a
196
+ # steady rate instead of as fast as the loop can spin.
197
+ def sleep_rest_of_frame(frame_started_at)
198
+ remaining = @frame - (monotonic - frame_started_at)
199
+ sleep(remaining) if remaining > 0
200
+ end
201
+
202
+ def drain_until_close
203
+ # Drain only what's already queued; events arriving while we drain wait
204
+ # for the next frame, so a burst can't keep the loop here and starve the
205
+ # repaint.
206
+ @queue.size.times do
207
+ event = @queue.pop(true)
208
+ return true if event[0] == :close
209
+ flush_progress(event[1]) if event[0] == :finish
210
+ @renderer.apply(event)
211
+ end
212
+ false
213
+ rescue ThreadError
214
+ false
215
+ end
216
+
217
+ def monotonic
218
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
219
+ end
220
+ end
221
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MiniProgress
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "i18n"
4
+
5
+ require_relative "mini_progress/version"
6
+ require_relative "mini_progress/formatting"
7
+ require_relative "mini_progress/reporter"
8
+ require_relative "mini_progress/plain"
9
+ require_relative "mini_progress/tui"
10
+ require_relative "mini_progress/tui/ansi"
11
+ require_relative "mini_progress/tui/renderer"
12
+ require_relative "mini_progress/factory"
13
+
14
+ # Step and progress reporting for command line tools. Start with
15
+ # {MiniProgress::Factory.build}.
16
+ module MiniProgress
17
+ LOCALE_FILES = Dir[File.expand_path("mini_progress/locales/*.yml", __dir__)].freeze
18
+
19
+ # Adds the gem's translations to I18n. Runs when the gem is required and does
20
+ # nothing the second time.
21
+ def self.load_translations
22
+ new_files = LOCALE_FILES - I18n.load_path
23
+ return if new_files.empty?
24
+
25
+ I18n.load_path.concat(new_files)
26
+ # A backend that already loaded its translations (for example in a booted
27
+ # Rails app) doesn't look at the load path again until it reloads.
28
+ I18n.backend.load_translations(*new_files)
29
+ end
30
+ end
31
+
32
+ MiniProgress.load_translations
metadata ADDED
@@ -0,0 +1,97 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mini_progress
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Discourse Team
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: activesupport
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: i18n
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '1.8'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '1.8'
40
+ - !ruby/object:Gem::Dependency
41
+ name: unicode-display_width
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '3.0'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '3.0'
54
+ description: MiniProgress reports the steps of a command line run and their progress.
55
+ On a terminal it draws one live row per running step, while finished steps and notices
56
+ scroll into the terminal history. Pipes, CI logs and dumb terminals get plain lines
57
+ instead.
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - LICENSE.txt
63
+ - lib/mini_progress.rb
64
+ - lib/mini_progress/factory.rb
65
+ - lib/mini_progress/formatting.rb
66
+ - lib/mini_progress/locales/mini_progress.en.yml
67
+ - lib/mini_progress/plain.rb
68
+ - lib/mini_progress/reporter.rb
69
+ - lib/mini_progress/tui.rb
70
+ - lib/mini_progress/tui/ansi.rb
71
+ - lib/mini_progress/tui/renderer.rb
72
+ - lib/mini_progress/version.rb
73
+ homepage: https://github.com/discourse/mini_progress
74
+ licenses:
75
+ - MIT
76
+ metadata:
77
+ allowed_push_host: https://rubygems.org
78
+ homepage_uri: https://github.com/discourse/mini_progress
79
+ source_code_uri: https://github.com/discourse/mini_progress
80
+ rdoc_options: []
81
+ require_paths:
82
+ - lib
83
+ required_ruby_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '3.4'
88
+ required_rubygems_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '0'
93
+ requirements: []
94
+ rubygems_version: 3.6.9
95
+ specification_version: 4
96
+ summary: Step and progress reporting for command line tools
97
+ test_files: []