rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Command line: `--install`, `--uninstall`, `--update`, `--version` and `--help`.
//!
//! `cargo install rustimal` only puts the exe in `~/.cargo/bin`. `rustimal --install`
//! adds what makes it feel installed: a Start menu entry, "Open in rustimal" in
//! Explorer's right-click menu, and Win+R. That's the job of `install.ps1`, which is
//! embedded here so it works from a crates.io install, with no repo checkout.

use std::process::Command;

const INSTALL_SCRIPT: &str = include_str!("../install.ps1");

const HELP: &str = "\
rustimal - a GPU-rendered terminal for Windows

USAGE:
    rustimal [DIRECTORY]       open a window, starting in DIRECTORY
    rustimal --layout NAME     open a saved layout (save one from the command palette)
    rustimal --install         add Start menu, Explorer right-click and Win+R entries
    rustimal --install --desktop
                               ... and a desktop shortcut
    rustimal --uninstall       remove those entries (the exe and your config stay)
    rustimal --update          install the newest version from crates.io (needs cargo)
    rustimal --update --check  only say whether there is one
    rustimal --open FILE[:LINE[:COL]]
                               open a file in your editor at that line (the shell's `open` uses this)
    rustimal --review [TARGET]
                               what to check and how to test a change by hand: a pull
                               request, branch, commit or `demo` (--help for more)
                               in a rustimal window, `pr` and `review` open it as a panel
    rustimal --t3 [-l | NUMBER | FOLDER]
                               open a folder's conversation in the T3 Code desktop app
                               (`t3` in a rustimal pane shows it inside the pane)
    rustimal --browser [PAGE]  run a Firefox-based browser (Zen, Firefox, ...) with a profile of its own
                               (`embed browser` in a rustimal pane shows it inside the pane)
    rustimal --fork [FOLDER]   run Fork, the Git client, on a repository
                               (`fork` in a rustimal pane shows it inside the pane)
    rustimal --version
    rustimal --help
";

use crate::platform::win32::GetStdHandle;

#[link(name = "kernel32")]
unsafe extern "system" {
    fn AttachConsole(pid: u32) -> i32;
    fn SetStdHandle(which: u32, handle: isize) -> i32;
    fn GetConsoleMode(handle: isize, mode: *mut u32) -> i32;
    fn SetConsoleMode(handle: isize, mode: u32) -> i32;
}

const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
const STD_ERROR_HANDLE: u32 = -12i32 as u32;

/// The release build is a windowed program, so it starts without console output.
/// When run from a terminal, connect to that terminal so messages show up.
fn attach_console() {
    use std::os::windows::io::IntoRawHandle;
    // SAFETY: plain kernel32 calls; the handles passed to SetStdHandle stay open on purpose.
    unsafe {
        if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
            return; // no parent console (or we already have one, as in debug builds)
        }
        for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
            let h = GetStdHandle(which);
            if (h == 0 || h == -1)
                && let Ok(f) = std::fs::OpenOptions::new().write(true).open("CONOUT$")
            {
                SetStdHandle(which, f.into_raw_handle() as isize);
            }
        }
    }
}

/// Make the console show colors, which older Windows consoles only do when asked.
pub fn enable_ansi() {
    const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
    // SAFETY: plain kernel32 calls on this process's own output handle.
    unsafe {
        let out = GetStdHandle(STD_OUTPUT_HANDLE);
        let mut mode = 0;
        if GetConsoleMode(out, &mut mode) != 0 {
            SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
        }
    }
}

/// Handle a command line option. Returns the exit code, or `None` if `arg` isn't one
/// (it's then the starting directory).
pub fn run(arg: &str) -> Option<i32> {
    let rest = || std::env::args().skip(2).collect::<Vec<_>>();
    match arg {
        "--version" | "-V" => {
            attach_console();
            println!("rustimal {}", env!("CARGO_PKG_VERSION"));
            Some(0)
        }
        "--help" | "-h" | "/?" => {
            attach_console();
            print!("{HELP}");
            Some(0)
        }
        "--install" => {
            attach_console();
            Some(setup(false, &rest()))
        }
        "--uninstall" => {
            attach_console();
            Some(setup(true, &rest()))
        }
        "--update" => {
            attach_console();
            Some(update(&rest()))
        }
        "--review" => {
            attach_console();
            Some(crate::review::run(&rest()))
        }
        "--t3" => {
            attach_console();
            Some(crate::programs::t3::run(&rest()))
        }
        // Started by `t3` itself, to run T3 Code's server out of sight; it has nothing to say.
        "--t3-server" => Some(crate::programs::t3::server::supervise()),
        // Started by rustimal itself, to run VS Code's server out of sight.
        "--vscode-server" => Some(crate::programs::vscode::supervise()),
        // What `embed browser` runs in a pane: the browser, waited for.
        "--browser" => {
            attach_console();
            Some(crate::programs::browser::run(&rest()))
        }
        // What `embed fork` runs in a pane: Fork, the Git client, waited for.
        "--fork" => {
            attach_console();
            Some(crate::programs::fork::run(&rest()))
        }
        "--open" => {
            attach_console();
            Some(open_at(&rest()))
        }
        _ => None,
    }
}

