rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! The review rules. Each looks at the diff (and, where it must, the files on disk) and
//! reports findings the way rustc reports diagnostics: a code, a precise place, why it
//! matters, what to look for, and how to test it by hand.

mod description;
mod generic;
mod laravel;
mod tauri;

use serde::Serialize;

use super::desc::Description;
use super::diff::{Diff, FileDiff, Line};
use super::explain;
use super::project::{Laravel, Node, Project, Tauri};

/// How much a finding matters. Sorts most serious first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Level {
    /// Likely a bug, a security problem or lost data.
    Risk,
    /// Worth a careful look before merging.
    Warn,
    /// Something to be aware of, or to test.
    Note,
}

impl Level {
    pub fn name(self) -> &'static str {
        match self {
            Level::Risk => "risk",
            Level::Warn => "warning",
            Level::Note => "note",
        }
    }
}

/// A place in a file, as a snippet with the part that matters underlined.
#[derive(Clone, Debug, Serialize)]
pub struct Span {
    pub file: String,
    pub line: u32,
    /// 1-based column in characters.
    pub col: u32,
    pub len: u32,
    pub text: String,
    pub label: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct Finding {
    pub code: &'static str,
    pub level: Level,
    pub title: String,
    pub span: Option<Span>,
    /// Why it matters.
    pub note: Vec<String>,
    /// What to look for.
    pub check: Vec<String>,
    /// How to test it by hand: steps and commands.
    pub test: Vec<String>,
    /// How to fix it.
    pub help: Vec<String>,
}

impl Finding {
    pub fn new(code: &'static str, level: Level, title: impl Into<String>) -> Finding {
        debug_assert!(explain::lookup(code).is_some(), "unregistered code {code}");
        Finding { code, level, title: title.into(), span: None, note: vec![], check: vec![], test: vec![], help: vec![] }
    }

    /// Point at `needle` on `line` (or at the whole line if it is not there).
    pub fn at(mut self, file: &str, line: &Line, needle: &str, label: &str) -> Finding {
        let (col, len) = match line.text.find(needle).filter(|_| !needle.is_empty()) {
            Some(b) => (char_col(&line.text, b), needle.chars().count()),
            None => trimmed_range(&line.text),
        };
        self.span = Some(Span {
            file: file.to_string(),
            line: line.new_no.or(line.old_no).unwrap_or(0),
            col: col as u32 + 1,
            len: len.max(1) as u32,
            text: line.text.clone(),
            label: label.to_string(),
        });
        self
    }

    /// Point at a byte range of `line`.
    pub fn at_range(mut self, file: &str, line: &Line, start: usize, end: usize, label: &str) -> Finding {
        let col = char_col(&line.text, start);
        let len = line.text[start..end.min(line.text.len())].chars().count();
        self.span = Some(Span {
            file: file.to_string(),
            line: line.new_no.or(line.old_no).unwrap_or(0),
            col: col as u32 + 1,
            len: len.max(1) as u32,
            text: line.text.clone(),
            label: label.to_string(),
        });
        self
    }

    /// Point at a line of some other text (the PR description).
    pub fn at_text(mut self, file: &str, line_no: u32, text: &str, col0: usize, len: usize, label: &str) -> Finding {
        self.span = Some(Span {
            file: file.to_string(),
            line: line_no,
            col: col0 as u32 + 1,
            len: len.max(1) as u32,
            text: text.to_string(),
            label: label.to_string(),
        });
        self
    }

    pub fn note(mut self, s: impl Into<String>) -> Finding {
        self.note.push(s.into());
        self
    }
    pub fn check(mut self, s: impl Into<String>) -> Finding {
        self.check.push(s.into());
        self
    }
    pub fn test(mut self, s: impl Into<String>) -> Finding {
        self.test.push(s.into());
        self
    }
    pub fn help(mut self, s: impl Into<String>) -> Finding {
        self.help.push(s.into());
        self
    }
}

/// Column (in characters) of a byte index.
pub fn char_col(text: &str, byte: usize) -> usize {
    text[..byte.min(text.len())].chars().count()
}

/// The part of a line without its indentation and trailing space: (column, length).
fn trimmed_range(text: &str) -> (usize, usize) {
    let lead = text.chars().take_while(|c| c.is_whitespace()).count();
    (lead, text.trim().chars().count())
}

/// What the rules can see.
pub struct Cx<'a> {
    pub diff: &'a Diff,
    pub project: &'a Project,
    pub desc: Option<&'a Description>,
}

