rust-doctor 0.6.0

Local-first health audit for Cargo workspaces: curated Clippy lints and native detectors, scored out of 100
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use std::path::Path;
use std::time::Duration;

use crate::git_scope::ResolvedScope;
use crate::presentation::{DiagnosticGroup, GroupDiagnostic, ReportPresentation, code_frame};
use crate::terminal_text::{sanitize, truncate, wrap};
use crate::{GateStatus, InspectReport, Status};

mod score_header;

const DEFAULT_WIDTH: usize = 80;

/// The linear report never renders narrower than this, and every entry point
/// normalizes to it. That is what makes the score block total: at this width
/// the block always fits, so neither it nor this file carries a
/// narrow-terminal fallback with a second rounding of its own.
const MIN_WIDTH: usize = 80;
const _: () = assert!(MIN_WIDTH >= crate::score_block::MIN_BLOCK_COLUMNS);
/// Narrowest gutter a code frame is drawn with, so a report reads the same
/// whether its frames sit at line 7 or line 700.
const FRAME_GUTTER_COLUMNS: usize = 4;
const DOCS_URL: &str = "https://rust-doctor.com/docs";
const GITHUB_URL: &str = "https://github.com/arthjean/rust-doctor";

#[derive(Debug)]
pub enum RenderError {
    InvalidReport,
    Json(serde_json::Error),
    Write(io::Error),
}

impl RenderError {
    pub fn is_broken_pipe(&self) -> bool {
        match self {
            Self::InvalidReport => false,
            Self::Json(error) => error.io_error_kind() == Some(io::ErrorKind::BrokenPipe),
            Self::Write(error) => error.kind() == io::ErrorKind::BrokenPipe,
        }
    }
}

impl fmt::Display for RenderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidReport => formatter.write_str("refusing to render an invalid report"),
            Self::Json(error) => write!(formatter, "could not serialize report: {error}"),
            Self::Write(error) => write!(formatter, "could not write report: {error}"),
        }
    }
}

impl Error for RenderError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::InvalidReport => None,
            Self::Json(error) => Some(error),
            Self::Write(error) => Some(error),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct TerminalOptions<'a> {
    pub workspace_root: &'a Path,
    pub elapsed: Duration,
    pub verbose: bool,
    pub width: usize,
    pub color: bool,
    /// Allows the score block to animate. Reserved for a real interactive
    /// terminal: any captured output must stay deterministic.
    pub animate: bool,
}

impl<'a> TerminalOptions<'a> {
    pub const fn new(workspace_root: &'a Path) -> Self {
        Self {
            workspace_root,
            elapsed: Duration::ZERO,
            verbose: false,
            width: DEFAULT_WIDTH,
            color: false,
            animate: false,
        }
    }

    fn normalized(self) -> Self {
        Self {
            width: self.width.max(MIN_WIDTH),
            ..self
        }
    }
}

pub fn render_json<W: Write>(report: &InspectReport, mut writer: W) -> Result<(), RenderError> {
    if !report.is_valid() {
        return Err(RenderError::InvalidReport);
    }
    serde_json::to_writer(&mut writer, report).map_err(RenderError::Json)?;
    writer.write_all(b"\n").map_err(RenderError::Write)
}

pub fn render_terminal<W: Write>(report: &InspectReport, writer: W) -> Result<(), RenderError> {
    render_terminal_with_options(report, writer, TerminalOptions::new(Path::new(".")))
}

pub fn render_terminal_with_options<W: Write>(
    report: &InspectReport,
    writer: W,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let presentation = ReportPresentation::derive_terminal(report);
    render_terminal_with_presentation(report, &presentation, writer, options)
}

