rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! What kind of project a repository is, read from its manifests: Tauri, Laravel and the
//! JavaScript tooling around them. The rules use it to suggest the commands that actually
//! exist (`pnpm`, not `npm`; `php artisan test`, not `phpunit`).

use std::path::Path;

use super::tree::Tree;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Pm {
    #[default]
    Npm,
    Pnpm,
    Yarn,
    Bun,
}

#[derive(Clone, Debug, Default)]
pub struct Node {
    pub pm: Pm,
    pub scripts: Vec<String>,
    /// `vitest`, `jest`, `playwright` or `cypress`, if a dependency.
    pub test_tool: Option<&'static str>,
}

#[derive(Clone, Debug, Default)]
pub struct Tauri {
    /// Folder holding `tauri.conf.json`, relative to the repository (`src-tauri`, or `.`).
    pub dir: String,
    pub major: u8,
}

#[derive(Clone, Debug, Default)]
pub struct Laravel {
    pub pest: bool,
    pub sail: bool,
    pub livewire: bool,
    pub inertia: bool,
}

#[derive(Clone, Debug, Default)]
pub struct Project {
    /// Where the files of the change under review are read from.
    pub tree: Tree,
    pub tauri: Option<Tauri>,
    pub laravel: Option<Laravel>,
    pub node: Option<Node>,
    pub rust: bool,
}

impl Project {
    #[cfg(test)]
    pub fn detect(root: &Path) -> Project {
        Project::from_tree(Tree::Disk(root.to_path_buf()))
    }

    pub fn from_tree(tree: Tree) -> Project {
        Project {
            rust: tree.is_file("Cargo.toml"),
            node: detect_node(&tree),
            tauri: detect_tauri(&tree),
            laravel: detect_laravel(&tree),
            tree,
        }
    }

    /// A short description for the report header, like `Laravel (Pest), Tauri 2 (pnpm)`.
    pub fn describe(&self) -> Vec<String> {
        let mut out = Vec::new();
        if let Some(l) = &self.laravel {
            let mut s = "Laravel".to_string();
            let mut extras = vec![if l.pest { "Pest" } else { "PHPUnit" }];
            if l.livewire {
                extras.push("Livewire");
            }
            if l.inertia {
                extras.push("Inertia");
            }
            s += &format!(" ({})", extras.join(", "));
            out.push(s);
        }
        if let Some(t) = &self.tauri {
            out.push(format!("Tauri {}", t.major));
        }
        if let Some(n) = &self.node {
            out.push(format!("{:?}", n.pm).to_lowercase());
        }
        if self.rust && self.tauri.is_none() {
            out.push("Rust".into());
        }
        out
    }
}

impl Node {
    /// `pnpm run build`, `npm run build`, ...
    pub fn run(&self, script: &str) -> String {
        match self.pm {
            Pm::Npm if script == "test" => "npm test".into(),
            Pm::Npm => format!("npm run {script}"),
            Pm::Pnpm => format!("pnpm run {script}"),
            Pm::Yarn => format!("yarn {script}"),
            Pm::Bun => format!("bun run {script}"),
        }
    }

    /// Run a binary from node_modules: `pnpm exec vitest run`, `npx vitest run`.
    pub fn exec(&self, cmd: &str) -> String {
        match self.pm {
            Pm::Npm => format!("npx {cmd}"),
            Pm::Pnpm => format!("pnpm exec {cmd}"),
            Pm::Yarn => format!("yarn {cmd}"),
            Pm::Bun => format!("bunx {cmd}"),
        }
    }

    /// The command that runs the JS tests, if there is one.
    pub fn test_cmd(&self, path: Option<&str>) -> Option<String> {
        let tool = match self.test_tool {
            Some("vitest") => "vitest run",
            Some("jest") => "jest",
            Some("playwright") => "playwright test",
            Some("cypress") => "cypress run",
            _ => return self.scripts.iter().any(|s| s == "test").then(|| self.run("test")),
        };
        Some(self.exec(&match path {
            Some(p) => format!("{tool} {p}"),
            None => tool.to_string(),
        }))
    }
}

impl Tauri {
    /// `pnpm tauri dev` and friends, or `cargo tauri dev` without a JavaScript side.
    pub fn cli(&self, node: Option<&Node>, sub: &str) -> String {
        match node {
            Some(n) if n.scripts.iter().any(|s| s == "tauri") => match n.pm {
                Pm::Npm => format!("npm run tauri -- {sub}"),
                Pm::Pnpm => format!("pnpm tauri {sub}"),
                Pm::Yarn => format!("yarn tauri {sub}"),
                Pm::Bun => format!("bun run tauri {sub}"),
            },
            _ => format!("cargo tauri {sub}"),
        }
    }

    /// A path inside the Tauri folder, as it appears in a diff.
    pub fn path(&self, rel: &str) -> String {
        if self.dir == "." { rel.to_string() } else { format!("{}/{rel}", self.dir) }
    }
}

impl Laravel {
    pub fn artisan(&self, args: &str) -> String {
        if self.sail { format!("./vendor/bin/sail artisan {args}") } else { format!("php artisan {args}") }
    }
    pub fn test_cmd(&self, path: Option<&str>) -> String {
        self.artisan(&match path {
            Some(p) => format!("test {p}"),
            None => "test".to_string(),
        })
    }
}

fn read_json(tree: &Tree, path: &str) -> Option<serde_json::Value> {
    serde_json::from_str(&tree.read(path)?).ok()
}

fn has_key(v: &serde_json::Value, section: &str, key: &str) -> bool {
    v.get(section).and_then(|s| s.get(key)).is_some()
}

