Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

15.1 KB
Raw Blame
//! The Git program every Git command runs (Settings > Developer tools > "Git"): `git` from the PATH, or a program the user chose
//! (another Git, or `wslgit.exe`, which runs the Git inside WSL), and the version it answers with.
//!
//! A chosen program may hand what it is given to a shell: wslgit joins its arguments into one line for `bash -c` and escapes only
//! some of the characters a shell acts on. Git is run here just because a folder is browsed, and names out of the repository (its
//! filters, folders, branches) are among the arguments, so a downloaded repository could run anything that way. For a program that
//! is not Git for Windows itself, [`check`] refuses arguments a shell would not take as plain text.
//!
//! Everything that looks at a program blocks, but [`peek`], which is for the interface.

use std::collections::HashMap;
use std::ffi::OsStr;
use std::io::{self, Read};
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard};
use std::time::{Duration, Instant, SystemTime};

const CREATE_NO_WINDOW: u32 = 0x0800_0000;

/// What runs when no program is chosen: looked for on the PATH.
const AUTOMATIC: &str = "git";

/// What was seen is taken as it is for this long before the interface has it looked at again.
const FRESH: Duration = Duration::from_secs(15);

/// A program that has not answered by then is not Git (WSL's first start takes some seconds).
const LONGEST: Duration = Duration::from_secs(30);

static CHOSEN: Mutex<String> = Mutex::new(String::new());

/// Sets the program Git commands run: a path or a name, or empty for `git` from the PATH.
pub fn set(program: &str) {
    *CHOSEN.lock().unwrap_or_else(|e| e.into_inner()) = program.trim().trim_matches('"').to_string();
}

fn chosen() -> String {
    CHOSEN.lock().unwrap_or_else(|e| e.into_inner()).clone()
}

/// Whether the user chose a program in the settings.
pub(crate) fn is_chosen() -> bool {
    !chosen().is_empty()
}

/// A command that runs Git, with nothing but the program set. Run it after [`check`].
pub(crate) fn command() -> Command {
    let program = chosen();
    if program.is_empty() {
        return Command::new(AUTOMATIC);
    }
    let mut c = Command::new(program);
    // (the variables `git::git_base` and `git::git_read` set reach a Git inside WSL only when they are named here; without them it may wait for a
    // password in a console nobody sees)
    c.env("WSLENV", shared_with_wsl(std::env::var("WSLENV").ok().as_deref()));
    c
}

/// `WSLENV` with the variables of our Git commands added to what it already names.
fn shared_with_wsl(current: Option<&str>) -> String {
    let mut names: Vec<&str> = current.unwrap_or_default().split(':').filter(|n| !n.is_empty()).collect();
    for ours in ["GIT_TERMINAL_PROMPT", "GIT_OPTIONAL_LOCKS", "GIT_NO_LAZY_FETCH", "GIT_ALLOW_PROTOCOL"] {
        if !names.iter().any(|n| n.split('/').next() == Some(ours)) {
            names.push(ours);
        }
    }
    names.join(":")
}

// ---------------------------------------------------------------- the version

/// What a program turned out to be.
#[derive(Clone)]
struct Seen {
    /// The version it answered with; `None`: it is not there, or it is not Git.
    version: Option<String>,
    /// It was started and did not answer. Not tried again by itself: what does not end may be a program with a window.
    hung: bool,
    /// Git for Windows' own program, which takes its arguments as they are.
    native: bool,
    /// The file as it was then.
    stamp: Option<(SystemTime, u64)>,
    at: Instant,
}

fn seen() -> MutexGuard<'static, HashMap<String, Seen>> {
    static SEEN: std::sync::LazyLock<Mutex<HashMap<String, Seen>>> = std::sync::LazyLock::new(Default::default);
    SEEN.lock().unwrap_or_else(|e| e.into_inner())
}

/// The program a setting's text names.
fn named(setting: &str) -> &str {
    let program = setting.trim().trim_matches('"');
    if program.is_empty() { AUTOMATIC } else { program }
}