pub fn render_terminal_with_presentation<W: Write>(
    report: &InspectReport,
    presentation: &ReportPresentation,
    mut writer: W,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    if !report.is_valid() {
        return Err(RenderError::InvalidReport);
    }
    let options = options.normalized();
    let writer = &mut writer;

    if report.status == Status::Failed {
        return render_failure(writer, report, options);
    }

    // The report is its sections, in order. Nothing is composed inline here:
    // a line written straight into the entry point is a section nobody named,
    // and eight of them are what made this function the report's own worst
    // complexity hotspot.
    render_scope(writer, report, options)?;
    render_scanned(writer, report, options)?;
    render_findings(writer, presentation, options)?;
    render_totals(writer, presentation, options)?;
    render_categories(writer, report, options)?;
    render_configuration(writer, report, options)?;
    render_delta(writer, report, options)?;
    render_gate(writer, report, options)?;
    render_scan_errors(writer, report, options)?;
    render_advisories(writer, presentation, options)?;
    render_score(writer, report, options)?;
    render_links(writer, report, options)
}

/// What a failed scan may say: the scope it was attempted under, and the stage
/// that failed.
///
/// It measured nothing, so none of the sections below it apply: each of them
/// counts, tallies, ranks or scores a population no producer ever produced.
/// `No issues found.` over a scan that never ran is the same false claim as the
/// `100 / 100` face that used to close such a report, under the line naming the
/// failure.
fn render_failure<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    render_scope(writer, report, options)?;
    render_scan_errors(writer, report, options)
}

/// What the scan covered and how long it took.
fn render_scanned<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    line(
        writer,
        &format!(
            "Scanned {} files in {:.1}s",
            report.audit.source_files,
            options.elapsed.as_secs_f64()
        ),
        options,
        Style::Accent,
    )
}

/// The findings themselves: all of them under `--verbose`, the worst one
/// otherwise, and a sentence when there are none.
fn render_findings<W: Write>(
    writer: &mut W,
    presentation: &ReportPresentation,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    if presentation.issue_count == 0 {
        return line(writer, "No issues found.", options, Style::Success);
    }
    if options.verbose {
        for group in &presentation.groups {
            render_group(writer, group, options, GroupView::Full)?;
        }
        return Ok(());
    }
    let Some(group) = presentation.groups.first() else {
        return Ok(());
    };
    render_group(writer, group, options, GroupView::Top)
}

/// The rule below the findings, the two totals, and the hint that the rest is
/// one flag away.
fn render_totals<W: Write>(
    writer: &mut W,
    presentation: &ReportPresentation,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    line(
        writer,
        &"─".repeat(options.width.min(48)),
        options,
        Style::Muted,
    )?;
    line(
        writer,
        &format!(
            "All {} occurrences across {} findings",
            presentation.issue_count, presentation.finding_count
        ),
        options,
        Style::Heading,
    )
}

/// A rule firing across enough files that fixing it one site at a time is the
/// wrong plan.
fn render_advisories<W: Write>(
    writer: &mut W,
    presentation: &ReportPresentation,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    if !options.verbose && !presentation.groups.is_empty() {
        line(
            writer,
            "Run with --verbose to see every issue.",
            options,
            Style::Muted,
        )?;
    }
    for advisory in &presentation.migration_advisories {
        line(
            writer,
            &format!(
                "Migration advisory: {} appears {} times across {} files.",
                advisory.rule_id, advisory.occurrences, advisory.files
            ),
            options,
            Style::Warning,
        )?;
    }
    Ok(())
}

/// Where to take the report next. A failed scan reaches none of this: it is
/// rendered by `render_failure`, having no score to share and nothing the docs
/// would explain.
fn render_links<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    if let Ok(url) = report.audit.share_url() {
        line(writer, &format!("Share: {url}"), options, Style::Accent)?;
    }
    line(writer, &format!("Docs: {DOCS_URL}"), options, Style::Muted)?;
    line(
        writer,
        &format!("GitHub: {GITHUB_URL}"),
        options,
        Style::Muted,
    )
}

