Skip to content

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

fix(shell): shell-correct (PowerShell + fish) escaping for the --execute payload (#2843)

Maximilian Roos62a7a6c0a5c9
diff --git a/skills/worktrunk/reference/shell-integration.md b/skills/worktrunk/reference/shell-integration.md
index 10280d06d..bee3bfcd3 100644
--- a/skills/worktrunk/reference/shell-integration.md
+++ b/skills/worktrunk/reference/shell-integration.md
@@ -253,7 +253,7 @@ If you see path issues, ensure you're using a recent Git for Windows version.
| `WORKTRUNK_DIRECTIVE_CD_FILE` | Set by shell wrapper; wt writes a raw path, wrapper `cd`s to it |
| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Set by shell wrapper; wt writes shell commands, wrapper sources the file |
| `WORKTRUNK_BIN` | Override binary path (for testing dev builds) |
-| `WORKTRUNK_SHELL` | Set by PowerShell wrapper to indicate shell type |
+| `WORKTRUNK_SHELL` | Set by the PowerShell (`powershell`) and fish (`fish`) wrappers; selects how wt escapes the EXEC directive payload for that shell |
## See Also
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index a2f77b5ea..af32a4ee1 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -10,6 +10,7 @@ use worktrunk::config::{
};
use worktrunk::git::{ErrorExt, Repository, WorktrunkError};
use worktrunk::path::{format_path_for_display, to_posix_path};
+use worktrunk::shell_exec::ShellEscapeMode;
use worktrunk::styling::{
eprintln, error_message, format_bash_with_gutter, format_with_gutter, info_message,
progress_message, verbosity,
@@ -376,10 +377,12 @@ pub fn wait_first_error<E>(
/// Expand a shell-command template against a context map.
///
/// Builds the `&str` vars map required by `expand_template` and fixes
-/// `shell_escape=true` since every caller interpolates the result into a
-/// shell string. Used by the three execution paths — foreground hooks,
-/// background pipelines, and aliases — that defer `vars.*` expansion until
-/// just before the command runs so prior steps can set vars via git config.
+/// [`ShellEscapeMode::Posix`]: every caller (foreground hooks, background
+/// pipelines, aliases) interpolates the result into a command line run
+/// through `Cmd::shell` (`sh`/Git Bash), which is always POSIX — unlike the
+/// `--execute` payload, this never reaches a PowerShell wrapper. Used by the
+/// three execution paths that defer `vars.*` expansion until just before the
+/// command runs so prior steps can set vars via git config.
pub fn expand_shell_template(
template: &str,
context: &HashMap<String, String>,
@@ -390,7 +393,13 @@ pub fn expand_shell_template(
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- Ok(expand_template(template, &vars, true, repo, label)?)
+ Ok(expand_template(
+ template,
+ &vars,
+ ShellEscapeMode::Posix,
+ repo,
+ label,
+ )?)
}
/// Resolve the shell string to execute for a prepared command.
diff --git a/src/commands/eval.rs b/src/commands/eval.rs
index ecfc39957..1ceaafc08 100644
--- a/src/commands/eval.rs
+++ b/src/commands/eval.rs
@@ -7,6 +7,7 @@ use std::collections::HashMap;
use worktrunk::config::{UserConfig, expand_template};
use worktrunk::git::Repository;
+use worktrunk::shell_exec::ShellEscapeMode;
use crate::commands::command_executor::{CommandContext, build_hook_context};
@@ -33,7 +34,7 @@ pub fn step_eval(template: &str, dry_run: bool) -> anyhow::Result<()> {
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- let result = expand_template(template, &vars, false, &repo, "eval")?;
+ let result = expand_template(template, &vars, ShellEscapeMode::Literal, &repo, "eval")?;
if dry_run {
let mut keys: Vec<&str> = context_map.keys().map(|k| k.as_str()).collect();
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index e707ecc5b..e1caf0c80 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -31,7 +31,7 @@ use std::process::Stdio;
use color_print::cformat;
use worktrunk::config::{UserConfig, expand_template};
use worktrunk::git::{ErrorExt, Repository, WorktreeInfo, WorktrunkError};
-use worktrunk::shell_exec::Cmd;
+use worktrunk::shell_exec::{Cmd, ShellEscapeMode};
use worktrunk::styling::{
eprintln, error_message, format_with_gutter, progress_message, success_message, warning_message,
};
@@ -86,7 +86,15 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
.collect();
let expanded: Vec<String> = args
.iter()
- .map(|arg| expand_template(arg, &vars, false, &repo, "for-each argument"))
+ .map(|arg| {
+ expand_template(
+ arg,
+ &vars,
+ ShellEscapeMode::Literal,
+ &repo,
+ "for-each argument",
+ )
+ })
.collect::<Result<_, _>>()?;
// Build JSON context for stdin
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 9bbb66271..6215ce062 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -702,10 +702,15 @@ fn expand_command_template(
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- // Use the standard template expansion (shell-escaped)
+ // Standard template expansion. Hooks always run through `Cmd::shell`
+ // (POSIX), so the preview is POSIX-escaped.
// On any error, show both the template and error message
- Ok(
- worktrunk::config::expand_template(template, &vars, true, ctx.repo, "hook preview")
- .unwrap_or_else(|err| format!("# {}\n{}", err.message, template)),
+ Ok(worktrunk::config::expand_template(
+ template,
+ &vars,
+ worktrunk::shell_exec::ShellEscapeMode::Posix,
+ ctx.repo,
+ "hook preview",
)
+ .unwrap_or_else(|err| format!("# {}\n{}", err.message, template)))
}
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 7338958e1..7539d04f0 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -328,8 +328,14 @@ pub fn work_items_for_worktree(
wt.branch.as_ref().and_then(|branch| {
let mut vars = std::collections::HashMap::new();
vars.insert("branch", branch.as_str());
- worktrunk::config::expand_template(template, &vars, false, repo, "url-template")
- .ok()
+ worktrunk::config::expand_template(
+ template,
+ &vars,
+ worktrunk::shell_exec::ShellEscapeMode::Literal,
+ repo,
+ "url-template",
+ )
+ .ok()
})
})
} else {
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 60df55ace..cf0bc7ea5 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -24,6 +24,7 @@ use worktrunk::git::{
GitError, GitRemoteUrl, RefContext, RefType, Repository, SwitchSuggestionCtx,
current_or_recover,
};
+use worktrunk::shell_exec::{ShellEscapeMode, directive_shell_escape_mode, shell_escape_for};
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,
warning_message,
@@ -1749,21 +1750,38 @@ pub fn run_switch(
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- // Expand template variables in command (shell_escape: true for safety)
- let expanded_cmd = expand_template(cmd, &vars, true, &repo, "--execute command")?;
+ // The `--execute` payload is parsed by the active directive shell: the
+ // PowerShell wrapper `Invoke-Expression`s the EXEC directive file, every
+ // other wrapper (and the direct `sh -c` non-integration path) is POSIX.
+ // Escape interpolated values for whichever it is — the one place the
+ // escaping is shell-aware (hooks/aliases stay POSIX). See
+ // `worktrunk::shell_exec::directive_shell_escape_mode`.
+ let escape_mode = directive_shell_escape_mode();
- // Append any trailing args (after --) to the execute command
- // Each arg is also expanded, then shell-escaped
+ // Expand template variables in command, escaped for the directive shell.
+ let expanded_cmd = expand_template(cmd, &vars, escape_mode, &repo, "--execute command")?;
+
+ // Append any trailing args (after --) to the execute command.
+ // Each arg is template-expanded literally, then escaped for the
+ // directive shell so the wrapper parses it as one literal argument.
let full_cmd = if execute_args.is_empty() {
expanded_cmd
} else {
let expanded_args: Result<Vec<_>, _> = execute_args
.iter()
- .map(|arg| expand_template(arg, &vars, false, &repo, "--execute argument"))
+ .map(|arg| {
+ expand_template(
+ arg,
+ &vars,
+ ShellEscapeMode::Literal,
+ &repo,
+ "--execute argument",
+ )
+ })
.collect();
let escaped_args: Vec<_> = expanded_args?
.iter()
- .map(|arg| shell_escape::unix::escape(arg.into()).into_owned())
+ .map(|arg| shell_escape_for(escape_mode, arg))
.collect();
format!("{} {}", expanded_cmd, escaped_args.join(" "))
};
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index d2867bf0f..c4d96035e 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -1,14 +1,17 @@
//! Template expansion utilities for worktrunk
//!
-//! Uses minijinja for template rendering. Single generic function with escaping flag:
-//! - `shell_escape: true` — Shell-escaped for safe command execution
-//! - `shell_escape: false` — Literal values for filesystem paths
+//! Uses minijinja for template rendering. A single generic function takes a
+//! [`ShellEscapeMode`] selecting how interpolated values are escaped:
+//! - `Posix` — POSIX single-quoting, for command lines fed to `Cmd::shell`
+//! (`sh`/Git Bash): hooks, aliases.
+//! - `PowerShell` — PowerShell single-quoting, for the `--execute` payload
+//! when the active directive shell is the PowerShell wrapper.
+//! - `Literal` — values substituted verbatim, for filesystem paths.
//!
//! All templates support Jinja2 syntax including filters, conditionals, and loops.
//!
//! See `wt hook --help` for available filters and functions.
-use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::hash::{Hash, Hasher};
@@ -20,10 +23,10 @@ use minijinja::value::{Enumerator, Object, ObjectRepr};
use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
use sha2::{Digest, Sha256};
-use shell_escape::unix::escape;
use crate::git::{Diagnostic, HookType, Repository};
use crate::path::to_posix_path;
+use crate::shell_exec::{ShellEscapeMode, shell_escape_for};
use crate::styling::{
eprintln, error_message, format_bash_with_gutter, format_with_gutter, hint_message,
info_message, verbosity,
@@ -307,11 +310,15 @@ pub fn alias_context_filter(mut referenced: BTreeSet<String>) -> BTreeSet<String
/// behave as expected because the object reports as an
/// [`ObjectRepr::Seq`].
///
-/// Shell escaping happens at render time via `shell_escape::unix::escape`
+/// Shell escaping happens at render time via POSIX [`shell_escape_for`]
/// rather than through the template environment's formatter — the formatter
/// would otherwise quote the already-escaped joined string as a whole. The
/// formatter installed by `expand_template` detects `ShellArgs` and writes
/// it through unmodified.
+///
+/// `args` exists only in alias scope, whose bodies always run through
+/// `Cmd::shell` (POSIX) — so this rendering is unconditionally POSIX,
+/// independent of the active directive shell.
#[derive(Debug)]
struct ShellArgs(Vec<String>);
@@ -340,12 +347,12 @@ impl Object for ShellArgs {
}
}
-/// Space-join shell-escaped args — the canonical rendering of `{{ args }}`
-/// used by both `ShellArgs::render` (template expansion) and the alias
-/// `-v` variable table.
+/// Space-join POSIX-shell-escaped args — the canonical rendering of
+/// `{{ args }}` used by both `ShellArgs::render` (template expansion) and the
+/// alias `-v` variable table. Always POSIX: see [`ShellArgs`].
fn shell_join(args: &[String]) -> String {
args.iter()
- .map(|a| escape(Cow::Borrowed(a)).into_owned())
+ .map(|a| shell_escape_for(ShellEscapeMode::Posix, a))
.collect::<Vec<_>>()
.join(" ")
}
@@ -881,8 +888,14 @@ pub fn validate_template(
/// # Arguments
/// * `template` - Template string using Jinja2 syntax (e.g., `{{ branch }}`)
/// * `vars` - Variables to substitute
-/// * `shell_escape` - If true, shell-escape all values for safe command execution.
-/// If false, substitute values literally (for filesystem paths).
+/// * `escape_mode` - How to escape interpolated values:
+/// - [`ShellEscapeMode::Posix`] / [`ShellEscapeMode::PowerShell`] — escape
+/// for safe splicing into a command line of that shell. Callers that feed
+/// the result to `Cmd::shell` (hooks, aliases) always pass `Posix`; only
+/// the `--execute` payload, parsed by the active directive shell, may pass
+/// `PowerShell`.
+/// - [`ShellEscapeMode::Literal`] — substitute values verbatim (filesystem
+/// paths).
/// * `repo` - Repository for looking up worktree paths
///
/// # Filters
@@ -903,7 +916,7 @@ pub fn validate_template(
pub fn expand_template(
template: &str,
vars: &HashMap<&str, &str>,
- shell_escape: bool,
+ escape_mode: ShellEscapeMode,
repo: &Repository,
name: &str,
) -> Result<String, TemplateExpandError> {
@@ -924,7 +937,7 @@ pub fn expand_template(
}
let mut env = setup_template_env(repo);
- if shell_escape {
+ if escape_mode != ShellEscapeMode::Literal {
// Preserve trailing newlines in templates (important for multiline shell commands)
env.set_keep_trailing_newline(true);
@@ -932,7 +945,7 @@ pub fn expand_template(
// This ensures filters (sanitize, sanitize_db, etc.) operate on raw values
// and the escaping is applied to the final output, preventing corruption
// when filters modify already-escaped strings.
- env.set_formatter(|out, _state, value| {
+ env.set_formatter(move |out, _state, value| {
if value.is_none() {
return Ok(());
}
@@ -945,8 +958,7 @@ pub fn expand_template(
write!(out, "{value}")?;
return Ok(());
}
- let s = value.to_string();
- let escaped = escape(Cow::Borrowed(&s));
+ let escaped = shell_escape_for(escape_mode, &value.to_string());
write!(out, "{escaped}")?;
Ok(())
});
@@ -1181,30 +1193,57 @@ mod tests {
let mut vars = HashMap::new();
vars.insert("name", "world");
assert_eq!(
- expand_template("Hello {{ name }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "Hello {{ name }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"Hello world"
);
// Multiple variables
vars.insert("repo", "myrepo");
assert_eq!(
- expand_template("{{ repo }}/{{ name }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ repo }}/{{ name }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"myrepo/world"
);
// Empty/static cases
let empty: HashMap<&str, &str> = HashMap::new();
assert_eq!(
- expand_template("", &empty, false, &test.repo, "test").unwrap(),
+ expand_template("", &empty, ShellEscapeMode::Literal, &test.repo, "test").unwrap(),
""
);
assert_eq!(
- expand_template("static text", &empty, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "static text",
+ &empty,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"static text"
);
// Undefined variables now error in SemiStrict mode
- let err = expand_template("no {{ variables }} here", &empty, false, &test.repo, "test")
- .unwrap_err();
+ let err = expand_template(
+ "no {{ variables }} here",
+ &empty,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap_err();
assert!(
err.message.contains("undefined value"),
"got: {}",
@@ -1217,18 +1256,39 @@ mod tests {
let test = test_repo();
let mut vars = HashMap::new();
vars.insert("path", "my path");
- let expanded = expand_template("cd {{ path }}", &vars, true, &test.repo, "test").unwrap();
+ let expanded = expand_template(
+ "cd {{ path }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert!(expanded.contains("'my path'") || expanded.contains(r"my\ path"));
// Command injection prevention
vars.insert("arg", "test;rm -rf");
- let expanded = expand_template("echo {{ arg }}", &vars, true, &test.repo, "test").unwrap();
+ let expanded = expand_template(
+ "echo {{ arg }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert!(!expanded.contains(";rm") || expanded.contains("'"));
// No escape for literal mode
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"feature/foo"
);
}
@@ -1237,9 +1297,25 @@ mod tests {
fn test_expand_template_errors() {
let test = test_repo();
let vars = HashMap::new();
- let err = expand_template("{{ unclosed", &vars, false, &test.repo, "test").unwrap_err();
+ let err = expand_template(
+ "{{ unclosed",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap_err();
assert!(err.message.contains("syntax error"), "got: {}", err.message);
- assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());
+ assert!(
+ expand_template(
+ "{{ 1 + }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .is_err()
+ );
// Diagnostic::render produces source line but no available vars hint for syntax errors
assert_snapshot!(crate::git::Diagnostic::render(&err), @"
@@ -1255,8 +1331,14 @@ mod tests {
vars.insert("branch", "main");
vars.insert("remote", "origin");
- let err =
- expand_template("echo {{ target }}", &vars, false, &test.repo, "test").unwrap_err();
+ let err = expand_template(
+ "echo {{ target }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap_err();
assert!(
err.message.contains("undefined value"),
"should mention undefined value: {}",
@@ -1283,7 +1365,7 @@ mod tests {
expand_template(
"{% if debug %}DEBUG{% endif %}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1296,7 +1378,7 @@ mod tests {
expand_template(
"{% if debug %}DEBUG{% endif %}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1309,7 +1391,7 @@ mod tests {
expand_template(
"{{ missing | default('fallback') }}",
&empty,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1319,7 +1401,14 @@ mod tests {
vars.insert("name", "hello");
assert_eq!(
- expand_template("{{ name | upper }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ name | upper }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"HELLO"
);
}
@@ -1335,7 +1424,7 @@ mod tests {
expand_template(
"{{ branch | replace('feature/', '') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1348,7 +1437,7 @@ mod tests {
expand_template(
"{{ branch | replace('feature/', '') | sanitize }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1362,7 +1451,7 @@ mod tests {
expand_template(
"{{ branch | replace('feature/', '') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1373,7 +1462,14 @@ mod tests {
// Slicing for prefix-only removal (avoids replacing mid-string)
vars.insert("branch", "feature/nested/feature/deep");
assert_eq!(
- expand_template("{{ branch[8:] }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch[8:] }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"nested/feature/deep"
);
@@ -1382,7 +1478,7 @@ mod tests {
expand_template(
"{% if branch[:8] == 'feature/' %}{{ branch[8:] }}{% else %}{{ branch }}{% endif %}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1396,7 +1492,7 @@ mod tests {
expand_template(
"{% if branch[:8] == 'feature/' %}{{ branch[8:] }}{% else %}{{ branch }}{% endif %}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1411,28 +1507,56 @@ mod tests {
let mut vars = HashMap::new();
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"feature-foo"
);
// Backslashes are also sanitized
vars.insert("branch", r"feature\bar");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"feature-bar"
);
// Multiple slashes
vars.insert("branch", "user/feature/task");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"user-feature-task"
);
// Raw branch is unchanged
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"feature/foo"
);
@@ -1440,8 +1564,14 @@ mod tests {
// Previously, shell escaping was applied BEFORE filters, corrupting the result
// when values contained shell-special characters (quotes, backslashes).
vars.insert("branch", "user's/feature");
- let result =
- expand_template("{{ branch | sanitize }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
// sanitize replaces / with -, producing "user's-feature"
// shell_escape wraps it: 'user'\''s-feature' (valid shell for user's-feature)
assert_eq!(result, r"'user'\''s-feature'", "sanitize + shell escape");
@@ -1450,7 +1580,14 @@ mod tests {
// sanitize would replace the / and \ in the already-escaped value.
// Shell escaping without filter: raw value with special chars
- let result = expand_template("{{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "{{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
// shell_escape wraps: 'user'\''s/feature' (valid shell for user's/feature)
assert_eq!(
result, r"'user'\''s/feature'",
@@ -1458,8 +1595,14 @@ mod tests {
);
// Shell-escape formatter handles none values (renders as empty string)
- let result =
- expand_template("prefix-{{ none }}-suffix", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "prefix-{{ none }}-suffix",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(result, "prefix--suffix", "none renders as empty");
}
@@ -1473,7 +1616,7 @@ mod tests {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1485,7 +1628,7 @@ mod tests {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1497,7 +1640,7 @@ mod tests {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1507,7 +1650,14 @@ mod tests {
// Raw branch is unchanged
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ branch }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"feature/foo"
);
}
@@ -1518,9 +1668,15 @@ mod tests {
let mut vars = HashMap::new();
vars.insert("cmd", "echo hello");
assert!(
- expand_template("{{ cmd }}\n", &vars, true, &test.repo, "test")
- .unwrap()
- .ends_with('\n')
+ expand_template(
+ "{{ cmd }}\n",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test"
+ )
+ .unwrap()
+ .ends_with('\n')
);
}
@@ -1541,8 +1697,14 @@ mod tests {
vars.insert("branch", "feature/very-long-branch-name");
// Filter produces a 3-char base36 digest
- let result =
- expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "{{ branch | hash }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(result.len(), 3);
assert!(
result
@@ -1552,17 +1714,38 @@ mod tests {
);
// Deterministic: same input produces same hash across calls
- let r1 = expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
- let r2 = expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
+ let r1 = expand_template(
+ "{{ branch | hash }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ let r2 = expand_template(
+ "{{ branch | hash }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(r1, r2);
// Composable: hash reflects the upstream filter's output
vars.insert("branch", "feature/auth");
- let raw = expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
+ let raw = expand_template(
+ "{{ branch | hash }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
let sanitized = expand_template(
"{{ branch | sanitize | hash }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1574,7 +1757,7 @@ mod tests {
let truncated = expand_template(
"{{ (branch | sanitize)[:8] }}_{{ branch | sanitize | hash }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1584,8 +1767,14 @@ mod tests {
// Empty input: still produces a 3-char digest (empty-string hash is stable)
vars.insert("branch", "");
- let empty =
- expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
+ let empty = expand_template(
+ "{{ branch | hash }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(empty.len(), 3);
}
@@ -1595,12 +1784,18 @@ mod tests {
let mut vars = HashMap::new();
vars.insert("branch", "feature/very-long-branch-name");
- let default =
- expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
+ let default = expand_template(
+ "{{ branch | codename }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
let explicit_default = expand_template(
"{{ branch | codename(2) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1611,7 +1806,7 @@ mod tests {
let one_word = expand_template(
"{{ branch | codename(1) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1624,27 +1819,39 @@ mod tests {
let three_words = expand_template(
"{{ branch | codename(3) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
.unwrap();
assert_eq!(three_words.split('-').count(), 3, "got: {three_words}");
- let repeat =
- expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
+ let repeat = expand_template(
+ "{{ branch | codename }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(default, repeat);
vars.insert("branch", "feature/different-name");
- let other =
- expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
+ let other = expand_template(
+ "{{ branch | codename }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(other.split('-').count(), 2, "got: {other}");
vars.insert("branch", "feature/73");
let ticket_73 = expand_template(
"{{ branch | codename(3) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1653,7 +1860,7 @@ mod tests {
let ticket_149 = expand_template(
"{{ branch | codename(3) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1670,7 +1877,7 @@ mod tests {
let zero = expand_template(
"{{ branch | codename(0) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1684,7 +1891,7 @@ mod tests {
let too_many = expand_template(
"{{ branch | codename(9) }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1796,8 +2003,14 @@ mod tests {
vars.insert("repo", "myrepo");
// Filter produces a number in range
- let result =
- expand_template("{{ branch | hash_port }}", &vars, false, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "{{ branch | hash_port }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
let port: u16 = result.parse().expect("should be a number");
assert!((10000..20000).contains(&port));
@@ -1805,7 +2018,7 @@ mod tests {
let r1 = expand_template(
"{{ (repo ~ '-' ~ branch) | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1814,7 +2027,7 @@ mod tests {
let r2 = expand_template(
"{{ (repo ~ '-' ~ branch) | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1838,7 +2051,7 @@ mod tests {
let result = expand_template(
"{{ repo_path | dirname | basename }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1850,7 +2063,7 @@ mod tests {
let result = expand_template(
"{{ repo_path }}/../{{ repo_path | dirname | basename }}.{{ branch | sanitize }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1862,7 +2075,7 @@ mod tests {
let dirname = expand_template(
"{{ repo_path | dirname }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1873,7 +2086,7 @@ mod tests {
let basename = expand_template(
"{{ repo_path | basename }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -1886,7 +2099,7 @@ mod tests {
expand_template(
"{{ repo_path | dirname }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1897,7 +2110,7 @@ mod tests {
expand_template(
"{{ repo_path | basename }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -1991,18 +2204,32 @@ mod tests {
// Access vars via dot notation
assert_eq!(
- expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ vars.env }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"staging"
);
assert_eq!(
- expand_template(r#"{{ vars["env"] }}"#, &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ r#"{{ vars["env"] }}"#,
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"staging"
);
assert_eq!(
expand_template(
"{% if vars %}vars loaded{% endif %}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -2010,7 +2237,14 @@ mod tests {
"vars loaded"
);
assert_eq!(
- expand_template("{{ vars.port }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ vars.port }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"3000"
);
@@ -2019,7 +2253,7 @@ mod tests {
expand_template(
"{{ vars.missing | default('fallback') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -2032,7 +2266,7 @@ mod tests {
expand_template(
"{% if vars.env %}env={{ vars.env }}{% endif %}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -2079,23 +2313,51 @@ mod tests {
// Dot access into JSON object
assert_eq!(
- expand_template("{{ vars.config.port }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ vars.config.port }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"3000"
);
assert_eq!(
- expand_template("{{ vars.config.debug }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ vars.config.debug }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"true"
);
// Array index access
assert_eq!(
- expand_template("{{ vars.tags[0] }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ vars.tags[0] }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"alpha"
);
// Plain string still works
assert_eq!(
- expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ vars.env }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"staging"
);
@@ -2104,7 +2366,7 @@ mod tests {
expand_template(
"{{ vars.config.missing | default('fallback') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -2131,12 +2393,24 @@ mod tests {
vars.insert("branch", "main");
// Shell escaping should work on JSON-parsed nested values
- let result =
- expand_template("{{ vars.config.name }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "{{ vars.config.name }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(result, "'my project'");
- let result =
- expand_template("{{ vars.config.cmd }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "{{ vars.config.cmd }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(result, "'echo hello'");
}
@@ -2150,7 +2424,7 @@ mod tests {
expand_template(
"{{ vars | default('none') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -2170,7 +2444,7 @@ mod tests {
expand_template(
"{{ vars.env | default('dev') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test"
)
@@ -2189,23 +2463,51 @@ mod tests {
// Bare {{ args }} with shell escaping: space-joined, per-element escaped,
// NOT wrapped in outer quotes as a single token.
assert_eq!(
- expand_template("wt switch {{ args }}", &vars, true, &test.repo, "test").unwrap(),
+ expand_template(
+ "wt switch {{ args }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"wt switch foo 'bar baz' qux"
);
// Indexing returns a plain string — flows through the shell-escape formatter.
assert_eq!(
- expand_template("{{ args[0] }}", &vars, true, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ args[0] }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"foo"
);
assert_eq!(
- expand_template("{{ args[1] }}", &vars, true, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ args[1] }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"'bar baz'"
);
// Length works like any sequence.
assert_eq!(
- expand_template("{{ args | length }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ args | length }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"3"
);
@@ -2214,7 +2516,7 @@ mod tests {
expand_template(
"{% for a in args %}[{{ a }}]{% endfor %}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test"
)
@@ -2232,13 +2534,27 @@ mod tests {
// Empty args renders empty. No stray whitespace, no error.
assert_eq!(
- expand_template("wt switch{{ args }}", &vars, true, &test.repo, "test").unwrap(),
+ expand_template(
+ "wt switch{{ args }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"wt switch"
);
// Length still defined for empty.
assert_eq!(
- expand_template("{{ args | length }}", &vars, false, &test.repo, "test").unwrap(),
+ expand_template(
+ "{{ args | length }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
"0"
);
@@ -2247,7 +2563,7 @@ mod tests {
expand_template(
"{% for a in args %}X{% endfor %}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test"
)
@@ -2260,14 +2576,21 @@ mod tests {
fn test_expand_template_args_shell_metachar_safety() {
// The point of ShellArgs is that bare {{ args }} is safe to splice into
// a command line even when args contain shell metacharacters — each
- // element is individually single-quoted by `shell_escape::unix::escape`,
- // and the outer formatter doesn't re-quote the joined result.
+ // element is individually POSIX single-quoted by `shell_join`, and the
+ // outer formatter doesn't re-quote the joined result.
let test = test_repo();
let args_json = serde_json::to_string(&["; rm -rf /", "$(whoami)", "a'b"]).unwrap();
let mut vars = HashMap::new();
vars.insert("args", args_json.as_str());
- let rendered = expand_template("echo {{ args }}", &vars, true, &test.repo, "test").unwrap();
+ let rendered = expand_template(
+ "echo {{ args }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(rendered, r#"echo '; rm -rf /' '$(whoami)' 'a'\''b'"#);
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index f3bb773ae..9e41477c5 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -148,6 +148,7 @@ mod tests {
use insta::assert_snapshot;
use super::*;
+ use crate::shell_exec::ShellEscapeMode;
use crate::testing::TestRepo;
fn test_repo() -> TestRepo {
@@ -476,7 +477,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
let result = expand_template(
"../{{ main_worktree }}.{{ branch }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -498,7 +499,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
let result = expand_template(
"{{ main_worktree }}/{{ branch | sanitize }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -511,7 +512,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
let result = expand_template(
".worktrees/{{ main_worktree }}/{{ branch | sanitize }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -530,7 +531,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
let result = expand_template(
"{{ repo_root }}/target -> {{ worktree }}/target",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test_repo().repo,
"test",
)
diff --git a/src/config/test.rs b/src/config/test.rs
index 52d5d736c..f390162f3 100644
--- a/src/config/test.rs
+++ b/src/config/test.rs
@@ -4,6 +4,7 @@
//! edge cases in template variable substitution.
use super::expand_template;
+use crate::shell_exec::ShellEscapeMode;
use crate::testing::TestRepo;
use std::collections::HashMap;
@@ -27,7 +28,7 @@ fn test_expand_template_normal() {
let result = expand_template(
"echo {{ branch }} {{ main_worktree }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -43,7 +44,7 @@ fn test_expand_template_branch_with_slashes() {
let result = expand_template(
"echo {{ branch | sanitize }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -60,7 +61,7 @@ fn test_expand_template_sanitize_hash_filter() {
let result = expand_template(
"{{ branch | sanitize_hash }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -72,7 +73,7 @@ fn test_expand_template_sanitize_hash_filter() {
let result = expand_template(
"{{ branch | sanitize_hash }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -86,7 +87,7 @@ fn test_expand_template_sanitize_hash_filter() {
let result = expand_template(
"{{ name | sanitize_hash }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -100,7 +101,14 @@ fn test_expand_template_branch_raw_with_slashes() {
let test = test_repo();
// Raw branch preserves slashes
let vars = vars_with_branch("feature/nested/branch");
- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo {{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(result, "echo feature/nested/branch");
}
@@ -113,7 +121,7 @@ fn test_expand_template_branch_escaping() {
expand_template(
"echo {{ branch }}",
&vars_with_branch(input),
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -130,7 +138,14 @@ fn test_expand_template_branch_escaping() {
fn snapshot_expand_template_branch_with_quotes() {
let test = test_repo();
let vars = vars_with_branch("feature'test");
- let result = expand_template("echo '{{ branch }}'", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo '{{ branch }}'",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
insta::assert_snapshot!(result, @r"echo ''feature'\''test''");
}
@@ -142,7 +157,7 @@ fn test_expand_template_extra_vars_path_escaping() {
expand_template(
"cd {{ worktree }}",
&HashMap::from([("worktree", path)]),
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -162,8 +177,14 @@ fn snapshot_expand_template_extra_vars_with_command_substitution() {
let test = test_repo();
let mut extras = HashMap::new();
extras.insert("target", "main; rm -rf /");
- let result =
- expand_template("git merge {{ target }}", &extras, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "git merge {{ target }}",
+ &extras,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
insta::assert_snapshot!(result, @"git merge 'main; rm -rf /'");
}
@@ -174,7 +195,14 @@ fn test_expand_template_variable_override() {
// Variables in the hashmap take precedence
let mut vars = HashMap::new();
vars.insert("branch", "overridden");
- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo {{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
assert_eq!(result, "echo overridden");
}
@@ -184,7 +212,13 @@ fn test_expand_template_missing_variable() {
let test = test_repo();
// Undefined variables error in SemiStrict mode (catches typos)
let vars: HashMap<&str, &str> = HashMap::new();
- let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo, "test");
+ let result = expand_template(
+ "echo {{ undefined }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ );
assert!(result.is_err());
let err = result.unwrap_err();
@@ -201,7 +235,14 @@ fn test_expand_template_empty_branch() {
let test = test_repo();
let mut vars = HashMap::new();
vars.insert("branch", "");
- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo {{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
// Empty string is shell-escaped to ''
assert_eq!(result, "echo ''");
@@ -213,7 +254,14 @@ fn test_expand_template_unicode_in_branch() {
let test = test_repo();
// Unicode characters in branch name are shell-escaped
let vars = vars_with_branch("feature-\u{1F680}");
- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo {{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
// Unicode is preserved but quoted for shell safety
assert_eq!(result, "echo 'feature-\u{1F680}'");
@@ -228,7 +276,7 @@ fn test_expand_template_backslash_in_branch() {
let result = expand_template(
"path/{{ branch | sanitize }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -248,7 +296,7 @@ fn test_expand_template_multiple_replacements() {
let result = expand_template(
"cd {{ worktree }} && git merge {{ target }} from {{ branch }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -262,7 +310,8 @@ fn test_expand_template_curly_braces_without_variables() {
let test = test_repo();
// Just curly braces, not variables
let vars: HashMap<&str, &str> = HashMap::new();
- let result = expand_template("echo {}", &vars, true, &test.repo, "test").unwrap();
+ let result =
+ expand_template("echo {}", &vars, ShellEscapeMode::Posix, &test.repo, "test").unwrap();
assert_eq!(result, "echo {}");
}
@@ -275,7 +324,7 @@ fn test_expand_template_nested_curly_braces() {
let result = expand_template(
"echo {{ '{' ~ branch ~ '}' }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -314,7 +363,14 @@ fn snapshot_shell_escaping_special_chars() {
let mut results = Vec::new();
for (name, branch) in test_cases {
let vars = vars_with_branch(branch);
- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo {{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
results.push((name, branch, result));
}
@@ -336,7 +392,14 @@ fn snapshot_shell_escaping_quotes() {
let mut results = Vec::new();
for (name, branch) in test_cases {
let vars = vars_with_branch(branch);
- let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();
+ let result = expand_template(
+ "echo {{ branch }}",
+ &vars,
+ ShellEscapeMode::Posix,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
results.push((name, branch, result));
}
@@ -363,7 +426,7 @@ fn snapshot_shell_escaping_paths() {
let result = expand_template(
"cd {{ worktree }} && echo {{ branch }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&test.repo,
"test",
)
@@ -405,7 +468,8 @@ fn snapshot_complex_templates() {
vars.insert("main_worktree", "/repo/path");
vars.insert("worktree", "/path with spaces/wt");
vars.insert("target", "main; rm -rf /");
- let result = expand_template(template, &vars, true, &test.repo, "test").unwrap();
+ let result =
+ expand_template(template, &vars, ShellEscapeMode::Posix, &test.repo, "test").unwrap();
results.push((name, template, branch, result));
}
@@ -423,7 +487,7 @@ fn test_expand_template_literal_normal() {
let result = expand_template(
"{{ main_worktree }}.{{ branch }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -441,7 +505,7 @@ fn test_expand_template_literal_unicode_no_escaping() {
let result = expand_template(
"{{ main_worktree }}.{{ branch }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -464,7 +528,7 @@ fn test_expand_template_literal_spaces_no_escaping() {
let result = expand_template(
"{{ main_worktree }}.{{ branch }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -487,7 +551,7 @@ fn test_expand_template_literal_sanitizes_slashes() {
let result = expand_template(
"{{ main_worktree }}.{{ branch | sanitize }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&test.repo,
"test",
)
@@ -505,8 +569,16 @@ fn test_expand_template_literal_vs_escaped_unicode() {
vars.insert("branch", "test-\u{2282}");
let template = "{{ main_worktree }}.{{ branch }}";
- let literal_result = expand_template(template, &vars, false, &test.repo, "test").unwrap();
- let escaped_result = expand_template(template, &vars, true, &test.repo, "test").unwrap();
+ let literal_result = expand_template(
+ template,
+ &vars,
+ ShellEscapeMode::Literal,
+ &test.repo,
+ "test",
+ )
+ .unwrap();
+ let escaped_result =
+ expand_template(template, &vars, ShellEscapeMode::Posix, &test.repo, "test").unwrap();
// Literal has no quotes
assert_eq!(literal_result, "myrepo.test-\u{2282}");
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index f4182d071..43c625c8e 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -8,6 +8,7 @@ use std::collections::{BTreeMap, HashMap};
use crate::config::HooksConfig;
use crate::config::commands::CommandConfig;
use crate::config::expansion::expand_template;
+use crate::shell_exec::ShellEscapeMode;
use super::UserConfig;
use super::merge::Merge;
@@ -223,9 +224,13 @@ impl UserConfig {
if let Some(ref owner) = owner {
vars.insert("owner", owner.as_str());
}
- Ok(
- expand_template(&template, &vars, false, repo, "worktree-path")
- .map(|p| shellexpand::tilde(&p).into_owned())?,
+ Ok(expand_template(
+ &template,
+ &vars,
+ ShellEscapeMode::Literal,
+ repo,
+ "worktree-path",
)
+ .map(|p| shellexpand::tilde(&p).into_owned())?)
}
}
diff --git a/src/output/global.rs b/src/output/global.rs
index 821249af4..6d8ba4905 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -65,6 +65,7 @@ use worktrunk::shell_exec::Cmd;
use worktrunk::shell_exec::ShellConfig;
use worktrunk::shell_exec::{
DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR,
+ ShellEscapeMode, directive_shell_escape_mode,
};
use worktrunk::styling::{hint_message, warning_message};
@@ -333,21 +334,25 @@ fn write_cd_path(file: &Path, path: &Path) -> io::Result<()> {
f.flush()
}
-/// Escape a path as a POSIX-shell (or PowerShell) single-quoted string. Only
-/// used in legacy mode where we still emit shell commands.
+/// Escape a path as a single-quoted `cd` command for the active directive
+/// shell. Only used in legacy mode where we still emit shell commands.
+///
+/// Always wraps the path in `'…'` (even when the path has no metacharacters),
+/// unlike the POSIX `--execute` payload escaper which omits quotes around safe
+/// values — a constant `cd '…'` shape keeps the legacy directive predictable.
+/// The per-shell decision comes from the shared [`directive_shell_escape_mode`],
+/// so the path body is escaped for POSIX (`'\''`), PowerShell (`''`), or fish
+/// (`\\` and `\'`) consistently with the rest of the directive payload.
fn escape_legacy_cd(path: &Path) -> String {
let path_str = path.to_string_lossy();
- // POSIX and PowerShell both single-quote, but escape embedded quotes
- // differently:
- // POSIX: 'it'\''s'
- // PSH: 'it''s'
- let is_powershell = std::env::var("WORKTRUNK_SHELL")
- .map(|v| v.eq_ignore_ascii_case("powershell"))
- .unwrap_or(false);
- let escaped = if is_powershell {
- path_str.replace('\'', "''")
- } else {
- path_str.replace('\'', r"'\''")
+ let escaped = match directive_shell_escape_mode() {
+ ShellEscapeMode::PowerShell => path_str.replace('\'', "''"),
+ // fish treats `\` as an escape inside `'…'`, so the path body must
+ // double `\` (before escaping `'`) — POSIX `'\''` would corrupt it.
+ ShellEscapeMode::Fish => path_str.replace('\\', r"\\").replace('\'', r"\'"),
+ // Literal is unreachable here (directive_shell_escape_mode yields only
+ // Posix/PowerShell/Fish); grouped with Posix as the safe default.
+ ShellEscapeMode::Literal | ShellEscapeMode::Posix => path_str.replace('\'', r"'\''"),
};
format!("cd '{}'", escaped)
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
index 841ad889e..7cde05fd2 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
@@ -26,12 +26,16 @@ function wt
set -l cd_file (mktemp)
set -l exec_file (mktemp)
+ # WORKTRUNK_SHELL tells the binary to escape the exec directive for fish's
+ # `eval` below — fish treats `\` as an escape inside '...', unlike POSIX.
# --source: use cargo run (builds from source)
if test $use_source = true
env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ WORKTRUNK_SHELL=fish \
cargo run --bin wt --quiet -- $args
else
env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ WORKTRUNK_SHELL=fish \
$WORKTRUNK_BIN $args
end
set -l exit_code $status
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index ef1eda63f..974559155 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -333,6 +333,98 @@ pub fn scrub_directive_env_vars(cmd: &mut std::process::Command) {
cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
}
+// ============================================================================
+// Directive-Payload Shell Escaping
+// ============================================================================
+
+/// Environment variable a shell wrapper sets to identify itself.
+///
+/// The PowerShell wrapper sets `WORKTRUNK_SHELL=powershell` and the fish
+/// wrapper sets `WORKTRUNK_SHELL=fish`; bash, zsh, and nushell leave it unset.
+/// Absence therefore means "POSIX", which is correct for those three wrappers
+/// *and* for the non-integration path where wt runs the `--execute` payload
+/// itself through `sh -c`.
+pub const WORKTRUNK_SHELL_ENV_VAR: &str = "WORKTRUNK_SHELL";
+
+/// How to single-quote a value spliced into a directive payload.
+///
+/// `wt switch --execute` builds one command string and hands it to the active
+/// shell — directly (`sh -c`) or, under shell integration, by writing it to the
+/// EXEC directive file the wrapper evaluates. POSIX shells, PowerShell, and
+/// fish all single-quote, but escape the string body differently — POSIX takes
+/// `\` literally inside `'…'` while fish treats it as an escape — so the
+/// escaper must be keyed on which shell will parse the payload.
+///
+/// `Literal` is the no-escaping mode for filesystem-path templates that are
+/// never spliced into a shell command line.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ShellEscapeMode {
+ /// Substitute values verbatim — used for filesystem paths.
+ Literal,
+ /// POSIX single-quoting (`'it'\''s'`). The wrapper-independent default for
+ /// bash, zsh, and nushell, plus `Cmd::shell` (hooks, aliases).
+ Posix,
+ /// PowerShell single-quoting (`'it''s'`), for the PowerShell wrapper's
+ /// `Invoke-Expression` of the EXEC directive file.
+ PowerShell,
+ /// fish single-quoting (`'it\'s'`), for the fish wrapper's `eval` of the
+ /// EXEC directive file. fish — unlike POSIX — treats `\` as an escape
+ /// inside `'…'`, so the POSIX escaper corrupts backslashes there.
+ Fish,
+}
+
+/// Escape mode for a payload the *active directive shell* will parse.
+///
+/// Reads [`WORKTRUNK_SHELL_ENV_VAR`] — the single source of truth for the
+/// per-shell escaping decision shared by `escape_legacy_cd`, the `--execute`
+/// command template, and its trailing args. `powershell` ⇒
+/// [`ShellEscapeMode::PowerShell`], `fish` ⇒ [`ShellEscapeMode::Fish`], any
+/// other value or absent ⇒ [`ShellEscapeMode::Posix`].
+pub fn directive_shell_escape_mode() -> ShellEscapeMode {
+ match std::env::var(WORKTRUNK_SHELL_ENV_VAR) {
+ Ok(v) if v.eq_ignore_ascii_case("powershell") => ShellEscapeMode::PowerShell,
+ Ok(v) if v.eq_ignore_ascii_case("fish") => ShellEscapeMode::Fish,
+ _ => ShellEscapeMode::Posix,
+ }
+}
+
+/// Single-quote `s` for PowerShell: wrap in `'…'`, doubling every embedded `'`.
+///
+/// PowerShell's literal string is `'…'` with `''` as the escape for one quote
+/// (`'can''t'` is `can't`). The POSIX `'\''` idiom is invalid here — that is
+/// the bug B1 fixes for the PowerShell wrapper's `Invoke-Expression` path.
+/// Empty input yields `''`.
+pub fn powershell_escape(s: &str) -> String {
+ format!("'{}'", s.replace('\'', "''"))
+}
+
+/// Single-quote `s` for fish: wrap in `'…'`, backslash-escaping `\` and `'`.
+///
+/// fish's single-quoted string — unlike POSIX — treats `\` as an escape
+/// character, with only `\\` and `\'` recognized inside `'…'`. So `\` must be
+/// doubled and `'` backslash-escaped; backslash *before* quote, since escaping
+/// the quote introduces a backslash that must not be doubled again. The POSIX
+/// `'\''` idiom would corrupt backslashes (and leave a trailing-`\` argument
+/// as an unterminated string) under the fish wrapper's `eval`. Empty input
+/// yields `''`.
+pub fn fish_escape(s: &str) -> String {
+ format!("'{}'", s.replace('\\', r"\\").replace('\'', r"\'"))
+}
+
+/// Shell-escape `s` for the given [`ShellEscapeMode`].
+///
+/// The single dispatcher every directive-payload escaper routes through.
+pub fn shell_escape_for(mode: ShellEscapeMode, s: &str) -> String {
+ match mode {
+ ShellEscapeMode::Literal => s.to_string(),
+ ShellEscapeMode::Posix => {
+ shell_escape::unix::escape(std::borrow::Cow::Borrowed(s)).into_owned()
+ }
+ ShellEscapeMode::PowerShell => powershell_escape(s),
+ ShellEscapeMode::Fish => fish_escape(s),
+ }
+}
+
// ============================================================================
// Thread-Local Command Timeout
// ============================================================================
@@ -1483,6 +1575,66 @@ pub fn forward_signal_with_escalation(pgid: i32, sig: i32) {
mod tests {
use super::*;
+ #[test]
+ fn test_powershell_escape() {
+ // Plain word: wrapped but unchanged inside the quotes.
+ assert_eq!(powershell_escape("rg"), "'rg'");
+ // Embedded single quote: doubled (PowerShell's only escape).
+ assert_eq!(powershell_escape("can't"), "'can''t'");
+ // `$(...)` is inert inside a PowerShell single-quoted string — no
+ // expansion, no doubling needed.
+ assert_eq!(powershell_escape("$(whoami)"), "'$(whoami)'");
+ // Spaces are covered by the surrounding quotes.
+ assert_eq!(powershell_escape("with space"), "'with space'");
+ // Empty string still produces a valid empty literal.
+ assert_eq!(powershell_escape(""), "''");
+ // Multiple quotes each double independently.
+ assert_eq!(powershell_escape("a'b'c"), "'a''b''c'");
+ }
+
+ #[test]
+ fn test_fish_escape() {
+ // Plain word: wrapped but unchanged inside the quotes.
+ assert_eq!(fish_escape("rg"), "'rg'");
+ // Two consecutive backslashes: each doubled, so fish's `eval`
+ // collapses `\\\\` back to `\\` — POSIX `'…'` would corrupt this.
+ assert_eq!(fish_escape(r"a\\b"), r"'a\\\\b'");
+ // Trailing backslash: doubled, so the closing `'` is not swallowed
+ // (the POSIX form `'end\'` is an unterminated string for fish).
+ assert_eq!(fish_escape(r"end\"), r"'end\\'");
+ // Embedded single quote: backslash-escaped (fish's escape inside `'…'`).
+ assert_eq!(fish_escape("can't"), r"'can\'t'");
+ // `$(...)` and backticks are inert inside a fish single-quoted string.
+ assert_eq!(fish_escape("$(whoami)"), "'$(whoami)'");
+ assert_eq!(fish_escape("`whoami`"), "'`whoami`'");
+ // Empty string still produces a valid empty literal.
+ assert_eq!(fish_escape(""), "''");
+ // Backslash then quote: `\` doubled first, then `'` escaped, so the
+ // escaping backslash of `\'` is not itself doubled.
+ assert_eq!(fish_escape(r"\'"), r"'\\\''");
+ }
+
+ #[test]
+ fn test_shell_escape_for_dispatch() {
+ // Literal passes the value through untouched.
+ assert_eq!(shell_escape_for(ShellEscapeMode::Literal, "can't"), "can't");
+ // Posix uses the `'\''` idiom for an embedded quote.
+ assert_eq!(
+ shell_escape_for(ShellEscapeMode::Posix, "can't"),
+ r"'can'\''t'"
+ );
+ // PowerShell doubles the embedded quote.
+ assert_eq!(
+ shell_escape_for(ShellEscapeMode::PowerShell, "can't"),
+ "'can''t'"
+ );
+ // Fish backslash-escapes the embedded quote.
+ assert_eq!(
+ shell_escape_for(ShellEscapeMode::Fish, "can't"),
+ r"'can\'t'"
+ );
+ }
+
#[test]
fn test_compute_git_env_overrides() {
// Use a platform-appropriate absolute base path so `Path::is_absolute`
diff --git a/templates/fish.fish b/templates/fish.fish
index fb9e31b78..a4824ef95 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -22,12 +22,16 @@ function {{ cmd }}
set -l cd_file (mktemp)
set -l exec_file (mktemp)
+ # WORKTRUNK_SHELL tells the binary to escape the exec directive for fish's
+ # `eval` below — fish treats `\` as an escape inside '...', unlike POSIX.
# --source: use cargo run (builds from source)
if test $use_source = true
env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ WORKTRUNK_SHELL=fish \
cargo run --bin {{ cmd }} --quiet -- $args
else
env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ WORKTRUNK_SHELL=fish \
$WORKTRUNK_BIN $args
end
set -l exit_code $status
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index 1515c3c70..aba6505c2 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -83,6 +83,35 @@ fn test_switch_legacy_directive_file_powershell(#[from(repo_with_remote)] mut re
});
}
+/// Legacy directive file in fish mode: the `cd` path is fish-escaped (`\`
+/// doubled, `'` backslash-escaped) instead of using the POSIX `'\''` idiom,
+/// which the fish wrapper's `eval` would mis-parse.
+#[rstest]
+fn test_switch_legacy_directive_file_fish(#[from(repo_with_remote)] mut repo: TestRepo) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (directive_path, _guard) = legacy_directive_file();
+
+ let settings = setup_snapshot_settings(&repo);
+
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ configure_legacy_directive_file(&mut cmd, &directive_path);
+ cmd.env("WORKTRUNK_SHELL", "fish");
+ cmd.arg("switch")
+ .arg("feature")
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+
+ let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
+ assert!(
+ directives.contains("cd '"),
+ "Legacy directive file should contain cd command, got: {directives}",
+ );
+ });
+}
+
/// Legacy directive file with --execute: both cd and execute commands
/// should be written to the single file.
#[rstest]
diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rs
index af747365c..ec0a0765c 100644
--- a/tests/integration_tests/doc_templates.rs
+++ b/tests/integration_tests/doc_templates.rs
@@ -11,6 +11,7 @@ use std::collections::HashMap;
use rstest::rstest;
use worktrunk::config::expand_template;
use worktrunk::git::Repository;
+use worktrunk::shell_exec::ShellEscapeMode;
use crate::common::{TestRepo, repo};
@@ -39,19 +40,47 @@ fn test_doc_basic_variables(repo: TestRepo) {
// Each variable substitutes correctly
assert_eq!(
- expand_template("{{ repo }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ repo }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"myproject"
);
assert_eq!(
- expand_template("{{ branch }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ branch }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"feature/auth"
);
assert_eq!(
- expand_template("{{ worktree }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ worktree }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"/home/user/myproject.feature-auth"
);
assert_eq!(
- expand_template("{{ default_branch }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ default_branch }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"main"
);
}
@@ -69,14 +98,28 @@ fn test_doc_sanitize_filter(repo: TestRepo) {
// From docs: {{ branch | sanitize }} replaces / and \ with -
vars.insert("branch", "feature/foo");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"feature-foo",
"sanitize should replace / with -"
);
vars.insert("branch", r"user\task");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"user-task",
r"sanitize should replace \ with -"
);
@@ -84,7 +127,14 @@ fn test_doc_sanitize_filter(repo: TestRepo) {
// Nested paths
vars.insert("branch", "user/feature/task");
assert_eq!(
- expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),
+ expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test"
+ )
+ .unwrap(),
"user-feature-task",
"sanitize should handle multiple slashes"
);
@@ -106,7 +156,7 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -121,7 +171,7 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -136,7 +186,7 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -151,7 +201,7 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -166,7 +216,7 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {
let result1 = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -175,7 +225,7 @@ fn test_doc_sanitize_db_filter(repo: TestRepo) {
let result2 = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -197,7 +247,7 @@ fn test_doc_sanitize_db_truncation(repo: TestRepo) {
let result = expand_template(
"{{ branch | sanitize_db }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -223,7 +273,7 @@ fn test_doc_hash_port_filter(repo: TestRepo) {
let result = expand_template(
"{{ branch | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -239,7 +289,7 @@ fn test_doc_hash_port_filter(repo: TestRepo) {
let result2 = expand_template(
"{{ branch | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -268,7 +318,7 @@ fn test_doc_hash_port_concatenation_precedence(repo: TestRepo) {
let with_parens = expand_template(
"{{ ('db-' ~ branch) | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -286,7 +336,7 @@ fn test_doc_hash_port_concatenation_precedence(repo: TestRepo) {
let without_parens = expand_template(
"{{ 'db-' ~ branch | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -321,7 +371,7 @@ fn test_doc_hash_port_repo_branch_concatenation(repo: TestRepo) {
let result = expand_template(
"{{ (repo ~ '-' ~ branch) | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -356,7 +406,14 @@ fn test_doc_example_docker_postgres(repo: TestRepo) {
-p {{ ('db-' ~ branch) | hash_port }}:5432 \
postgres:16"#;
- let result = expand_template(template, &vars, false, &repository, "test").unwrap();
+ let result = expand_template(
+ template,
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test",
+ )
+ .unwrap();
// Check the container name uses sanitized branch
assert!(
@@ -384,7 +441,14 @@ fn test_doc_example_database_url(repo: TestRepo) {
let template = "DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}";
- let result = expand_template(template, &vars, false, &repository, "test").unwrap();
+ let result = expand_template(
+ template,
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test",
+ )
+ .unwrap();
let expected_port = hash_port("db-feature");
assert_eq!(
@@ -404,7 +468,14 @@ fn test_doc_example_dev_server(repo: TestRepo) {
let template = "npm run dev -- --host {{ branch }}.localhost --port {{ branch | hash_port }}";
- let result = expand_template(template, &vars, false, &repository, "test").unwrap();
+ let result = expand_template(
+ template,
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test",
+ )
+ .unwrap();
let expected_port = hash_port("feature-auth");
assert_eq!(
@@ -425,7 +496,14 @@ fn test_doc_example_worktree_path_sanitize(repo: TestRepo) {
let template = "{{ main_worktree }}.{{ branch | sanitize }}";
- let result = expand_template(template, &vars, false, &repository, "test").unwrap();
+ let result = expand_template(
+ template,
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test",
+ )
+ .unwrap();
assert_eq!(result, "/home/user/project.feature-user-auth");
}
@@ -442,7 +520,7 @@ fn test_doc_hash_port_empty_string(repo: TestRepo) {
let result = expand_template(
"{{ branch | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -461,8 +539,14 @@ fn test_doc_sanitize_no_slashes(repo: TestRepo) {
let mut vars = HashMap::new();
vars.insert("branch", "simple-branch");
- let result =
- expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap();
+ let result = expand_template(
+ "{{ branch | sanitize }}",
+ &vars,
+ ShellEscapeMode::Literal,
+ &repository,
+ "test",
+ )
+ .unwrap();
assert_eq!(
result, "simple-branch",
"sanitize should be no-op without slashes"
@@ -479,7 +563,7 @@ fn test_doc_combined_filters(repo: TestRepo) {
let result = expand_template(
"{{ branch | sanitize | hash_port }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -503,7 +587,7 @@ fn test_worktree_path_of_branch_function_registered(repo: TestRepo) {
let result = expand_template(
"{{ worktree_path_of_branch('nonexistent') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
);
@@ -536,7 +620,7 @@ fn test_worktree_path_of_branch_shell_escape(repo: TestRepo) {
let result_literal = expand_template(
"{{ worktree_path_of_branch('test-branch') }}",
&vars,
- false,
+ ShellEscapeMode::Literal,
&repository,
"test",
)
@@ -551,7 +635,7 @@ fn test_worktree_path_of_branch_shell_escape(repo: TestRepo) {
let result_escaped = expand_template(
"{{ worktree_path_of_branch('test-branch') }}",
&vars,
- true,
+ ShellEscapeMode::Posix,
&repository,
"test",
)
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 7602ebfd7..7bfeb0665 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -532,6 +532,96 @@ fn test_switch_with_execute_trailing_args_metachars(repo: TestRepo) {
);
});
}
+
+/// Same scenario as `test_switch_with_execute_trailing_args_metachars`, but
+/// with `WORKTRUNK_SHELL=powershell` — the env var the PowerShell wrapper
+/// sets. The wrapper evaluates the EXEC directive file via `Invoke-Expression`,
+/// where the POSIX `'\''` idiom is invalid; each trailing arg must instead use
+/// PowerShell single-quoting (embedded `'` doubled to `''`). Guards the
+/// `directive_shell_escape_mode()` branch in `run_switch`'s `escaped_args`.
+#[rstest]
+fn test_switch_with_execute_trailing_args_metachars_powershell(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-psh",
+ "--execute",
+ "echo",
+ "--",
+ "$x's hello",
+ "with space",
+ ],
+ None,
+ );
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ cmd.env("WORKTRUNK_SHELL", "powershell");
+ assert_cmd_snapshot!(
+ "switch_with_execute_trailing_args_metachars_powershell_stderr",
+ cmd
+ );
+
+ // Under PowerShell, the exec file must contain the trailing args
+ // PowerShell-escaped: wrapped in `'…'` with embedded `'` doubled to
+ // `''`. `$(...)` / `$x` are inert inside a PowerShell single-quoted
+ // string, so they need no further escaping.
+ let exec_contents = fs::read_to_string(&exec_path).unwrap();
+ insta::assert_snapshot!(
+ "switch_with_execute_trailing_args_metachars_powershell_exec",
+ &exec_contents
+ );
+ });
+}
+
+/// Same scenario as `test_switch_with_execute_trailing_args_metachars`, but
+/// with `WORKTRUNK_SHELL=fish` — the env var the fish wrapper sets. The wrapper
+/// evaluates the EXEC directive file via `eval`, where fish treats `\` as an
+/// escape inside `'…'`; the POSIX escaper would collapse a `\\` pair and turn
+/// a trailing `\` into an unterminated string. Each trailing arg must instead
+/// use fish single-quoting (`\` doubled, `'` backslash-escaped). The args
+/// carry a literal backslash — the byte that POSIX and fish escaping diverge
+/// on. Guards the `directive_shell_escape_mode()` branch in `run_switch`.
+#[rstest]
+fn test_switch_with_execute_trailing_args_metachars_fish(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-fish",
+ "--execute",
+ "echo",
+ "--",
+ r"a\\b's hello",
+ "with space",
+ ],
+ None,
+ );
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ cmd.env("WORKTRUNK_SHELL", "fish");
+ assert_cmd_snapshot!(
+ "switch_with_execute_trailing_args_metachars_fish_stderr",
+ cmd
+ );
+
+ // Under fish, the exec file must contain the trailing args
+ // fish-escaped: wrapped in `'…'` with each `\` doubled and each `'`
+ // backslash-escaped — not the POSIX `'\''` idiom, which fish's `eval`
+ // would mis-parse.
+ let exec_contents = fs::read_to_string(&exec_path).unwrap();
+ insta::assert_snapshot!(
+ "switch_with_execute_trailing_args_metachars_fish_exec",
+ &exec_contents
+ );
+ });
+}
// Error tests
#[rstest]
fn test_switch_error_missing_worktree_directory(mut repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_fish.snap b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_fish.snap
new file mode 100644
index 000000000..a750ea054
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_fish.snap
@@ -0,0 +1,61 @@
+---
+source: tests/integration_tests/directives.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature
+ 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_FILE: "[DIRECTIVE_FILE]"
+ WORKTRUNK_SHELL: fish
+ 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_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 -----
+○ Switched to worktree for feature @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 165c29cb2..0dd46ebc9 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -13,13 +13,19 @@ info:
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]"
@@ -32,13 +38,19 @@ info:
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_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
@@ -68,12 +80,16 @@ function wt
set -l cd_file (mktemp)
set -l exec_file (mktemp)
+ # WORKTRUNK_SHELL tells the binary to escape the exec directive for fish's
+ # `eval` below — fish treats `\` as an escape inside '...', unlike POSIX.
# --source: use cargo run (builds from source)
if test $use_source = true
env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ WORKTRUNK_SHELL=fish \
cargo run --bin wt --quiet -- $args
else
env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
+ WORKTRUNK_SHELL=fish \
$WORKTRUNK_BIN $args
end
set -l exit_code $status
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_exec.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_exec.snap
new file mode 100644
index 000000000..eb1f3bde6
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_exec.snap
@@ -0,0 +1,5 @@
+---
+source: tests/integration_tests/switch.rs
+expression: "&exec_contents"
+---
+echo 'a\\\\b\'s hello' 'with space'
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_stderr.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_stderr.snap
new file mode 100644
index 000000000..fd6124651
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_stderr.snap
@@ -0,0 +1,71 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - exec-trailing-fish
+ - "--execute"
+ - echo
+ - "--"
+ - "a\\\\b'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_SHELL: fish
+ 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_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 -----
+✓ Created branch exec-trailing-fish from main and worktree @ _REPO_.exec-trailing-fish
+↳ To customize worktree locations, run wt config create
+◎ Executing (--execute):
+  echo 'a\\\\b\'s hello' 'with space'
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_exec.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_exec.snap
new file mode 100644
index 000000000..b82c3a6eb
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_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_powershell_stderr.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_stderr.snap
new file mode 100644
index 000000000..3760d15ca
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_stderr.snap
@@ -0,0 +1,71 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - exec-trailing-psh
+ - "--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_SHELL: powershell
+ 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_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 -----
+✓ Created branch exec-trailing-psh from main and worktree @ _REPO_.exec-trailing-psh
+↳ To customize worktree locations, run wt config create
+◎ Executing (--execute):
+  echo '$x''s hello' 'with space'