impl Cx<'_> {
    /// The Tauri folder (`src-tauri`), from the project or, failing that, from the diff paths.
    pub fn tauri(&self) -> Option<Tauri> {
        self.project.tauri.clone().or_else(|| {
            self.diff
                .files
                .iter()
                .any(|f| f.path.starts_with("src-tauri/"))
                .then(|| Tauri { dir: "src-tauri".into(), major: 2 })
        })
    }

    pub fn laravel(&self) -> Option<Laravel> {
        self.project.laravel.clone().or_else(|| {
            let laravelish = |p: &str| {
                let php = p.ends_with(".php");
                p == "artisan"
                    || p.ends_with(".blade.php")
                    || php && ["app/", "database/migrations/", "routes/", "config/"].iter().any(|d| p.starts_with(d))
            };
            self.diff.files.iter().any(|f| laravelish(&f.path)).then(Laravel::default)
        })
    }

    pub fn node(&self) -> Option<&Node> {
        self.project.node.as_ref()
    }

    pub fn file(&self, path: &str) -> Option<&FileDiff> {
        self.diff.files.iter().find(|f| f.path == path)
    }

    /// Read a file of the repository as the change leaves it.
    pub fn read(&self, rel: &str) -> Option<String> {
        self.project.tree.read(rel)
    }

    /// The text files under `dir` (relative to the repository) with one of `exts`, as
    /// (path, content).
    pub fn scan(&self, dir: &str, exts: &[&str]) -> Vec<(String, String)> {
        self.project.tree.scan(dir, exts)
    }
}

pub fn file_name(path: &str) -> &str {
    path.rsplit('/').next().unwrap_or(path)
}

/// The extension in lowercase, without the dot (`blade.php` counts as `php`).
pub fn ext(path: &str) -> String {
    let name = file_name(path);
    name.rsplit_once('.').map(|(_, e)| e.to_lowercase()).unwrap_or_default()
}

pub fn is_test_path(path: &str) -> bool {
    let name = file_name(path);
    path.starts_with("tests/")
        || path.starts_with("test/")
        || path.contains("/tests/")
        || path.contains("/test/")
        || path.contains("__tests__/")
        || path.contains("/e2e/")
        || name.contains(".test.")
        || name.contains(".spec.")
        || name.ends_with("Test.php")
        || name.ends_with("_test.rs")
        || name.ends_with("_test.go")
}

/// Whether a line is only a comment (so that code in it is not code).
pub fn is_comment(line: &str) -> bool {
    let t = line.trim_start();
    t.starts_with("//") || t.starts_with('#') && !t.starts_with("#[") && !t.starts_with("#!") || t.starts_with("/*") || t.starts_with('*')
}

fn is_ident(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '$'
}

/// Find `needle` (like `dd(`) as a call of its own: not the end of a longer name such as
/// `add(` or `$odd(`. A method call (`->dump(`) does count.
pub fn find_call(text: &str, needle: &str) -> Option<usize> {
    text.match_indices(needle).map(|(i, _)| i).find(|&i| !text[..i].chars().next_back().is_some_and(is_ident))
}

/// Find `needle` as a whole word.
pub fn find_word(text: &str, needle: &str) -> Option<usize> {
    text.match_indices(needle)
        .map(|(i, _)| i)
        .find(|&i| !text[..i].chars().next_back().is_some_and(is_ident) && !text[i + needle.len()..].chars().next().is_some_and(is_ident))
}

/// The first quoted string at or after byte `from`: (start of the quote, end after the closing
/// quote, quote character).
pub fn string_at(text: &str, from: usize) -> Option<(usize, usize, char)> {
    let (start, q) = text[from..].char_indices().find(|&(_, c)| c == '"' || c == '\'' || c == '`').map(|(i, c)| (from + i, c))?;
    let mut escaped = false;
    for (i, c) in text[start + 1..].char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' => escaped = true,
            c if c == q => return Some((start, start + 1 + i + 1, q)),
            _ => {}
        }
    }
    None
}