/// `rustimal --open FILE[:LINE[:COL]]` or `--open FILE LINE [COL]`: open the file in the editor
/// from the config, at that place.
fn open_at(args: &[String]) -> i32 {
    use crate::terminal::links::{Pos, open_in_editor_blocking, split_position};
    let Some(first) = args.first() else {
        eprintln!("usage: rustimal --open FILE[:LINE[:COL]]");
        return 2;
    };
    let (file, pos) = match args[1..].iter().map(|a| a.parse::<u32>()).collect::<Result<Vec<_>, _>>() {
        Ok(nums) if !nums.is_empty() && nums.len() <= 2 => {
            (first.as_str(), Some(Pos { line: nums[0], col: nums.get(1).copied() }))
        }
        Ok(nums) if nums.is_empty() => split_position(first),
        _ => {
            eprintln!("usage: rustimal --open FILE[:LINE[:COL]]");
            return 2;
        }
    };
    let path = std::path::absolute(file).unwrap_or_else(|_| file.into());
    if !path.is_file() {
        eprintln!("rustimal: {file}: no such file");
        return 1;
    }
    let editor = crate::config::Config::load().editor;
    open_in_editor_blocking(&path, pos.unwrap_or(Pos { line: 1, col: None }), &editor);
    0
}

fn setup(uninstall: bool, extra: &[String]) -> i32 {
    let mut args = vec!["-NoProfile".to_string(), "-ExecutionPolicy".into(), "Bypass".into(), "-File".into()];
    let script = std::env::temp_dir().join(format!("rustimal-setup-{}.ps1", std::process::id()));
    if let Err(e) = std::fs::write(&script, INSTALL_SCRIPT) {
        eprintln!("could not write {}: {e}", script.display());
        return 1;
    }
    args.push(script.to_string_lossy().into_owned());
    match std::env::current_exe() {
        Ok(exe) => {
            args.push("-ExePath".into());
            args.push(exe.to_string_lossy().into_owned());
        }
        Err(e) => {
            eprintln!("could not find the rustimal executable: {e}");
            let _ = std::fs::remove_file(&script);
            return 1;
        }
    }
    if uninstall {
        args.push("-Uninstall".into());
    }
    for a in extra {
        match a.to_ascii_lowercase().as_str() {
            "--desktop" if !uninstall => args.push("-Desktop".into()),
            other => {
                eprintln!("unknown option: {other}\n\n{HELP}");
                let _ = std::fs::remove_file(&script);
                return 2;
            }
        }
    }
    let status = Command::new("powershell.exe").args(&args).status();
    let _ = std::fs::remove_file(&script);
    match status {
        Ok(s) if s.success() => 0,
        Ok(s) => s.code().unwrap_or(1),
        Err(e) => {
            eprintln!("could not run powershell.exe: {e}");
            1
        }
    }
}

/// The newest version on crates.io, from `cargo search` (which also covers any mirror or
/// proxy the user has set up for cargo).
fn latest_version() -> Result<String, String> {
    let out = Command::new("cargo")
        .args(["search", "rustimal", "--limit", "1"])
        .output()
        .map_err(|e| format!("could not run cargo ({e}); updating needs the Rust toolchain: https://rustup.rs"))?;
    if !out.status.success() {
        return Err(format!("cargo search failed: {}", String::from_utf8_lossy(&out.stderr).trim()));
    }
    parse_search(&String::from_utf8_lossy(&out.stdout)).ok_or_else(|| "rustimal was not found on crates.io".to_string())
}

/// The version in `cargo search` output: `rustimal = "0.4.0"    # a terminal`.
fn parse_search(output: &str) -> Option<String> {
    let line = output.lines().find(|l| l.starts_with("rustimal = \""))?;
    let rest = &line["rustimal = \"".len()..];
    Some(rest[..rest.find('"')?].to_string())
}