fn render_scope<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let description = report.scope.as_ref().map_or_else(
        || "Scope: full codebase".to_owned(),
        |scope| match scope.kind() {
            ResolvedScope::Full => "Scope: full codebase".to_owned(),
            ResolvedScope::Files {
                comparison_base,
                files,
            } => format!(
                "Scope: changed files ({} selected, base {})",
                files.len(),
                short_revision(comparison_base)
            ),
            ResolvedScope::Baseline { comparison_base } => format!(
                "Scope: baseline comparison (base {})",
                short_revision(comparison_base)
            ),
        },
    );
    line(writer, &description, options, Style::Heading)
}

/// How much of a group the report is drawing.
///
/// The two used to be two positional booleans, `top` and `all_locations`,
/// naming four combinations for the two that exist: the summary shows the
/// worst group with its first location, the verbose run shows every group with
/// every location. A call site read `(.., true, false)`, which said nothing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum GroupView {
    /// The single worst group, heading it as the top finding.
    Top,
    /// One group among all of them, with every location it carries.
    Full,
}

impl GroupView {
    /// How many of the group's diagnostics get a location and a code frame.
    /// The summary shows one; the verbose run shows them all, and `usize::MAX`
    /// is what `take` reads as all of them.
    const fn location_limit(self) -> usize {
        match self {
            Self::Top => 1,
            Self::Full => usize::MAX,
        }
    }
}

fn render_group<W: Write>(
    writer: &mut W,
    group: &DiagnosticGroup,
    options: TerminalOptions<'_>,
    view: GroupView,
) -> Result<(), RenderError> {
    let heading = match view {
        GroupView::Top => format!("Top {}: {}", group.severity, group.title),
        GroupView::Full => format!(
            "{}: {} ({} occurrences)",
            capitalize(group.severity.to_string()),
            group.title,
            group.occurrences
        ),
    };
    line(writer, &heading, options, severity_style(group.severity))?;
    line(
        writer,
        &format!("Rule ID: {}", group.rule_id),
        options,
        Style::Accent,
    )?;

    for diagnostic in group.diagnostics.iter().take(view.location_limit()) {
        line(writer, &diagnostic.message, options, Style::Plain)?;
        if let Some(help) = &diagnostic.help {
            line(writer, &format!("Help: {help}"), options, Style::Muted)?;
        }
        if diagnostic.base_severity != diagnostic.severity {
            line(
                writer,
                &format!(
                    "Policy: base severity {}, effective severity {}",
                    diagnostic.base_severity, diagnostic.severity
                ),
                options,
                Style::Muted,
            )?;
        }
        render_related(writer, diagnostic, options, view)?;
        if let Some(location) = diagnostic.location() {
            render_code_frame(writer, &location, options)?;
        }
    }
    line(
        writer,
        &format!("Rule: {}", group.rule_url),
        options,
        Style::Muted,
    )
}

/// The source window around one finding, or the reason there is none.
fn render_code_frame<W: Write>(
    writer: &mut W,
    location: &crate::presentation::GroupLocation,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let frame = match code_frame(options.workspace_root, location) {
        Ok(frame) => frame,
        Err(unavailable) => {
            if let Some(location) = unavailable.location {
                line(writer, &location, options, Style::Accent)?;
            }
            return line(writer, &unavailable.message, options, Style::Muted);
        }
    };
    line(writer, &frame.location, options, Style::Accent)?;
    // The gutter comes from the frame rather than from a constant, so a source
    // row and the caret row under it agree on where the text begins whatever
    // line numbers the frame carries. The four columns are the floor the
    // report has always drawn at, not a ceiling on what a line number may
    // need.
    let gutter = frame.gutter_width().max(FRAME_GUTTER_COLUMNS);
    let indent = " ".repeat(gutter.saturating_add(3));
    for source in frame.lines {
        let prefix = if source.primary { ">" } else { " " };
        frame_line(
            writer,
            &format!("{prefix} {:>gutter$} | {}", source.number, source.text),
            options,
            Style::Plain,
        )?;
        if let Some(marker) = source.marker {
            let spaces = marker.column_start.saturating_sub(1);
            let carets = marker.column_end.saturating_sub(marker.column_start).max(1);
            frame_line(
                writer,
                &format!("{indent}| {}{}", " ".repeat(spaces), "^".repeat(carets)),
                options,
                Style::Warning,
            )?;
        }
    }
    Ok(())
}