/// Run every rule over the diff, most serious findings first.
pub fn analyze(cx: &Cx) -> Vec<Finding> {
    let mut out = Vec::new();
    generic::run(cx, &mut out);
    tauri::run(cx, &mut out);
    laravel::run(cx, &mut out);
    description::run(cx, &mut out);
    out.sort_by(|a, b| {
        let key = |f: &Finding| f.span.as_ref().map(|s| (s.file.clone(), s.line)).unwrap_or_default();
        (a.level, key(a), a.code).cmp(&(b.level, key(b), b.code))
    });
    out.dedup_by(|a, b| a.code == b.code && a.title == b.title && a.span.as_ref().map(|s| (&s.file, s.line)) == b.span.as_ref().map(|s| (&s.file, s.line)));
    out
}

#[cfg(test)]
pub mod testing {
    use super::*;
    use crate::review::diff;

    /// A diff that adds `lines` to `path` (a new file when `new`, else a one-hunk edit).
    pub fn add(path: &str, lines: &[&str]) -> String {
        let body: String = lines.iter().map(|l| format!("+{l}\n")).collect();
        format!(
            "diff --git a/{path} b/{path}\nnew file mode 100644\n--- /dev/null\n+++ b/{path}\n@@ -0,0 +1,{} @@\n{body}",
            lines.len()
        )
    }

    /// An edit of `path`: `-` and `+` prefixed lines and plain context lines, starting at line 10.
    pub fn edit(path: &str, lines: &[&str]) -> String {
        let old = lines.iter().filter(|l| !l.starts_with('+')).count();
        let new = lines.iter().filter(|l| !l.starts_with('-')).count();
        let body: String = lines
            .iter()
            .map(|l| if l.starts_with('+') || l.starts_with('-') { format!("{l}\n") } else { format!(" {l}\n") })
            .collect();
        format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -10,{old} +10,{new} @@\n{body}")
    }

    pub fn review(parts: &[String]) -> Vec<Finding> {
        review_with(parts, &Project::default(), None)
    }

    pub fn review_with(parts: &[String], project: &Project, desc: Option<&Description>) -> Vec<Finding> {
        let d = diff::parse(&parts.concat());
        analyze(&Cx { diff: &d, project, desc })
    }

    pub fn codes(f: &[Finding]) -> Vec<&'static str> {
        f.iter().map(|f| f.code).collect()
    }

    pub fn has(f: &[Finding], code: &str) -> bool {
        f.iter().any(|f| f.code == code)
    }

    pub fn get<'a>(f: &'a [Finding], code: &str) -> &'a Finding {
        f.iter().find(|f| f.code == code).unwrap_or_else(|| panic!("no {code} in {:?}", codes(f)))
    }
}

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

    #[test]
    fn finds_calls_but_not_longer_names() {
        assert_eq!(find_call("dd($x);", "dd("), Some(0));
        assert_eq!(find_call("add($x);", "dd("), None);
        assert_eq!(find_call("$a = odd(1); dd(2)", "dd("), Some(13));
        assert_eq!(find_call("$c->dump()", "dump("), Some(4));
        assert_eq!(find_word("a debugger;", "debugger"), Some(2));
        assert_eq!(find_word("mydebugger", "debugger"), None);
    }

    #[test]
    fn strings_are_found_with_escapes() {
        let t = r#"x("a \" b", 'c')"#;
        let (s, e, q) = string_at(t, 0).unwrap();
        assert_eq!((&t[s..e], q), (r#""a \" b""#, '"'));
        assert_eq!(string_at("no quotes", 0), None);
    }

    #[test]
    fn extensions_and_test_paths() {
        assert_eq!(ext("resources/views/a.blade.php"), "php");
        assert_eq!(ext("Makefile"), "");
        assert!(is_test_path("tests/Feature/UserTest.php"));
        assert!(is_test_path("src/app.test.ts"));
        assert!(!is_test_path("src/latest.rs"));
    }

    #[test]
    fn every_registered_code_is_unique_and_explained() {
        let mut seen = std::collections::HashSet::new();
        for r in explain::RULES {
            assert!(seen.insert(r.code), "duplicate {}", r.code);
            assert!(r.explain.len() > 40, "{} needs an explanation", r.code);
        }
    }
}