fn version_parts(v: &str) -> Vec<u64> {
    v.split('-').next().unwrap_or("").split('.').map(|p| p.parse().unwrap_or(0)).collect()
}

/// Is `latest` newer than `current`? (`0.10.0` is newer than `0.9.9`.)
fn is_newer(latest: &str, current: &str) -> bool {
    let (mut a, mut b) = (version_parts(latest), version_parts(current));
    let n = a.len().max(b.len());
    a.resize(n, 0);
    b.resize(n, 0);
    a > b
}

/// Where `cargo install` puts the exe.
fn installed_exe() -> Option<std::path::PathBuf> {
    let home = std::env::var_os("CARGO_HOME")
        .map(std::path::PathBuf::from)
        .or_else(|| dirs::home_dir().map(|h| h.join(".cargo")))?;
    Some(home.join("bin").join("rustimal.exe"))
}

/// Delete the exes earlier updates moved aside. One still running can't be deleted; it is
/// picked up by the next update.
fn remove_old_copies(dir: &std::path::Path) {
    for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
        let name = entry.file_name().to_string_lossy().to_lowercase();
        if name.starts_with("rustimal.old") && name.ends_with(".exe") {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// `rustimal --update [--check]`: install the newest version with cargo.
///
/// Windows won't let `cargo install` overwrite an exe that is running, and rustimal windows
/// are usually open (this one included), but a running exe can be renamed. So the installed
/// exe is moved aside first; open windows keep running it, and new ones start the new version.
fn update(args: &[String]) -> i32 {
    let (mut check, mut force) = (false, false);
    for a in args {
        match a.as_str() {
            "--check" => check = true,
            "--force" => force = true,
            other => {
                eprintln!("unknown option: {other}\n\n{HELP}");
                return 2;
            }
        }
    }
    let current = env!("CARGO_PKG_VERSION");
    println!("rustimal {current}; asking crates.io for the newest version...");
    let latest = match latest_version() {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    if !is_newer(&latest, current) && !force {
        println!("rustimal {current} is up to date (the newest is {latest}).");
        return 0;
    }
    if check {
        println!("rustimal {latest} is available (this is {current}). Run `rustimal --update` to install it.");
        return 0;
    }
    println!("Installing rustimal {latest} with cargo. This compiles it, so it takes a few minutes.");
    let target = installed_exe().filter(|p| p.exists());
    let moved = target.as_ref().and_then(|exe| {
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
        let aside = exe.with_file_name(format!("rustimal.old{stamp}.exe"));
        std::fs::rename(exe, &aside).ok().map(|()| (exe.clone(), aside))
    });
    let status = Command::new("cargo").args(["install", "rustimal", "--locked", "--force"]).status();
    let installed = matches!(status, Ok(s) if s.success());
    if installed {
        if let Some(dir) = target.as_ref().and_then(|p| p.parent()) {
            remove_old_copies(dir);
        }
        println!(
            "\nUpdated to rustimal {latest}. New windows use it; open windows keep running {current} until you close them."
        );
        return 0;
    }
    // Put the old exe back so rustimal still works.
    if let Some((exe, aside)) = moved
        && !exe.exists()
    {
        let _ = std::fs::rename(aside, exe);
    }
    match status {
        Ok(_) => eprintln!("\ncargo could not install rustimal {latest}; the version you have is unchanged."),
        Err(e) => eprintln!("\ncould not run cargo: {e}"),
    }
    1
}

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

    #[test]
    fn reads_the_version_from_cargo_search() {
        let out = "rustimal = \"0.4.0\"    # A minimal, GPU-rendered terminal\nrustimal-extras = \"1.0.0\"  # other\n";
        assert_eq!(parse_search(out), Some("0.4.0".to_string()));
        assert_eq!(parse_search("rustimal-extras = \"1.0.0\"\n"), None, "another crate is not ours");
        assert_eq!(parse_search(""), None);
    }

    #[test]
    fn versions_compare_by_number() {
        assert!(is_newer("0.4.0", "0.3.9"));
        assert!(is_newer("0.10.0", "0.9.9"), "numbers, not text");
        assert!(is_newer("1.0", "0.9.9"));
        assert!(!is_newer("0.4.0", "0.4.0"));
        assert!(!is_newer("0.3.9", "0.4.0"));
        assert!(is_newer("0.4.1", "0.4"));
    }
}