rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Prints a review the way rustc prints diagnostics, followed by one manual test plan.
//!
//! Everything shown can come from someone else's pull request, so control characters are
//! replaced before printing: a diff must not be able to send escape codes to the terminal.

use serde::Serialize;

use super::rules::{Finding, Level, Span};

#[derive(Serialize)]
pub struct Step {
    pub text: String,
    pub codes: Vec<&'static str>,
}

#[derive(Serialize)]
pub struct Report {
    /// What was compared, such as `origin/main...HEAD`.
    pub against: String,
    pub project: Vec<String>,
    pub files: usize,
    pub added: usize,
    pub removed: usize,
    pub findings: Vec<Finding>,
    pub plan: Vec<Step>,
    /// The steps the description's own test section lists.
    pub described_steps: Vec<String>,
}

/// Every finding's test steps, each once, in the order of the findings (most serious first).
pub fn plan(findings: &[Finding]) -> Vec<Step> {
    let mut steps: Vec<Step> = Vec::new();
    for f in findings {
        for t in &f.test {
            match steps.iter_mut().find(|s| s.text == *t) {
                Some(s) => {
                    if !s.codes.contains(&f.code) {
                        s.codes.push(f.code);
                    }
                }
                None => steps.push(Step { text: t.clone(), codes: vec![f.code] }),
            }
        }
    }
    steps
}

#[derive(Clone, Copy)]
pub struct Style {
    pub color: bool,
    pub width: usize,
}

const BOLD: &str = "1";
const RED: &str = "1;31";
const YELLOW: &str = "1;33";
const CYAN: &str = "1;36";
const BLUE: &str = "1;34";

impl Style {
    fn paint(self, sgr: &str, s: &str) -> String {
        if self.color && !s.is_empty() { format!("\x1b[{sgr}m{s}\x1b[0m") } else { s.to_string() }
    }
    fn level(self, level: Level) -> &'static str {
        match level {
            Level::Risk => RED,
            Level::Warn => YELLOW,
            Level::Note => CYAN,
        }
    }
}

fn clean(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c == '\t' {
                ' '
            } else if c.is_control() {
                '\u{fffd}'
            } else {
                c
            }
        })
        .collect()
}

/// The words of a text, keeping anything in backticks together.
fn words(text: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut open = false;
    for word in text.split(' ') {
        match out.last_mut() {
            Some(last) if open => {
                last.push(' ');
                last.push_str(word);
            }
            _ => out.push(word.to_string()),
        }
        open ^= word.matches('`').count() % 2 == 1;
    }
    out
}

/// Greedy word wrap. Commands in backticks and words longer than the width are left whole,
/// so they can be copied.
fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = vec![String::new()];
    for word in &words(text) {
        let line = lines.last_mut().unwrap();
        if !line.is_empty() && line.chars().count() + 1 + word.chars().count() > width {
            lines.push(word.to_string());
        } else {
            if !line.is_empty() {
                line.push(' ');
            }
            line.push_str(word);
        }
    }
    lines
}

/// The snippet as it will be shown, with the underline's column and length in it: tabs are
/// expanded, and a long line is cut to a window around the underlined part.
pub fn snippet(span: &Span, max: usize) -> (String, usize, usize) {
    let mut shown: Vec<char> = Vec::new();
    let (from, to) = (span.col as usize - 1, span.col as usize - 1 + span.len as usize);
    let (mut start_col, mut end_col) = (None, None);
    for (i, c) in span.text.chars().enumerate() {
        if i == from {
            start_col = Some(shown.len());
        }
        if i == to {
            end_col = Some(shown.len());
        }
        match c {
            '\t' => shown.extend([' '; 4]),
            c if c.is_control() => shown.push('\u{fffd}'),
            c => shown.push(c),
        }
    }
    let col = start_col.unwrap_or(shown.len());
    let mut len = end_col.unwrap_or(shown.len()).saturating_sub(col).max(1);
    if shown.len() <= max {
        return (shown.iter().collect(), col, len);
    }
    let start = if col + len < max { 0 } else { col.saturating_sub(12) };
    let end = (start + max).min(shown.len());
    let mut text: String = shown[start..end].iter().collect();
    if end < shown.len() {
        text.push('…');
    }
    let mut col = col - start;
    if start > 0 {
        text.insert(0, '…');
        col += 1;
    }
    len = len.min((end - start).saturating_sub(col).max(1));
    (text, col, len)
}

