Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Find Windows Git Bash through Git's installed runtime (#4452)
Maximilian Roosb280a6ac3bc4
diff --git a/plugins/worktrunk/hooks/wt.cmd b/plugins/worktrunk/hooks/wt.cmdindex eb2e9e3d1..fd1eeaaeb 100644--- a/plugins/worktrunk/hooks/wt.cmd+++ b/plugins/worktrunk/hooks/wt.cmd@@ -22,39 +22,31 @@ rem hands each hook the session env snapshot, so an inherited BASH would namerem what every event runs.set "BASH="-rem git.exe installs at Git\cmd\git.exe, Git\bin\git.exe, or-rem Git\mingw64\bin\git.exe, and bash.exe at Git\bin\bash.exe or-rem Git\usr\bin\bash.exe. The lookup uses `where`'s `$var:` prefix, which-rem searches the directories named in that variable and nowhere else: a bare-rem `where git.exe` searches the current directory first, as cmd's-rem own bare-name lookup does, and a hook's current directory is the user's-rem project -- so a `git.exe` committed to a repo would otherwise choose the-rem bash every event runs. `where` itself is spelled absolutely for the same-rem reason: cmd resolves that name from the current directory too.-for /f "delims=" %%I in ('"%SystemRoot%\System32\where.exe" "$PATH:git.exe" 2^>nul') do if not defined BASH call :derive "%%~dpI"--rem A git.exe PATH doesn't name, or names through a shim outside its install:-rem the system-wide default, then the per-user one an install without admin-rem rights writes (#1259).-if not defined BASH call :accept "%ProgramFiles%\Git\bin\bash.exe"-if not defined BASH call :accept "%LOCALAPPDATA%\Programs\Git\bin\bash.exe"+rem Ask Git for its runtime path so PATH shims resolve to the installation+rem they launch. Ignore GIT_EXEC_PATH in the query: it overrides the installed+rem helper path. The hook itself keeps the caller's environment.+rem cmd's PATH modifier finds the first git.exe on PATH without consulting+rem the project directory or spawning another command interpreter for lookup.+for %%I in (git.exe) do if not "%%~$PATH:I"=="" call :derive "%%~$PATH:I"if not defined BASH goto :missing"%BASH%" "%~dp0wt.sh" %*exit /b 0-rem %1 is a Git install's cmd\, bin\, or mingw64\bin\ directory, with the-rem trailing separator `%~dpI` leaves on; the last sits a level deeper, so the-rem install root is tried one level further up when the first two miss.-rem Git\bin\bash.exe first, as find_git_bash does: it is the wrapper that-rem sets up the MSYS environment for a caller outside Git Bash, which is what-rem puts `uname` and friends within reach of wt.sh.+rem Git for Windows reports <install>/<runtime>/libexec/git-core. The bin+rem wrapper sets up MSYS for wt.sh; usr/bin is the runtime Bash itself.:derive-call :accept "%~1..\bin\bash.exe"-if not defined BASH call :accept "%~1..\usr\bin\bash.exe"-if not defined BASH call :accept "%~1..\..\bin\bash.exe"-if not defined BASH call :accept "%~1..\..\usr\bin\bash.exe"+for /f "delims=" %%I in ('set "GIT_EXEC_PATH=" ^& "%~1" --exec-path 2^>nul') do call :runtime "%%I"+goto :eof++:runtime+rem Normalize Git's forward slashes before matching its runtime suffix.+set "GIT_RUNTIME=%~1"+set "GIT_RUNTIME=%GIT_RUNTIME:/=\%"+if /i not "%GIT_RUNTIME:~-17%"=="\libexec\git-core" goto :eof+call :accept "%GIT_RUNTIME%\..\..\..\bin\bash.exe"+if not defined BASH call :accept "%GIT_RUNTIME%\..\..\..\usr\bin\bash.exe"goto :eof:acceptdiff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 195d4b70e..11d914988 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -526,49 +526,32 @@ fn detect_windows_shell() -> Result<ShellConfig, String> {/// (WSL launcher) often comes before Git Bash in PATH.#[cfg(windows)]fn find_git_bash() -> Option<PathBuf> {- // Primary: find git in PATH and derive bash location- if let Ok(git_path) = which::which("git")- && let Some(bash_path) = git_bash_beside_git(&git_path)- {- return Some(bash_path);- }-- // Fallback: standard Git for Windows paths (needed on some CI environments- // where `which` doesn't find git even though it's installed)- let bash_path = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");- if bash_path.exists() {- return Some(bash_path);- }-- // Per-user Git for Windows installation (default path when installed without admin rights)- if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {- let bash_path = PathBuf::from(local_app_data)- .join("Programs")- .join("Git")- .join("bin")- .join("bash.exe");- if bash_path.exists() {- return Some(bash_path);- }+ // Ask Git itself so PATH shims resolve to the installation they launch.+ let git_path = which::which("git").ok()?;+ let output = Cmd::new(git_path.to_string_lossy())+ .arg("--exec-path")+ .env_remove("GIT_EXEC_PATH") // User overrides name helpers, not the install.+ .run()+ .ok()?;+ if !output.status.success() {+ return None;}-- None+ let exec_path = std::str::from_utf8(&output.stdout).ok()?;+ git_bash_from_exec_path(Path::new(exec_path.trim_end()))}-/// Derive Git Bash's location from a Git for Windows `git.exe` path.-///-/// `git.exe` sits one level below the install root (`Git/cmd`, `Git/bin`) or-/// below `usr` (`Git/usr/bin`), or two levels below the root in-/// `Git/mingw64/bin` — the copy MSYS puts first on PATH inside a Git Bash-/// session. bash.exe is at `Git/bin/bash.exe` or `Git/usr/bin/bash.exe`.+/// Git for Windows reports `<install>/<runtime>/libexec/git-core` for --exec-path.+/// The runtime name varies by architecture; Bash belongs to the install root.#[cfg(any(windows, test))]-fn git_bash_beside_git(git_path: &Path) -> Option<PathBuf> {- git_path.ancestors().skip(2).take(2).find_map(|root| {- [root.join("bin"), root.join("usr").join("bin")]- .into_iter()- .map(|dir| dir.join("bash.exe"))- .find(|bash_path| bash_path.exists())- })+fn git_bash_from_exec_path(exec_path: &Path) -> Option<PathBuf> {+ if !exec_path.ends_with(Path::new("libexec").join("git-core")) {+ return None;+ }+ let root = exec_path.parent()?.parent()?.parent()?;+ [root.join("bin"), root.join("usr").join("bin")]+ .into_iter()+ .map(|dir| dir.join("bash.exe"))+ .find(|bash_path| bash_path.is_file())}/// Environment variable naming the directive file for `cd` path changes.@@ -3055,34 +3038,29 @@ print(*counts)}#[test]- fn test_git_bash_beside_git_install_layouts() {+ fn test_git_bash_from_exec_path() {let dir = tempfile::tempdir().unwrap();let root = dir.path().join("Git");- for sub in ["bin", "usr/bin", "cmd", "mingw64/bin"] {- std::fs::create_dir_all(root.join(sub)).unwrap();- }- let bin_bash = root.join("bin").join("bash.exe");+ let bin_bash = root.join("bin/bash.exe");+ let usr_bash = root.join("usr/bin/bash.exe");+ std::fs::create_dir_all(bin_bash.parent().unwrap()).unwrap();+ std::fs::create_dir_all(usr_bash.parent().unwrap()).unwrap();std::fs::write(&bin_bash, "").unwrap();- std::fs::write(root.join("usr").join("bin").join("bash.exe"), "").unwrap();+ std::fs::write(&usr_bash, "").unwrap();- for git in ["cmd/git.exe", "bin/git.exe", "mingw64/bin/git.exe"] {- assert_eq!(- git_bash_beside_git(&root.join(git)),- Some(bin_bash.clone()),- "{git}"- );- }- assert_eq!(- git_bash_beside_git(&root.join("usr/bin/git.exe")),- Some(root.join("usr").join("bin").join("bash.exe"))- );-- // A minimal install with only usr/bin/bash.exe, reached from mingw64/bin+ // ARM uses a different runtime prefix; discovery must not enumerate them.+ let exec_path = root.join("clangarm64/libexec/git-core");+ assert_eq!(git_bash_from_exec_path(&exec_path), Some(bin_bash.clone()));+ assert_eq!(git_bash_from_exec_path(&root.join("x/y/z")), None);std::fs::remove_file(&bin_bash).unwrap();- assert_eq!(- git_bash_beside_git(&root.join("mingw64/bin/git.exe")),- Some(root.join("usr").join("bin").join("bash.exe"))- );+ assert_eq!(git_bash_from_exec_path(&exec_path), Some(usr_bash.clone()));++ // MinGit can report the same layout without shipping Bash. Never climb+ // outside that installation to select an unrelated executable.+ std::fs::remove_file(&usr_bash).unwrap();+ std::fs::create_dir(dir.path().join("bin")).unwrap();+ std::fs::write(dir.path().join("bin/bash.exe"), "outside install").unwrap();+ assert_eq!(git_bash_from_exec_path(&exec_path), None);}#[test]diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 943b6ea79..d21808d25 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -6203,21 +6203,11 @@ fn test_wt_sh_ignores_an_inherited_wt(repo: TestRepo) {);}-/// `where git.exe` searches the current directory before it searches PATH, and-/// cmd resolves a bare `git.exe` the same way — so with the lookup unscoped, a-/// `git.exe` committed to a repo decides which `bash.exe` every prompt,-/// permission request, stop, and session end runs, since the hook runs with the-/// user's project as its current directory. `wt.sh` carries no such surface:-/// `command -v` consults PATH only.-///-/// Neither decoy planted here is a valid executable, which is what makes the-/// shim's choice observable: the version line can only be printed by the real-/// bash the pinned PATH leads to. Taking the decoy `git.exe` would derive the-/// `bash.exe` beside it — planted so that the wrong branch *resolves* rather-/// than falling through to the standard install locations and passing anyway.+/// Never execute a project's git.exe when finding the PATH installation.#[cfg(windows)]#[rstest]fn test_shim_ignores_a_git_in_the_current_directory(repo: TestRepo) {+ use crate::common::mock_commands::{MockConfig, mock_calls};use std::os::windows::process::CommandExt;let shim =@@ -6229,17 +6219,12 @@ fn test_shim_ignores_a_git_in_the_current_directory(repo: TestRepo) {fs::create_dir_all(&path_dir).unwrap();fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();- // ...and the decoys: a `git.exe` in the directory the hook runs from, plus- // the `bash.exe` the shim would derive from it (`<cwd>\..\bin\bash.exe`).let project = repo.root_path().join("project");fs::create_dir_all(&project).unwrap();- fs::write(project.join("git.exe"), b"not an executable").unwrap();- fs::create_dir_all(repo.root_path().join("bin")).unwrap();- fs::write(- repo.root_path().join("bin").join("bash.exe"),- b"not an executable",- )- .unwrap();+ MockConfig::new("git")+ .command("--exec-path", MockResponse::output("not-an-install"))+ .write(&project);+ let call_log = TempDir::new().unwrap();let mut cmd = std::process::Command::new("cmd.exe");repo.configure_wt_cmd(&mut cmd);@@ -6247,6 +6232,8 @@ fn test_shim_ignores_a_git_in_the_current_directory(repo: TestRepo) {.arg("/C").raw_arg(format!("\"\"{}\" --version\"", shim.display())).env("PATH", pinned_windows_path(&[path_dir]))+ .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", &project)+ .env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path()).env_remove("WORKTRUNK_BIN").current_dir(&project).output()@@ -6263,113 +6250,11 @@ fn test_shim_ignores_a_git_in_the_current_directory(repo: TestRepo) {output.status,String::from_utf8_lossy(&output.stderr));+ assert!(mock_calls(call_log.path(), "git").is_empty());}-/// The scoping above is only as good as the command doing it. `where` is not a-/// cmd built-in — it is `System32\where.exe` — so cmd resolves that name the-/// way it resolves any other: current directory first, then PATH. A `where`-/// committed to a repo therefore picks the `git.exe` that picks the `bash.exe`-/// every prompt, permission request, stop, and session end runs, which is the-/// surface `$PATH:` closes one level down.-///-/// The decoy is a `.bat` rather than an inert `where.exe`, and it names a Git-/// install whose `bin\bash.exe` exists, because both are what make the wrong-/// answer *observable*: a decoy that cannot run leaves the lookup empty, and a-/// decoy install without a `bash.exe` falls through — either way the shim-/// reaches `%ProgramFiles%\Git\bin\bash.exe`, which resolves on any Windows-/// box, and the test would pass on the unscoped shim for the wrong reason.-/// Reaching `:derive` with a decoy instead leaves `BASH` set and unrunnable.-///-/// The probe below pins the premise separately, so this cannot go green-/// because the planted `where` was never the one cmd would have chosen.-#[cfg(windows)]-#[rstest]-fn test_shim_ignores_a_where_in_the_current_directory(repo: TestRepo) {- use std::os::windows::process::CommandExt;-- let shim =- std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("plugins/worktrunk/hooks/wt.cmd");-- // The only worktrunk the shim is allowed to find: a real one, in a- // directory on the PATH this test pins.- let path_dir = repo.root_path().join("path-dir");- fs::create_dir_all(&path_dir).unwrap();- fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();-- // The decoy Git install the planted `where` names. `:derive` takes- // `<install>\cmd\` and accepts `<install>\bin\bash.exe`, so that file has- // to exist for the wrong branch to win rather than fall through.- let decoy = repo.root_path().join("decoy-git");- fs::create_dir_all(decoy.join("bin")).unwrap();- fs::write(decoy.join("bin").join("bash.exe"), b"not an executable").unwrap();-- // ...and the lookup that names it, in the directory the hook runs from.- // `.bat` is enough to shadow `System32\where.exe`: cmd tries every PATHEXT- // extension in one directory before it moves to the next.- let project = repo.root_path().join("project");- fs::create_dir_all(&project).unwrap();- let decoy_git = decoy.join("cmd").join("git.exe");- fs::write(- project.join("where.bat"),- format!("@echo {}\r\n", decoy_git.display()),- )- .unwrap();-- // The premise, checked directly: without it the decoy is never consulted- // and every assertion below would hold on the unscoped shim too.- let mut probe = std::process::Command::new("cmd.exe");- repo.configure_wt_cmd(&mut probe);- let probe_output = probe- .arg("/C")- .raw_arg("\"where $PATH:git.exe\"")- .env("PATH", pinned_windows_path(&[]))- .current_dir(&project)- .output()- .unwrap();- let probed = String::from_utf8_lossy(&probe_output.stdout);- assert!(- probed.contains("decoy-git"),- "a `where.bat` in the current directory must shadow System32's `where.exe`, \- or this test pins nothing; got {probed:?}"- );-- let mut cmd = std::process::Command::new("cmd.exe");- repo.configure_wt_cmd(&mut cmd);- let output = cmd- .arg("/C")- .raw_arg(format!("\"\"{}\" --version\"", shim.display()))- .env("PATH", pinned_windows_path(&[path_dir]))- .env_remove("WORKTRUNK_BIN")- .current_dir(&project)- .output()- .unwrap();-- let stdout = String::from_utf8_lossy(&output.stdout);- assert!(- output.status.success() && stdout.trim_start().starts_with("wt "),- "the shim must run System32's `where.exe`, not one from the current \- directory; got {}\nstdout:\n{stdout}\nstderr:\n{}",- output.status,- String::from_utf8_lossy(&output.stderr)- );-}--/// The two scoping tests above see only the *wrong* bash: they go red because-/// the shim picks a decoy. Neither sees a lookup that finds nothing at all — a-/// mis-quoted `for /f`, a `where` spelling cmd cannot run — because the shim-/// then falls through to `%ProgramFiles%\Git\bin\bash.exe`, which resolves on-/// any Windows box, and every assertion still holds. So the derive branch is-/// the one route to a bash that nothing observes.-///-/// This takes the fallbacks away: `ProgramFiles` and `LOCALAPPDATA` point at an-/// empty directory, leaving `:derive` as the only way to a bash, so the-/// `%SystemRoot%\System32\where.exe` line has to return the Git install — under-/// the quoting `for /f` wraps it in — for the shim to reach `wt.sh` at all.-///-/// Both variables reach a real hook: Codex's strictest `inherit = "core"`-/// policy keeps `SYSTEMROOT`, `PROGRAMFILES` and `LOCALAPPDATA`-/// (`WINDOWS_CORE_ENV_VARS` in `codex-rs/protocol/src/shell_environment.rs`),-/// and `scrub_non_inheritable_env_vars` drops only auth-token names.+/// The hook must use Git's installed runtime, even if GIT_EXEC_PATH names a+/// different helper directory. Run through cmd's real for/f quoting.#[cfg(windows)]#[rstest]fn test_shim_derives_bash_from_the_git_on_path(repo: TestRepo) {@@ -6384,9 +6269,8 @@ fn test_shim_derives_bash_from_the_git_on_path(repo: TestRepo) {fs::create_dir_all(&path_dir).unwrap();fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();- // Where the two standard-install fallbacks now point: no Git under either.- let no_git = repo.root_path().join("no-git");- fs::create_dir_all(&no_git).unwrap();+ let helper_override = repo.root_path().join("other-helpers");+ fs::create_dir_all(&helper_override).unwrap();let mut cmd = std::process::Command::new("cmd.exe");repo.configure_wt_cmd(&mut cmd);@@ -6394,8 +6278,7 @@ fn test_shim_derives_bash_from_the_git_on_path(repo: TestRepo) {.arg("/C").raw_arg(format!("\"\"{}\" --version\"", shim.display())).env("PATH", pinned_windows_path(&[path_dir]))- .env("ProgramFiles", &no_git)- .env("LOCALAPPDATA", &no_git)+ .env("GIT_EXEC_PATH", &helper_override).env_remove("WORKTRUNK_BIN").current_dir(repo.root_path()).output()@@ -6404,8 +6287,8 @@ fn test_shim_derives_bash_from_the_git_on_path(repo: TestRepo) {let stdout = String::from_utf8_lossy(&output.stdout);assert!(output.status.success() && stdout.trim_start().starts_with("wt "),- "the shim must derive Git Bash from the git.exe PATH names, with no install \- default left to fall back on; got {}\nstdout:\n{stdout}\nstderr:\n{}",+ "the shim must query the installed Git runtime, ignoring GIT_EXEC_PATH; \+ got {}\nstdout:\n{stdout}\nstderr:\n{}",output.status,String::from_utf8_lossy(&output.stderr));