Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Require Git 2.43 and test it nightly (#3895)

Maximilian Roosdf2bc6e7f11c
diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml
index e9d7ec7ce..348bf99ad 100644
--- a/.github/workflows/nightly.yaml
+++ b/.github/workflows/nightly.yaml
@@ -2,8 +2,8 @@ name: nightly
# Slower checks that aren't worth running on every PR but should run before a
# release. Jobs:
# - feature-powerset: feature-flag unification, check + test suite (motivated by #2442)
-# - full-tests: full nextest suite on the linux/macos/windows matrix — the
-# cargo-affected safety net (see the job comment and ci.yaml's affected block)
+# - full-tests: full nextest suite on the standard OS matrix and Git 2.43.0 —
+# the cargo-affected safety net (see the job comment and ci.yaml's affected block)
# - release-target: PTY+shell suite on the release triples ci.yaml doesn't cover
# - check-unused-dependencies: cargo-udeps on nightly toolchain
# - minimal-versions: cargo check against minimum-version dep resolution
@@ -157,8 +157,9 @@ jobs:
# means affected missed something, and that must not redden main — nightly
# failures are non-blocking and Tend-fixable. Complements feature-powerset
# (Linux, feature combos) and release-target (cross triples) by covering
- # the standard 3-OS matrix that neither runs. At the affected-only flip,
- # ci.yaml's `test` job is deleted and this becomes the sole full run.
+ # the standard 3-OS matrix that neither runs. A fourth row runs the same
+ # job with the minimum supported Git. At the affected-only flip, ci.yaml's
+ # `test` job is deleted and this becomes the sole full run.
needs: gate
if: needs.gate.outputs.run == 'true'
strategy:
@@ -167,6 +168,9 @@ jobs:
include:
- os: ubuntu-24.04
name: linux
+ - os: ubuntu-24.04
+ name: git-2.43.0
+ git: '2.43.0'
- os: macos-15
name: macos
- os: windows-2022
@@ -178,6 +182,24 @@ jobs:
- uses: ./.github/actions/test-setup
+ - name: Install Git 2.43.0
+ if: matrix.git == '2.43.0'
+ shell: bash
+ run: |
+ sudo apt-get update
+ git_package_version="$(apt-cache madison git | awk '$3 ~ /^1:2[.]43[.]0-/ { print $3; exit }')"
+ if [ -z "$git_package_version" ]; then
+ echo "::error::Ubuntu package sources do not provide Git 2.43.0"
+ exit 1
+ fi
+ sudo apt-get install -y --allow-downgrades \
+ "git=$git_package_version" "git-man=$git_package_version"
+ echo "/usr/bin" >> "$GITHUB_PATH"
+
+ - name: Verify minimum Git
+ if: matrix.git == '2.43.0'
+ run: test "$(git --version)" = "git version 2.43.0"
+
- name: Install wt
uses: baptiste0928/cargo-install@v3
with:
diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.md
index 9b2bc0e9e..33761ff3a 100644
--- a/docs/src/content/docs/faq.md
+++ b/docs/src/content/docs/faq.md
@@ -278,9 +278,9 @@ Confirm it with `wt config alias dry-run <name>`: if the value is already substi
To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% endraw %}`; for `wt step for-each`, also keep it inside a quoted `sh -c '…'` so the alias's shell doesn't word-split it. See [deferring expansion in an alias](/extending/#deferring-expansion-to-a-nested-wt-command). A repo-level variable like `{{ default_branch }}` is unaffected — it is identical in every worktree.
-## Installation fails with C compilation errors
+## What system dependencies are required?
-Worktrunk requires Git 2.34 or newer.
+Worktrunk requires Git 2.43 or newer.
Installing with Cargo and the default features also requires a C99 compiler for bash syntax highlighting. If tree-sitter or C compilation fails (C99 mode, `le16toh` undefined), install without syntax highlighting:
diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.md
index 53e883be2..f9e1361b8 100644
--- a/docs/src/content/docs/step.md
+++ b/docs/src/content/docs/step.md
@@ -1103,7 +1103,7 @@ expected path. Untracked and gitignored files remain at the original location.
### Dirty worktrees
Linked worktrees relocate as-is — `git worktree move` carries uncommitted
-changes along. Only the main worktree skips when dirty (its `git checkout`
+changes along. Only the main worktree skips when dirty (its `git switch`
refuses), unless `--commit` is passed.
### Skipped worktrees
diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.md
index f06ea859c..130a28514 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md
@@ -274,9 +274,9 @@ Confirm it with `wt config alias dry-run <name>`: if the value is already substi
To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% endraw %}`; for `wt step for-each`, also keep it inside a quoted `sh -c '…'` so the alias's shell doesn't word-split it. See [deferring expansion in an alias](https://worktrunk.dev/extending/#deferring-expansion-to-a-nested-wt-command). A repo-level variable like `{{ default_branch }}` is unaffected — it is identical in every worktree.
-## Installation fails with C compilation errors
+## What system dependencies are required?
-Worktrunk requires Git 2.34 or newer.
+Worktrunk requires Git 2.43 or newer.
Installing with Cargo and the default features also requires a C99 compiler for bash syntax highlighting. If tree-sitter or C compilation fails (C99 mode, `le16toh` undefined), install without syntax highlighting:
diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.md
index e69bfe85f..05cba928b 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/step.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md
@@ -1091,7 +1091,7 @@ expected path. Untracked and gitignored files remain at the original location.
### Dirty worktrees
Linked worktrees relocate as-is — `git worktree move` carries uncommitted
-changes along. Only the main worktree skips when dirty (its `git checkout`
+changes along. Only the main worktree skips when dirty (its `git switch`
refuses), unless `--commit` is passed.
### Skipped worktrees
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index f06ea859c..130a28514 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -274,9 +274,9 @@ Confirm it with `wt config alias dry-run <name>`: if the value is already substi
To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% endraw %}`; for `wt step for-each`, also keep it inside a quoted `sh -c '…'` so the alias's shell doesn't word-split it. See [deferring expansion in an alias](https://worktrunk.dev/extending/#deferring-expansion-to-a-nested-wt-command). A repo-level variable like `{{ default_branch }}` is unaffected — it is identical in every worktree.
-## Installation fails with C compilation errors
+## What system dependencies are required?
-Worktrunk requires Git 2.34 or newer.
+Worktrunk requires Git 2.43 or newer.
Installing with Cargo and the default features also requires a C99 compiler for bash syntax highlighting. If tree-sitter or C compilation fails (C99 mode, `le16toh` undefined), install without syntax highlighting:
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index e69bfe85f..05cba928b 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -1091,7 +1091,7 @@ expected path. Untracked and gitignored files remain at the original location.
### Dirty worktrees
Linked worktrees relocate as-is — `git worktree move` carries uncommitted
-changes along. Only the main worktree skips when dirty (its `git checkout`
+changes along. Only the main worktree skips when dirty (its `git switch`
refuses), unless `--commit` is passed.
### Skipped worktrees
diff --git a/src/cli/step.rs b/src/cli/step.rs
index d8d1aea6c..b24c245b6 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -706,7 +706,7 @@ expected path. Untracked and gitignored files remain at the original location.
## Dirty worktrees
Linked worktrees relocate as-is — `git worktree move` carries uncommitted
-changes along. Only the main worktree skips when dirty (its `git checkout`
+changes along. Only the main worktree skips when dirty (its `git switch`
refuses), unless `--commit` is passed.
## Skipped worktrees
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 558921074..7abf0a2b0 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -421,7 +421,7 @@ fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {
"{}",
info_message(cformat!("{cmd}: <bold>{version}</>"))
)?;
- if let Ok(git_version) = crate::diagnostic::git_version() {
+ if let Ok(git_version) = worktrunk::git::git_version() {
writeln!(
out,
"{}",
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 04b31d710..bda92500f 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -292,7 +292,7 @@ pub fn validate_candidates(
// along with the worktree, so for linked worktrees we don't need to
// require a clean state. The main worktree is different: it can't be
// moved with `git worktree move`, and the fallback path runs
- // `git checkout <default-branch>` which refuses to switch over
+ // `git switch <default-branch>` which refuses to switch over
// uncommitted changes — so we still skip dirty main worktrees unless
// `--commit` was passed.
let worktree = repo.worktree_at(&candidate.wt.path);
@@ -658,7 +658,7 @@ impl<'a> RelocationExecutor<'a> {
/// Main worktree can't use `git worktree move`; must create new + switch.
///
- /// If `worktree add` fails after the initial checkout, the main worktree
+ /// If `worktree add` fails after the initial switch, the main worktree
/// is left on `default_branch` rather than the original branch — the user
/// can recover with `git switch -`. Restoring it here would be best-effort
/// (no error surface) and the failure modes for `worktree add` (invalid
@@ -674,8 +674,8 @@ impl<'a> RelocationExecutor<'a> {
let main_wt = self.repo.worktree_at(self.repo.repo_path()?);
main_wt
- .run_command(&["checkout", "--end-of-options", default_branch])
- .with_context(|| format!("Failed to checkout default branch '{default_branch}'"))?;
+ .run_command(&["switch", "--end-of-options", default_branch])
+ .with_context(|| format!("Failed to switch to default branch '{default_branch}'"))?;
let dest = candidate.expected_path.to_string_lossy();
main_wt
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index 037fe6dc5..b815f2c96 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -59,11 +59,10 @@
use std::path::PathBuf;
use ansi_str::AnsiStr;
-use anyhow::Context;
use color_print::cformat;
use minijinja::{Environment, context};
use worktrunk::config::ConfigFileKind;
-use worktrunk::git::Repository;
+use worktrunk::git::{Repository, git_version};
use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{eprintln, hint_message, info_message, warning_message};
@@ -425,32 +424,6 @@ fn truncate_log(content: &str) -> String {
format!("(log truncated to last ~50KB)\n{}", &content[start..])
}
-/// Get the version reported by `git --version`.
-pub(crate) fn git_version() -> anyhow::Result<String> {
- let output = Cmd::new("git")
- .arg("--version")
- .run()
- .context("Failed to run git --version")?;
-
- anyhow::ensure!(output.status.success(), "git --version failed");
- parse_git_version(&output.stdout)
-}
-
-fn parse_git_version(stdout: &[u8]) -> anyhow::Result<String> {
- let stdout = std::str::from_utf8(stdout)
- .context("git --version returned invalid UTF-8")?
- .trim();
- let version = stdout
- .strip_prefix("git version ")
- .context("git --version returned an unexpected response")?;
- anyhow::ensure!(
- !version.is_empty() && !version.contains(['\r', '\n']),
- "git --version returned an unexpected response"
- );
-
- Ok(version.to_string())
-}
-
/// Render the curated environment variables ([`DIAGNOSTIC_ENV_VARS`]) plus git's
/// resolved `core.pager` as `KEY=value` lines for the diagnostic report.
///
@@ -633,27 +606,6 @@ mod tests {
assert!(render_trace_profile("not a trace line\nanother line\n").is_none());
}
- #[test]
- fn test_parse_git_version_requires_standard_single_line_output() {
- assert_eq!(
- parse_git_version(b"git version 2.47.1\n").unwrap(),
- "2.47.1"
- );
- assert_eq!(
- parse_git_version(b"git version 2.39.5 (Apple Git-154)\n").unwrap(),
- "2.39.5 (Apple Git-154)"
- );
-
- for malformed in [
- b"2.47.1".as_slice(),
- b"git version \n",
- b"git version 2.47.1\nextra",
- b"git version 2.\xff",
- ] {
- assert!(parse_git_version(malformed).is_err());
- }
- }
-
#[test]
fn test_truncate_log_small_content() {
let content = "small log content";
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 36df8cd9b..afb376fa8 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -15,6 +15,7 @@ pub mod remote_ref;
pub mod remove;
mod repository;
mod url;
+mod version;
#[cfg(test)]
mod test;
@@ -87,6 +88,8 @@ pub use repository::{
pub use url::parse_owner_repo;
pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};
pub(crate) use url::{canonical_url_path_segment, url_path_segments_eq};
+pub use version::{git_version, require_minimum_git};
+
/// Why branch content is considered integrated into the target branch.
///
/// Used by both `wt list` (for status symbols) and `wt remove` (for messages).
diff --git a/src/git/version.rs b/src/git/version.rs
new file mode 100644
index 000000000..f5e73ed4c
--- /dev/null
+++ b/src/git/version.rs
@@ -0,0 +1,154 @@
+//! Detection and validation of the Git executable used by Worktrunk.
+
+use anyhow::Context;
+use once_cell::sync::OnceCell;
+
+use crate::shell_exec::Cmd;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+struct GitVersion {
+ major: u32,
+ minor: u32,
+ patch: u32,
+}
+
+impl GitVersion {
+ const fn new(major: u32, minor: u32, patch: u32) -> Self {
+ Self {
+ major,
+ minor,
+ patch,
+ }
+ }
+}
+
+impl std::fmt::Display for GitVersion {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
+ }
+}
+
+const MINIMUM_GIT_VERSION: GitVersion = GitVersion::new(2, 43, 0);
+
+struct GitInfo {
+ version: GitVersion,
+ reported_version: String,
+}
+
+static GIT_INFO: OnceCell<GitInfo> = OnceCell::new();
+
+fn current_git() -> anyhow::Result<&'static GitInfo> {
+ GIT_INFO.get_or_try_init(|| {
+ let output = Cmd::new("git")
+ .arg("--version")
+ .run()
+ .context("Failed to run git --version")?;
+ anyhow::ensure!(output.status.success(), "git --version failed");
+ parse_git_version(&output.stdout)
+ })
+}
+
+/// Return the version string reported by the Git executable on `PATH`.
+pub fn git_version() -> anyhow::Result<String> {
+ Ok(current_git()?.reported_version.clone())
+}
+
+/// Reject Git versions older than Worktrunk's supported minimum.
+pub fn require_minimum_git() -> anyhow::Result<()> {
+ let current = current_git()?;
+ anyhow::ensure!(
+ current.version >= MINIMUM_GIT_VERSION,
+ "Git {} is unsupported; Worktrunk requires Git {} or newer",
+ current.version,
+ MINIMUM_GIT_VERSION
+ );
+ Ok(())
+}
+
+fn parse_git_version(stdout: &[u8]) -> anyhow::Result<GitInfo> {
+ let stdout = std::str::from_utf8(stdout)
+ .context("git --version returned invalid UTF-8")?
+ .trim();
+ let reported_version = stdout
+ .strip_prefix("git version ")
+ .context("git --version returned an unexpected response")?;
+ anyhow::ensure!(
+ !reported_version.is_empty() && !reported_version.contains(['\r', '\n']),
+ "git --version returned an unexpected response"
+ );
+
+ let numeric_version = reported_version
+ .split_whitespace()
+ .next()
+ .context("git --version returned an unexpected response")?;
+ let mut components = numeric_version.split('.');
+ let mut parse_component = |name: &str| -> anyhow::Result<u32> {
+ let component = components.next().unwrap_or_default();
+ let digits = component
+ .chars()
+ .take_while(char::is_ascii_digit)
+ .collect::<String>();
+ anyhow::ensure!(
+ !digits.is_empty(),
+ "could not parse Git {name} version from {reported_version:?}"
+ );
+ digits.parse().with_context(|| {
+ format!("could not parse Git {name} version from {reported_version:?}")
+ })
+ };
+
+ Ok(GitInfo {
+ version: GitVersion {
+ major: parse_component("major")?,
+ minor: parse_component("minor")?,
+ patch: parse_component("patch").unwrap_or(0),
+ },
+ reported_version: reported_version.to_string(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_supported_platform_version_formats() {
+ for (input, expected, reported) in [
+ ("git version 2.43.0\n", GitVersion::new(2, 43, 0), "2.43.0"),
+ ("git version 2.43\n", GitVersion::new(2, 43, 0), "2.43"),
+ (
+ "git version 2.45.GIT\n",
+ GitVersion::new(2, 45, 0),
+ "2.45.GIT",
+ ),
+ (
+ "git version 2.50.1 (Apple Git-155)\n",
+ GitVersion::new(2, 50, 1),
+ "2.50.1 (Apple Git-155)",
+ ),
+ (
+ "git version 2.47.1.windows.1\n",
+ GitVersion::new(2, 47, 1),
+ "2.47.1.windows.1",
+ ),
+ ] {
+ let parsed = parse_git_version(input.as_bytes()).unwrap();
+ assert_eq!(parsed.version, expected);
+ assert_eq!(parsed.reported_version, reported);
+ }
+ }
+
+ #[test]
+ fn rejects_malformed_version_output() {
+ for malformed in [
+ b"2.43.0".as_slice(),
+ b"git version \n",
+ b"git version 2.43.0\nextra",
+ b"git version 2.x.0\n",
+ b"git version 4294967296.43.0\n",
+ b"git version 2.43.0\xff\n",
+ ] {
+ assert!(parse_git_version(malformed).is_err());
+ }
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 848afb523..b30b02345 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,7 +4,8 @@ use color_print::cformat;
use std::process;
use worktrunk::config::{set_config_overrides, set_config_path};
use worktrunk::git::{
- ErrorExt, Repository, WorktrunkError, current_or_recover, cwd_removed_hint, set_base_path,
+ ErrorExt, Repository, WorktrunkError, current_or_recover, cwd_removed_hint,
+ require_minimum_git, set_base_path,
};
use worktrunk::styling::{
eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,
@@ -920,6 +921,17 @@ fn command_suppresses_warnings(command: Option<&Commands>) -> bool {
}
}
+/// Shell setup is Git-independent and may be evaluated or redirected during
+/// shell startup, so it remains available while the user upgrades Git.
+fn command_requires_supported_git(command: Option<&Commands>) -> bool {
+ !matches!(
+ command,
+ None | Some(Commands::Config {
+ action: ConfigCommand::Shell { .. },
+ })
+ )
+}
+
fn dispatch_command(
command: Commands,
working_dir: Option<std::path::PathBuf>,
@@ -1174,16 +1186,30 @@ fn main() {
logging::init(verbose);
}
- // Fold the two cold-path rev-parses (`--git-common-dir` from
- // `init_command_log`, the `prewarm_info` batch from `try_alias` →
- // `project_config_path`) into one fork. Best-effort — failure leaves both
- // on-demand callers unchanged.
- Repository::prewarm();
-
let command_line = std::env::args_os()
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" ");
+ let git_version_result = std::thread::scope(|scope| {
+ let git_version_check = command_requires_supported_git(command.as_ref())
+ .then(|| scope.spawn(require_minimum_git));
+
+ // Fold the two cold-path rev-parses (`--git-common-dir` from
+ // `init_command_log`, the `prewarm_info` batch from `try_alias` →
+ // `project_config_path`) into one fork. Best-effort — failure leaves
+ // both on-demand callers unchanged. The independent version probe
+ // runs alongside it so the minimum-version gate adds no serial fork.
+ Repository::prewarm();
+
+ git_version_check.map(|check| match check.join() {
+ Ok(result) => result,
+ Err(panic) => std::panic::resume_unwind(panic),
+ })
+ });
+ if let Some(Err(error)) = git_version_result {
+ handle_command_failure(error, verbose, &command_line);
+ }
+
{
let _span = worktrunk::trace::Span::new("init_command_log");
init_command_log(&command_line);
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 886f6c3da..938a12188 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -495,6 +495,16 @@ pub fn configure_pty_command(cmd: &mut portable_pty::CommandBuilder) {
pass_coverage_env_to_pty_cmd(cmd);
}
+/// Build a minimal PATH that keeps the test process's Git while excluding
+/// user-installed tools such as `wt`, `claude`, and `codex`.
+#[cfg(unix)]
+pub fn setup_minimal_path_with_git(bin_dir: &Path) -> String {
+ std::fs::create_dir_all(bin_dir).unwrap();
+ let git = which::which("git").expect("git must be installed to run tests");
+ std::os::unix::fs::symlink(git, bin_dir.join("git")).unwrap();
+ format!("{}:/usr/bin:/bin", bin_dir.display())
+}
+
/// Pass through LLVM coverage profiling environment to a portable_pty::CommandBuilder.
///
/// PTY tests use `cmd.env_clear()` for isolation, which removes LLVM_PROFILE_FILE.
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 24e2e445a..4b9fd64fe 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -1034,7 +1034,8 @@ if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
// Keep PATH minimal so the probe zsh doesn't find a globally-installed `wt`.
- cmd.env("PATH", "/usr/bin:/bin");
+ let path = crate::common::setup_minimal_path_with_git(&temp_home.path().join("bin"));
+ cmd.env("PATH", path);
cmd.env(
"ZDOTDIR",
crate::common::canonicalize(temp_home.path())
@@ -1083,7 +1084,8 @@ if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
// Keep PATH minimal so the probe zsh doesn't find a globally-installed `wt`.
- cmd.env("PATH", "/usr/bin:/bin");
+ let path = crate::common::setup_minimal_path_with_git(&temp_home.path().join("bin"));
+ cmd.env("PATH", path);
cmd.env(
"ZDOTDIR",
crate::common::canonicalize(temp_home.path())
diff --git a/tests/integration_tests/custom.rs b/tests/integration_tests/custom.rs
index bbf3e8226..2f724b2b5 100644
--- a/tests/integration_tests/custom.rs
+++ b/tests/integration_tests/custom.rs
@@ -34,6 +34,18 @@ fn mock_bin_dir(name: &str, response: MockResponse) -> TempDir {
dir
}
+/// Limit PATH to a supported Git executable, excluding every `wt-*` custom
+/// subcommand without bypassing wt's startup requirements.
+fn set_git_only_path(cmd: &mut Command) -> TempDir {
+ let dir = TempDir::new().unwrap();
+ MockConfig::new("git")
+ .version("git version 2.43.0")
+ .write(dir.path());
+ cmd.env("PATH", dir.path())
+ .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", dir.path());
+ dir
+}
+
#[test]
fn custom_subcommand_runs_wt_prefixed_binary_on_path() {
// `wt wt-test-extcmd-ok` should find `wt-wt-test-extcmd-ok` on PATH.
@@ -144,10 +156,7 @@ printf 'retired=%s\ncd=%s\nexec=%s\n' "${WORKTRUNK_DIRECTIVE_FILE-unset}" "${WOR
#[test]
fn custom_subcommand_not_found_prints_clap_error() {
let mut cmd = wt_command();
- // Clear PATH so no `wt-*` binaries can be discovered, then add a single
- // empty dir so `which` has somewhere to look.
- let empty = TempDir::new().unwrap();
- cmd.env("PATH", empty.path());
+ let _git_only_path = set_git_only_path(&mut cmd);
cmd.arg("definitely-not-a-wt-subcommand");
let output = cmd.output().expect("failed to run wt");
@@ -170,8 +179,7 @@ fn custom_subcommand_not_found_prints_clap_error() {
#[test]
fn custom_subcommand_typo_suggests_closest_builtin() {
let mut cmd = wt_command();
- let empty = TempDir::new().unwrap();
- cmd.env("PATH", empty.path());
+ let _git_only_path = set_git_only_path(&mut cmd);
cmd.arg("siwtch"); // typo of `switch`
let output = cmd.output().expect("failed to run wt");
@@ -195,8 +203,7 @@ fn custom_subcommand_nested_suggestion_wins_over_path_lookup() {
// not on PATH. The nested tip is layered on top of clap's standard
// unrecognized-subcommand error.
let mut cmd = wt_command();
- let empty = TempDir::new().unwrap();
- cmd.env("PATH", empty.path());
+ let _git_only_path = set_git_only_path(&mut cmd);
cmd.arg("squash");
let output = cmd.output().expect("failed to run wt");
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 49529cad5..2ee07c2f4 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -1,10 +1,31 @@
use insta::assert_snapshot;
use std::path::PathBuf;
+use std::process::Command;
+use tempfile::TempDir;
use worktrunk::git::{
Diagnostic, FailedCommand, GitError, HookErrorWithHint, HookType, RefType, WorktrunkError,
add_hook_skip_hint,
};
+use crate::common::{mock_commands::MockConfig, test_tempdir, wt_command};
+
+fn wt_with_git_version(version: &str) -> (TempDir, Command) {
+ let mock_bin = test_tempdir();
+ MockConfig::new("git")
+ .version(version)
+ .write(mock_bin.path());
+
+ let mut paths = vec![mock_bin.path().to_path_buf()];
+ paths.extend(std::env::split_paths(
+ &std::env::var_os("PATH").unwrap_or_default(),
+ ));
+
+ let mut cmd = wt_command();
+ cmd.env("PATH", std::env::join_paths(paths).unwrap())
+ .env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", mock_bin.path());
+ (mock_bin, cmd)
+}
+
fn render_cases(cases: impl IntoIterator<Item = (&'static str, String)>) -> String {
cases
.into_iter()
@@ -459,7 +480,7 @@ fn multiline_error_helpers_normalize_line_endings() {
#[test]
#[cfg(unix)]
fn git_unavailable_error_includes_command() {
- let mut cmd = crate::common::wt_command();
+ let mut cmd = wt_command();
cmd.arg("list")
.env("PATH", "/nonexistent")
.env_remove("GIT_EXEC_PATH");
@@ -467,8 +488,37 @@ fn git_unavailable_error_includes_command() {
let output = cmd.output().expect("run wt without git");
assert!(!output.status.success());
assert!(
- String::from_utf8_lossy(&output.stderr).contains("Failed to execute: git"),
+ String::from_utf8_lossy(&output.stderr).contains("Failed to run git --version"),
"stderr was:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}
+
+#[test]
+fn rejects_git_older_than_the_supported_minimum() {
+ let (_mock_bin, mut cmd) = wt_with_git_version("git version 2.42.4");
+ cmd.arg("list");
+ let output = cmd.output().unwrap();
+
+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"\u{1b}[31m✗\u{1b}[39m \u{1b}[31mGit 2.42.4 is unsupported; Worktrunk requires Git 2.43.0 or newer\u{1b}[39m\n");
+ assert_eq!(output.status.code(), Some(1));
+ assert!(output.stdout.is_empty());
+}
+
+#[test]
+fn shell_init_remains_available_on_older_git() {
+ let (_mock_bin, mut cmd) = wt_with_git_version("git version 2.42.4");
+ cmd.args(["config", "shell", "init", "nu"]);
+ let output = cmd.output().unwrap();
+
+ assert!(
+ output.status.success(),
+ "shell init failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ String::from_utf8_lossy(&output.stdout).contains("export def \"nu-complete wt\""),
+ "shell init must emit the Nushell integration:\n{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index e36ddbbc0..b2883f345 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -596,7 +596,12 @@ fn test_remove_refuses_foreign_repository_at_worktree_path(mut repo: TestRepo) {
/// test never depends on how git derives the id.
fn registration_dir(worktree: &Path) -> PathBuf {
let dot_git = std::fs::read_to_string(worktree.join(".git")).unwrap();
- PathBuf::from(dot_git.trim().strip_prefix("gitdir: ").unwrap())
+ let path = PathBuf::from(dot_git.trim().strip_prefix("gitdir: ").unwrap());
+ if path.is_relative() {
+ worktree.join(path)
+ } else {
+ path
+ }
}
/// A registration whose directory now holds a *sibling worktree of the same
@@ -698,38 +703,32 @@ approved-commands = ['{hook}']
);
}
-/// A registration recording its worktree with a *relative* `gitdir` entry is
-/// recognized, and that worktree removes normally.
+/// A registration using Git's configured path format is recognized and the
+/// worktree removes normally.
///
-/// git writes the relative form under `worktree.useRelativePaths` and resolves
-/// either, so the gate resolves an entry against the registration directory as
-/// git does. Rewriting the entry rather than setting the config keeps this
-/// independent of the git version that introduced the option — and git reads the
-/// rewritten entry back, which is what makes it the same form git would write.
+/// Git 2.48 and newer honor `worktree.useRelativePaths` and enable the
+/// `extensions.relativeWorktrees` repository extension. Older supported Git
+/// versions ignore the setting and keep writing absolute registrations. A
+/// hand-written relative entry would be unusable on Git 2.43, so Git creates
+/// the entry: this exercises the relative form where supported and the absolute
+/// form on older versions.
#[rstest]
-fn test_remove_worktree_with_relative_registration_gitdir(mut repo: TestRepo) {
+fn test_remove_worktree_with_git_generated_registration_paths(mut repo: TestRepo) {
+ repo.run_git(&["config", "worktree.useRelativePaths", "true"]);
let worktree_path = repo.add_worktree("feature");
let registration = registration_dir(&worktree_path);
-
- // From `<repo>/.git/worktrees/<id>`, four levels up is the directory the
- // worktree sits in, under the default `../{{ repo }}.{{ branch }}` layout.
- let relative = Path::new("../../../..")
- .join(worktree_path.file_name().unwrap())
- .join(".git");
+ let gitdir = std::fs::read_to_string(registration.join("gitdir")).unwrap();
+ let relative_extension_enabled = repo
+ .git_command()
+ .args(["config", "--get", "extensions.relativeWorktrees"])
+ .run()
+ .unwrap()
+ .status
+ .success();
assert_eq!(
- dunce::canonicalize(registration.join(&relative)).unwrap(),
- dunce::canonicalize(worktree_path.join(".git")).unwrap(),
- "the relative entry must resolve to this worktree's own .git",
- );
- std::fs::write(
- registration.join("gitdir"),
- relative.to_slash_lossy().as_ref(),
- )
- .unwrap();
- assert!(
- repo.git_output(&["worktree", "list", "--porcelain"])
- .contains(&worktree_path.to_slash_lossy().to_string()),
- "git must still resolve the worktree from the relative entry",
+ Path::new(gitdir.trim()).is_relative(),
+ relative_extension_enabled,
+ "Git must write a relative registration exactly when it enables the repository extension",
);
assert_cmd_snapshot!(make_snapshot_cmd(
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index bbf331bef..5437afc74 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -723,8 +723,10 @@ mod commit_generation_prompt_tests {
repo.run_git(&["add", "test.txt"]);
let mut env_vars = repo.test_env_vars();
- // Use minimal PATH to ensure claude/codex aren't found
- env_vars.push(("PATH".to_string(), "/usr/bin:/bin".to_string()));
+ // Use minimal PATH to ensure claude/codex aren't found while retaining
+ // the supported Git selected by the test runner.
+ let path = crate::common::setup_minimal_path_with_git(&temp_home.path().join("bin"));
+ env_vars.push(("PATH".to_string(), path));
let cmd = build_pty_command(
wt_bin().to_str().unwrap(),
@@ -759,7 +761,7 @@ mod commit_generation_prompt_tests {
let mut env_vars = repo.test_env_vars();
// Add our fake claude to PATH
- let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ let path = crate::common::setup_minimal_path_with_git(&bin_dir);
env_vars.push(("PATH".to_string(), path));
let cmd = build_pty_command(
@@ -799,7 +801,7 @@ mod commit_generation_prompt_tests {
repo.run_git(&["add", "test.txt"]);
let mut env_vars = repo.test_env_vars();
- let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ let path = crate::common::setup_minimal_path_with_git(&bin_dir);
env_vars.push(("PATH".to_string(), path));
let cmd = build_pty_command(
@@ -840,7 +842,7 @@ mod commit_generation_prompt_tests {
repo.run_git(&["add", "test.txt"]);
let mut env_vars = repo.test_env_vars();
- let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ let path = crate::common::setup_minimal_path_with_git(&bin_dir);
env_vars.push(("PATH".to_string(), path));
let cmd = build_pty_command(
@@ -884,7 +886,7 @@ mod commit_generation_prompt_tests {
let unwritable_config = blocker.join("config.toml");
let mut env_vars = repo.test_env_vars();
- let path = format!("{}:/usr/bin:/bin", bin_dir.display());
+ let path = crate::common::setup_minimal_path_with_git(&bin_dir);
env_vars.push(("PATH".to_string(), path));
// Overrides the WORKTRUNK_CONFIG_PATH from test_env_vars (last wins).
env_vars.push((
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 7afabf467..a4911fbe5 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -1978,13 +1978,15 @@ approved-commands = ["echo 'bash background'"]
let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
+ let path = crate::common::setup_minimal_path_with_git(&repo.home_path().join("test-bin"));
+ let path_quoted = shell_quote(&path);
// Script that explicitly removes wt from PATH but sets WORKTRUNK_BIN
let script = match shell {
"fish" => format!(
r#"
# Clear PATH to ensure wt is not found via PATH
- set -x PATH /usr/bin /bin
+ set -x PATH {}
set -x WORKTRUNK_BIN {}
set -x WORKTRUNK_CONFIG_PATH {}
set -x WORKTRUNK_APPROVALS_PATH {}
@@ -1993,12 +1995,12 @@ approved-commands = ["echo 'bash background'"]
wt switch --create fallback-test
echo "__PWD__ $PWD"
"#,
- wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
+ path_quoted, wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
),
_ => format!(
r#"
# Clear PATH to ensure wt is not found via PATH
- export PATH="/usr/bin:/bin"
+ export PATH={}
export WORKTRUNK_BIN={}
export WORKTRUNK_CONFIG_PATH={}
export WORKTRUNK_APPROVALS_PATH={}
@@ -2007,7 +2009,7 @@ approved-commands = ["echo 'bash background'"]
wt switch --create fallback-test
echo "__PWD__ $PWD"
"#,
- wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
+ path_quoted, wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
),
};
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_worktree_with_relative_registration_gitdir.snap b/tests/snapshots/integration__integration_tests__remove__remove_worktree_with_git_generated_registration_paths.snap
similarity index 100%
rename from tests/snapshots/integration__integration_tests__remove__remove_worktree_with_relative_registration_gitdir.snap
rename to tests/snapshots/integration__integration_tests__remove__remove_worktree_with_git_generated_registration_paths.snap