/// Other sites a structural finding spans.
///
/// The list is bounded here and complete in `--json`: a function cloned two
/// hundred times is one finding, and printing two hundred references would bury
/// every other finding under it.
fn render_related<W: Write>(
    writer: &mut W,
    diagnostic: &GroupDiagnostic,
    options: TerminalOptions<'_>,
    view: GroupView,
) -> Result<(), RenderError> {
    const MAX_RELATED: usize = 3;
    if view != GroupView::Full || diagnostic.related.is_empty() {
        return Ok(());
    }
    for location in diagnostic.related.iter().take(MAX_RELATED) {
        line(
            writer,
            &format!(
                "Also at: {}:{}:{}",
                location.path, location.span.line_start, location.span.column_start
            ),
            options,
            Style::Accent,
        )?;
    }
    let remaining = diagnostic.related.len().saturating_sub(MAX_RELATED);
    if remaining > 0 {
        line(
            writer,
            &format!("and {remaining} more locations"),
            options,
            Style::Muted,
        )?;
    }
    Ok(())
}

fn render_categories<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    for category in &report.audit.categories {
        line(
            writer,
            &format!(
                "{}: {} errors, {} warnings, {} info, {} unknown (occurrences)",
                category.name,
                category.occurrences.errors,
                category.occurrences.warnings,
                category.occurrences.info,
                category.occurrences.unknown
            ),
            options,
            Style::Plain,
        )?;
    }
    if report.audit.categories.is_empty() {
        line(writer, "Categories: none", options, Style::Plain)?;
    }
    Ok(())
}

/// How the run was configured, when a policy reached the report.
fn render_configuration<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let Some(policy) = &report.policy else {
        return Ok(());
    };
    let source = match policy.blocking.source {
        crate::BlockingLevelSource::Default => "default",
        crate::BlockingLevelSource::Config => "config",
        crate::BlockingLevelSource::Request => "request",
    };
    let configuration = policy
        .config_file
        .as_deref()
        .map_or_else(|| "none loaded".to_owned(), |file| format!("{file} loaded"));
    line(
        writer,
        &format!(
            "Configuration: {configuration}; blocking {} ({source})",
            policy.blocking.level
        ),
        options,
        Style::Muted,
    )
}

/// What a baseline comparison found, and every finding the branch fixed.
///
/// The two used to sit at opposite ends of one grab-bag function with three
/// unrelated sections between them, each testing `report.delta` again.
fn render_delta<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let Some(delta) = &report.delta else {
        return Ok(());
    };
    line(
        writer,
        &format!(
            "Delta: +{} introduced; ={} pre-existing; -{} fixed; {} cross-file matches.",
            delta.summary.introduced,
            delta.summary.pre_existing,
            delta.summary.fixed,
            delta.summary.cross_file_matches
        ),
        options,
        Style::Muted,
    )?;
    for diagnostic in &delta.fixed {
        let path = diagnostic.path.as_deref().unwrap_or("<unknown>");
        let (line_number, column) = diagnostic
            .span
            .as_ref()
            .map_or((0, 0), |span| (span.line_start, span.column_start));
        let code = diagnostic
            .code
            .as_deref()
            .map_or_else(String::new, |code| format!(" [{code}]"));
        line(
            writer,
            &format!(
                "Fixed: {path}:{line_number}:{column} {}{code} {}",
                diagnostic.severity, diagnostic.message
            ),
            options,
            Style::Success,
        )?;
    }
    if delta.introduced.is_empty() && delta.fixed.is_empty() {
        return Ok(());
    }
    line(
        writer,
        "Baseline details remain available in the JSON report.",
        options,
        Style::Muted,
    )
}