fn detect_node(tree: &Tree) -> Option<Node> {
    let pkg = read_json(tree, "package.json")?;
    let pm_field = pkg.get("packageManager").and_then(|v| v.as_str()).unwrap_or("");
    let pm = if tree.is_file("pnpm-lock.yaml") || pm_field.starts_with("pnpm") {
        Pm::Pnpm
    } else if tree.is_file("yarn.lock") || pm_field.starts_with("yarn") {
        Pm::Yarn
    } else if tree.is_file("bun.lockb") || tree.is_file("bun.lock") || pm_field.starts_with("bun") {
        Pm::Bun
    } else {
        Pm::Npm
    };
    let dep = |name: &str| has_key(&pkg, "dependencies", name) || has_key(&pkg, "devDependencies", name);
    let test_tool = ["vitest", "jest", "@playwright/test", "cypress"].into_iter().find(|t| dep(t)).map(|t| match t {
        "@playwright/test" => "playwright",
        "vitest" => "vitest",
        "jest" => "jest",
        _ => "cypress",
    });
    let scripts = pkg
        .get("scripts")
        .and_then(|s| s.as_object())
        .map(|o| o.keys().cloned().collect())
        .unwrap_or_default();
    Some(Node { pm, scripts, test_tool })
}

fn detect_tauri(tree: &Tree) -> Option<Tauri> {
    let within = |dir: &str, file: &str| if dir == "." { file.to_string() } else { format!("{dir}/{file}") };
    let dir = ["src-tauri", "."]
        .into_iter()
        .find(|d| ["tauri.conf.json", "tauri.conf.json5", "Tauri.toml"].iter().any(|f| tree.is_file(&within(d, f))))?;
    let major = tree
        .read(&within(dir, "Cargo.toml"))
        .and_then(|s| s.parse::<toml::Table>().ok())
        .and_then(|t| {
            let dep = t.get("dependencies")?.get("tauri")?;
            let v = dep.as_str().or_else(|| dep.get("version")?.as_str())?;
            v.trim_start_matches(['^', '~', '=', '>', '<', ' ']).split('.').next()?.parse::<u8>().ok()
        })
        .unwrap_or(if tree.is_dir(&within(dir, "capabilities")) { 2 } else { 1 });
    Some(Tauri { dir: dir.to_string(), major })
}

fn detect_laravel(tree: &Tree) -> Option<Laravel> {
    let composer = read_json(tree, "composer.json")?;
    let dep = |name: &str| has_key(&composer, "require", name) || has_key(&composer, "require-dev", name);
    if !tree.is_file("artisan") && !dep("laravel/framework") {
        return None;
    }
    // `vendor` is never committed, so whether Sail is installed is asked of the disk.
    let sail_installed = tree.disk_root().is_some_and(|root: &Path| root.join("vendor/bin/sail").exists());
    Some(Laravel {
        pest: dep("pestphp/pest"),
        sail: dep("laravel/sail") && sail_installed,
        livewire: dep("livewire/livewire"),
        inertia: dep("inertiajs/inertia-laravel"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::review::testutil::Scratch;

    #[test]
    fn detects_tauri_with_pnpm() {
        let s = Scratch::new("tauri");
        s.write("package.json", r#"{"scripts":{"tauri":"tauri","test":"vitest"},"devDependencies":{"vitest":"^2"}}"#);
        s.write("pnpm-lock.yaml", "");
        s.write("src-tauri/tauri.conf.json", "{}");
        s.write("src-tauri/Cargo.toml", "[dependencies]\ntauri = { version = \"2.1\", features = [] }\n");
        let p = Project::detect(&s.0);
        let t = p.tauri.as_ref().unwrap();
        assert_eq!((t.dir.as_str(), t.major), ("src-tauri", 2));
        let n = p.node.as_ref().unwrap();
        assert_eq!(n.pm, Pm::Pnpm);
        assert_eq!(t.cli(Some(n), "dev"), "pnpm tauri dev");
        assert_eq!(n.test_cmd(Some("src/a.test.ts")).unwrap(), "pnpm exec vitest run src/a.test.ts");
        assert!(p.laravel.is_none());
    }

    #[test]
    fn tauri_version_one_and_npm_need_the_double_dash() {
        let s = Scratch::new("tauri1");
        s.write("package.json", r#"{"scripts":{"tauri":"tauri"}}"#);
        s.write("src-tauri/tauri.conf.json", "{}");
        s.write("src-tauri/Cargo.toml", "[dependencies]\ntauri = \"1.5\"\n");
        let p = Project::detect(&s.0);
        let t = p.tauri.as_ref().unwrap();
        assert_eq!(t.major, 1);
        assert_eq!(t.cli(p.node.as_ref(), "build"), "npm run tauri -- build");
        assert_eq!(t.cli(None, "build"), "cargo tauri build");
    }

    #[test]
    fn detects_laravel_with_pest() {
        let s = Scratch::new("laravel");
        s.write("artisan", "");
        s.write("composer.json", r#"{"require":{"laravel/framework":"^11"},"require-dev":{"pestphp/pest":"^3"}}"#);
        let p = Project::detect(&s.0);
        let l = p.laravel.as_ref().unwrap();
        assert!(l.pest && !l.sail);
        assert_eq!(l.test_cmd(Some("tests/Feature/A.php")), "php artisan test tests/Feature/A.php");
        assert_eq!(p.describe(), vec!["Laravel (Pest)"]);
    }

    #[test]
    fn an_empty_folder_is_nothing_special() {
        let s = Scratch::new("empty");
        let p = Project::detect(&s.0);
        assert!(p.tauri.is_none() && p.laravel.is_none() && p.node.is_none() && !p.rust);
    }
}