padded_cell 0.1.0 → 0.2.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.
Files changed (58) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/Cargo.lock +2 -2
  4. data/README.md +148 -7
  5. data/ext/padded_cell_native/core/Cargo.toml +1 -1
  6. data/ext/padded_cell_native/core/src/chart/directives/tests.rs +56 -0
  7. data/ext/padded_cell_native/core/src/chart/directives.rs +144 -0
  8. data/ext/padded_cell_native/core/src/chart/json/tests.rs +46 -0
  9. data/ext/padded_cell_native/core/src/chart/json.rs +175 -0
  10. data/ext/padded_cell_native/core/src/chart/lcov.rs +50 -0
  11. data/ext/padded_cell_native/core/src/chart/markdown/tests.rs +93 -0
  12. data/ext/padded_cell_native/core/src/chart/markdown.rs +201 -0
  13. data/ext/padded_cell_native/core/src/chart/methods/tests.rs +38 -0
  14. data/ext/padded_cell_native/core/src/chart/methods.rs +62 -0
  15. data/ext/padded_cell_native/core/src/chart/output/tests.rs +45 -0
  16. data/ext/padded_cell_native/core/src/chart/output.rs +103 -0
  17. data/ext/padded_cell_native/core/src/chart/results/tests.rs +96 -0
  18. data/ext/padded_cell_native/core/src/chart/results.rs +379 -0
  19. data/ext/padded_cell_native/core/src/chart/source/tests.rs +64 -0
  20. data/ext/padded_cell_native/core/src/chart/source.rs +153 -0
  21. data/ext/padded_cell_native/core/src/chart/stats/tests.rs +52 -0
  22. data/ext/padded_cell_native/core/src/chart/stats.rs +218 -0
  23. data/ext/padded_cell_native/core/src/chart/test_support.rs +93 -0
  24. data/ext/padded_cell_native/core/src/chart/tests.rs +97 -0
  25. data/ext/padded_cell_native/core/src/chart/thresholds/tests.rs +36 -0
  26. data/ext/padded_cell_native/core/src/chart/thresholds.rs +116 -0
  27. data/ext/padded_cell_native/core/src/chart.rs +302 -0
  28. data/ext/padded_cell_native/core/src/discover/tests.rs +2 -0
  29. data/ext/padded_cell_native/core/src/discover.rs +7 -53
  30. data/ext/padded_cell_native/core/src/error.rs +24 -0
  31. data/ext/padded_cell_native/core/src/lib.rs +5 -1
  32. data/ext/padded_cell_native/core/src/parallel.rs +43 -0
  33. data/ext/padded_cell_native/ffi/Cargo.toml +1 -1
  34. data/ext/padded_cell_native/ffi/src/chart.rs +205 -0
  35. data/ext/padded_cell_native/ffi/src/lib.rs +3 -0
  36. data/lib/padded_cell/asylum.rb +91 -0
  37. data/lib/padded_cell/cell.rb +14 -8
  38. data/lib/padded_cell/chart/accumulator.rb +103 -0
  39. data/lib/padded_cell/chart/config.rb +129 -0
  40. data/lib/padded_cell/chart/delta.rb +148 -0
  41. data/lib/padded_cell/chart/document.rb +64 -0
  42. data/lib/padded_cell/chart/filter.rb +55 -0
  43. data/lib/padded_cell/chart/merge.rb +63 -0
  44. data/lib/padded_cell/chart/probe.rb +70 -0
  45. data/lib/padded_cell/chart/raw.rb +48 -0
  46. data/lib/padded_cell/chart/report.rb +128 -0
  47. data/lib/padded_cell/chart/source_files.rb +90 -0
  48. data/lib/padded_cell/chart.rb +38 -0
  49. data/lib/padded_cell/cli.rb +59 -4
  50. data/lib/padded_cell/loader.rb +5 -1
  51. data/lib/padded_cell/pool.rb +19 -42
  52. data/lib/padded_cell/reporters.rb +20 -3
  53. data/lib/padded_cell/results.rb +13 -0
  54. data/lib/padded_cell/runner.rb +125 -22
  55. data/lib/padded_cell/version.rb +1 -1
  56. data/lib/padded_cell/worker.rb +63 -0
  57. data/lib/padded_cell.rb +8 -0
  58. metadata +39 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b89fce8fce6e50ada1a385206f76070b475a2f9e90f495170753d6d66a6f8332
