Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Reject invalid alias arguments without falling through to PATH (#4550)
Maximilian Roosd15ba8e5296c
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 71ebef285..2bc2abb8f 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -41,6 +41,7 @@use crate::commands::command_executor::ForegroundStdin;use std::collections::{BTreeMap, BTreeSet};+use std::ffi::OsString;use std::sync::LazyLock;use anyhow::{Context, bail};@@ -471,7 +472,7 @@ fn referenced_vars_for_entry(name: &str, entry: &AliasEntry) -> anyhow::Result<B/// a broken `wt.toml` should fail loudly here just as it does for `wt list`,/// rather than silently turning into an "unrecognized subcommand" once we/// fall through to PATH lookup.-pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::Result<Option<()>> {+pub fn try_alias(name: String, rest: &[OsString], global_yes: bool) -> anyhow::Result<Option<()>> {let _span = Span::new(format!("try_alias:{}", name));let repo = match Repository::current() {Ok(repo) => repo,@@ -486,6 +487,16 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::Rlet Some(entry) = aliases.get(&name) else {return Ok(None);};+ // Argument encoding cannot change which command owns this name. Validate+ // only after resolving the alias, leaving non-alias argv untouched.+ let rest = rest+ .iter()+ .map(|arg| {+ arg.to_str()+ .map(str::to_owned)+ .with_context(|| cformat!("Alias <bold>{name}</> requires UTF-8 arguments"))+ })+ .collect::<anyhow::Result<Vec<_>>>()?;let referenced = {let _span = Span::new("referenced_vars");referenced_vars_for_entry(&name, entry)?@@ -500,9 +511,6 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::Rlet _span = Span::new("parse_alias_args");AliasOptions::parse(alias_args, &referenced)?};- let entry = aliases- .get(&opts.name)- .expect("entry verified above and `opts.name` matches the dispatched name");run_alias(opts,warnings,@@ -557,9 +565,6 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {return Ok(());}let (opts, warnings) = AliasOptions::parse(args, &referenced)?;- let entry = aliases- .get(&opts.name)- .expect("entry verified above and `opts.name` matches the dispatched name");run_alias(opts,warnings,diff --git a/src/commands/custom.rs b/src/commands/custom.rsindex 5ae4dbaf3..45b6d1b9d 100644--- a/src/commands/custom.rs+++ b/src/commands/custom.rs@@ -91,13 +91,7 @@ pub(crate) fn handle_custom_command(// requires UTF-8, but we only run it after confirming the name is a// configured alias, so non-UTF-8 args meant for a custom subcommand binary// don't surface as alias parse errors.- let alias_args: Option<Vec<String>> = rest- .iter()- .map(|a| a.to_str().map(|s| s.to_owned()))- .collect();- if let Some(alias_args) = alias_args- && let Some(()) = try_alias(name.clone(), alias_args, yes)?- {+ if let Some(()) = try_alias(name.clone(), &rest, yes)? {return Ok(());}diff --git a/tests/integration_tests/custom.rs b/tests/integration_tests/custom.rsindex d4f84f2ed..291457569 100644--- a/tests/integration_tests/custom.rs+++ b/tests/integration_tests/custom.rs@@ -353,12 +353,7 @@ fn custom_subcommand_alias_outside_repo_wins_over_path_binary() {#[cfg(unix)]#[test]-fn custom_subcommand_alias_with_non_utf8_arg_never_self_suggests() {- // Non-UTF-8 args skip alias dispatch wholesale (the alias arg parser- // requires UTF-8), so inside a repo `wt co <raw byte>` with `co`- // configured still falls through to the clap-style error. The- // self-suggestion filter in similar_subcommands keeps that error's tip- // from suggesting 'co' — the name the user typed.+fn custom_subcommand_alias_rejects_non_utf8_without_running_path_binary() {use std::ffi::OsString;use std::os::unix::ffi::OsStringExt;@@ -368,33 +363,15 @@ fn custom_subcommand_alias_with_non_utf8_arg_never_self_suggests() {co = "echo hi""#,);-+ let bin_dir = mock_bin_dir("wt-co", MockResponse::output("path binary ran\n"));let mut cmd = repo.wt_command();+ prepend_path(&mut cmd, bin_dir.path());+ cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", bin_dir.path());cmd.arg("co").arg(OsString::from_vec(vec![0xff]));- let output = cmd.output().expect("failed to run wt");- assert!(!output.status.success());- assert_eq!(output.status.code(), Some(2));- let stderr = String::from_utf8_lossy(&output.stderr)- .ansi_strip()- .into_owned();- assert!(- stderr.contains("unrecognized subcommand 'co'"),- "dispatch falls through to the clap-style error: {stderr}"- );- // The error line legitimately quotes 'co'; only the tip must not.- let tip = stderr- .lines()- .find(|line| line.contains("tip:"))- .unwrap_or_default();- assert!(- tip.contains("'config'"),- "tip should suggest the built-in it is similar to: {stderr}"- );- assert!(- !tip.contains("'co'"),- "the tip must not suggest the typed name itself: {tip}"- );+ let settings = crate::common::setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();+ assert_cmd_snapshot!(cmd);}#[test]diff --git a/tests/snapshots/integration__integration_tests__custom__custom_subcommand_alias_rejects_non_utf8_without_running_path_binary.snap b/tests/snapshots/integration__integration_tests__custom__custom_subcommand_alias_rejects_non_utf8_without_running_path_binary.snapnew file mode 100644index 000000000..c5df5821b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__custom__custom_subcommand_alias_rejects_non_utf8_without_running_path_binary.snap@@ -0,0 +1,62 @@+---+source: tests/integration_tests/custom.rs+info:+ program: wt+ args:+ - co+ - �+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mAlias [1mco[22m requires UTF-8 arguments[39m