Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(shell): always POSIX-escape, never platform/MSYSTEM-sensitive (#2815)
Maximilian Roos13ac7364ef13
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 6c4fb5fdc..73e766776 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -567,11 +567,11 @@ pub fn handle_picker(};let signal_path_escaped =- shell_escape::escape(signal_path.display().to_string().into()).into_owned();+ shell_escape::unix::escape(signal_path.display().to_string().into()).into_owned();// Get state path for key bindings (shell-escaped for safety)let state_path_display = state.path.display().to_string();- let state_path_str = shell_escape::escape(state_path_display.into()).into_owned();+ let state_path_str = shell_escape::unix::escape(state_path_display.into()).into_owned();// Calculate half-page scroll: skim uses 90% of terminal height, half of that = 45%let half_page = terminal_size::terminal_size()diff --git a/src/commands/process.rs b/src/commands/process.rsindex f3987b853..13a4d8e45 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -116,6 +116,25 @@ fn posix_command_separator(command: &str) -> &'static str {}}+/// Build the POSIX-shell payload for a detached spawn that pipes optional+/// `context_json` into `command`'s stdin. With a JSON context, wraps the+/// command in a `printf '%s' '…' | { …; }` group so the inner command receives+/// the JSON verbatim and pipeline parsing isn't perturbed by `&&`/`||` inside+/// `command`. Without one, returns `command` unchanged. Shared by the Unix+/// path and the Windows Git-Bash branch — both feed POSIX shells, so the JSON+/// is POSIX-single-quote-escaped regardless of host.+fn build_printf_pipe_command(command: &str, context_json: Option<&str>) -> String {+ match context_json {+ Some(json) => format!(+ "printf '%s' {} | {{ {}{} }}",+ shell_escape::unix::escape(json.into()),+ command,+ posix_command_separator(command)+ ),+ None => command.to_string(),+ }+}+/// Create the log directory and file for a detached process.////// Returns `(log_path, log_file)`. Shared by `spawn_detached` and@@ -202,21 +221,7 @@ fn spawn_detached_unix() -> anyhow::Result<()> {use std::os::unix::process::CommandExt;- // Build the command, optionally piping JSON context to stdin- let full_command = match context_json {- Some(json) => {- // Use printf to pipe JSON to the command's stdin- // printf is more portable than echo for arbitrary content- // Wrap command in braces to ensure proper grouping with &&, ||, etc.- format!(- "printf '%s' {} | {{ {}{} }}",- shell_escape::escape(json.into()),- command,- posix_command_separator(command)- )- }- None => command.to_string(),- };+ let full_command = build_printf_pipe_command(command, context_json);// Wrap in braces so `&` backgrounds the entire compound command.// Without braces, `cmd1 && cmd2; cmd3 &` parses as two statements:@@ -279,18 +284,7 @@ fn spawn_detached_windows(// Build the command based on shell typelet mut cmd = if shell.is_posix() {// Git Bash available - use same syntax as Unix- let full_command = match context_json {- Some(json) => {- // Use printf to pipe JSON to the command's stdin (same as Unix)- format!(- "printf '%s' {} | {{ {}{} }}",- shell_escape::escape(json.into()),- command,- posix_command_separator(command)- )- }- None => command.to_string(),- };+ let full_command = build_printf_pipe_command(command, context_json);shell.command(&full_command)} else {// PowerShell fallback@@ -500,13 +494,7 @@ pub fn sweep_stale_trash(repo: &Repository) {return;}- // Join all paths into a single `rm -rf` invocation so we spawn one- // background process regardless of how many entries are stale.- let escaped: Vec<String> = stale- .iter()- .map(|p| shell_escape::escape(p.to_string_lossy().as_ref().into()).into_owned())- .collect();- let command = format!("rm -rf -- {}", escaped.join(" "));+ let command = build_trash_sweep_command(&stale);// The sweep is repo-wide (not branch-scoped), so it logs under// `internal/trash-sweep.log` alongside the other shared logs@@ -524,6 +512,19 @@ pub fn sweep_stale_trash(repo: &Repository) {}}+/// Build the `rm -rf -- …` command that [`sweep_stale_trash`] hands to+/// [`spawn_detached`]. All entries are joined into a single invocation so the+/// sweep spawns one background process regardless of how many stale entries+/// exist; each path is POSIX-escaped so directories with spaces or shell+/// metacharacters round-trip safely through the wrapping `sh -c`.+fn build_trash_sweep_command(paths: &[PathBuf]) -> String {+ let escaped: Vec<String> = paths+ .iter()+ .map(|p| shell_escape::unix::escape(p.to_string_lossy().as_ref().into()).into_owned())+ .collect();+ format!("rm -rf -- {}", escaped.join(" "))+}+/// Collect paths in `trash_dir` whose embedded timestamp is older than/// `threshold_secs` relative to `now`.///@@ -669,7 +670,7 @@ pub fn build_remove_command_staged(original_path: &std::path::Path,changed_directory: bool,) -> String {- use shell_escape::escape;+ use shell_escape::unix::escape;let staged_path_str = staged_path.to_string_lossy();let staged_escaped = escape(staged_path_str.as_ref().into());@@ -713,7 +714,7 @@ pub fn build_remove_command(force_worktree: bool,changed_directory: bool,) -> String {- use shell_escape::escape;+ use shell_escape::unix::escape;let worktree_path_str = worktree_path.to_string_lossy();let worktree_escaped = escape(worktree_path_str.as_ref().into());@@ -877,6 +878,73 @@ mod tests {assert_snapshot!(build_remove_command_staged(&special_path, &special_original, true), @"sleep 1 && rmdir -- '/tmp/test worktree' 2>/dev/null; rm -rf -- '/tmp/repo/.git/wt/trash/test worktree-123'");}+ #[test]+ fn test_build_printf_pipe_command() {+ // No JSON context: command passes through unchanged.+ assert_snapshot!(+ build_printf_pipe_command("echo hi", None),+ @"echo hi"+ );++ // With JSON: command wrapped in a printf-pipe group. The JSON is+ // POSIX-single-quote-escaped, the closing `}` is preceded by `;`+ // because the command doesn't already end with one.+ assert_snapshot!(+ build_printf_pipe_command("jq .", Some(r#"{"branch":"main"}"#)),+ @r#"printf '%s' '{"branch":"main"}' | { jq .; }"#+ );++ // Command that already ends in a semicolon: separator suppressed.+ assert_snapshot!(+ build_printf_pipe_command("jq .;", Some(r#"{"k":"v"}"#)),+ @r#"printf '%s' '{"k":"v"}' | { jq .; }"#+ );++ // JSON containing characters POSIX shells treat specially must end up+ // inside single quotes so command substitution doesn't fire inside the+ // detached `sh -c` wrapping the spawn. The embedded single quote uses+ // the standard `'\''` idiom. Regression guard for+ // shell_escape::escape vs unix::escape on Windows.+ assert_snapshot!(+ build_printf_pipe_command("jq .", Some(r#"{"x":"$(echo pwned)","y":"a'b"}"#)),+ @r#"printf '%s' '{"x":"$(echo pwned)","y":"a'\''b"}' | { jq .; }"#+ );+ }++ #[test]+ fn test_build_trash_sweep_command() {+ // Empty list still produces a well-formed command — the caller+ // (`sweep_stale_trash`) bails before we get here, but the helper itself+ // must not panic on an empty slice.+ assert_snapshot!(build_trash_sweep_command(&[]), @"rm -rf -- ");++ // Plain paths — joined with spaces, no quoting.+ let paths = [+ PathBuf::from("/tmp/repo/.git/wt/trash/feature-1700000000"),+ PathBuf::from("/tmp/repo/.git/wt/trash/bugfix-1700000100"),+ ];+ assert_snapshot!(+ build_trash_sweep_command(&paths),+ @"rm -rf -- /tmp/repo/.git/wt/trash/feature-1700000000 /tmp/repo/.git/wt/trash/bugfix-1700000100"+ );++ // Shell metacharacters — POSIX single-quote escaping isolates each path+ // so the wrapping `sh -c` reads them as literal arguments. The embedded+ // single quote uses the standard `'\''` idiom. This is the regression+ // guard for the platform/MSYSTEM-sensitive `shell_escape::escape` we+ // replaced: under cmd.exe quoting `$(echo pwned)` would still execute+ // when spliced into a POSIX shell.+ let nasty = [+ PathBuf::from("/tmp/trash/with space-1"),+ PathBuf::from("/tmp/trash/$(echo pwned)-2"),+ PathBuf::from("/tmp/trash/a'b-3"),+ ];+ assert_snapshot!(+ build_trash_sweep_command(&nasty),+ @"rm -rf -- '/tmp/trash/with space-1' '/tmp/trash/$(echo pwned)-2' '/tmp/trash/a'\\''b-3'"+ );+ }+#[test]fn test_hook_log_path() {use worktrunk::git::HookType;diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 22ce57377..60df55ace 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1572,7 +1572,7 @@ pub fn run_switch(// Without this, errors like "branch already exists" would suggest `wt switch <branch>`// instead of the full `wt switch <branch> --execute=<cmd> -- <args>`.let suggestion_ctx = execute.map(|exec| {- let escaped = shell_escape::escape(exec.into());+ let escaped = shell_escape::unix::escape(exec.into());SwitchSuggestionCtx {extra_flags: vec![format!("--execute={escaped}")],trailing_args: execute_args.to_vec(),@@ -1763,7 +1763,7 @@ pub fn run_switch(.collect();let escaped_args: Vec<_> = expanded_args?.iter()- .map(|arg| shell_escape::escape(arg.into()).into_owned())+ .map(|arg| shell_escape::unix::escape(arg.into()).into_owned()).collect();format!("{} {}", expanded_cmd, escaped_args.join(" "))};diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 4acd819a5..4533febc7 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -20,7 +20,7 @@ use minijinja::value::{Enumerator, Object, ObjectRepr};use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};use regex::Regex;use sha2::{Digest, Sha256};-use shell_escape::escape;+use shell_escape::unix::escape;use crate::git::{Diagnostic, HookType, Repository};use crate::path::to_posix_path;diff --git a/src/git/error.rs b/src/git/error.rsindex de645751b..bce10aa89 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -25,7 +25,7 @@ use std::borrow::Cow;use std::path::PathBuf;use color_print::cformat;-use shell_escape::escape;+use shell_escape::unix::escape;use super::HookType;use crate::path::format_path_for_display;diff --git a/src/llm.rs b/src/llm.rsindex 5bdaeb297..6affe22b8 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -1,6 +1,6 @@use anyhow::Context;use color_print::cformat;-use shell_escape::escape;+use shell_escape::unix::escape;use std::borrow::Cow;use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};diff --git a/src/styling/suggest.rs b/src/styling/suggest.rsindex 23ebbc9c8..48a2e07b9 100644--- a/src/styling/suggest.rs+++ b/src/styling/suggest.rs@@ -37,7 +37,7 @@//! assert_eq!(cmd, "wt -C /tmp/repo config update");//! ```-use shell_escape::escape;+use shell_escape::unix::escape;use std::borrow::Cow;use std::path::Path;diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 7ee365835..7602ebfd7 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -108,6 +108,31 @@ fn test_switch_create_existing_with_execute(mut repo: TestRepo) {);}+/// When --execute carries shell metacharacters (spaces, `$(...)`, embedded+/// single quotes), the rendered suggestion must POSIX-single-quote the value+/// so a copy-paste into bash/zsh/fish runs the intended literal command+/// instead of executing a command substitution. Guards the+/// `unix::escape(exec)` call on `run_switch`'s `suggestion_ctx` path against+/// regressing to platform-sensitive escaping (which on Windows-without-MSYSTEM+/// produces cmd.exe double-quote quoting — still subject to POSIX command+/// substitution when spliced into bash).+#[rstest]+fn test_switch_create_existing_with_execute_metachars(mut repo: TestRepo) {+ repo.add_worktree("emails");++ snapshot_switch(+ "switch_create_existing_with_execute_metachars",+ &repo,+ &[+ "--create",+ "--execute=echo \"$x's\"",+ "emails",+ "--",+ "Check my emails",+ ],+ );+}+/// When --execute is passed and the branch doesn't exist (without --create),/// the "create" suggestion should include --execute and trailing args.#[rstest]@@ -465,6 +490,48 @@ fn test_switch_internal_with_execute(repo: TestRepo) {&["--create", "exec-internal", "--execute", execute_cmd],);}++/// `--execute` with trailing `-- args` containing shell metacharacters: the+/// constructed command appended to the exec directive file must POSIX-escape+/// each trailing arg so the user's shell wrapper (`sh -c`, `bash -c`, …)+/// reads them as literal arguments — no command substitution, no $-expansion,+/// embedded single quotes via the standard `'\''` idiom. Guards+/// `run_switch`'s `escaped_args` map at `worktree/switch.rs` from regressing+/// to platform-sensitive escaping.+#[rstest]+fn test_switch_with_execute_trailing_args_metachars(repo: TestRepo) {+ let (cd_path, exec_path, _guard) = directive_files();+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(+ &repo,+ "switch",+ &[+ "--create",+ "exec-trailing",+ "--execute",+ "echo",+ "--",+ "$x's hello",+ "with space",+ ],+ None,+ );+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ assert_cmd_snapshot!("switch_with_execute_trailing_args_metachars_stderr", cmd);++ // The exec file is what the shell wrapper would source. It must contain+ // the trailing args POSIX-escaped — exactly the form a POSIX shell+ // parses back to the original literal values. (No command+ // substitution, no `$` expansion; embedded single quote uses the+ // standard `'\''` idiom.)+ let exec_contents = fs::read_to_string(&exec_path).unwrap();+ insta::assert_snapshot!(+ "switch_with_execute_trailing_args_metachars_exec",+ &exec_contents+ );+ });+}// Error tests#[rstest]fn test_switch_error_missing_worktree_directory(mut repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__switch__switch_create_existing_with_execute_metachars.snap b/tests/snapshots/integration__integration_tests__switch__switch_create_existing_with_execute_metachars.snapnew file mode 100644index 000000000..88bd69677--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_create_existing_with_execute_metachars.snap@@ -0,0 +1,63 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - "--execute=echo \"$x's\""+ - emails+ - "--"+ - Check my emails+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMON_DIR: ""+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_DIR: ""+ GIT_EDITOR: ""+ GIT_INDEX_FILE: ""+ GIT_OBJECT_DIRECTORY: ""+ GIT_TERMINAL_PROMPT: "0"+ GIT_WORK_TREE: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ 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_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ 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 [31mBranch [1memails[22m already exists[39m+[2m↳[22m [2mTo switch to the existing branch, run without [4m--create[24m: [4mwt switch emails --execute='echo "$x'\''s"' -- 'Check my emails'[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_exec.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_exec.snapnew file mode 100644index 000000000..5ff115ab9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_exec.snap@@ -0,0 +1,5 @@+---+source: tests/integration_tests/switch.rs+expression: "&exec_contents"+---+echo '$x'\''s hello' 'with space'diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_stderr.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_stderr.snapnew file mode 100644index 000000000..3afe275ac--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_stderr.snap@@ -0,0 +1,69 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - exec-trailing+ - "--execute"+ - echo+ - "--"+ - "$x's hello"+ - with space+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMON_DIR: ""+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_DIR: ""+ GIT_EDITOR: ""+ GIT_INDEX_FILE: ""+ GIT_OBJECT_DIRECTORY: ""+ GIT_TERMINAL_PROMPT: "0"+ GIT_WORK_TREE: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"+ WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"+ 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_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCreated branch [1mexec-trailing[22m from [1mmain[22m and worktree @ [1m_REPO_.exec-trailing[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[36m◎[39m [36mExecuting (--execute):[39m+[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'$x'[0m[2m\'[0m[2m[32m's hello'[0m[2m [0m[2m[32m'with space'[0m[2m