pub fn finding(f: &Finding, st: Style) -> String {
    let color = st.level(f.level);
    let mut out = format!(
        "{}{}\n",
        st.paint(color, &format!("{}[{}]", f.level.name(), f.code)),
        st.paint(BOLD, &format!(": {}", clean(&f.title)))
    );
    let width = f.span.as_ref().map_or(1, |s| s.line.to_string().len());
    let pad = " ".repeat(width);
    let gutter = st.paint(BLUE, &format!("{pad} |"));
    if let Some(s) = &f.span {
        let (text, col, len) = snippet(s, st.width.saturating_sub(width + 4).max(40));
        out += &format!("{pad}{} {}:{}:{}\n", st.paint(BLUE, "-->"), clean(&s.file), s.line, s.col);
        out += &format!("{gutter}\n");
        out += &format!("{} {text}\n", st.paint(BLUE, &format!("{:<width$} |", s.line)));
        out += &format!(
            "{gutter} {}{}\n",
            " ".repeat(col),
            st.paint(color, &format!("{} {}", "^".repeat(len), clean(&s.label)))
        );
    }
    let trailers = [("note", &f.note), ("check", &f.check), ("test", &f.test), ("help", &f.help)];
    if f.span.is_some() && trailers.iter().any(|(_, v)| !v.is_empty()) {
        out += &format!("{gutter}\n");
    }
    for (label, items) in trailers {
        // `   = check: text`, with later lines and items lined up under the text.
        let indent = width + label.len() + 5;
        let numbered = label == "test" && items.len() > 1;
        for (i, item) in items.iter().enumerate() {
            let number = if numbered { format!("{}. ", i + 1) } else { String::new() };
            let room = st.width.saturating_sub(indent + number.len()).max(40);
            for (j, line) in wrap(&clean(item), room).iter().enumerate() {
                if i == 0 && j == 0 {
                    out += &format!(
                        "{pad} {} {} {number}{line}\n",
                        st.paint(BLUE, "="),
                        st.paint(BOLD, &format!("{label}:"))
                    );
                } else {
                    // Numbered items repeat the number; others start a new `= label:` line.
                    if j == 0 && !numbered {
                        out +=
                            &format!("{pad} {} {} {line}\n", st.paint(BLUE, "="), st.paint(BOLD, &format!("{label}:")));
                    } else {
                        let lead = if j == 0 { number.clone() } else { " ".repeat(number.len()) };
                        out += &format!("{}{lead}{line}\n", " ".repeat(indent));
                    }
                }
            }
        }
    }
    out
}

fn count(n: usize, one: &str) -> String {
    format!("{n} {one}{}", if n == 1 { "" } else { "s" })
}

pub fn report(r: &Report, st: Style) -> String {
    let mut out = String::new();
    let project = if r.project.is_empty() { String::new() } else { format!(" [{}]", r.project.join(", ")) };
    out += &format!(
        "{} {}: {}, +{} -{}{project}\n\n",
        st.paint(BOLD, "reviewing"),
        clean(&r.against),
        count(r.files, "file"),
        r.added,
        r.removed
    );
    for f in &r.findings {
        out += &finding(f, st);
        out.push('\n');
    }

    const SHOWN: usize = 25;
    if !r.described_steps.is_empty() {
        out += &format!("{}\n", st.paint(BOLD, "the description's own test steps"));
        for s in r.described_steps.iter().take(SHOWN) {
            out += &list_item("[ ] ", s, st);
        }
        out.push('\n');
    }
    if !r.plan.is_empty() {
        out += &format!("{}\n", st.paint(BOLD, "manual test plan (most important first)"));
        for s in r.plan.iter().take(SHOWN) {
            out += &list_item("[ ] ", &format!("{} ({})", s.text, s.codes.join(", ")), st);
        }
        if r.plan.len() > SHOWN {
            out += &format!("  ... and {} more in the findings above\n", r.plan.len() - SHOWN);
        }
        out.push('\n');
    }

    let n = |level| r.findings.iter().filter(|f| f.level == level).count();
    let (risks, warns, notes) = (n(Level::Risk), n(Level::Warn), n(Level::Note));
    if r.findings.is_empty() {
        out += &format!(
            "{}: no findings. That is not proof the change works; it still wants a run.\n",
            st.paint(BOLD, "review finished")
        );
    } else {
        out += &format!(
            "{}: {}, {}, {}\n",
            st.paint(BOLD, "review finished"),
            st.paint(if risks > 0 { RED } else { BOLD }, &count(risks, "risk")),
            st.paint(if warns > 0 { YELLOW } else { BOLD }, &count(warns, "warning")),
            count(notes, "note")
        );
        out += &format!("For more about a finding: `rustimal --review --explain {}`.\n", r.findings[0].code);
    }
    out
}

