rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! `review demo`: a small Laravel and Tauri pull request with mistakes planted in it, to try
//! the review on without a project of one's own. It is made as a real git repository, with
//! fixed dates and author so its commits, and the test results saved against them, stay put.

use std::path::{Path, PathBuf};

use super::git;

pub const TITLE: &str = "Demo pull request: invoice PDF export";
pub const BRANCH: &str = "invoice-export";
/// Bump when the files below change.
const VERSION: u32 = 1;

pub const DESCRIPTION: &str = "\
## Summary
<!-- what does this do? -->
PDF export and search for invoices. Added tests. Fixes #42

## Test plan
1. Open an invoice and click Export
2. Search for an invoice by its number

- [ ] Docs updated
";

/// (path, before, after). `None` means the file is not there.
type File = (&'static str, Option<&'static str>, Option<&'static str>);

const SAME: &[(&str, &str)] = &[
    (".env.example", "APP_NAME=demo\n"),
    ("artisan", ""),
    ("composer.json", "{\n  \"require\": { \"laravel/framework\": \"^11.0\" },\n  \"require-dev\": { \"pestphp/pest\": \"^3.0\" }\n}\n"),
    ("package.json", "{\n  \"scripts\": { \"tauri\": \"tauri\", \"build\": \"vite build\" },\n  \"devDependencies\": { \"vitest\": \"^2.0.0\" }\n}\n"),
    ("pnpm-lock.yaml", ""),
    ("src-tauri/Cargo.toml", "[dependencies]\ntauri = \"2.1\"\n"),
    ("src-tauri/tauri.conf.json", "{ }\n"),
];

const CHANGED: &[File] = &[
    (
        "app/Http/Controllers/InvoiceController.php",
        Some("<?php\n\nclass InvoiceController\n{\n    public function destroy(Invoice $invoice)\n    {\n        $this->authorize('delete', $invoice);\n        $invoice->delete();\n    }\n}\n"),
        Some("<?php\n\nclass InvoiceController\n{\n    public function destroy(Invoice $invoice)\n    {\n        $invoice->delete();\n    }\n\n    public function search(Request $request)\n    {\n        return Invoice::whereRaw(\"number like '%{$request->q}%'\")->get();\n    }\n}\n"),
    ),
    (
        "config/billing.php",
        Some("<?php\n\nreturn [\n    'name' => env('APP_NAME'),\n];\n"),
        Some("<?php\n\nreturn [\n    'name' => env('APP_NAME'),\n    'pdf_key' => env('PDF_SERVICE_KEY'),\n];\n"),
    ),
    (
        "database/migrations/2026_11_25_000000_drop_legacy_total.php",
        None,
        Some("<?php\n\nreturn new class extends Migration\n{\n    public function up(): void\n    {\n        Schema::table('invoices', function (Blueprint $table) {\n            $table->dropColumn('legacy_total');\n        });\n    }\n\n    public function down(): void\n    {\n    }\n};\n"),
    ),
    ("resources/views/invoice.blade.php", None, Some("<div>{!! $invoice->notes !!}</div>\n")),
    (
        "routes/web.php",
        Some("<?php\n\nRoute::get('/', fn () => view('home'));\n"),
        Some("<?php\n\nRoute::get('/', fn () => view('home'));\nRoute::delete('/invoices/{invoice}', [InvoiceController::class, 'destroy']);\n"),
    ),
    (
        "src-tauri/src/lib.rs",
        Some("#[tauri::command]\nfn load_invoice(id: u32) -> String {\n    String::new()\n}\n\npub fn run() {\n    tauri::Builder::default().invoke_handler(tauri::generate_handler![load_invoice]);\n}\n"),
        Some("#[tauri::command]\nfn load_invoice(id: u32, with_lines: bool) -> String {\n    String::new()\n}\n\n#[tauri::command]\nfn export_pdf(invoice_id: u32) -> Result<(), String> {\n    Ok(())\n}\n\npub fn run() {\n    tauri::Builder::default().invoke_handler(tauri::generate_handler![load_invoice]);\n}\n"),
    ),
    (
        "src/api.ts",
        Some("import { invoke } from '@tauri-apps/api/core';\nexport const load = (id: number) => invoke('load_invoice', { id });\n"),
        Some("import { invoke } from '@tauri-apps/api/core';\nexport const load = (id: number) => invoke('load_invoice', { id });\nexport const pdf = (id: number) => invoke('exportPdf', { invoiceId: id });\n"),
    ),
];

/// Two windows could be making it at once.
static MAKING: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// The demo repository, made the first time it is asked for.
pub fn create() -> Result<PathBuf, String> {
    // Tests must not touch the real data folder.
    let home = match crate::config::state_dir() {
        Some(dir) if !cfg!(test) => dir,
        _ => std::env::temp_dir().join(if cfg!(test) { "rustimal-test" } else { "rustimal" }),
    };
    create_in(&home.join(format!("demo-pr-v{VERSION}")))
}

fn ready(dir: &Path) -> bool {
    dir.join(".git").is_dir() && git::commit_id(dir, "main").is_some() && git::commit_id(dir, BRANCH).is_some()
}

fn write(dir: &Path, rel: &str, text: &str) -> Result<(), String> {
    let path = dir.join(rel);
    path.parent()
        .map_or(Ok(()), std::fs::create_dir_all)
        .and_then(|()| std::fs::write(&path, text))
        .map_err(|e| format!("could not write {}: {e}", path.display()))
}

fn commit(dir: &Path, message: &str, date: &str) -> Result<(), String> {
    git::output(dir, &["add", "--all"])?;
    let out = git::command(dir)
        .args(["commit", "--quiet", "--no-verify", "-m", message])
        .env("GIT_AUTHOR_DATE", date)
        .env("GIT_COMMITTER_DATE", date)
        .output()
        .map_err(|e| format!("could not run git: {e}"))?;
    if out.status.success() { Ok(()) } else { Err(format!("git commit: {}", String::from_utf8_lossy(&out.stderr).trim())) }
}

fn create_in(dir: &Path) -> Result<PathBuf, String> {
    let _one = MAKING.lock().unwrap_or_else(|e| e.into_inner());
    if ready(dir) {
        return Ok(dir.to_path_buf());
    }
    std::fs::create_dir_all(dir).map_err(|e| format!("could not make {}: {e}", dir.display()))?;
    git::output(dir, &["init", "--quiet", "--template="])?;
    git::output(dir, &["symbolic-ref", "HEAD", "refs/heads/main"])?;
    // Everything that could change what gets committed, or run something while committing.
    for (key, value) in [
        ("user.name", "rustimal demo"),
        ("user.email", "demo@rustimal.invalid"),
        ("core.autocrlf", "false"),
        ("core.hooksPath", ".git/no-hooks"),
        ("core.excludesFile", ".git/no-excludes"),
        ("core.attributesFile", ".git/no-attributes"),
        ("commit.gpgsign", "false"),
    ] {
        git::output(dir, &["config", key, value])?;
    }
    for (path, text) in SAME {
        write(dir, path, text)?;
    }
    for (path, before, _) in CHANGED {
        if let Some(text) = before {
            write(dir, path, text)?;
        }
    }
    commit(dir, "Start the demo project", "2026-01-01T12:00:00 +0000")?;
    git::output(dir, &["switch", "--quiet", "--force-create", BRANCH])?;
    for (path, _, after) in CHANGED {
        if let Some(text) = after {
            write(dir, path, text)?;
        }
    }
    commit(dir, "Invoice PDF export", "2026-01-02T12:00:00 +0000")?;
    Ok(dir.to_path_buf())
}

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

    #[test]
    fn the_demo_is_the_same_every_time_and_shows_its_planted_mistakes() {
        let (a, b) = (Scratch::new("demo-a"), Scratch::new("demo-b"));
        create_in(&a.0.join("d")).unwrap();
        create_in(&b.0.join("d")).unwrap();
        let head = |s: &Scratch| git::commit_id(&s.0.join("d"), BRANCH).unwrap();
        assert_eq!(head(&a), head(&b));
        // Asking again leaves it alone.
        create_in(&a.0.join("d")).unwrap();
        assert_eq!(head(&a), head(&b));

        let tree = crate::review::tree::Tree::commit(&a.0.join("d"), BRANCH).unwrap();
        let project = crate::review::project::Project::from_tree(tree);
        let text = git::output(&a.0.join("d"), &["diff", "--src-prefix=a/", "--dst-prefix=b/", "main...invoice-export"]).unwrap();
        let diff = crate::review::diff::parse(&text);
        let desc = crate::review::desc::parse(DESCRIPTION, "PR description");
        let found = crate::review::rules::analyze(&crate::review::rules::Cx { diff: &diff, project: &project, desc: Some(&desc) });
        for code in ["TAU005", "LAR001", "LAR006", "LAR011", "PR004"] {
            assert!(found.iter().any(|f| f.code == code), "no {code}");
        }
        assert!(found.iter().any(|f| f.level == crate::review::rules::Level::Risk));
    }
}