rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Fork, the Git client, in a pane: a quick look at a repository, its history and its
//! changes, where the full review panel is more than is needed.
//!
//! It is the program's own window that is moved into the pane (see [`super::hosted`]), so
//! all this has to do is start it on the right folder. Fork runs once: a second start hands
//! its folder to the one that runs and ends at once, which is what `fork` does when Fork is
//! already open in the pane.

use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::platform::process::CREATE_NO_WINDOW;

/// Fork's program: `RUSTIMAL_FORK` if it names one, else where its installer puts it (in the
/// user's folder, or in Program Files).
pub fn find() -> Option<PathBuf> {
    if let Some(chosen) = std::env::var_os("RUSTIMAL_FORK").map(PathBuf::from).filter(|p| p.is_file()) {
        return Some(chosen);
    }
    let places = [
        std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Fork").join("current").join("Fork.exe")),
        std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Fork").join("Fork.exe")),
        std::env::var_os("ProgramFiles").map(|d| PathBuf::from(d).join("Fork").join("Fork.exe")),
    ];
    places.into_iter().flatten().find(|p| p.is_file())
}

/// The repository `path` is in: its root, as Git names it. The folder itself when it is in
/// none, so that Fork says so rather than rustimal guessing.
pub fn repository_for(path: &Path) -> PathBuf {
    let asked = Command::new("git")
        .arg("-C")
        .arg(path)
        .args(["rev-parse", "--show-toplevel"])
        .creation_flags(CREATE_NO_WINDOW)
        .output();
    match asked {
        Ok(out) if out.status.success() => {
            let root = String::from_utf8_lossy(&out.stdout).trim().replace('/', "\\");
            if root.is_empty() { path.to_path_buf() } else { PathBuf::from(root) }
        }
        _ => path.to_path_buf(),
    }
}

/// `rustimal --fork [--reuse] [FOLDER]`: run Fork on the repository of FOLDER (the current
/// folder by default) and wait for it. With `--reuse` Fork is already open, and the
/// repository is handed to it.
pub fn run(args: &[String]) -> i32 {
    let rest: Vec<&String> = args.iter().filter(|a| *a != "--reuse").collect();
    let Some(fork) = find() else {
        eprintln!("embed: Fork is not installed (https://git-fork.com). RUSTIMAL_FORK names its Fork.exe.");
        return 1;
    };
    let folder = match rest.first() {
        Some(given) => std::path::absolute(given).unwrap_or_else(|_| PathBuf::from(given)),
        None => std::env::current_dir().unwrap_or_default(),
    };
    let repository = repository_for(&folder);
    match Command::new(&fork).arg(&repository).status() {
        Ok(status) => status.code().unwrap_or(1),
        Err(e) => {
            eprintln!("embed: could not start {}: {e}", fork.display());
            1
        }
    }
}

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

    #[test]
    fn a_folder_in_a_repository_gives_its_root() {
        let root = std::env::current_dir().unwrap();
        let inside = root.join("src").join("programs");
        let found = repository_for(&inside);
        // Git writes the root its own way (case, drive letter); the same folder is what counts.
        assert_eq!(found.canonicalize().unwrap(), root.canonicalize().unwrap());
    }

    #[test]
    fn a_folder_outside_any_repository_is_left_as_it_is() {
        let dir = std::env::temp_dir().join(format!("rustimal-no-repo-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        assert_eq!(repository_for(&dir), dir);
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn the_program_can_be_named() {
        let own = std::env::current_exe().unwrap();
        // SAFETY: tests of this binary do not read this variable on other threads.
        unsafe { std::env::set_var("RUSTIMAL_FORK", &own) };
        assert_eq!(find(), Some(own));
        unsafe { std::env::remove_var("RUSTIMAL_FORK") };
    }
}