Skip to content

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

fix: strip only the executable suffix when naming wt from argv[0] (#3719)

Maximilian Roosa3daf0ded663
diff --git a/src/invocation.rs b/src/invocation.rs
index 0ed447751..f1a8df6b0 100644
--- a/src/invocation.rs
+++ b/src/invocation.rs
@@ -9,16 +9,17 @@
///
/// Used as the default for `--cmd` in shell integration commands.
/// When invoked as `git-wt`, returns "git-wt"; when invoked as `wt`, returns "wt".
-/// On Windows, strips `.exe` extension — users should use `wt` not `wt.exe` in aliases.
+/// On Windows, strips the `.exe` suffix — users should use `wt` not `wt.exe` in aliases.
+///
+/// The derivation is [`worktrunk::path::executable_name`], shared with the mock
+/// dispatch that reads the same `argv[0]`. A dotted name keeps its dot, since
+/// `.` is a valid shell command name character and the wrapper wt generates has
+/// to name the command the user actually runs. The "wt" fallback covers only an
+/// `argv[0]` with no name in it at all.
pub fn binary_name() -> String {
std::env::args_os()
.next()
- .and_then(|arg0| {
- std::path::Path::new(&arg0)
- .file_stem()
- .and_then(|name| name.to_str())
- .map(String::from)
- })
+ .and_then(|arg0| worktrunk::path::executable_name(std::path::Path::new(&arg0)))
.unwrap_or_else(|| "wt".to_string())
}
diff --git a/src/path.rs b/src/path.rs
index f8c036f63..3ed5e2875 100644
--- a/src/path.rs
+++ b/src/path.rs
@@ -234,13 +234,70 @@ pub fn sanitize_for_filename(value: &str) -> String {
result
}
+/// The command name a path to an executable names: its file name with the
+/// platform's executable suffix stripped.
+///
+/// The one place wt turns `argv[0]` into a command name.
+/// `invocation::binary_name` names wt in the shell integration it generates and
+/// in its own hints; [`testing::mock_stub`](crate::testing::mock_stub) selects a
+/// mock's config by it. A name that resolved differently in the two would be a
+/// silent disagreement about what this process is called. The shell-integration
+/// warning is not a third caller: it reports the name as typed, `.exe` and all,
+/// so it can tell a Windows user to drop the suffix.
+///
+/// Stripping [`std::env::consts::EXE_SUFFIX`] rather than taking
+/// [`Path::file_stem`] keeps a dotted name (`wt.old`, `python3.11`) whole.
+/// `file_stem` cuts at the last dot wherever that dot is, so the same name
+/// resolves differently per platform: Unix's `python3.11` becomes `python3`
+/// while the Windows link `python3.11.exe` keeps `python3.11`. The suffix
+/// matches case-insensitively, because Windows resolves `WT.EXE` and `wt.exe`
+/// to the same file.
+///
+/// Non-UTF8 bytes convert lossily rather than failing. The callers that embed
+/// the name in shell syntax validate it first
+/// ([`shell::validate_shell_command_name`](crate::shell::validate_shell_command_name)),
+/// and a name that can't be spelled is better rejected there than silently
+/// replaced by wt's own.
+///
+/// `None` when the path has no file name, or when the file name is nothing but
+/// the suffix — a degenerate `argv[0]`, which a caller treats as "no name"
+/// rather than panicking inside `main()`.
+///
+/// Not [`shell::extract_filename_from_path`](crate::shell::extract_filename_from_path),
+/// which strips `.exe` on every platform: that one names shells from `$SHELL`
+/// and the process tree, where a Unix-form path can still carry a Windows
+/// `.exe` (Git Bash), while `argv[0]` always spells its name the way the
+/// running platform does.
+pub fn executable_name(path: &Path) -> Option<String> {
+ let name = path.file_name()?.to_string_lossy();
+ let name = strip_suffix_ignoring_case(&name, std::env::consts::EXE_SUFFIX);
+ (!name.is_empty()).then(|| name.to_string())
+}
+
+/// Strip `suffix` from the end of `name`, matching it case-insensitively.
+///
+/// The suffix is a parameter rather than [`std::env::consts::EXE_SUFFIX`] read
+/// in place so that a test on any platform can exercise the Windows answer: the
+/// constant is empty on Unix, where this can only ever be a no-op, and the
+/// merge gate runs one platform.
+///
+/// `str::get` rather than a byte slice, so a name whose trailing bytes fall
+/// mid-character yields the name unchanged instead of panicking.
+fn strip_suffix_ignoring_case<'a>(name: &'a str, suffix: &str) -> &'a str {
+ let stem_len = name.len().saturating_sub(suffix.len());
+ match name.get(stem_len..) {
+ Some(tail) if tail.eq_ignore_ascii_case(suffix) => &name[..stem_len],
+ _ => name,
+ }
+}
+
#[cfg(test)]
mod tests {
- use std::path::PathBuf;
+ use std::path::{Path, PathBuf};
use super::{
- canonicalize_with_parents, expand_tilde, format_path_for_display, home_dir, paths_match,
- sanitize_for_filename, to_posix_path,
+ canonicalize_with_parents, executable_name, expand_tilde, format_path_for_display,
+ home_dir, paths_match, sanitize_for_filename, strip_suffix_ignoring_case, to_posix_path,
};
/// The tilde form `format_path_for_display` prints is a form wt reads back,
@@ -571,4 +628,65 @@ mod tests {
let _ = std::fs::remove_dir_all(&existing);
}
+
+ /// A dot in `argv[0]` is part of the name, not an extension to drop:
+ /// `file_stem` would cut `wt.old` down to `wt` while leaving the Windows
+ /// `wt.old.exe` whole, and both callers need one answer everywhere.
+ #[test]
+ fn executable_name_strips_only_the_executable_suffix() {
+ let cases = [
+ ("wt", Some("wt")),
+ ("./wt", Some("wt")),
+ ("target/debug/wt", Some("wt")),
+ ("/usr/local/bin/git-wt", Some("git-wt")),
+ ("wt.old", Some("wt.old")),
+ ("python3.11", Some("python3.11")),
+ ("", None),
+ ("/", None),
+ ];
+ for (arg0, expected) in cases {
+ assert_eq!(
+ executable_name(Path::new(arg0)).as_deref(),
+ expected,
+ "{arg0}"
+ );
+ }
+
+ // The suffix stripped is the running platform's own: a Unix file
+ // really named `wt.exe` keeps the name it has.
+ let (exe, suffix_only) = if cfg!(windows) {
+ (Some("wt"), None)
+ } else {
+ (Some("wt.exe"), Some(".exe"))
+ };
+ assert_eq!(executable_name(Path::new("wt.exe")).as_deref(), exe);
+ assert_eq!(executable_name(Path::new(".exe")).as_deref(), suffix_only);
+ }
+
+ /// The `.exe` half of that, on whichever platform runs the test: `EXE_SUFFIX`
+ /// is empty on Unix, so `executable_name` alone can never exercise the
+ /// answer Windows gets.
+ #[test]
+ fn strip_suffix_ignoring_case_matches_every_exe_spelling() {
+ let cases = [
+ ("wt.exe", "wt"),
+ // Windows resolves these to one file, so all three name one command.
+ ("WT.EXE", "WT"),
+ ("wt.Exe", "wt"),
+ ("git-wt.exe", "git-wt"),
+ // Only a suffix: `wt.exe.old` is named for its dot, not its middle.
+ ("wt.exe.old", "wt.exe.old"),
+ ("wt", "wt"),
+ ("exe", "exe"),
+ (".exe", ""),
+ // Trailing bytes falling mid-character are not a suffix match.
+ ("€ab", "€ab"),
+ ];
+ for (name, expected) in cases {
+ assert_eq!(strip_suffix_ignoring_case(name, ".exe"), expected, "{name}");
+ }
+
+ // The empty suffix Unix carries strips nothing.
+ assert_eq!(strip_suffix_ignoring_case("wt.exe", ""), "wt.exe");
+ }
}
diff --git a/src/testing/mock_stub.rs b/src/testing/mock_stub.rs
index 48c71ae0c..b82976cc9 100644
--- a/src/testing/mock_stub.rs
+++ b/src/testing/mock_stub.rs
@@ -80,7 +80,14 @@ pub fn maybe_run() {
let Some(dir) = env::var_os("WORKTRUNK_TEST_MOCK_CONFIG_DIR") else {
return;
};
- let Some(name) = command_name() else {
+ // args_os, not args: `env::args()` panics during iteration on a
+ // non-Unicode argument, and this runs inside wt's `main()` on every
+ // invocation. A non-UTF8 or degenerate argv[0] yields a name matching no
+ // config, so the invocation falls through to "not a mock" instead.
+ let Some(name) = env::args_os()
+ .next()
+ .and_then(|arg0| crate::path::executable_name(Path::new(&arg0)))
+ else {
return;
};
// The wt under test runs with the variable set too (that's how its mock
@@ -106,28 +113,6 @@ pub fn maybe_run() {
run(&name, &config_dir);
}
-/// Command name from argv\[0\]: the link name the harness gave this binary,
-/// with the platform's executable suffix (`.exe`) stripped. Stripping the
-/// suffix rather than taking `file_stem` keeps a dotted mock name
-/// (`python3.11`) intact, and identical across platforms. `None` when
-/// argv\[0\] is missing or degenerate — the caller treats that as "not a
-/// mock" rather than panicking inside wt's `main()`.
-///
-/// The bin crate's `invocation::binary_name` reads the same argv\[0\] to name
-/// wt in its own help output; keep the two derivations aligned.
-fn command_name() -> Option<String> {
- // args_os, not args: `env::args()` panics during iteration on a
- // non-Unicode argument, and this runs inside wt's `main()` on every
- // invocation. A non-UTF8 argv[0] lossily converts, matches no config
- // name, and falls through to "not a mock".
- let argv0 = env::args_os().next()?;
- let name = Path::new(&argv0).file_name()?.to_string_lossy();
- let name = name
- .strip_suffix(std::env::consts::EXE_SUFFIX)
- .unwrap_or(&name);
- (!name.is_empty()).then(|| name.to_string())
-}
-
/// Append this invocation's argv to
/// `<WORKTRUNK_TEST_MOCK_CALL_LOG_DIR>/<command>.calls` so a test can assert
/// *how many times* and *with what arguments* a command was spawned, not just
@@ -159,7 +144,7 @@ fn log_invocation(cmd_name: &str, args: &[String]) {
fn run(cmd_name: &str, config_dir: &Path) -> ! {
let config_path = config_dir.join(format!("{}.json", cmd_name));
- // Lossy for the same reason as `command_name`: a non-UTF8 argument can't
+ // Lossy for the same reason as the name above: a non-UTF8 argument can't
// match a config key (JSON keys are UTF-8), and the mock must not panic
// on one.
let args: Vec<String> = env::args_os()
diff --git a/tests/integration_tests/init.rs b/tests/integration_tests/init.rs
index c88c82dda..9adb36022 100644
--- a/tests/integration_tests/init.rs
+++ b/tests/integration_tests/init.rs
@@ -104,8 +104,8 @@ fn test_init_rejects_unsafe_cmd(#[case] shell: &str, repo: TestRepo) {
}
/// A degenerate argv\[0\] — empty here, so it has no file name — never selects
-/// mock playback: `command_name()` yields `None` and the process runs as wt,
-/// rather than panicking inside `main()` or probing the config dir.
+/// mock playback: `path::executable_name` yields `None` and the process runs as
+/// wt, rather than panicking inside `main()` or probing the config dir.
#[test]
fn test_mock_dispatch_ignores_degenerate_argv0() {
use std::os::unix::process::CommandExt;
@@ -151,6 +151,74 @@ fn test_mock_dispatch_survives_non_utf8_argv0() {
);
}
+/// A dot in argv\[0\] is part of the command name, not an extension to drop:
+/// `validate_shell_command_name` accepts `.`, so a `wt.old` invocation must
+/// wrap `wt.old` — wrapping the truncated `wt` would name a command the user
+/// may not have installed at all.
+#[rstest]
+fn test_init_keeps_dotted_argv0_command_name(repo: TestRepo) {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let dotted_bin = temp_dir.path().join("wt.old");
+ std::os::unix::fs::symlink(wt_bin(), &dotted_bin).unwrap();
+
+ let mut cmd = Command::new(&dotted_bin);
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.arg("config")
+ .arg("shell")
+ .arg("init")
+ .arg("bash")
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ assert!(
+ output.status.success(),
+ "shell init failed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ stdout.contains("wt.old() {"),
+ "expected a wrapper for the full invocation name:\n{stdout}"
+ );
+ assert!(
+ !stdout.contains("wt() {"),
+ "wrapper must not fall back to the truncated name:\n{stdout}"
+ );
+}
+
+/// A non-UTF8 argv\[0\] names a command that cannot be spelled in shell syntax,
+/// so it reaches the same rejection as the `wt;touch` case below. Answering
+/// with wt's own name instead would generate integration for a command other
+/// than the one that ran.
+#[test]
+fn test_init_rejects_non_utf8_argv0_command_name() {
+ use std::ffi::OsStr;
+ use std::os::unix::ffi::OsStrExt;
+ use std::os::unix::process::CommandExt;
+
+ let mut cmd = wt_command();
+ cmd.arg0(OsStr::from_bytes(b"\xff\xfe"))
+ .arg("config")
+ .arg("shell")
+ .arg("init")
+ .arg("bash");
+
+ let output = cmd.output().unwrap();
+
+ assert!(!output.status.success());
+ assert!(
+ output.stdout.is_empty(),
+ "unspellable command name must not emit shell code:\n{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("Invalid shell integration command name"),
+ "expected validation error, got:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
+
#[rstest]
fn test_init_rejects_unsafe_argv0_command_name(repo: TestRepo) {
let temp_dir = tempfile::tempdir().unwrap();