/// The gate's verdict, evaluated or not.
fn render_gate<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let description = match (report.gate.status, report.gate.blocking_diagnostics) {
        (GateStatus::Passed | GateStatus::Failed, Some(count)) => format!(
            "Gate {}: blocking {}, {count} blocking diagnostic(s)",
            report.gate.status, report.gate.blocking
        ),
        _ => format!("Gate not evaluated: blocking {}", report.gate.blocking),
    };
    line(writer, &description, options, Style::Muted)
}

/// Every stage that failed, on a scan that did not complete.
fn render_scan_errors<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let heading = match report.status {
        Status::Complete => return Ok(()),
        Status::Incomplete => "Scan incomplete",
        Status::Failed => "Scan failed",
    };
    for error in &report.errors {
        line(
            writer,
            &format!(
                "{heading}: {} ({}/{})",
                error.message, error.stage, error.code
            ),
            options,
            Style::Warning,
        )?;
    }
    Ok(())
}

/// Rules of the worst tier present in the score scope, bounded to fit on one
/// line. A cap with no named cause cannot be explained.
fn capping_rule_ids(report: &InspectReport, tier: crate::RuleTier) -> Vec<String> {
    const MAX_NAMED_RULES: usize = 3;
    let scoped: Option<BTreeSet<_>> = report.delta.as_ref().map(|delta| {
        delta
            .introduced
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>()
    });
    let mut ids: Vec<_> = report
        .diagnostics
        .iter()
        .filter(|diagnostic| {
            scoped
                .as_ref()
                .is_none_or(|scoped| scoped.contains(diagnostic.id.as_str()))
        })
        .filter_map(|diagnostic| diagnostic.code.as_deref())
        .filter(|code| crate::policy::find(code).is_some_and(|definition| definition.tier == tier))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .map(str::to_owned)
        .collect();
    ids.truncate(MAX_NAMED_RULES);
    ids
}

fn render_score<W: Write>(
    writer: &mut W,
    report: &InspectReport,
    options: TerminalOptions<'_>,
) -> Result<(), RenderError> {
    let Some(score) = &report.audit.score else {
        return line(
            writer,
            "Score unavailable: no Rust files were analyzed.",
            options,
            Style::Warning,
        );
    };
    if let Some((tier, ceiling)) = score.worst_tier.zip(score.applied_ceiling) {
        let blocking = capping_rule_ids(report, tier);
        line(
            writer,
            &format!(
                "Capped at {ceiling}/100 by a {} finding: {}",
                tier.as_str(),
                blocking.join(", ")
            ),
            options,
            Style::Warning,
        )?;
    }
    score_header::render(writer, score, options, score_header::Cadence::DEFAULT)?;
    if !score.authoritative {
        line(
            writer,
            "Score is partial because the scan did not complete or contains unscored findings.",
            options,
            Style::Warning,
        )?;
    }
    if let Some(projected) = score
        .projected_after_top_three
        .filter(|projected| *projected > score.value)
    {
        line(
            writer,
            &format!(
                "Fix the top {} rules to reach a projected {projected}/100: {}",
                score.projected_rule_ids.len(),
                named_with_measurement(&score.projected_rule_ids)
            ),
            options,
            Style::Accent,
        )?;
    }
    if let Some(withheld) = withheld_sentence(&score.withheld_rule_ids) {
        line(writer, &withheld, options, Style::Plain)?;
    }
    Ok(())
}

/// How a rule's rate is qualified wherever the ranking names the rule.
///
/// A rate published alone cannot be weighed. Thirty-three percent measured on
/// one adjudicated site and thirty-three measured on forty are the same number
/// and not the same claim, and the difference is exactly what the ranking's
/// smoothing acts on, invisibly, in the rate it produces. So the sample is
/// printed beside the rate wherever a rule is named.
///
/// A rule the corpus never adjudicated is named as unmeasured rather than shown
/// as a number. It is ranked at the middle of the interval, and printing that
/// middle as a measurement would publish an assumption as an observation.
fn measurement_note(id: &str) -> String {
    match crate::policy::corpus_measurement(id) {
        Some(measurement) => {
            let percent = (u32::from(measurement.noise_basis_points()) + 50) / 100;
            let sites = measurement.reviewed();
            let unit = if sites == 1 { "site" } else { "sites" };
            format!(" ({percent}% noise on {sites} {unit})")
        }
        None => " (unmeasured)".to_owned(),
    }
}