fn stamp(program: &str) -> Option<(SystemTime, u64)> {
    let path = Path::new(program);
    let m = path.is_absolute().then(|| std::fs::metadata(path).ok())??;
    Some((m.modified().ok()?, m.len()))
}

/// The version out of what `git --version` prints ("git version 2.51.0.windows.1"; a shell's greeting may stand before it).
fn version_in(text: &str) -> Option<String> {
    text.lines().find_map(|l| l.trim().strip_prefix("git version ")?.split_whitespace().next().map(str::to_string))
}

/// Git for Windows' own program, by its version resource. (Not by the version it answers with: wslgit can pass that question on to
/// a Windows Git and still give other commands to a shell.)
fn is_native(program: &str) -> bool {
    let path = Path::new(program);
    path.is_absolute() && crate::pe::info(path).and_then(|i| i.company).is_some_and(|c| c == "The Git Development Community")
}

/// Runs `program --version`: the version, and whether it had to be stopped.
fn ask(program: &str) -> (Option<String>, bool) {
    let spawned = Command::new(program)
        .arg("--version")
        .current_dir(std::env::temp_dir())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .creation_flags(CREATE_NO_WINDOW)
        .spawn();
    let mut child = match spawned {
        Ok(child) => child,
        Err(e) => {
            log::info!("git: {program}: {e}");
            return (None, false);
        }
    };
    let out = child.stdout.take().expect("stdout piped");
    let (tx, rx) = std::sync::mpsc::channel();
    // (a thread of its own, left behind when the program does not end: something it started may keep the pipe open)
    std::thread::spawn(move || {
        let mut text = Vec::new();
        let _ = out.take(16 * 1024).read_to_end(&mut text);
        let _ = tx.send(text);
    });
    let text = rx.recv_timeout(LONGEST);
    let _ = child.kill();
    let _ = child.wait();
    match text {
        Ok(text) => (version_in(&String::from_utf8_lossy(&text)), false),
        Err(_) => (None, true),
    }
}

fn look(program: &str) -> Seen {
    let stamp = stamp(program);
    let (version, hung) = ask(program);
    let now = Seen { version, hung, native: is_native(program), stamp, at: Instant::now() };
    seen().insert(program.to_string(), now.clone());
    now
}

/// What `program` is, looked at now unless it is known. Blocking.
fn known(program: &str) -> Seen {
    let before = seen().get(program).cloned();
    match before {
        Some(s) if s.stamp == stamp(program) && (s.version.is_some() || s.hung || s.at.elapsed() < FRESH) => s,
        _ => look(program),
    }
}

/// The version of the program `setting` names, as last seen (`None`: not looked at yet; `Some(None)`: no Git there), and whether
/// that is recent enough to leave it.
pub fn peek(setting: &str) -> (Option<Option<String>>, bool) {
    match seen().get(named(setting)) {
        Some(s) => (Some(s.version.clone()), s.hung || s.at.elapsed() < FRESH),
        None => (None, false),
    }
}

/// Looks at the program `setting` names; says whether its version is another than before. Blocking.
pub fn refresh(setting: &str) -> bool {
    let program = named(setting);
    let before = seen().get(program).map(|s| s.version.clone());
    before != Some(look(program).version)
}

/// Forgets what was seen of the program `setting` names (it was chosen again: one that did not answer gets another try).
pub fn forget(setting: &str) {
    seen().remove(named(setting));
}

// ---------------------------------------------------------------- what it may be given

/// Whether the chosen program is something other than Git for Windows, so that a shell may stand between us and Git. Blocking.
pub(crate) fn may_use_shell() -> bool {
    let program = chosen();
    !program.is_empty() && program != AUTOMATIC && !known(&program).native
}

