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
//! Styled text primitives for the interactive report.
//!
//! Ink builds a line out of `<Text>` nodes that each carry their own color,
//! bold and dim flags, and lays them out in display columns. This is the same
//! model: a [`Span`] is one `<Text>`, a [`Line`] is one rendered row.
//!
//! Every span sanitizes on construction, so a rule message, a path or a help
//! string coming out of Clippy can never smuggle an escape sequence into a
//! frame. That matters more here than in the linear renderer: a stray sequence
//! would desynchronize the cursor rewind and corrupt every frame after it.
//!
//! Sanitizing and measuring are the library's, not this module's
//! ([`rust_doctor::terminal_text`]). A second sanitizer is a second set of
//! escape forms to get wrong, and the two this crate carried had already
//! drifted apart on string sequences.

use rust_doctor::terminal_text::{display_width, sanitize};
use std::fmt::Write as _;

use unicode_width::UnicodeWidthChar;

/// The eight colors Ink's report actually uses.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Color {
    #[default]
    Default,
    Red,
    Green,
    Yellow,
    Blue,
    Cyan,
    Gray,
}

impl Color {
    const fn code(self) -> Option<&'static str> {
        match self {
            Self::Default => None,
            Self::Red => Some("31"),
            Self::Green => Some("32"),
            Self::Yellow => Some("33"),
            Self::Blue => Some("34"),
            Self::Cyan => Some("36"),
            Self::Gray => Some("90"),
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Style {
    pub color: Color,
    pub bold: bool,
    pub dim: bool,
}

impl Style {
    pub const PLAIN: Self = Self {
        color: Color::Default,
        bold: false,
        dim: false,
    };
    pub const DIM: Self = Self {
        color: Color::Default,
        bold: false,
        dim: true,
    };
    pub const BOLD: Self = Self {
        color: Color::Default,
        bold: true,
        dim: false,
    };

    pub const fn color(color: Color) -> Self {
        Self {
            color,
            bold: false,
            dim: false,
        }
    }

    pub const fn bold(self) -> Self {
        Self { bold: true, ..self }
    }

    pub const fn dim(self) -> Self {
        Self { dim: true, ..self }
    }

    fn sequence(self) -> Option<String> {
        let mut codes: Vec<&str> = Vec::new();
        if self.bold {
            codes.push("1");
        }
        if self.dim {
            codes.push("2");
        }
        if let Some(color) = self.color.code() {
            codes.push(color);
        }
        (!codes.is_empty()).then(|| codes.join(";"))
    }
}

#[derive(Clone, Debug)]
pub struct Span {
    text: String,
    style: Style,
    link: Option<String>,
}

impl Span {
    pub fn new(text: impl AsRef<str>, style: Style) -> Self {
        Self {
            text: sanitize(text.as_ref()),
            style,
            link: None,
        }
    }

    pub fn plain(text: impl AsRef<str>) -> Self {
        Self::new(text, Style::PLAIN)
    }

    pub fn dim(text: impl AsRef<str>) -> Self {
        Self::new(text, Style::DIM)
    }

    /// A span a capable terminal turns into a click target. The visible
    /// characters stay exactly `text`.
    pub fn linked(text: impl AsRef<str>, style: Style, url: &str) -> Self {
        Self {
            link: Some(sanitize(url)),
            ..Self::new(text, style)
        }
    }

    /// A span whose text is already sanitized, which is the case for every
    /// slice cut out of another span.
    fn raw(text: String, style: Style, link: Option<String>) -> Self {
        Self { text, style, link }
    }

    fn width(&self) -> usize {
        display_width(&self.text)
    }
}

#[derive(Clone, Debug, Default)]
pub struct Line {
    spans: Vec<Span>,
}

impl Line {
    pub const fn blank() -> Self {
        Self { spans: Vec::new() }
    }

    pub fn of(span: Span) -> Self {
        Self { spans: vec![span] }
    }

    pub fn text(content: impl AsRef<str>, style: Style) -> Self {
        Self::of(Span::new(content, style))
    }

    pub fn push(&mut self, span: Span) {
        self.spans.push(span);
    }

    pub fn with(mut self, span: Span) -> Self {
        self.spans.push(span);
        self
    }

    pub fn width(&self) -> usize {
        self.spans
            .iter()
            .fold(0usize, |width, span| width.saturating_add(span.width()))
    }

    pub fn is_blank(&self) -> bool {
        self.spans.iter().all(|span| span.text.is_empty())
    }

    /// Ink's `wrap="truncate-end"`: cut at the box edge and mark the cut with
    /// an ellipsis.
    pub fn truncate_end(self, width: usize) -> Self {
        if self.width() <= width {
            return self;
        }
        if width == 0 {
            return Self::blank();
        }
        let budget = width.saturating_sub(1);
        let mut spans: Vec<Span> = Vec::new();
        let mut used = 0usize;
        for span in self.spans {
            if used >= budget {
                break;
            }
            let mut kept = String::new();
            for character in span.text.chars() {
                let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
                if used.saturating_add(character_width) > budget {
                    break;
                }
                kept.push(character);
                used = used.saturating_add(character_width);
            }
            if !kept.is_empty() {
                spans.push(Span::raw(kept, span.style, span.link.clone()));
            }
        }
        // The ellipsis continues the text it replaces, so it carries the style
        // of the last span that survived the cut. A line cut before its first
        // span has no such style and the mark stays plain.
        let style = spans.last().map_or(Style::PLAIN, |span| span.style);
        spans.push(Span::raw("".to_owned(), style, None));
        Self { spans }
    }

    pub fn indented(self, columns: usize) -> Self {
        if columns == 0 || self.spans.is_empty() {
            return self;
        }
        let mut spans = vec![Span::raw(" ".repeat(columns), Style::PLAIN, None)];
        spans.extend(self.spans);
        Self { spans }
    }

    /// Pads to `width` so the next column of a split row starts at a fixed
    /// offset whatever the content measured.
    pub fn padded_to(mut self, width: usize) -> Self {
        let padding = width.saturating_sub(self.width());
        if padding > 0 {
            self.spans
                .push(Span::raw(" ".repeat(padding), Style::PLAIN, None));
        }
        self
    }

    pub fn extend(mut self, other: Self) -> Self {
        self.spans.extend(other.spans);
        self
    }

    pub fn render(&self, color: bool, links: bool) -> String {
        let mut rendered = String::new();
        for span in &self.spans {
            if span.text.is_empty() {
                continue;
            }
            let link = links.then_some(span.link.as_deref()).flatten();
            if let Some(url) = link {
                let _ = write!(rendered, "\u{1b}]8;;{url}\u{1b}\\");
            }
            match span.style.sequence().filter(|_| color) {
                Some(sequence) => {
                    let _ = write!(rendered, "\u{1b}[{sequence}m{}\u{1b}[0m", span.text);
                }
                None => rendered.push_str(&span.text),
            }
            if link.is_some() {
                rendered.push_str("\u{1b}]8;;\u{1b}\\");
            }
        }
        rendered
    }
}

/// Word-wraps a styled paragraph, Ink's `wrap="wrap"`. Styles survive the
/// break, which is what lets a cyan `Impact` label share a line with the plain
/// sentence that follows it.
pub fn wrap_spans(spans: &[Span], width: usize) -> Vec<Line> {
    if width == 0 {
        return vec![Line::blank()];
    }
    let mut wrapping = Wrapping::new(width);
    let mut pending_space = false;
    for span in spans {
        for (index, word) in span.text.split(' ').enumerate() {
            // The separator survives an empty word, so a run of spaces still
            // separates the words around it by exactly one column.
            pending_space |= index > 0;
            if word.is_empty() {
                continue;
            }
            wrapping.place(word, span, &mut pending_space);
        }
    }
    wrapping.finish()
}

/// The line under construction, and the lines already closed.
///
/// The four variables this replaced were mutated by five branches of a nested
/// loop, which is what made `wrap_spans` the crate's own worst
/// cognitive-complexity hotspot: what a reader had to hold was not the
/// algorithm but where each of them could next change. Here the line is one
/// value, `close` and `push` are the only two things that happen to it, and
/// `remaining` cannot go negative in a crate that builds with
/// `overflow-checks`.
struct Wrapping {
    lines: Vec<Line>,
    current: Line,
    used: usize,
    width: usize,
}

impl Wrapping {
    const fn new(width: usize) -> Self {
        Self {
            lines: Vec::new(),
            current: Line::blank(),
            used: 0,
            width,
        }
    }

    const fn is_empty(&self) -> bool {
        self.used == 0
    }

    /// Columns left on the line under construction.
    const fn remaining(&self) -> usize {
        self.width.saturating_sub(self.used)
    }

    /// Would this many columns, plus a separator, run past the edge?
    const fn overflows(&self, columns: usize, separator: usize) -> bool {
        self.used.saturating_add(separator).saturating_add(columns) > self.width
    }

    fn close(&mut self) {
        self.lines
            .push(std::mem::replace(&mut self.current, Line::blank()));
        self.used = 0;
    }

    fn push(&mut self, text: String, style: Style, link: Option<String>) {
        self.used = self.used.saturating_add(display_width(&text));
        self.current.push(Span::raw(text, style, link));
    }

    /// Places one word, breaking the line before it and, if it is wider than
    /// the box on its own, inside it.
    fn place(&mut self, word: &str, span: &Span, pending_space: &mut bool) {
        let mut remainder = word;
        loop {
            let word_width = display_width(remainder);
            let separator = usize::from(*pending_space && !self.is_empty());
            if !self.is_empty() && self.overflows(word_width.min(self.width), separator) {
                self.close();
                *pending_space = false;
            }
            if *pending_space && !self.is_empty() {
                // The separator carries the style around it and never a link:
                // a space is not part of what the link points at.
                self.push(" ".to_owned(), span.style, None);
            }
            *pending_space = false;
            if word_width <= self.width {
                self.push(remainder.to_owned(), span.style, span.link.clone());
                return;
            }
            // A word wider than the box, a long path or URL: it is cut on a
            // column boundary rather than pushed past the edge.
            let (head, tail) = split_at_width(remainder, self.remaining());
            self.push(head, span.style, span.link.clone());
            self.close();
            remainder = tail;
            if remainder.is_empty() {
                return;
            }
        }
    }

    fn finish(mut self) -> Vec<Line> {
        if !self.current.is_blank() || self.lines.is_empty() {
            self.lines.push(self.current);
        }
        self.lines
    }
}

fn split_at_width(content: &str, width: usize) -> (String, &str) {
    let mut used = 0usize;
    for (offset, character) in content.char_indices() {
        let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
        if used.saturating_add(character_width) > width {
            return (content[..offset].to_owned(), &content[offset..]);
        }
        used = used.saturating_add(character_width);
    }
    (content.to_owned(), "")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn visible(line: &Line) -> String {
        line.render(false, false)
    }

    #[test]
    fn a_span_never_carries_an_escape_sequence_into_a_frame() {
        let hostile = Span::plain("safe\u{1b}[2Jmore\u{1b}]0;title\u{7}end\u{9b}31mtail");
        assert_eq!(hostile.text, "safemoreendtail");
        assert!(!Line::of(hostile).render(true, true).contains("[2J"));
    }

    /// The forms a hand-written sanitizer gets wrong: a string sequence closed
    /// by `ESC \` rather than `BEL`, and a device control string whose
    /// introducer is not `[` or `]`. Both must vanish whole, payload included.
    #[test]
    fn a_span_drops_string_sequences_whole_whatever_closes_them() {
        let osc = Span::plain("head\u{1b}]8;;https://example.com\u{1b}\\tail");
        assert_eq!(osc.text, "headtail");
        let dcs = Span::plain("head\u{1b}Pq#0;2;0;0;0\u{1b}\\tail");
        assert_eq!(dcs.text, "headtail");
    }

    #[test]
    fn truncation_measures_display_columns_and_marks_the_cut() {
        let line = Line::blank()
            .with(Span::plain("界界界"))
            .with(Span::dim(" tail"));
        assert_eq!(line.width(), 11);
        assert_eq!(visible(&line.clone().truncate_end(11)), "界界界 tail");
        assert_eq!(visible(&line.clone().truncate_end(5)), "界界…");
        assert_eq!(visible(&line.truncate_end(0)), "");
    }

    /// The ellipsis continues what survived the cut, never what was dropped:
    /// a mark painted in the color of absent text reads as content.
    #[test]
    fn the_ellipsis_carries_the_style_of_the_last_span_that_survived() {
        let line = Line::blank()
            .with(Span::new("kept", Style::color(Color::Cyan)))
            .with(Span::new("dropped", Style::color(Color::Red)));
        let rendered = line.truncate_end(5).render(true, false);
        assert!(rendered.contains("\u{1b}[36m…\u{1b}[0m"), "{rendered:?}");
        assert!(!rendered.contains("\u{1b}[31m"));

        // Cut before the first span keeps a plain mark rather than inventing a
        // style.
        let plain = Line::text("wide", Style::color(Color::Red)).truncate_end(1);
        assert_eq!(plain.render(true, false), "");
    }

    #[test]
    fn wrapping_preserves_styles_and_breaks_words_wider_than_the_box() {
        let wrapped = wrap_spans(
            &[
                Span::new("Impact ", Style::color(Color::Cyan)),
                Span::plain("real users hit crashes"),
            ],
            12,
        );
        assert_eq!(
            wrapped.iter().map(visible).collect::<Vec<_>>(),
            ["Impact real", "users hit", "crashes"]
        );

        let split = wrap_spans(&[Span::plain("abcdefghijkl")], 5);
        assert_eq!(
            split.iter().map(visible).collect::<Vec<_>>(),
            ["abcde", "fghij", "kl"]
        );
    }

    #[test]
    fn rendering_is_plain_without_color_and_hyperlinked_only_when_allowed() {
        let line = Line::of(Span::linked(
            "Rust Doctor",
            Style::color(Color::Cyan),
            "https://rust-doctor.com",
        ));
        assert_eq!(line.render(false, false), "Rust Doctor");
        let full = line.render(true, true);
        assert!(full.contains("\u{1b}]8;;https://rust-doctor.com\u{1b}\\"));
        assert!(full.contains("\u{1b}[36m"));
        assert!(!line.render(true, false).contains("]8;;"));
    }

    #[test]
    fn padding_and_indentation_land_on_exact_columns() {
        let padded = Line::text("abc", Style::PLAIN).padded_to(6);
        assert_eq!(padded.width(), 6);
        assert_eq!(visible(&padded.clone().indented(2)), "  abc   ");
        assert_eq!(Line::blank().indented(4).width(), 0);
    }
}