fn named_with_measurement(ids: &[String]) -> String {
    ids.iter()
        .map(|id| format!("{id}{}", measurement_note(id)))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Why the loudest rule is missing from what to fix.
///
/// The rule with the most findings is often the one the corpus found most often
/// wrong, so a list that drops it without a word reads as a defect of the tool.
/// Two names carry the point; past that a count does, because the sentence is
/// there to explain an absence, not to enumerate one.
///
/// The sentence says the discount emptied the value rather than that the corpus
/// adjudicated no true positive, which is what it used to say and what the
/// smoothed rate can no longer support: no smoothed rate reaches ten thousand
/// basis points, so a rule reaches this list by having little enough left after
/// the discount rather than by having been adjudicated wrong everywhere.
fn withheld_sentence(withheld: &[String]) -> Option<String> {
    let named: Vec<String> = withheld
        .iter()
        .take(2)
        .map(|id| format!("{id}{}", measurement_note(id)))
        .collect();
    let subject = match (named.as_slice(), withheld.len()) {
        ([], _) => return None,
        ([only], _) => format!("{only} reports here but is"),
        ([first, second], 2) => format!("{first} and {second} report here but are"),
        ([first, second], total) => format!(
            "{first}, {second} and {} more report here but are",
            total - 2
        ),
        _ => return None,
    };
    Some(format!(
        "{subject} left out: once the rate the corpus adjudicated is applied, nothing \
         worth repairing is left."
    ))
}

#[derive(Clone, Copy)]
enum Style {
    Plain,
    Heading,
    Accent,
    Success,
    Warning,
    Muted,
}

fn severity_style(severity: crate::Severity) -> Style {
    match severity {
        crate::Severity::Error => Style::Warning,
        crate::Severity::Warning => Style::Warning,
        crate::Severity::Info => Style::Accent,
        crate::Severity::Unknown => Style::Muted,
    }
}

/// One line of prose: sanitized, then wrapped onto as many rows as it needs.
fn line<W: Write>(
    writer: &mut W,
    content: &str,
    options: TerminalOptions<'_>,
    style: Style,
) -> Result<(), RenderError> {
    for bounded in wrap(&sanitize(content), options.width) {
        write_styled(writer, &bounded, options.color, style)?;
    }
    Ok(())
}

/// One row of a code frame: sanitized, then cut rather than wrapped.
///
/// A source line and the caret row under it are aligned by column, so wrapping
/// either of them would put the caret under the wrong text. This is the only
/// thing that separates it from [`line`].
fn frame_line<W: Write>(
    writer: &mut W,
    content: &str,
    options: TerminalOptions<'_>,
    style: Style,
) -> Result<(), RenderError> {
    let bounded = truncate(&sanitize(content), options.width);
    write_styled(writer, &bounded, options.color, style)
}

fn write_styled<W: Write>(
    writer: &mut W,
    content: &str,
    color: bool,
    style: Style,
) -> Result<(), RenderError> {
    if color && !matches!(style, Style::Plain) {
        let code = match style {
            Style::Heading => "1",
            Style::Accent => "36",
            Style::Success => "32",
            Style::Warning => "33",
            Style::Muted => "2",
            Style::Plain => "0",
        };
        writeln!(writer, "\u{1b}[{code}m{content}\u{1b}[0m").map_err(RenderError::Write)
    } else {
        writeln!(writer, "{content}").map_err(RenderError::Write)
    }
}

fn short_revision(revision: &str) -> &str {
    revision.get(..12).unwrap_or(revision)
}

fn capitalize(mut value: String) -> String {
    if let Some(first) = value.get_mut(..1) {
        first.make_ascii_uppercase();
    }
    value
}

#[cfg(test)]
mod tests;