4
- data.tar.gz: 9ee3b35b649b6be14e016202f87989441145c8c3ace22e6061a0a61016bb8751
3
+ metadata.gz: 71107b6522d03ca5d3c7f11cb93cd0e6374f283b843a1b456699d69f2a131e11
4
+ data.tar.gz: efd0654d4986a1fca13380f8a5abcea88ead77944e7e7a92b4cd6a58a69208de
5
5
  SHA512:
6
- metadata.gz: 9bf53e2049839807e263fa6af61852e63ee7574e2f3902448ef73fbf926b607b02e93bc6a7fbc61a603998321b8f7461f907666d59cdcb816be999665f4ed258
7
- data.tar.gz: 90fc61b89533d99849333689f04ff149e079fb775a835cc4d26a0d9224d722a698fb9198f1a23ea0875fb4ac0be21a4949d641e6be45de1ca0f5d848a98886c5
6
+ metadata.gz: 64a6eca62591f0b9c6c887587ae7a00be9135f4b6addb9fb4e869fe9fae10b6be9145c9a3834d05e83a2e9e225319f846b91f85a92266038db1bf383b40d3c65
7
+ data.tar.gz: 53049afc045f49d8a3e62504780babf42a7800988055c2075a961c57fb124085c868a31fff5356f4bf8ed5fd1db3c61e2c771ae151b2d243e62d92facb304c81
data/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-10-11)
4
+
5
+ - Built-in coverage: `--coverage[=lines,branches,methods,eval]` (or
6
+ `PADDED_CELL_COVERAGE`) measures the runner, every worker and every cell,
7
+ and sums them exactly. Configured with `PaddedCell.coverage` in the test
8
+ helper: tracked files, filters, groups, the `:rails` profile. Honors
9
+ `# :nocov:` blocks and `# simplecov:disable` comments. Writes
10
+ `coverage.md` (the code that never ran, for agents, reviews and CI
11
+ summaries), `lcov.info`, and `coverage.json` / `.resultset.json`.
12
+ `minimum`, `minimum_by_file`, `minimum_by_group` and `maximum_drop` fail a
13
+ whole passing run with exit 3. `--coverage-merge` merges shards' reports.
14
+ - `--seed` must be 0 to 2**64 - 1; others crashed the planner.
15
+ - `--asylum[=N]`: retry failed tests (N times, default 2) after the run,
16
+ alone and in fresh cells. Tests that pass on retry count as passed and are
17
+ reported as flaky, with the likely cause (timing and shared state, or
18
+ randomness and order) and their first failure; JUnit gets
19
+ `<flakyFailure>`, JSON a `flaky` field.
20
+ - A `cleanup` hook that raises fails the run (exit 1), `--asylum` retries
21
+ included. It exited 0 when the tests passed.
22
+ - A passing run filtered with `--name` exits 0: it exited 1, reporting that
23
+ nothing ran.
24
+ - `--list` applies `--name` and `--exclude`, before `--shard`, as a run does.
25
+ - An invalid `--name` or `--exclude` regexp is a usage error (exit 2), not a
26
+ crash.
27
+
3
28
  ## 0.1.0 (2026-10-11)
4
29
 
5
30
  First release, for CRuby 4.0+ and Minitest 6 on Linux, macOS and FreeBSD: a
data/Cargo.lock CHANGED
@@ -220,7 +220,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
220
220
 
221
221
  [[package]]
222
222
  name = "padded_cell"
