rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! `rustimal --review`: read a change (a pull request, a branch, a commit, work in progress or
//! any diff) and its description, and say what to look for and how to test it by hand.
//!
//! The analysis is separate from where the change comes from and from how it is shown: the
//! terminal report here and the view inside the window use the same [`source::Change`].

mod demo;
mod desc;
pub mod diff;
mod explain;
pub mod forge;
pub mod guide;
pub(crate) mod git;
pub mod workspace;
mod project;
pub mod propose;
pub mod render;
pub mod rules;
pub mod session;
pub mod source;
mod tree;

use std::io::{IsTerminal, Write};

const USAGE: &str = "\
rustimal --review - what to check and how to test a change by hand

USAGE:
    rustimal --review              this branch's commits since it left the main branch
    rustimal --review TARGET       a pull request (12, #12 or its address), a branch,
                                   a commit, or `demo` for a made-up one to try
    rustimal --review --uncommitted
                                   everything not committed yet, new files included
    rustimal --review --staged     only what is staged
    rustimal --review --diff FILE  a diff from a file, or from stdin with `-`
    rustimal --review --prs        list the open pull requests

OPTIONS:
    --base REF      what to compare a branch with (default: origin's main branch)
    --desc FILE     the pull request description (`-` for stdin); without it, the pull
                    request's own, or else the commit messages
    --json          machine-readable output
    --color WHEN    auto (default), always or never
    --explain CODE  what a finding means; without CODE, list them all

Run it from inside the repository. In a rustimal window, `review` and `pr` open the same
thing as a panel with guided testing (`review --print` prints here instead).

Pull requests come from GitHub, GitLab, Gitea or Bitbucket, as named by the `origin`
remote. For a self-hosted server whose name does not say which it is:
    git config rustimal.forge gitea
";

#[derive(Clone, Debug, Default, PartialEq)]
pub enum Source {
    #[default]
    Branch,
    Staged,
    Uncommitted,
    File(String),
}

#[derive(Clone, Debug, Default)]
pub struct Options {
    /// A pull request, branch, commit or `demo`; none is the current branch.
    pub target: Option<String>,
    pub base: Option<String>,
    pub source: Source,
    pub desc: Option<String>,
    json: bool,
    color: Option<bool>,
}

#[derive(Debug)]
pub enum Parsed {
    Review(Options),
    List,
    Explain(Option<String>),
    Help,
}

pub fn parse_args(args: &[String]) -> Result<Parsed, String> {
    let mut o = Options::default();
    let mut sources = 0;
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let mut value = |what: &str| it.next().cloned().ok_or_else(|| format!("{what} needs a value"));
        match a.as_str() {
            "--help" | "-h" => return Ok(Parsed::Help),
            "--prs" => return Ok(Parsed::List),
            "--explain" => return Ok(Parsed::Explain(it.next().cloned())),
            // The shell's `review` takes it to mean "here, not in the panel".
            "--print" => {}
            "--staged" => {
                o.source = Source::Staged;
                sources += 1;
            }
            "--uncommitted" => {
                o.source = Source::Uncommitted;
                sources += 1;
            }
            "--diff" => {
                o.source = Source::File(value("--diff")?);
                sources += 1;
            }
            "--base" => o.base = Some(value("--base")?),
            "--desc" => o.desc = Some(value("--desc")?),
            "--json" => o.json = true,
            "--no-color" => o.color = Some(false),
            "--color" => {
                o.color = match value("--color")?.as_str() {
                    "always" => Some(true),
                    "never" => Some(false),
                    "auto" => None,
                    other => return Err(format!("--color is auto, always or never, not `{other}`")),
                }
            }
            s if s.starts_with('-') => return Err(format!("unknown option `{s}`")),
            s if o.target.is_none() => o.target = Some(s.to_string()),
            s => return Err(format!("unexpected `{s}`")),
        }
    }
    if sources > 1 {
        return Err("use only one of --staged, --uncommitted and --diff".into());
    }
    if (o.target.is_some() || o.base.is_some()) && o.source != Source::Branch {
        return Err("a target or --base does not go with --staged, --uncommitted or --diff".into());
    }
    if o.source == Source::File("-".into()) && o.desc.as_deref() == Some("-") {
        return Err("only one of --diff and --desc can read stdin".into());
    }
    Ok(Parsed::Review(o))
}

fn print(text: &str) {
    // A closed pipe (`| head`) is not an error worth a panic.
    let _ = std::io::stdout().write_all(text.as_bytes());
}

/// Handle `rustimal --review ...`. Returns the exit code.
pub fn run(args: &[String]) -> i32 {
    match parse_args(args) {
        Ok(Parsed::Help) => {
            print(USAGE);
            0
        }
        Ok(Parsed::Explain(code)) => explain_code(code.as_deref()),
        Ok(Parsed::List) => match list_pull_requests() {
            Ok(text) => {
                print(&text);
                0
            }
            Err(e) => {
                eprintln!("rustimal: {e}");
                2
            }
        },
        Ok(Parsed::Review(o)) => match review(&o) {
            Ok(text) => {
                print(&text);
                0
            }
            Err(e) => {
                eprintln!("rustimal: {e}");
                2
            }
        },
        Err(e) => {
            eprintln!("rustimal: {e}\n\n{USAGE}");
            2
        }
    }
}

fn explain_code(code: Option<&str>) -> i32 {
    let Some(code) = code else {
        for r in explain::RULES {
            print(&format!("{}  {}\n", r.code, r.name));
        }
        return 0;
    };
    match explain::lookup(code) {
        Some(r) => {
            print(&format!("{}: {}\n\n{}\n", r.code, r.name, r.explain));
            0
        }
        None => {
            eprintln!("rustimal: no rule `{code}`; `rustimal --review --explain` lists them");
            1
        }
    }
}

fn current_dir() -> Result<std::path::PathBuf, String> {
    std::env::current_dir().map_err(|e| e.to_string())
}

fn list_pull_requests() -> Result<String, String> {
    let root = source::repository(&current_dir()?)?;
    let (kind, prs) = forge::list(&root)?;
    if prs.is_empty() {
        return Ok(format!("no open pull requests on {}\n", kind.label()));
    }
    // Titles and names are other people's text: no control characters reach the terminal.
    let clean = |s: &str| s.chars().filter(|c| !c.is_control()).collect::<String>();
    let mut out = String::new();
    for p in &prs {
        let e = source::pull_request_entry(p);
        out += &format!("{}\n    {}\n", clean(&e.title), clean(&e.detail));
    }
    out += "\nReview one with `rustimal --review NUMBER`.\n";
    Ok(out)
}

fn review(o: &Options) -> Result<String, String> {
    let change = match source::load(&current_dir()?, o)? {
        source::Loaded::Change(c) => c,
        source::Loaded::Empty(why) => return Ok(format!("{why}\n")),
    };
    for note in &change.notes {
        eprintln!("note: {note}");
    }
    let report = &change.report;
    if o.json {
        return serde_json::to_string_pretty(report).map(|s| s + "\n").map_err(|e| e.to_string());
    }
    let color = o.color.unwrap_or_else(|| std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none());
    if color {
        crate::cli::enable_ansi();
    }
    let width = std::env::var("COLUMNS").ok().and_then(|c| c.parse().ok()).unwrap_or(100usize).clamp(60, 200);
    let mut text = render::report(report, render::Style { color, width });
    // Only in a rustimal pane, where `pr` is a command, and only for someone reading it.
    let in_pane = std::env::var_os("RUSTIMAL_REVIEW_TOKEN").is_some() && std::io::stdout().is_terminal();
    if let Some(of) = change.branch.as_ref().filter(|_| in_pane) {
        text += &new_pull_hint(&of.name);
    }
    Ok(text)
}

fn new_pull_hint(reference: &str) -> String {
    let name = reference.strip_prefix("refs/heads/").or_else(|| reference.strip_prefix("refs/remotes/"));
    format!("\nOpen a pull request for this branch: pr new {}\n", name.unwrap_or(reference))
}

#[cfg(test)]
pub mod testutil {
    use std::path::PathBuf;

    /// A fresh scratch folder that is removed when dropped.
    pub struct Scratch(pub PathBuf);

    impl Scratch {
        pub fn new(name: &str) -> Scratch {
            let p = std::env::temp_dir().join(format!("rustimal-review-{}-{name}", std::process::id()));
            let _ = std::fs::remove_dir_all(&p);
            std::fs::create_dir_all(&p).unwrap();
            Scratch(p)
        }
        pub fn write(&self, rel: &str, text: &str) {
            let f = self.0.join(rel);
            std::fs::create_dir_all(f.parent().unwrap()).unwrap();
            std::fs::write(f, text).unwrap();
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }
}

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

    fn args(a: &[&str]) -> Result<Parsed, String> {
        parse_args(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>())
    }

    #[test]
    fn parses_options() {
        let Ok(Parsed::Review(o)) = args(&["12", "--base", "origin/dev", "--desc", "pr.md", "--json", "--print"]) else { panic!() };
        assert_eq!((o.target.as_deref(), o.base.as_deref()), (Some("12"), Some("origin/dev")));
        assert_eq!((o.desc.as_deref(), o.json), (Some("pr.md"), true));
        assert!(matches!(args(&["--prs"]), Ok(Parsed::List)));
        assert!(args(&["a", "b"]).is_err());
        assert!(matches!(args(&["--explain", "lar001"]), Ok(Parsed::Explain(Some(c))) if c == "lar001"));
        assert!(matches!(args(&["--help"]), Ok(Parsed::Help)));
        assert!(args(&["--staged", "--uncommitted"]).is_err());
        assert!(args(&["main", "--staged"]).is_err());
        assert!(args(&["--base", "main", "--uncommitted"]).is_err());
        assert!(args(&["--diff", "-", "--desc", "-"]).is_err());
        assert!(args(&["--wat"]).is_err());
        assert!(args(&["--desc"]).is_err());
    }

    #[test]
    fn reads_utf16_input_from_powershell() {
        let s = testutil::Scratch::new("utf16");
        let bytes: Vec<u8> = [0xff, 0xfe].into_iter().chain("hi".encode_utf16().flat_map(u16::to_le_bytes)).collect();
        std::fs::write(s.0.join("a.diff"), bytes).unwrap();
        assert_eq!(source::read_input(&s.0, "a.diff").unwrap(), "hi");
    }
}