/// To be asked before a [`command`] runs: an error when its program is not Git, or when an argument is not safe to give to it.
/// Always fine for `git` from the PATH. Blocking.
pub(crate) fn check(c: &Command) -> io::Result<()> {
    let program = c.get_program().to_string_lossy();
    if program == AUTOMATIC {
        return Ok(());
    }
    let known = known(&program);
    if known.version.is_none() {
        return Err(io::ErrorKind::NotFound.into());
    }
    if known.native {
        return Ok(());
    }
    match refused(c.get_args()) {
        None => Ok(()),
        Some(arg) => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bu metin seçilen Git programına güvenle verilemez: {arg}"))),
    }
}

/// The first argument a program that may use a shell is not given.
pub(crate) fn refused<'a>(args: impl Iterator<Item = &'a OsStr>) -> Option<String> {
    // wslgit puts what these commands print through a shell too, and takes the word for one wherever it stands among the arguments
    // (a folder or a branch named "remote")
    const PRINT_THROUGH_SHELL: [&str; 3] = ["rev-parse", "remote", "init"];
    let (mut command_seen, mut config_next) = (false, false);
    for arg in args {
        let Some(arg) = arg.to_str() else { return Some(arg.to_string_lossy().into_owned()) };
        let fine = if config_next {
            config_next = false;
            is_plain_config(arg)
        } else if command_seen {
            is_plain(arg) && !PRINT_THROUGH_SHELL.contains(&arg)
        } else {
            config_next = arg == "-c";
            command_seen = !arg.starts_with('-');
            is_plain(arg)
        };
        if !fine {
            return Some(arg.to_string());
        }
    }
    None
}

/// A text no shell does anything with, inside double quotes or (its spaces aside) outside them. `%` only in our own `--format=` texts;
/// brackets only there or in a text that is quoted (it has a space: "Program Files (x86)"); `~` and `#` not at its start, where a shell
/// takes them for a home folder and a comment, unless it is quoted. A batch file expands `%NAME%` even inside quotes (a private security
/// report: a folder or branch name out of a repository is an argument too).
fn is_plain(arg: &str) -> bool {
    let ours = arg.starts_with("--format=");
    let quoted = arg.contains(' ');
    !arg.ends_with('\\')
        && arg.char_indices().all(|(i, c)| {
            c.is_alphanumeric()
                || r" -_./\:=,+@".contains(c)
                || (ours && "%()".contains(c))
                || (quoted && "()~#".contains(c))
                || (i > 0 && "~#".contains(c))
        })
}