223
- version = "0.1.0"
223
+ version = "0.2.0"
224
224
  dependencies = [
225
225
  "ruby-prism",
226
226
  "tempfile",
@@ -229,7 +229,7 @@ dependencies = [
229
229
 
230
230
  [[package]]
231
231
  name = "padded_cell_native"
232
- version = "0.1.0"
232
+ version = "0.2.0"
233
233
  dependencies = [
234
234
  "magnus",
235
235
  "padded_cell",
data/README.md CHANGED
@@ -70,13 +70,15 @@ $ padded_cell -n /refund/ -e test_slow # Minitest's --include / --exclude
70
70
  $ padded_cell -j 8 --seed 1234 # 8 workers, reproducible order
71
71
  $ padded_cell --timeout 30 # kill and fail anything running 30s
72
72
  $ padded_cell --fail-fast
73
+ $ padded_cell --asylum # retry failures; report the flaky ones (see below)
73
74
  $ padded_cell --list # what would run, without loading anything
74
75
  $ padded_cell --shard 2/4 # CI: the second quarter of the classes
75
76
  $ padded_cell --junit tmp/junit.xml --json tmp/results.jsonl
77
+ $ padded_cell --coverage # line and branch coverage (see Coverage)
76
78
  ```
77
79
 
78
80
  Exit status: 0 when everything passed, 1 otherwise, 2 for usage or load
79
- errors, 130 when interrupted.
81
+ errors, 3 when only coverage is below a threshold, 130 when interrupted.
80
82
 
81
83
  ### How a run works
82
84
 
@@ -113,6 +115,38 @@ discards Active Record's connection pool, and every test would reload its
113
115
  fixtures, so those suites default to `worker`. The `Run options:` line shows
114
116
  which one a run uses; `--isolation` overrides it.
115
117
 
118
+ ### Flaky tests
119
+
120
+ `--asylum[=N]` gives failed tests up to N more attempts (default 2) once the
121
+ run is over: one test at a time, each in a fresh cell. A test that passes on
122
+ retry counts as passed, but padded_cell shows every attempt, its seed, and
123
+ what made the difference:
124
+
125
+ ```console
126
+ 4 runs, 4 assertions, 1 failures, 0 errors, 0 skips
127
+
128
+ You're not crazy, the world is. 2 tests failed, then passed:
129
+
130
+ FlakyTest#test_passes_when_retried
131
+ seed 1 lost the race
132
+ seed 1 passed, alone → timing, contention or state left by other tests
133
+
134
+ FlakyTest#test_depends_on_the_seed
135
+ seed 1 unlucky seed.
136
+ seed 1 unlucky seed. (alone)
137
+ seed 15472 passed, alone → randomness or test order
138
+
139
+ It's not the world, it's the test:
140
+ FlakyTest#test_always_fails failed all 3 attempts
141
+ ```
142
+
143
+ The first retry keeps the run's seed and runs alone, so passing there points
144
+ at timing, contention or leftover state; later retries change the seed, so
145
+ passing only there points at randomness or order. A test that fails every
146
+ attempt keeps its first failure, and the run fails. JUnit reports carry a
147
+ `<flakyFailure>` per flaky test; JSON lines carry the attempts in a `flaky`
148
+ field, or an `asylum` field for a test that never passed.
149
+
116
150
  ### Hooks
117
151
 
118
152
  For anything that must not be shared across forks:
@@ -125,7 +159,115 @@ PaddedCell.cleanup { |worker| Database.drop("app_test_#{worker}") }
125
159
  ```
126
160
 
127
161
  `before_fork` runs in the runner, `after_fork` and `cleanup` once per worker
128
- (`0...jobs`). Cells run no hooks: they inherit their worker's state.
162
+ (`0...jobs`). Cells run no hooks: they inherit their worker's state. A
163
+ failing `after_fork` fails every test of its worker; a failing `cleanup`
164
+ fails the run, even when every test passed.
165
+
166
+ ## Coverage
167
+
168
+ Ruby's `Coverage`, measured in the runner, in every worker and in every
169
+ cell, and summed exactly: a parallel run reports the counts of a serial one.
170
+
171
+ ```console
172
+ $ padded_cell --coverage test/ # lines and branches
173
+ $ padded_cell --coverage=lines,branches,methods test/
174
+ $ PADDED_CELL_COVERAGE=1 bin/rails padded_cell
175
+ ```
176
+
177
+ Measuring starts before the suite loads, so what is measured (`lines`,
178
+ `branches`, `methods`, and `eval` for templates, experimental) comes from the
179
+ command line. The report is configured in the test helper:
180
+
181
+ ```ruby
182
+ # test/test_helper.rb
183
+ PaddedCell.coverage(:rails) do
184
+ track "{app,lib}/**/*.rb" # report files never loaded, at 0%
185
+ skip "app/legacy/" # also `filter`
186
+ group "Operations", "app/concepts" # string, regexp, array or block
187
+ group("Contracts") { |file| file.filename.include?("contract") }
188
+ minimum line: 90, branch: 80
189
+ minimum_by_file line: 50
190
+ minimum_by_group "Operations", line: 95
191
+ maximum_drop line: 1 # since the previous whole run
192
+ formats :markdown, :lcov, :json
193
+ dir "coverage" # --coverage-dir wins
194
+ end
195
+ ```
196
+
197
+ - Paths are matched relative to the project root. A string matches whole
198
+ path segments (`"app/models"` takes `app/models/user.rb`, not
199
+ `app/models_old/`), `"lib/"` a directory anywhere, `"contract.rb"` a file
200
+ name ending; a regexp matches the path; a block gets the file
201
+ (`filename`, `project_filename`, `src`).
202
+ - Left out by default: `vendor/bundle`, hidden files, `test/`, `spec/`,
203
+ `features/`. `clear_filters` drops these.
204
+ - `:rails` skips `config/` and `db/`, groups `app/channels`,
205
+ `app/controllers`, `app/helpers`, `app/jobs` and `app/workers`, `lib/`,
206
+ `app/mailers`, `app/models` and `app/views`, and tracks
207
+ `{app,lib}/**/*.rb`. A file in no group is Ungrouped.
208
+ - Thresholds compare percents floored to 2 decimals.
209
+
210
+ `PaddedCell.coverage` configures only; without `--coverage` nothing is
211
+ measured. Outside padded_cell, guard it with `if defined?(PaddedCell.coverage)`.
212
+
213
+ Into `coverage/` go, by format:
214
+
215
+ - `markdown`: `coverage.md`, for agents, reviews and CI summaries
216
+ (`cat coverage/coverage.md >> $GITHUB_STEP_SUMMARY`): the totals and
217
+ groups, then every file with code that never ran, the most missed first,
218
+ with its missed lines, branches and methods, and that code. It stops
219
+ listing files at 1 MB, the size of a GitHub job summary.
220
+ - `lcov`: `lcov.info` (`SF:./path`), for CI and editors.
221
+ - `json`: `coverage.json` and `.resultset.json`, in SimpleCov's formats, for
222
+ the tools reading them.
223
+
224
+ Also, every run: `.padded_cell.json` (what the report is made of, and what
225
+ `--coverage-merge` reads), and after a whole passing run `.last_run.json`.
226
+
227
+ Lines and branches inside `# :nocov:` blocks, and under
228
+ `# simplecov:disable [line|branch|method]` / `# simplecov:enable` comments,
229
+ are skipped. A directive after code skips its own line.
230
+
231
+ A run below a threshold exits 3. Thresholds hold for a whole, passing,
232
+ complete run only: they are not checked when tests failed, when tests were
233
+ picked by name or line, under `--shard`, or when a worker or cell died
234
+ before handing over what it measured (the report then says it is partial).
235
+ Reports are written either way, failing runs included.
236
+
237
+ A suite that starts SimpleCov as well is refused (exit 2): two tools cannot
238
+ share Ruby's `Coverage`.
239
+
240
+ ### Shards
241
+
242
+ Each shard reports on its own; merge them, at the same commit, without
243
+ running anything:
244
+
245
+ ```console
246
+ $ padded_cell --coverage --coverage-dir coverage/1 --shard 1/2 test/ # machine 1
247
+ $ padded_cell --coverage --coverage-dir coverage/2 --shard 2/2 test/ # machine 2
248
+ $ padded_cell --coverage-merge coverage/1,coverage/2 --coverage-dir coverage
249
+ ```
250
+
251
+ The merge refuses files that differ between shards or from the checkout,
252
+ and checks thresholds when every shard of the run is there. Lines that run
253
+ while the suite loads count once per shard.
254
+
255
+ ### Cost
256
+
257
+ Measuring is opt-in: Ruby's instrumentation slows tests down. On a Rails
258
+ suite of 6,300 tests, lines and branches took the run from 465 s to 638 s of
259
+ CPU.
260
+
261
+ A worker hands over what it measured every 10 seconds or more: each time,
262
+ Ruby copies the coverage of every file it loaded, gems included (a few
263
+ milliseconds in a small app, a few hundred in a big Rails one), so the
264
+ interval stretches to keep this under 1% of the worker's time. A worker that
265
+ dies loses what it measured since. With `--isolation test` every cell pays
266
+ one such copy, at its end.
267
+
268
+ Files never loaded report their branches in the order Ruby compiles them.
269
+ With `eval`, code that `class_eval` runs from a heredoc counts as lines of
270
+ its file; directives in templates are not read.
129
271
 
130
272
  ## Rails
131
273
 
@@ -144,8 +286,7 @@ $ bin/rails padded_cell ARGS="-j 8 test/models"
144
286
  Rails suites with fixtures run with `--isolation worker` unless told
145
287
  otherwise (see [Isolation](#isolation)).
146
288
 
147
- Coverage tools that write their results from an `at_exit` hook (SimpleCov)
148
- see only the runner, as with Rails' process parallelization.
289
+ For coverage, see [Coverage](#coverage).
149
290
 
150
291
  ## Library
151
292
 
@@ -173,9 +314,9 @@ Needs Rust 1.99+ (`mise install` reads `mise.toml`).
173
314
 
174
315
  ```console
175
316
  bundle install
176
- rake test:all # cargo test, then the Ruby suite (compiles the extension first)
177
- rake test # the Ruby suite only
178
- rake dogfood # this suite, run by padded_cell
317
+ rake test:all # cargo test, then this suite run by padded_cell itself
318
+ rake dogfood # this suite, run by padded_cell (compiles the extension first)
319
+ rake test # this suite on plain Minitest, for when padded_cell itself is broken
179
320
  rake lint # dictator, cargo fmt --check, clippy
180
321
  ```
181
322
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "padded_cell"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Static Minitest discovery and test scheduling for the padded_cell gem"
5
5
  publish = false
6
6
  edition.workspace = true
@@ -0,0 +1,56 @@
1
+ use super::*;
2
+
3
+ fn skipped(text: &str) -> Skipped {
4
+ Skipped::of(&Source::new(text.as_bytes().to_vec()), "nocov")
5
+ }
6
+
7
+ /// Where the `#` is, disable, and the criteria named.
8
+ type Found = Option<(usize, bool, [bool; 3])>;
9
+
10
+ #[test]
11
+ fn directives_found_in_comments() {
12
+ const CASES: &[(&str, Found)] = &[
13
+ ("# simplecov:disable", Some((0, true, [true; 3]))),
14
+ ("#simplecov : enable", Some((0, false, [true; 3]))),
15
+ ("# simplecov:disable branch", Some((0, true, [false, true, false]))),
16
+ ("# simplecov:disable line , method because", Some((0, true, [true, false, true]))),
17
+ // The longest list ending at a word boundary.
18
+ ("# simplecov:disable line, branchy", Some((0, true, [true, false, false]))),
19
+ ("# simplecov:disable lines", Some((0, true, [true; 3]))),
20
+ ("# note # simplecov:disable", Some((7, true, [true; 3]))),
21
+ ("# simplecov:disabled", None),
22
+ ("# simplecov disable", None),
23
+ ("# rubocop:disable Style", None),
24
+ ];
25
+ for (text, expected) in CASES {
26
+ let found = Directive::find(text.as_bytes())
27
+ .map(|(at, directive)| (at, directive.disable, directive.criteria));
28
+ assert_eq!(found, *expected, "comment: {text:?}");
29
+ }
30
+ }
31
+
32
+ #[test]
33
+ fn blocks_inline_directives_and_nocov() {
34
+ let text = "\
35
+ a
36
+ # simplecov:disable branch
37
+ b
38
+ # simplecov:enable branch
39
+ c # simplecov:disable
40
+ # :nocov:
41
+ d
42
+ # :nocov:
43
+ # simplecov:disable method
44
+ e
45
+ ";
46
+ let skipped = skipped(text);
47
+ assert_eq!(skipped.line, [6..=8, 5..=5]);
48
+ assert_eq!(skipped.branch, [6..=8, 2..=4, 5..=5]);
49
+ assert_eq!(skipped.method, [6..=8, 5..=5, 9..=10], "an open block runs to the end");
50
+ }
51
+
52
+ #[test]
53
+ fn only_real_comments_count() {
54
+ let text = "x = \"# simplecov:disable\"\ny = <<~TEXT\n # simplecov:disable\nTEXT\n";
55
+ assert_eq!(skipped(text), Skipped::default());
56
+ }
@@ -0,0 +1,144 @@
1
+ use std::ops::RangeInclusive;
2
+
3
+ use ruby_prism::CommentType;
4
+
5
+ use super::Source;
6
+ use super::source::{ruby_space, trim_start as skip_space};
7
+
8
+ #[cfg(test)]
9
+ mod tests;
10
+
11
+ /// Blocks of lines, inclusive.
12
+ pub type Blocks = Vec<RangeInclusive<u32>>;
13
+
14
+ /// The lines each criterion ignores.
15
+ #[derive(Debug, Clone, Default, PartialEq, Eq)]
16
+ pub struct Skipped {
17
+ pub line: Blocks,
18
+ pub branch: Blocks,
19
+ pub method: Blocks,
20
+ }
21
+
22
+ impl Skipped {
23
+ #[must_use]
24
+ pub fn of(source: &Source, nocov_token: &str) -> Self {
25
+ let nocov = source.nocov(nocov_token);
26
+ let mut skipped = Self { line: nocov.clone(), branch: nocov.clone(), method: nocov };
27
+ // Parsing only sources that may hold one.
28
+ if source.bytes().windows(9).any(|window| window == b"simplecov") {
29
+ skipped.add_directives(source);
30
+ }
31
+ skipped
32
+ }
33
+
34
+ fn add_directives(&mut self, source: &Source) {
35
+ let result = ruby_prism::parse(source.bytes());
36
+ let mut open: [Option<u32>; 3] = [None; 3];
37
+ let comments =
38
+ result.comments().filter(|comment| comment.type_() == CommentType::InlineComment);
39
+ for comment in comments {
40
+ let Some((at, directive)) = Directive::find(comment.text()) else {
41
+ continue;
42
+ };
43
+ let offset = comment.location().start_offset().strict_add(at);
44
+ let (line, _) = source.position(offset);
45
+ let before = &source.bytes()[source.line_start(offset)..offset];
46
+ let inline = before.iter().any(|&byte| !ruby_lstrip_space(byte));
47
+ let blocks = self.blocks_mut().into_iter().zip(&mut open);
48
+ for ((blocks, open), _) in blocks.zip(directive.criteria).filter(|&(_, named)| named) {
49
+ directive.apply(line, inline, blocks, open);
50
+ }
51
+ }
52
+ let last = u32::try_from(source.len()).unwrap_or(u32::MAX);
53
+ for (blocks, open) in self.blocks_mut().into_iter().zip(open) {
54
+ blocks.extend(open.map(|start| start..=last));
55
+ }
56
+ }
57
+
58
+ const fn blocks_mut(&mut self) -> [&mut Blocks; 3] {
59
+ [&mut self.line, &mut self.branch, &mut self.method]
60
+ }
61
+ }
62
+
63
+ /// A `# simplecov:disable` or `enable`, and the criteria it names: line,
64
+ /// branch, method.
65
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
66
+ struct Directive {
67
+ disable: bool,
68
+ criteria: [bool; 3],
69
+ }
70
+
71
+ impl Directive {
72
+ /// The first directive in a comment, and where its `#` is:
73
+ /// `/#\s*simplecov\s*:\s*(disable|enable)\b(?:\s+(criteria)\b)?/`.
74
+ fn find(text: &[u8]) -> Option<(usize, Self)> {
75
+ text.iter().enumerate().filter(|&(_, &byte)| byte == b'#').find_map(|(at, _)| {
76
+ Self::parse(&text[at.strict_add(1)..]).map(|directive| (at, directive))
77
+ })
78
+ }
79
+
80
+ fn parse(text: &[u8]) -> Option<Self> {
81
+ let text = skip_space(skip_space(text).strip_prefix(b"simplecov")?).strip_prefix(b":")?;
82
+ let text = skip_space(text);
83
+ let (disable, rest) = match text.strip_prefix(b"disable") {
84
+ Some(rest) => (true, rest),
85
+ None => (false, text.strip_prefix(b"enable")?),
86
+ };
87
+ if starts_with_word(rest) {
88
+ return None;
89
+ }
90
+ Some(Self { disable, criteria: criteria(rest).unwrap_or([true; 3]) })
91
+ }
92
+
93
+ /// After code, a directive covers its own line; alone on its line, it
94
+ /// opens or closes a block (a block already open stays as it is).
95
+ fn apply(self, line: u32, inline: bool, blocks: &mut Blocks, open: &mut Option<u32>) {
96
+ if inline {
97
+ if self.disable {
98
+ blocks.push(line..=line);
99
+ }
100
+ } else if self.disable {
101
+ open.get_or_insert(line);
102
+ } else if let Some(start) = open.take() {
103
+ blocks.push(start..=line);
104
+ }
105
+ }
106
+ }
107
+
108
+ /// `\s+(line|branch|method)(\s*,\s*(line|branch|method))*\b`, the longest
109
+ /// list that ends at a word boundary.
110
+ fn criteria(text: &[u8]) -> Option<[bool; 3]> {
111
+ if !text.first().is_some_and(|&byte| ruby_space(byte)) {
112
+ return None;
113
+ }
114
+ let (mut text, mut found, mut accepted) = (skip_space(text), [false; 3], None);
115
+ while let Some((index, rest)) = criterion(text) {
116
+ found[index] = true;
117
+ if starts_with_word(rest) {
118
+ break;
119
+ }
120
+ accepted = Some(found);
121
+ let Some(next) = skip_space(rest).strip_prefix(b",") else {
122
+ break;
123
+ };
124
+ text = skip_space(next);
125
+ }
126
+ accepted
127
+ }
128
+
129
+ fn criterion(text: &[u8]) -> Option<(usize, &[u8])> {
130
+ [&b"line"[..], b"branch", b"method"]
131
+ .iter()
132
+ .enumerate()
133
+ .find_map(|(index, name)| text.strip_prefix(*name).map(|rest| (index, rest)))
134
+ }
135
+
136
+ /// What Ruby's `String#lstrip` strips.
137
+ const fn ruby_lstrip_space(byte: u8) -> bool {
138
+ byte == 0 || ruby_space(byte)
139
+ }
140
+
141
+ /// Not at a word boundary: Ruby's `\w` comes next.
142
+ fn starts_with_word(text: &[u8]) -> bool {
143
+ text.first().is_some_and(|&byte| byte.is_ascii_alphanumeric() || byte == b'_')
144
+ }
@@ -0,0 +1,46 @@
1
+ use super::*;
2
+
3
+ fn render(pretty: bool, write: impl FnOnce(&mut Json<'_, Vec<u8>>) -> io::Result<()>) -> String {
4
+ let mut out = Vec::new();
5
+ let mut json = if pretty { Json::pretty(&mut out) } else { Json::compact(&mut out) };
6
+ write(&mut json).unwrap();
7
+ String::from_utf8(out).unwrap()
8
+ }
9
+
10
+ /// Ruby's output for `{a: [], b: {}, c: [1, {d: nil}]}`.
11
+ #[test]
12
+ fn layouts_of_pretty_generate_and_generate() {
13
+ let document = |json: &mut Json<'_, Vec<u8>>| {
14
+ json.object(|json| {
15
+ json.key("a")?.array(|_| Ok(()))?;
16
+ json.key("b")?.object(|_| Ok(()))?;
17
+ json.key("c")?.array(|json| {
18
+ json.item()?.uint(1)?;
19
+ json.item()?.object(|json| json.key("d")?.null())
20
+ })
21
+ })
22
+ };
23
+ assert_eq!(
24
+ render(true, document),
25
+ "{\n \"a\": [],\n \"b\": {},\n \"c\": [\n 1,\n {\n \"d\": null\n }\n ]\n}"
26
+ );
27
+ assert_eq!(render(false, document), r#"{"a":[],"b":{},"c":[1,{"d":null}]}"#);
28
+ }
29
+
30
+ /// Ruby's `JSON.generate(["\x1f\x01\b\f\n\r\t\"\\/é ", 100.0, 66.66666666666667, 0.1 + 0.2])`.
31
+ #[test]
32
+ fn strings_and_floats_as_ruby_writes_them() {
33
+ let rendered = render(false, |json| {
34
+ json.array(|json| {
35
+ json.item()?.str("\u{1f}\u{1}\u{8}\u{c}\n\r\t\"\\/é ")?;
36
+ json.item()?.float(100.0)?;
37
+ json.item()?.float(200.0 / 3.0)?;
38
+ json.item()?.float(0.1 + 0.2)?;
39
+ json.item()?.bool(false)
40
+ })
41
+ });
42
+ assert_eq!(
43
+ rendered,
44
+ r#"["\u001f\u0001\b\f\n\r\t\"\\/é ",100.0,66.66666666666667,0.30000000000000004,false]"#
45
+ );
46
+ }
@@ -0,0 +1,175 @@
1
+ use std::io::{self, Write};
2
+
3
+ #[cfg(test)]
4
+ mod tests;
5
+
6
+ /// A JSON writer. Containers take a closure writing their members:
7
+ ///
8
+ /// ```text
9
+ /// json.object(|json| {
10
+ /// json.key("lines")?.array(|json| json.item()?.uint(1))
11
+ /// })
12
+ /// ```
13
+ pub struct Json<'w, W: Write> {
14
+ out: &'w mut W,
15
+ pretty: bool,
16
+ depth: usize,
17
+ /// The innermost container has no member yet.
18
+ empty: bool,
19
+ }
20
+
21
+ impl<'w, W: Write> Json<'w, W> {
22
+ /// `JSON.pretty_generate`'s layout: two-space indents, one member per
23
+ /// line, `[]` and `{}` when empty.
24
+ pub const fn pretty(out: &'w mut W) -> Self {
25
+ Self { out, pretty: true, depth: 0, empty: true }
26
+ }
27
+
28
+ /// `JSON.generate`'s: no whitespace.
29
+ pub const fn compact(out: &'w mut W) -> Self {
30
+ Self { out, pretty: false, depth: 0, empty: true }
31
+ }
32
+
33
+ /// # Errors
34
+ ///
35
+ /// What writing returns.
36
+ pub fn object(&mut self, members: impl FnOnce(&mut Self) -> io::Result<()>) -> io::Result<()> {
37
+ self.container(b'{', b'}', members)
38
+ }
39
+
40
+ /// # Errors
41
+ ///
42
+ /// What writing returns.
43
+ pub fn array(&mut self, items: impl FnOnce(&mut Self) -> io::Result<()>) -> io::Result<()> {
44
+ self.container(b'[', b']', items)
45
+ }
46
+
47
+ /// Starts an object member: its value comes next.
48
+ ///
49
+ /// # Errors
50
+ ///
51
+ /// What writing returns.
52
+ pub fn key(&mut self, key: &str) -> io::Result<&mut Self> {
53
+ self.separate()?;
54
+ self.raw_str(key)?;
55
+ self.out.write_all(if self.pretty { b": " } else { b":" })?;
56
+ Ok(self)
57
+ }
58
+
59
+ /// Starts an array item: its value comes next.
60
+ ///
61
+ /// # Errors
62
+ ///
63
+ /// What writing returns.
64
+ pub fn item(&mut self) -> io::Result<&mut Self> {
65
+ self.separate()?;
66
+ Ok(self)
67
+ }
68
+
69
+ /// # Errors
70
+ ///
71
+ /// What writing returns.
72
+ pub fn str(&mut self, value: &str) -> io::Result<()> {
73
+ self.raw_str(value)
74
+ }
75
+
76
+ /// # Errors
77
+ ///
78
+ /// What writing returns.
79
+ pub fn uint(&mut self, value: u64) -> io::Result<()> {
80
+ write!(self.out, "{value}")
81
+ }
82
+
83
+ /// Ruby's way: `100.0`, not `100`.
84
+ ///
85
+ /// # Errors
86
+ ///
87
+ /// What writing returns.
88
+ pub fn float(&mut self, value: f64) -> io::Result<()> {
89
+ let mut text = value.to_string();
90
+ if !text.contains(['.', 'e', 'N', 'i']) {
91
+ text.push_str(".0");
92
+ }
93
+ self.out.write_all(text.as_bytes())
94
+ }
95
+
96
+ /// # Errors
97
+ ///
98
+ /// What writing returns.
99
+ pub fn bool(&mut self, value: bool) -> io::Result<()> {
100
+ self.out.write_all(if value { b"true" } else { b"false" })
101
+ }
102
+
103
+ /// # Errors
104
+ ///
105
+ /// What writing returns.
106
+ pub fn null(&mut self) -> io::Result<()> {
107
+ self.out.write_all(b"null")
108
+ }
109
+
110
+ fn container(
111
+ &mut self,
112
+ open: u8,
113
+ close: u8,
114
+ members: impl FnOnce(&mut Self) -> io::Result<()>,
115
+ ) -> io::Result<()> {
116
+ self.out.write_all(&[open])?;
117
+ self.depth = self.depth.strict_add(1);
118
+ self.empty = true;
119
+ members(self)?;
120
+ self.depth = self.depth.strict_sub(1);
121
+ if !self.empty {
122
+ self.newline()?;
123
+ }
124
+ // The enclosing container has this one as a member.
125
+ self.empty = false;
126
+ self.out.write_all(&[close])
127
+ }
128
+
129
+ fn separate(&mut self) -> io::Result<()> {
130
+ if !self.empty {
131
+ self.out.write_all(b",")?;
132
+ }
133
+ self.empty = false;
134
+ self.newline()
135
+ }
136
+
137
+ fn newline(&mut self) -> io::Result<()> {
138
+ if self.pretty {
139
+ self.out.write_all(b"\n")?;
140
+ for _ in 0..self.depth {
141
+ self.out.write_all(b" ")?;
142
+ }
143
+ }
144
+ Ok(())
145
+ }
146
+
147
+ /// Escapes what JSON requires, in runs: no copy of the string.
148
+ fn raw_str(&mut self, value: &str) -> io::Result<()> {
149
+ self.out.write_all(b"\"")?;
150
+ let bytes = value.as_bytes();
151
+ let mut start = 0;
152
+ for (index, &byte) in bytes.iter().enumerate() {
153
+ let escape: &[u8] = match byte {
154
+ b'"' => b"\\\"",
155
+ b'\\' => b"\\\\",
156
+ 0x08 => b"\\b",
157
+ 0x0c => b"\\f",
158
+ b'\n' => b"\\n",
159
+ b'\r' => b"\\r",
160
+ b'\t' => b"\\t",
161
+ 0x20.. => continue,
162
+ _ => b"",
163
+ };
164
+ self.out.write_all(&bytes[start..index])?;
165
+ if escape.is_empty() {
166
+ write!(self.out, "\\u{byte:04x}")?;
167
+ } else {
168
+ self.out.write_all(escape)?;
169
+ }
170
+ start = index.strict_add(1);
171
+ }
172
+ self.out.write_all(&bytes[start..])?;
173
+ self.out.write_all(b"\"")
174
+ }
175
+ }