fn list_item(bullet: &str, text: &str, st: Style) -> String {
    let indent = 2 + bullet.len();
    let mut out = String::new();
    for (i, line) in wrap(&clean(text), st.width.saturating_sub(indent).max(40)).iter().enumerate() {
        if i == 0 {
            out += &format!("  {bullet}{line}\n");
        } else {
            out += &format!("{}{line}\n", " ".repeat(indent));
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::review::diff::{Kind, Line};

    const PLAIN: Style = Style { color: false, width: 100 };

    fn line(text: &str) -> Line {
        Line { kind: Kind::Added, text: text.into(), old_no: None, new_no: Some(12) }
    }

    #[test]
    fn looks_like_rustc() {
        let f = Finding::new("LAR007", Level::Warn, "unescaped output")
            .at("a.blade.php", &line("  {!! $x !!}"), "{!! $x !!}", "raw HTML")
            .check("who sets it?")
            .test("try a script tag")
            .test("try an img tag")
            .help("use {{ }}");
        let expected = "\
warning[LAR007]: unescaped output
  --> a.blade.php:12:3
   |
12 |   {!! $x !!}
   |   ^^^^^^^^^^ raw HTML
   |
   = check: who sets it?
   = test: 1. try a script tag
           2. try an img tag
   = help: use {{ }}
";
        assert_eq!(finding(&f, PLAIN), expected);
    }

    #[test]
    fn long_notes_wrap_under_their_text() {
        let f = Finding::new("PR002", Level::Note, "t").note("word ".repeat(40).trim().to_string());
        let out = finding(&f, Style { color: false, width: 60 });
        let lines: Vec<&str> = out.lines().collect();
        assert!(lines[1].starts_with("  = note: word"));
        assert!(lines[2].starts_with("          word"));
        assert!(lines.iter().all(|l| l.len() <= 60));
    }

    #[test]
    fn commands_are_not_split_across_lines() {
        let lines = wrap("on a copy of real data run `php artisan migrate:rollback --step=1` and then look", 40);
        assert!(lines.iter().any(|l| l.contains("`php artisan migrate:rollback --step=1`")), "{lines:?}");
        assert_eq!(wrap("an ` unmatched tick stays", 80), vec!["an ` unmatched tick stays"]);
    }

    #[test]
    fn tabs_and_long_lines_keep_the_underline_in_place() {
        let f = Finding::new("GEN001", Level::Warn, "t").at("a", &line("\t\tdd($x);"), "dd(", "here");
        assert!(finding(&f, PLAIN).contains("12 |         dd($x);\n   |         ^^^ here"));
        let long = format!("{}needle{}", "a".repeat(200), "b".repeat(200));
        let f = Finding::new("GEN001", Level::Warn, "t").at("a", &line(&long), "needle", "x");
        let (text, col, len) = snippet(f.span.as_ref().unwrap(), 60);
        assert_eq!(text.chars().skip(col).take(len).collect::<String>(), "needle");
        assert!(text.chars().count() <= 62);
    }

    #[test]
    fn escape_codes_from_a_diff_are_not_printed() {
        let f = Finding::new("GEN001", Level::Warn, "bad \x1b]0;title\x07")
            .at("a\x1b[2J", &line("x \x1b[31m dd("), "dd(", "l")
            .note("n\x1b[0m");
        assert!(!finding(&f, PLAIN).contains(['\x1b', '\x07']));
    }

    #[test]
    fn the_plan_merges_repeated_steps() {
        let a = Finding::new("LAR001", Level::Risk, "a").test("same").test("only a");
        let b = Finding::new("LAR003", Level::Note, "b").test("same");
        let p = plan(&[a, b]);
        assert_eq!(p.len(), 2);
        assert_eq!(p[0].codes, vec!["LAR001", "LAR003"]);
    }
}