/// `key=value` after `-c`. Narrower than [`is_plain`]: these switch off the programs a repository's filters name, so nothing may
/// change the key on its way (wslgit rewrites what looks like a Windows path).
fn is_plain_config(arg: &str) -> bool {
    arg.chars().filter(|c| *c == '=').count() == 1 && arg.chars().all(|c| c.is_ascii_alphanumeric() || "._-=".contains(c))
}

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

    fn refuses(args: &[&str]) -> Option<String> {
        refused(args.iter().map(OsStr::new))
    }

    #[test]
    fn the_version_out_of_what_git_prints() {
        assert_eq!(version_in("git version 2.51.0.windows.1\r\n").as_deref(), Some("2.51.0.windows.1"));
        assert_eq!(version_in("git version 2.43.0\n").as_deref(), Some("2.43.0"));
        assert_eq!(version_in("git version 2.39.5 (Apple Git-154)\n").as_deref(), Some("2.39.5"));
        assert_eq!(version_in("Welcome to Ubuntu\ngit version 2.43.0\n").as_deref(), Some("2.43.0"), "a shell's greeting before it");
        for other in ["", "git version \n", "bash: git: command not found\n", "Python 3.13.1\n", "my git version 2\n"] {
            assert_eq!(version_in(other), None, "{other:?}");
        }
    }

    #[test]
    fn our_variables_are_shared_with_wsl_once() {
        const OURS: &str = "GIT_TERMINAL_PROMPT:GIT_OPTIONAL_LOCKS:GIT_NO_LAZY_FETCH:GIT_ALLOW_PROTOCOL";
        assert_eq!(shared_with_wsl(None), OURS);
        assert_eq!(shared_with_wsl(Some("")), OURS);
        assert_eq!(shared_with_wsl(Some("A/p:B")), format!("A/p:B:{OURS}"));
        assert_eq!(shared_with_wsl(Some("GIT_OPTIONAL_LOCKS/u:A")), "GIT_OPTIONAL_LOCKS/u:A:GIT_TERMINAL_PROMPT:GIT_NO_LAZY_FETCH:GIT_ALLOW_PROTOCOL");
    }

    /// The commands `git` runs, as it runs them.
    #[test]
    fn our_own_commands_are_fine() {
        const C: [&str; 4] = ["-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false"];
        let commands: &[&[&str]] = &[
            &["-c", "filter.lfs.clean=", "-c", "filter.lfs.required=false", "--no-optional-locks", "status", "--porcelain=v2", "--branch", "-z"],
            &["--no-optional-locks", "for-each-ref", "--format=%(HEAD)%00%(refname)%00%(upstream:short)%00%(upstream:track,nobracket)", "refs/heads"],
            &["-c", "core.quotepath=false", "log", "--no-renames", "--format=%x01%h%x1f%s%x1f%an%x1f%ct", "--", "src/Program Files (x86)/C#"],
            &["log", "-1", "--format=%h%x00%s%x00%an%x00%ct", "--", r"C:\repo\a b.txt"],
            &["stash", "push", "--include-untracked", "-m", "rustyfiles checkout"],
            &["remote", "add", "origin", "https://example.com/~me/repo.git"],
            &["clone", "--progress", "--", "[email protected]:me/repo.git", "repo"],
            &["switch", "--track", "origin/özellik-1"],
            &["config", "-z", "--name-only", "--list"],
            &["init", "-q"],
        ];
        for args in commands {
            let all: Vec<&str> = C.iter().chain(args.iter()).copied().collect();
            assert_eq!(refuses(&all), None, "{args:?}");
        }
    }

    #[test]
    fn what_a_shell_would_act_on_is_refused() {
        for name in ["a;calc", "a&calc", "a|calc", "`calc`", "$(calc)", "$HOME", "it's", "a\"b", "a>b", "a<b", "a\nb", "a!b", "a*", "a?", "{a,b}", "[ab]", "a^b", "a\\", "a"b"] {
            assert_eq!(refuses(&["log", "--", name]).as_deref(), Some(name));
        }
    }

    #[test]
    fn a_filters_name_must_reach_git_as_it_is() {
        for arg in ["filter.x;calc.clean=", "filter.x=c:/y.clean=", "filter.c:/y.clean=", "filter.[a].clean=", "filter.a b.clean=", r"filter.a\b.clean="] {
            assert_eq!(refuses(&["-c", arg, "status"]).as_deref(), Some(arg));
        }
    }

    #[test]
    fn a_name_wslgit_takes_for_a_command_is_refused() {
        for word in ["remote", "init", "rev-parse"] {
            assert_eq!(refuses(&["log", "--", word]).as_deref(), Some(word));
            assert_eq!(refuses(&["-c", word, "log"]).as_deref(), Some(word));
            assert_eq!(refuses(&["log", "--", &format!("src/{word}")]), None, "only the whole argument is one");
        }
    }

    #[test]
    fn a_program_that_is_not_there_has_no_version() {
        let program = std::env::temp_dir().join(format!("rf-no-git-{}.exe", std::process::id())).display().to_string();
        assert_eq!(peek(&program), (None, false));
        assert!(refresh(&program), "from not looked at to not there");
        assert_eq!(peek(&program), (Some(None), true));
        assert!(!refresh(&program));
        assert_eq!(check(&Command::new(&program)).unwrap_err().kind(), io::ErrorKind::NotFound);
        forget(&program);
        assert_eq!(peek(&program), (None, false));
    }

    #[test]
    fn git_from_the_path_is_given_everything() {
        let mut c = Command::new(AUTOMATIC);
        c.args(["log", "--", "a;b", "remote"]);
        assert!(check(&c).is_ok());
    }
}