rspec-collapsing-formatter 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: 45a249d406ec9457655dc880f499d9818ccdb028d301023febdaf76f8ab9d27d
4
+ data.tar.gz: b01f5967bdf5131e9cd23105e19de6950842f10c84490547a99740a6a8ab4e18
5
+ SHA512:
6
+ metadata.gz: be68c179c73e71dd36c2a3d0f6e3dd49f4fd04ce3ee05213f399fb4e6c53086bb4aa5835af456b90929d39642c8a30101d78a10bc7e5e64a72be872c9cb8bded
7
+ data.tar.gz: a7f91f970b37504a919450712f93d6a8c28d30a3dd1358dd15f2c86b03d002cc2180d91bcd9c70486c7593f103fbb3298998c2c3d633fa299dfe0a5f95b7c2bc
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adam Lett
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,186 @@
1
+ # rspec-collapsing-formatter
2
+
3
+ An RSpec formatter that works like the built-in `documentation` formatter, but collapses
4
+ each example group into a one-line summary as soon as it finishes. Failures stay expanded.
5
+
6
+ While the suite runs you can see exactly which group and example RSpec is executing, but
7
+ finished work no longer takes up one line per example.
8
+
9
+ ## What it looks like
10
+
11
+ While a suite is running, the current group is expanded as in the documentation
12
+ formatter, and `▸` marks the example that is running:
13
+
14
+ ```text
15
+ User
16
+ ✓ when active (3 examples)
17
+ when suspended
18
+ ✓ is invalid
19
+ ▸ cannot log in
20
+ ```
21
+
22
+ Finished groups collapse to a summary line. A group with a failure stays expanded, so the
23
+ failed example is shown in context; its successful subgroups still collapse:
24
+
25
+ ```text
26
+ ✗ User (4 passed, 1 failed, 1 pending)
27
+ ✓ when active (3 examples)
28
+ ✗ when suspended (1 passed, 1 failed, 1 pending)
29
+ ✓ is invalid
30
+ ✗ cannot log in (FAILED - 1)
31
+ • sends a notice (PENDING: mailer not wired up)
32
+ audit: bid of 90 rejected
33
+
34
+ ✓ Auction (3 examples)
35
+ ```
36
+
37
+ (`audit: …` was printed by a spec. See [Output from specs](#output-from-specs).)
38
+
39
+ RSpec's usual pending, failure and summary output then follows, unchanged:
40
+
41
+ ```text
42
+ Failures:
43
+
44
+ 1) User when suspended cannot log in
45
+ Failure/Error: it("cannot log in") { expect(:logged_in).to eq(:rejected) }
46
+
47
+ expected: :rejected
48
+ got: :logged_in
49
+ …
50
+
51
+ 9 examples, 1 failure, 1 pending
52
+ ```
53
+
54
+ The `(FAILED - n)` numbers match the numbers in that failure list.
55
+
56
+ ## Installation
57
+
58
+ The gem is not published to RubyGems yet. Add it to your Gemfile from GitHub:
59
+
60
+ ```ruby
61
+ group :test do
62
+ gem "rspec-collapsing-formatter", git: "https://github.com/KaptajnKold/rspec-collapsing-formatter"
63
+ end
64
+ ```
65
+
66
+ It requires Ruby 3.1 or later and rspec-core 3.10 or later. Its only other dependency is
67
+ `unicode-display_width` (2.4 up to 4), to measure line widths. It is tested on Ruby 3.1
68
+ and 3.4, with rspec-core 3.10 and 3.13 and `unicode-display_width` 2.x and 3.x.
69
+
70
+ ## Usage
71
+
72
+ ```sh
73
+ bundle exec rspec --format RSpec::CollapsingFormatter
74
+ ```
75
+
76
+ No `--require` is needed: RSpec loads the formatter from its constant name. To make it the
77
+ default, add this to `.rspec`:
78
+
79
+ ```text
80
+ --format RSpec::CollapsingFormatter
81
+ ```
82
+
83
+ ## Display
84
+
85
+ | Line | Meaning |
86
+ |---|---|
87
+ | `▸ description` | Example currently running |
88
+ | `✓ description` | Passed example |
89
+ | `✗ description (FAILED - 1)` | Failed example, numbered as in RSpec's failure list |
90
+ | `• description (PENDING: reason)` | Pending or skipped example |
91
+ | `✓ group (3 examples)` | Finished group in which everything passed |
92
+ | `• group (6 passed, 1 pending)` | Finished group with pending examples but no failures; collapsed, in yellow |
93
+ | `✗ group (1 passed, 1 failed)` | Finished group with a failure; stays expanded |
94
+
95
+ - Counts include examples in nested groups.
96
+ - Groups in which no examples ran, e.g. because of filters or `--fail-fast`, are hidden.
97
+ - Collapsed top-level groups are listed one after another. A blank line separates a
98
+ top-level group from its neighbors when either of them is expanded.
99
+ - If the output encoding is not UTF-8, the symbols fall back to `+`, `x`, `*`, `>` and
100
+ `...`.
101
+ - Colors follow RSpec's color settings (`--color`, `--no-color`, `--force-color`) and
102
+ roles (`success_color`, `failure_color`, `pending_color`, `detail_color`).
103
+
104
+ ## Interactive and non-interactive output
105
+
106
+ When the output is a terminal (and `TERM` is not `dumb`), the formatter redraws the tree in
107
+ place. It rewrites only the lines that changed, without clearing the screen, so it does
108
+ not flicker. Typically that is one line per example, plus a few when a group collapses.
109
+ Lines are cut to the terminal width with `…`, so a long description never wraps; the full
110
+ description is still shown in RSpec's failure output.
111
+
112
+ When the output is redirected to a file, piped, or not a terminal for any other reason,
113
+ the formatter falls back to append-only output in the style of the documentation
114
+ formatter, and never writes cursor-control sequences:
115
+
116
+ ```text
117
+ User
118
+ when active
119
+ ✓ is valid
120
+ ✓ can log in
121
+ ✓ receives notifications
122
+ when suspended
123
+ ✓ is invalid
124
+ ✗ cannot log in (FAILED - 1)
125
+ • sends a notice (PENDING: mailer not wired up)
126
+ ```
127
+
128
+ Nothing collapses in this mode, so a log of a hung CI job still shows where it stopped.
129
+
130
+ ## Output from specs
131
+
132
+ In interactive mode, `$stdout` and `$stderr` are replaced by thin proxies for the duration
133
+ of the run. Anything a spec writes there, via `puts`, `warn`, a logger and so on, is printed
134
+ above the tree, and the tree is redrawn below it. RSpec's own messages, such as
135
+ `Run options: …` or the notice printed on Ctrl-C, take the same path. A line printed
136
+ without a newline (`print "."`) waits until the newline arrives or the next example
137
+ starts or finishes.
138
+
139
+ The proxies pass everything else (`tty?`, `sync`, `winsize`, …) through to the real streams.
140
+ The real streams are restored before RSpec prints its summary.
141
+
142
+ ## Limitations
143
+
144
+ The first version makes these simplifying assumptions where terminal behavior gets
145
+ complicated:
146
+
147
+ - **Output that bypasses `$stdout`/`$stderr` can corrupt the tree.** That includes output
148
+ from subprocesses that write to the inherited file descriptors, and code that writes to
149
+ the `STDOUT`/`STDERR` constants. The next redraw then overwrites some of that output or
150
+ leaves stale lines behind.
151
+ - **Groups taller than the terminal.** The cursor cannot move into rows that have scrolled
152
+ off the top, so those lines are final once they scroll away. If such a group later
153
+ collapses, its summary is printed below the lines that can no longer be changed. If it
154
+ fails, its header keeps its plain running text instead of `✗ … (counts)`.
155
+ - **Resizing.** The terminal size is read on every redraw, but lines already drawn are not
156
+ reflowed. Making the window shorter than the expanded part of the tree can garble it
157
+ until the current top-level group finishes.
158
+ - **Ctrl-C.** RSpec's first interrupt lets the current example finish, so its "shutting
159
+ down" notice appears after that example, and the tree is completed normally. A second
160
+ Ctrl-C makes RSpec exit immediately, which leaves the tree as it was, with the cursor
161
+ on a fresh line.
162
+ - **Wide characters.** Emoji widths differ between versions of `unicode-display_width` and
163
+ between terminals. If they disagree, a line can be cut a little short, or in rare cases
164
+ wrap.
165
+
166
+ ## Development
167
+
168
+ ```sh
169
+ bundle install
170
+ bundle exec rspec
171
+ ```
172
+
173
+ The design is described in [PLAN.md](PLAN.md), and the original brief is in
174
+ [REQUIREMENTS.md](REQUIREMENTS.md). In short, RSpec events update a tree (`tree.rb`).
175
+ `layout.rb` turns the tree into lines without any IO, and `live_output.rb` or
176
+ `stream_output.rb` writes them. Only `live_output.rb` knows about cursor movement.
177
+
178
+ Most tests run without a real terminal. `spec/support/virtual_terminal.rb` is a small
179
+ terminal emulator that interprets the bytes the formatter writes, so specs can assert on
180
+ what would be visible on screen. It raises on any escape sequence it does not know. The
181
+ end-to-end tests run RSpec in a subprocess, both through a pipe and under a real
182
+ pseudo-terminal.
183
+
184
+ ## License
185
+
186
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "unicode/display_width"
4
+
5
+ module RSpec
6
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
7
+ # Turns the tree into display lines. Pure: no IO and no ANSI codes.
8
+ #
9
+ # Collapse rules:
10
+ # - running groups are expanded;
11
+ # - finished groups that passed, or had pending but no failed examples, collapse
12
+ # to one summary line;
13
+ # - finished groups with a failure stay expanded, so the failure stays visible
14
+ # in its hierarchy;
15
+ # - finished groups in which no examples ran are omitted.
16
+ #
17
+ # With a width, every line is truncated to fit in `width - 1` display columns, so
18
+ # that one line always occupies exactly one terminal row.
19
+ class Layout
20
+ # `indent` and `text` are plain strings; `style` is a ConsoleCodes color role or nil.
21
+ # `node` is the group or example the line shows (nil for a blank separator).
22
+ Line = Struct.new(:indent, :text, :style, :node) do
23
+ def to_s
24
+ indent + text
25
+ end
26
+ end
27
+
28
+ INDENT = " "
29
+
30
+ def initialize(symbols, width: nil)
31
+ @symbols = symbols
32
+ @width = width
33
+ end
34
+
35
+ # Lines for a list of top-level groups. A blank line separates adjacent groups
36
+ # when either of them is expanded; collapsed summaries stack directly.
37
+ #
38
+ # `previous` is the top-level group displayed just above these, if any (e.g. one
39
+ # already committed to the terminal), so the first group gets the right separator.
40
+ def lines(groups, previous: nil)
41
+ groups.each_with_object([]) do |group, lines|
42
+ group_lines = group_lines(group)
43
+ next if group_lines.empty?
44
+
45
+ lines << Line.new("", "", nil, nil) if previous && (expanded?(previous) || expanded?(group))
46
+ lines.concat(group_lines)
47
+ previous = group
48
+ end
49
+ end
50
+
51
+ # The lines from `node` to the end of its top-level group, as they appear in
52
+ # `lines`, without laying out anything before `node`: the node's own lines, then
53
+ # its following siblings, then those of each ancestor. Groups after the top-level
54
+ # group are not included.
55
+ def lines_from(node)
56
+ depth = node.depth
57
+ lines = node_lines(node, depth)
58
+ while (parent = node.parent)
59
+ parent.children[(node.index + 1)..].each { |sibling| lines.concat(node_lines(sibling, depth)) }
60
+ node = parent
61
+ depth -= 1
62
+ end
63
+ lines
64
+ end
65
+
66
+ # Whether a finished group is shown as a single summary line, or not at all.
67
+ def hides_children?(group)
68
+ %i[passed pending empty].include?(group.status)
69
+ end
70
+
71
+ def group_lines(group, depth = 0)
72
+ case group.status
73
+ when :empty then []
74
+ when :passed, :pending then [header_line(group, depth)]
75
+ else [header_line(group, depth), *children_lines(group, depth + 1)]
76
+ end
77
+ end
78
+
79
+ def header_line(group, depth)
80
+ status = group.status
81
+ return line(depth, group.description, nil, group) if status == :running
82
+
83
+ text = "#{@symbols.glyph(status)} #{group.description} (#{summary(group.counts)})"
84
+ line(depth, text, @symbols.style(status), group)
85
+ end
86
+
87
+ def example_line(example, depth)
88
+ text = "#{@symbols.glyph(example.status)} #{example.description}"
89
+ text += " (#{example.detail})" if example.detail
90
+ line(depth, text, @symbols.style(example.status), example)
91
+ end
92
+
93
+ private
94
+
95
+ def children_lines(group, depth)
96
+ group.children.flat_map { |child| node_lines(child, depth) }
97
+ end
98
+
99
+ def node_lines(node, depth)
100
+ node.is_a?(GroupNode) ? group_lines(node, depth) : [example_line(node, depth)]
101
+ end
102
+
103
+ def expanded?(group)
104
+ %i[running failed].include?(group.status)
105
+ end
106
+
107
+ # "3 examples" when everything passed, otherwise a breakdown such as
108
+ # "6 passed, 1 failed".
109
+ def summary(counts)
110
+ if counts.failed.zero? && counts.pending.zero?
111
+ "#{counts.total} #{counts.total == 1 ? "example" : "examples"}"
112
+ else
113
+ { "passed" => counts.passed, "failed" => counts.failed, "pending" => counts.pending }
114
+ .filter_map { |label, count| "#{count} #{label}" if count.positive? }
115
+ .join(", ")
116
+ end
117
+ end
118
+
119
+ def line(depth, text, style, node)
120
+ indent = INDENT * depth
121
+ if @width
122
+ max_width = [@width - 1, 0].max
123
+ indent = indent[0, max_width]
124
+ text = truncate(text, max_width - indent.length)
125
+ end
126
+ Line.new(indent, text, style, node)
127
+ end
128
+
129
+ def truncate(text, max_width)
130
+ # No character is wider than its UTF-8 encoding is long, so this skips measuring
131
+ # the common short line.
132
+ return text if text.bytesize <= max_width || Unicode::DisplayWidth.of(text) <= max_width
133
+
134
+ room = max_width - Unicode::DisplayWidth.of(@symbols.ellipsis)
135
+ return "" if room.negative?
136
+
137
+ used = 0
138
+ kept = text.each_grapheme_cluster.take_while do |grapheme|
139
+ used += Unicode::DisplayWidth.of(grapheme)
140
+ used <= room
141
+ end
142
+ kept.join + @symbols.ellipsis
143
+ end
144
+ end
145
+ end
146
+ end
@@ -0,0 +1,251 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/console"
4
+
5
+ module RSpec
6
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
7
+ # Output for interactive terminals: redraws the tree in place as it changes.
8
+ #
9
+ # The screen is split into committed lines, which are never touched again, and a
10
+ # live region below them. Finished top-level groups are committed; the running one
11
+ # is the live region. After every event the live region is laid out again and
12
+ # compared with what is on screen: the cursor moves up to the first line that
13
+ # differs, clears to the end of the screen and writes the rest, in one write call.
14
+ #
15
+ # The cursor is always parked at the start of the line below the live region.
16
+ # Lines are truncated to the terminal width so that each occupies one row, which
17
+ # keeps the cursor-up counts correct.
18
+ #
19
+ # The live region is never taller than the terminal, since the cursor cannot move
20
+ # into rows that have scrolled off the top. Lines above that limit are committed as
21
+ # they are, and the live region then starts at the node shown on its first line.
22
+ # Only that part is laid out on each render, so the cost of a render does not grow
23
+ # with the size of the running group.
24
+ #
25
+ # Committed lines can go stale: a group header keeps its running text if the group
26
+ # later fails, and if a group whose lines were committed collapses, its summary and
27
+ # everything after it is written below what is already on screen.
28
+ #
29
+ # While running, $stdout and $stderr (when they are terminals) are replaced by
30
+ # StrayOutput proxies. Complete lines written to them, and RSpec messages, are
31
+ # printed above the live region: it is cleared, the text is written through the
32
+ # original stream, and the live region is drawn again below it. Partial lines wait
33
+ # for their newline or the next event, whichever comes first.
34
+ class LiveOutput
35
+ DEFAULT_WIDTH = 80
36
+ DEFAULT_HEIGHT = 24
37
+ CURSOR_UP = "\e[%dA"
38
+ CLEAR_TO_END_OF_SCREEN = "\e[J"
39
+
40
+ def self.supported?(output, env = ENV)
41
+ output.respond_to?(:tty?) && output.tty? && env["TERM"] != "dumb"
42
+ end
43
+
44
+ def initialize(output, symbols, tree, env: ENV)
45
+ @output = output
46
+ @symbols = symbols
47
+ @tree = tree
48
+ @env = env
49
+ @frame = [] # live region lines currently on screen, as written
50
+ @frame_nodes = [] # the tree node each of those lines shows
51
+ @start = nil # node on the first live line, once lines were committed for lack of room
52
+ @committed_groups = 0 # number of top-level groups above the live region
53
+ @last_committed = nil # last committed group that was displayed
54
+ @started = false
55
+ @proxies = [] # StrayOutput proxies currently installed
56
+ @pending = {} # proxy => partial line not yet printed (bytes)
57
+ @deferred = [] # [proxy, text] written from signal handlers, printed at the next event
58
+ # Specs may write from other threads. Not reentrant, and need not be: drawing
59
+ # writes to the original streams, never through the proxies.
60
+ @lock = Mutex.new
61
+ end
62
+
63
+ # Starts capturing output written to $stdout and $stderr.
64
+ def start
65
+ @lock.synchronize do
66
+ $stdout = capture($stdout)
67
+ $stderr = capture($stderr)
68
+ end
69
+ end
70
+
71
+ def group_started(_group, _depth)
72
+ @lock.synchronize { render }
73
+ end
74
+
75
+ def group_finished(_group, depth)
76
+ @lock.synchronize do
77
+ render
78
+ commit if depth.zero?
79
+ end
80
+ end
81
+
82
+ def example_started(_example, _depth)
83
+ @lock.synchronize { render }
84
+ end
85
+
86
+ def example_finished(_example, _depth)
87
+ @lock.synchronize { render }
88
+ end
89
+
90
+ # An RSpec message notification.
91
+ def message(text)
92
+ @lock.synchronize { print_above("#{text}\n", @output) }
93
+ end
94
+
95
+ # Called by StrayOutput with everything written to it.
96
+ def stray_output(proxy, text)
97
+ @lock.synchronize do
98
+ buffer = (@pending[proxy] ||= String.new) << text.b
99
+ newline = buffer.rindex("\n")
100
+ print_above(buffer.slice!(0..newline), proxy.io) if newline
101
+ end
102
+ rescue ThreadError => e
103
+ # Signal handlers cannot take locks (RSpec writes its "shutting down" message from
104
+ # its SIGINT handler), and may have interrupted a render, so drawing now is unsafe.
105
+ raise unless e.message.include?("trap context")
106
+
107
+ @deferred << [proxy, text.b] # Array#<< needs no lock
108
+ end
109
+
110
+ # Final redraw before RSpec prints its failure, pending and summary output;
111
+ # everything shown so far becomes permanent, and $stdout and $stderr are restored.
112
+ def finish
113
+ @lock.synchronize do
114
+ release
115
+ render
116
+ commit
117
+ end
118
+ end
119
+
120
+ private
121
+
122
+ def capture(io)
123
+ return io if io.is_a?(StrayOutput) || !(io.respond_to?(:tty?) && io.tty?)
124
+
125
+ StrayOutput.new(io, self).tap { |proxy| @proxies << proxy }
126
+ end
127
+
128
+ # Restores the original streams, unless something else has replaced them since.
129
+ def release
130
+ flush_pending
131
+ $stdout = $stdout.io if @proxies.include?($stdout)
132
+ $stderr = $stderr.io if @proxies.include?($stderr)
133
+ @proxies = []
134
+ end
135
+
136
+ # Prints deferred output and partial lines, ending the latter so that the live
137
+ # region starts on a new line.
138
+ def flush_pending
139
+ while (proxy, text = @deferred.shift)
140
+ (@pending[proxy] ||= String.new) << text
141
+ end
142
+ @pending.each do |proxy, buffer|
143
+ print_above(buffer.end_with?("\n") ? buffer : "#{buffer}\n", proxy.io) unless buffer.empty?
144
+ buffer.clear
145
+ end
146
+ end
147
+
148
+ # Clears the live region, writes `text` (complete lines) through `io` and draws
149
+ # the live region again below it.
150
+ def print_above(text, io)
151
+ clear = @frame.empty? ? "" : "\r#{format(CURSOR_UP, @frame.size)}#{CLEAR_TO_END_OF_SCREEN}"
152
+ redraw = @frame.map { |line| "#{line}\n" }.join
153
+ if io.equal?(@output)
154
+ @output.write([clear, text, redraw].map(&:b).join) # text may hold any bytes
155
+ else
156
+ @output.write(clear)
157
+ @output.flush if @output.respond_to?(:flush)
158
+ io.write(text)
159
+ io.flush if io.respond_to?(:flush)
160
+ @output.write(redraw)
161
+ end
162
+ @output.flush if @output.respond_to?(:flush)
163
+ end
164
+
165
+ def render
166
+ flush_pending
167
+ columns, rows = terminal_size
168
+ layout = Layout.new(@symbols, width: columns)
169
+ lines =
170
+ if @start
171
+ @start = topmost_hidden_ancestor(layout, @start) || @start
172
+ layout.lines_from(@start)
173
+ else
174
+ layout.lines(@tree.groups.drop(@committed_groups), previous: @last_committed)
175
+ end
176
+ frame = lines.map { |line| @symbols.paint(line) }
177
+
178
+ data = redraw(frame)
179
+ unless @started
180
+ data = "\n#{data}" # matches the blank line StreamOutput writes before a group
181
+ @started = true
182
+ end
183
+ @output.write(data) unless data.empty?
184
+ @output.flush if @output.respond_to?(:flush)
185
+ @frame = frame
186
+ @frame_nodes = lines.map(&:node)
187
+ commit_overflow(rows - 1) # one row is left for the cursor
188
+ end
189
+
190
+ # The outermost group above `node` that now collapsed or turned out empty, which
191
+ # means `node`'s line is gone and the live region has to start at that group.
192
+ def topmost_hidden_ancestor(layout, node)
193
+ hidden = nil
194
+ while (node = node.parent)
195
+ hidden = node if node.finished? && layout.hides_children?(node)
196
+ end
197
+ hidden
198
+ end
199
+
200
+ def commit_overflow(max_lines)
201
+ excess = @frame.size - max_lines
202
+ return unless excess.positive?
203
+
204
+ @frame.shift(excess)
205
+ @frame_nodes.shift(excess)
206
+ # Never a separator: those only come first in the top-level group's lines.
207
+ @start = @frame_nodes.first
208
+ end
209
+
210
+ # The bytes that turn the current live region into `frame`.
211
+ def redraw(frame)
212
+ first_change = @frame.each_index.find { |index| @frame[index] != frame[index] } || @frame.size
213
+ lines_up = @frame.size - first_change
214
+
215
+ data = +""
216
+ # Never emit a zero count: terminals treat ESC[0A as ESC[1A.
217
+ data << "\r" << format(CURSOR_UP, lines_up) << CLEAR_TO_END_OF_SCREEN if lines_up.positive?
218
+ frame.drop(first_change).each { |line| data << line << "\n" }
219
+ data
220
+ end
221
+
222
+ def commit
223
+ groups = @tree.groups.drop(@committed_groups)
224
+ @last_committed = groups.reverse.find { |group| group.status != :empty } || @last_committed
225
+ @committed_groups = @tree.groups.size
226
+ @frame = []
227
+ @frame_nodes = []
228
+ @start = nil
229
+ end
230
+
231
+ # [columns, rows], read on every render: from the terminal, else $COLUMNS and
232
+ # $LINES, else 80x24. At least two rows: one line of live region plus the cursor.
233
+ def terminal_size
234
+ rows, columns = winsize
235
+ columns = [columns, env_size("COLUMNS"), DEFAULT_WIDTH].find { |size| size&.positive? }
236
+ rows = [rows, env_size("LINES"), DEFAULT_HEIGHT].find { |size| size&.positive? }
237
+ [columns, [rows, 2].max]
238
+ end
239
+
240
+ def winsize
241
+ @output.winsize if @output.respond_to?(:winsize)
242
+ rescue SystemCallError, IOError
243
+ nil
244
+ end
245
+
246
+ def env_size(name)
247
+ Integer(@env.fetch(name, ""), exception: false)
248
+ end
249
+ end
250
+ end
251
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stringio"
4
+
5
+ module RSpec
6
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
7
+ # Stands in for $stdout or $stderr while the live region is on screen, so that
8
+ # output from specs appears above the tree instead of corrupting it.
9
+ #
10
+ # Everything written is handed to LiveOutput#stray_output, which prints complete
11
+ # lines through the original stream above the live region. All other methods
12
+ # (tty?, sync, fileno, winsize, ...) are delegated to the original stream.
13
+ #
14
+ # Output written to the file descriptor directly, e.g. by subprocesses or through
15
+ # the STDOUT constant, bypasses this and can still corrupt the live region.
16
+ class StrayOutput
17
+ attr_reader :io
18
+
19
+ def initialize(io, live_output)
20
+ @io = io
21
+ @live_output = live_output
22
+ end
23
+
24
+ def write(*objects)
25
+ text = objects.join
26
+ @live_output.stray_output(self, text)
27
+ text.bytesize
28
+ end
29
+
30
+ def <<(object)
31
+ write(object)
32
+ self
33
+ end
34
+
35
+ # Formatted exactly as the original stream would format them.
36
+ %i[puts print printf putc].each do |method|
37
+ define_method(method) do |*args|
38
+ formatted = StringIO.new(+"")
39
+ formatted.public_send(method, *args)
40
+ write(formatted.string)
41
+ method == :putc ? args.first : nil
42
+ end
43
+ end
44
+
45
+ def respond_to_missing?(name, include_private = false)
46
+ @io.respond_to?(name, include_private) || super
47
+ end
48
+
49
+ def method_missing(name, ...)
50
+ return super unless @io.respond_to?(name)
51
+
52
+ @io.public_send(name, ...)
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RSpec
4
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
5
+ # Append-only output for pipes, files and CI logs.
6
+ #
7
+ # Writes documentation-style lines as events arrive: a header when a group starts,
8
+ # one line per example when it finishes. Never emits cursor-control sequences;
9
+ # color is applied only through RSpec's ConsoleCodes, which honours --color settings.
10
+ class StreamOutput
11
+ def initialize(output, symbols)
12
+ @output = output
13
+ @symbols = symbols
14
+ @layout = Layout.new(symbols)
15
+ end
16
+
17
+ def group_started(group, depth)
18
+ @output.puts if depth.zero?
19
+ write(@layout.header_line(group, depth))
20
+ end
21
+
22
+ def example_finished(example, depth)
23
+ write(@layout.example_line(example, depth))
24
+ end
25
+
26
+ def message(text)
27
+ @output.puts(text)
28
+ end
29
+
30
+ # Nothing is shown for these events: lines are only ever appended.
31
+ def start; end
32
+ def group_finished(_group, _depth); end
33
+ def example_started(_example, _depth); end
34
+ def finish; end
35
+
36
+ private
37
+
38
+ def write(line)
39
+ @output.puts(@symbols.paint(line))
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RSpec
4
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
5
+ # Glyphs and color roles shared by every output mode.
6
+ #
7
+ # Colors are named by RSpec's configurable roles (:success, :failure, ...), so they
8
+ # follow the user's RSpec color configuration when wrapped with ConsoleCodes.
9
+ class Symbols
10
+ UNICODE = { passed: "✓", failed: "✗", pending: "•", running: "▸", ellipsis: "…" }.freeze
11
+ ASCII = { passed: "+", failed: "x", pending: "*", running: ">", ellipsis: "..." }.freeze
12
+ STYLES = { passed: :success, failed: :failure, pending: :pending, running: :detail }.freeze
13
+
14
+ def self.for(output)
15
+ encoding = (output.external_encoding if output.respond_to?(:external_encoding)) || Encoding.default_external
16
+ new(encoding == Encoding::UTF_8 ? UNICODE : ASCII)
17
+ end
18
+
19
+ def initialize(glyphs)
20
+ @glyphs = glyphs
21
+ end
22
+
23
+ def glyph(status)
24
+ @glyphs.fetch(status)
25
+ end
26
+
27
+ def ellipsis
28
+ @glyphs.fetch(:ellipsis)
29
+ end
30
+
31
+ def style(status)
32
+ STYLES.fetch(status)
33
+ end
34
+
35
+ # The line as it is written to the terminal, colored according to RSpec's
36
+ # color configuration.
37
+ def paint(line)
38
+ text = line.style ? Core::Formatters::ConsoleCodes.wrap(line.text, line.style) : line.text
39
+ line.indent + text
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RSpec
4
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
5
+ # Number of finished examples by outcome.
6
+ Counts = Struct.new(:passed, :failed, :pending) do
7
+ def self.zero
8
+ new(0, 0, 0)
9
+ end
10
+
11
+ def +(other)
12
+ Counts.new(passed + other.passed, failed + other.failed, pending + other.pending)
13
+ end
14
+
15
+ def total
16
+ passed + failed + pending
17
+ end
18
+ end
19
+
20
+ # Position of a node in the tree: its parent group (nil at the top level) and its
21
+ # index among its siblings.
22
+ module TreePosition
23
+ attr_reader :parent, :index
24
+
25
+ def attach(parent, index)
26
+ @parent = parent
27
+ @index = index
28
+ self
29
+ end
30
+
31
+ def depth
32
+ parent ? parent.depth + 1 : 0
33
+ end
34
+ end
35
+
36
+ # An example in the tree. Its status is :running until it finishes as
37
+ # :passed, :failed or :pending; `detail` holds e.g. "FAILED - 1".
38
+ class ExampleNode
39
+ include TreePosition
40
+
41
+ attr_reader :description, :status, :detail
42
+
43
+ def initialize(description)
44
+ @description = description
45
+ @status = :running
46
+ @detail = nil
47
+ end
48
+
49
+ def finish(status, detail = nil, description: @description)
50
+ @description = description
51
+ @status = status
52
+ @detail = detail
53
+ end
54
+
55
+ def finished?
56
+ @status != :running
57
+ end
58
+
59
+ def counts
60
+ Counts.new(status == :passed ? 1 : 0, status == :failed ? 1 : 0, status == :pending ? 1 : 0)
61
+ end
62
+ end
63
+
64
+ # An example group in the tree, with its child groups and examples in run order.
65
+ class GroupNode
66
+ include TreePosition
67
+
68
+ attr_reader :description, :children
69
+
70
+ def initialize(description)
71
+ @description = description
72
+ @children = []
73
+ @finished = false
74
+ end
75
+
76
+ def finish
77
+ @finished = true
78
+ end
79
+
80
+ def finished?
81
+ @finished
82
+ end
83
+
84
+ # Counts of finished examples in this group and all nested groups. Fixed once the
85
+ # group has finished, so it is computed only once from then on.
86
+ def counts
87
+ @counts || children.map(&:counts).reduce(Counts.zero, :+).tap { |counts| @counts = counts if finished? }
88
+ end
89
+
90
+ # :running until finished; then :failed, :pending or :passed by the worst
91
+ # outcome among its examples, or :empty if no examples ran in it.
92
+ def status
93
+ return :running unless finished?
94
+
95
+ counts = self.counts
96
+ if counts.total.zero? then :empty
97
+ elsif counts.failed.positive? then :failed
98
+ elsif counts.pending.positive? then :pending
99
+ else :passed
100
+ end
101
+ end
102
+ end
103
+
104
+ # The hierarchy of groups and examples seen so far, built from RSpec events.
105
+ #
106
+ # RSpec runs examples one at a time, so the tree tracks the currently open groups
107
+ # as a stack and the currently running example.
108
+ class Tree
109
+ attr_reader :groups
110
+
111
+ def initialize
112
+ @groups = []
113
+ @open_groups = []
114
+ @current_example = nil
115
+ end
116
+
117
+ # Nesting depth of the innermost open group (0 when no group is open).
118
+ def depth
119
+ @open_groups.size
120
+ end
121
+
122
+ def group_started(description)
123
+ group = add(GroupNode.new(description), @open_groups.last)
124
+ @open_groups.push(group)
125
+ group
126
+ end
127
+
128
+ def group_finished
129
+ @open_groups.pop.tap(&:finish)
130
+ end
131
+
132
+ def example_started(description)
133
+ @current_example = add(ExampleNode.new(description), @open_groups.last)
134
+ end
135
+
136
+ def example_finished(description, status, detail = nil)
137
+ example = @current_example || example_started(description)
138
+ @current_example = nil
139
+ example.finish(status, detail, description: description)
140
+ example
141
+ end
142
+
143
+ private
144
+
145
+ def add(node, parent)
146
+ siblings = parent ? parent.children : @groups
147
+ siblings << node.attach(parent, siblings.size)
148
+ node
149
+ end
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rspec/core"
4
+ require "rspec/core/formatters/base_text_formatter"
5
+ require "rspec/collapsing_formatter/symbols"
6
+ require "rspec/collapsing_formatter/tree"
7
+ require "rspec/collapsing_formatter/layout"
8
+ require "rspec/collapsing_formatter/stream_output"
9
+ require "rspec/collapsing_formatter/stray_output"
10
+ require "rspec/collapsing_formatter/live_output"
11
+
12
+ module RSpec
13
+ # A documentation-style formatter that collapses finished example groups.
14
+ #
15
+ # Failure, pending and summary output is inherited unchanged from RSpec's
16
+ # BaseTextFormatter. This class only translates RSpec events into changes to the
17
+ # tree and calls on an output object, which owns everything about how lines reach
18
+ # the terminal.
19
+ class CollapsingFormatter < Core::Formatters::BaseTextFormatter
20
+ VERSION = "0.1.0"
21
+
22
+ Core::Formatters.register self,
23
+ :start, :message,
24
+ :example_group_started, :example_group_finished,
25
+ :example_started, :example_passed, :example_failed, :example_pending,
26
+ :start_dump
27
+
28
+ def initialize(output)
29
+ super
30
+ @tree = Tree.new
31
+ symbols = Symbols.for(output)
32
+ @renderer =
33
+ if LiveOutput.supported?(output)
34
+ LiveOutput.new(output, symbols, @tree)
35
+ else
36
+ StreamOutput.new(output, symbols)
37
+ end
38
+ @failure_count = 0
39
+ end
40
+
41
+ def start(notification)
42
+ super
43
+ @renderer.start
44
+ end
45
+
46
+ # RSpec messages (e.g. "Run options: ...") are printed above the live region.
47
+ def message(notification)
48
+ @renderer.message(notification.message)
49
+ end
50
+
51
+ def example_group_started(notification)
52
+ group = @tree.group_started(notification.group.description.strip)
53
+ @renderer.group_started(group, @tree.depth - 1)
54
+ end
55
+
56
+ def example_group_finished(_notification)
57
+ group = @tree.group_finished
58
+ @renderer.group_finished(group, @tree.depth)
59
+ end
60
+
61
+ def example_started(notification)
62
+ example = @tree.example_started(notification.example.description.strip)
63
+ @renderer.example_started(example, @tree.depth)
64
+ end
65
+
66
+ def example_passed(notification)
67
+ example_finished(notification.example, :passed)
68
+ end
69
+
70
+ def example_failed(notification)
71
+ @failure_count += 1
72
+ example_finished(notification.example, :failed, "FAILED - #{@failure_count}")
73
+ end
74
+
75
+ def example_pending(notification)
76
+ example = notification.example
77
+ example_finished(example, :pending, "PENDING: #{example.execution_result.pending_message}")
78
+ end
79
+
80
+ # Called before RSpec's failure, pending and summary output, which is then
81
+ # appended below the tree by the inherited dump methods.
82
+ def start_dump(_notification)
83
+ @renderer.finish
84
+ end
85
+
86
+ # Also finishes the output when the run ends without reaching start_dump.
87
+ # Finishing twice is harmless.
88
+ def close(notification)
89
+ @renderer.finish
90
+ super
91
+ end
92
+
93
+ private
94
+
95
+ # Descriptions are read again on finish: RSpec generates descriptions for
96
+ # examples like `it { is_expected.to be_valid }` only after they have run.
97
+ def example_finished(example, status, detail = nil)
98
+ node = @tree.example_finished(example.description.strip, status, detail)
99
+ @renderer.example_finished(node, @tree.depth)
100
+ end
101
+ end
102
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rspec-collapsing-formatter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Adam Lett
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: rspec-core
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '3.10'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '3.10'
26
+ - !ruby/object:Gem::Dependency
27
+ name: unicode-display_width
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '2.4'
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '4'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '2.4'
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '4'
46
+ email:
47
+ - adamlett@gmail.com
48
+ executables: []
49
+ extensions: []
50
+ extra_rdoc_files: []
51
+ files:
52
+ - LICENSE
53
+ - README.md
54
+ - lib/rspec/collapsing_formatter.rb
55
+ - lib/rspec/collapsing_formatter/layout.rb
56
+ - lib/rspec/collapsing_formatter/live_output.rb
57
+ - lib/rspec/collapsing_formatter/stray_output.rb
58
+ - lib/rspec/collapsing_formatter/stream_output.rb
59
+ - lib/rspec/collapsing_formatter/symbols.rb
60
+ - lib/rspec/collapsing_formatter/tree.rb
61
+ homepage: https://github.com/KaptajnKold/rspec-collapsing-formatter
62
+ licenses:
63
+ - MIT
64
+ metadata:
65
+ source_code_uri: https://github.com/KaptajnKold/rspec-collapsing-formatter
66
+ bug_tracker_uri: https://github.com/KaptajnKold/rspec-collapsing-formatter/issues
67
+ rubygems_mfa_required: 'true'
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '3.1'
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubygems_version: 3.6.9
83
+ specification_version: 4
84
+ summary: An RSpec documentation-style formatter that collapses finished example groups.
85
+ test_files: []