Skip to content

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

Refactor: Improve shell integration and command execution

Maximilian Roosae43eb187c36
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index a7c0623af..6c92d1593 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -10,7 +10,9 @@ pub use configure_shell::{ConfigAction, handle_configure_shell};
pub use init::handle_init;
pub use list::handle_list;
pub use merge::handle_merge;
-pub use worktree::{handle_push, handle_remove, handle_switch};
+pub use worktree::{
+ execute_command_in_worktree, handle_push, handle_remove, handle_switch, shell_integration_hint,
+};
// Re-export Shell from the canonical location
pub use worktrunk::shell::Shell;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 90cdc68f9..d095322f2 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -62,6 +62,36 @@
//! - `format_user_output()`: Returns human-friendly messages (no directives)
//! - `format_internal_output()`: Returns directive protocol + messages
//!
+//! ## Directive Protocol
+//!
+//! Directives are NUL-terminated to support multi-line commands (e.g., via `-x` flag):
+//!
+//! ```text
+//! __WORKTRUNK_CD__/path/to/worktree\0
+//! Message for user\0
+//! __WORKTRUNK_EXEC__echo 'line1'\necho 'line2'\0
+//! ```
+//!
+//! Shell wrappers split on `\0` bytes and process each chunk:
+//! - `__WORKTRUNK_CD__<path>`: Change directory to `<path>`
+//! - `__WORKTRUNK_EXEC__<command>`: Execute `<command>` (may contain newlines)
+//! - Other chunks: Print as regular output
+//!
+//! ## Exit Code Semantics
+//!
+//! When using `-x` to execute commands after switching:
+//!
+//! - **Exit code returned**: The `wt` command's exit code
+//! - **Command execution**: Runs for side effects; failures are logged but don't affect exit code
+//! - **Rationale**: Allows scripts to detect `wt` failures (e.g., branch already exists) while
+//! still executing post-switch commands for convenience
+//!
+//! Example:
+//! ```bash
+//! wt switch --create feature -x "editor ." # Opens editor even if branch exists
+//! echo $? # Returns wt's exit code, not editor's
+//! ```
+//!
//! The shell wrapper is generated by `wt init <shell>` from templates in `templates/`.
//!
//! See also: DEMO.md for detailed architecture explanation.
@@ -81,7 +111,7 @@ use worktrunk::styling::{
/// Returns a hint message based on whether shell integration is configured:
/// - If configured but not active: provides exact source command
/// - If not configured: suggests running configure-shell
-fn shell_integration_hint() -> String {
+pub fn shell_integration_hint() -> String {
if let Some(config_path) = Shell::is_integration_configured() {
format!(
"\n\nShell integration configured. Restart your shell or run: source {}",
@@ -101,28 +131,32 @@ pub enum SwitchResult {
}
impl SwitchResult {
- /// Format the result for display (non-internal mode)
- pub fn format_user_output(&self, branch: &str) -> Option<String> {
+ /// Get the worktree path
+ pub fn path(&self) -> &PathBuf {
+ match self {
+ SwitchResult::ExistingWorktree(path) => path,
+ SwitchResult::CreatedWorktree { path, .. } => path,
+ }
+ }
+
+ /// Format a user-friendly message for this result
+ pub fn format_message(&self, branch: &str) -> String {
use anstyle::{AnsiColor, Color};
+ let green = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
+ let green_bold = green.bold();
match self {
- SwitchResult::ExistingWorktree(_path) => {
- let green = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
- let green_bold = green.bold();
- Some(format!(
- "✅ {green}Switched to worktree for {green_bold}{branch}{green_bold:#}{green:#}\n\n{}",
- shell_integration_hint()
- ))
+ SwitchResult::ExistingWorktree(_) => {
+ format!(
+ "✅ {green}Switched to worktree for {green_bold}{branch}{green_bold:#}{green:#}"
+ )
}
SwitchResult::CreatedWorktree {
path,
created_branch,
} => {
- let green = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
- let green_bold = green.bold();
let dim = AnstyleStyle::new().dimmed();
-
- let msg = if *created_branch {
+ if *created_branch {
format!(
"✅ {green}Created new worktree for {green_bold}{branch}{green_bold:#}{green:#}\n {dim}Path: {}{dim:#}",
path.display()
@@ -132,43 +166,7 @@ impl SwitchResult {
"✅ {green}Added worktree for {green_bold}{branch}{green_bold:#}{green:#}\n {dim}Path: {}{dim:#}",
path.display()
)
- };
-
- Some(format!("{}{}", msg, shell_integration_hint()))
- }
- }
- }
-
- /// Format the result for shell integration (internal mode)
- pub fn format_internal_output(&self, branch: &str) -> Option<String> {
- use anstyle::{AnsiColor, Color};
-
- match self {
- SwitchResult::ExistingWorktree(path) => {
- let green = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
- let green_bold = green.bold();
- Some(format!(
- "__WORKTRUNK_CD__{}\n✅ {green}Switched to worktree for {green_bold}{branch}{green_bold:#}{green:#}",
- path.display()
- ))
- }
- SwitchResult::CreatedWorktree {
- path,
- created_branch,
- } => {
- let green = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
- let green_bold = green.bold();
-
- let msg = if *created_branch {
- format!(
- "✅ {green}Created new worktree for {green_bold}{branch}{green_bold:#}{green:#}"
- )
- } else {
- format!(
- "✅ {green}Added worktree for {green_bold}{branch}{green_bold:#}{green:#}"
- )
- };
- Some(format!("__WORKTRUNK_CD__{}\n{}", path.display(), msg))
+ }
}
}
}
@@ -216,6 +214,8 @@ impl RemoveResult {
}
/// Format the result for shell integration (internal mode)
+ ///
+ /// Directives are NUL-terminated for consistency with switch command.
pub fn format_internal_output(&self) -> Option<String> {
use anstyle::{AnsiColor, Color};
@@ -223,10 +223,13 @@ impl RemoveResult {
RemoveResult::AlreadyOnDefault(_) => None,
RemoveResult::RemovedWorktree { primary_path } => {
let green = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Green)));
- Some(format!(
- "__WORKTRUNK_CD__{}\n✅ {green}Removed worktree and returned to primary{green:#}",
- primary_path.display()
- ))
+ let mut result = format!("__WORKTRUNK_CD__{}", primary_path.display());
+ result.push('\0');
+ result.push_str(&format!(
+ "✅ {green}Removed worktree and returned to primary{green:#}"
+ ));
+ result.push('\0');
+ Some(result)
}
RemoveResult::SwitchedToDefault(_) => None,
}
@@ -237,7 +240,6 @@ pub fn handle_switch(
branch: &str,
create: bool,
base: Option<&str>,
- execute: Option<&str>,
force: bool,
config: &WorktrunkConfig,
) -> Result<SwitchResult, GitError> {
@@ -264,9 +266,6 @@ pub fn handle_switch(
// Check if worktree already exists for this branch
match repo.worktree_for_branch(branch)? {
Some(existing_path) if existing_path.exists() => {
- if let Some(cmd) = execute {
- execute_command_in_worktree(&existing_path, cmd)?;
- }
// Canonicalize the path for cleaner display
let canonical_existing_path = existing_path.canonicalize().unwrap_or(existing_path);
return Ok(SwitchResult::ExistingWorktree(canonical_existing_path));
@@ -315,14 +314,9 @@ pub fn handle_switch(
.canonicalize()
.unwrap_or_else(|_| worktree_path.clone());
- // Execute post-start commands from project config (before -x command)
+ // Execute post-start commands from project config
execute_post_start_commands(&canonical_path, &repo, config, branch, repo_name, force)?;
- // Execute -x command last (after setup is complete)
- if let Some(cmd) = execute {
- execute_command_in_worktree(&worktree_path, cmd)?;
- }
-
Ok(SwitchResult::CreatedWorktree {
path: canonical_path,
created_branch: create,
@@ -330,7 +324,19 @@ pub fn handle_switch(
}
/// Execute a command in the specified worktree directory
-fn execute_command_in_worktree(
+///
+/// # Security
+///
+/// This function executes arbitrary shell commands provided by the user via the -x flag.
+/// The command is passed directly to sh -c (or cmd /C on Windows) without sanitization.
+/// This is intentional - the user is executing their own commands in their own environment.
+///
+/// # Trust Model
+///
+/// - Commands originate from the user's CLI invocation (`wt switch -x "command"`)
+/// - Commands may contain newlines
+/// - The threat model assumes the user trusts their own command input
+pub fn execute_command_in_worktree(
worktree_path: &std::path::Path,
command: &str,
) -> Result<(), GitError> {
diff --git a/src/main.rs b/src/main.rs
index 5d26c8dde..5631dca8a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,6 @@
use anstyle::Style;
use clap::{CommandFactory, Parser, Subcommand};
+use std::io::Write;
use std::process;
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::GitError;
@@ -10,8 +11,9 @@ mod display;
mod llm;
use commands::{
- ConfigAction, Shell, handle_complete, handle_completion, handle_configure_shell, handle_init,
- handle_list, handle_merge, handle_push, handle_remove, handle_switch,
+ ConfigAction, Shell, execute_command_in_worktree, handle_complete, handle_completion,
+ handle_configure_shell, handle_init, handle_list, handle_merge, handle_push, handle_remove,
+ handle_switch, shell_integration_hint,
};
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
@@ -216,28 +218,48 @@ fn main() {
} => WorktrunkConfig::load()
.map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))
.and_then(|config| {
- handle_switch(
- &branch,
- create,
- base.as_deref(),
- execute.as_deref(),
- force,
- &config,
- )
- .map(|result| {
+ handle_switch(&branch, create, base.as_deref(), force, &config).and_then(|result| {
if internal {
- if let Some(output) = result.format_internal_output(&branch) {
- println!("{}", output);
+ // Internal mode: output directives for shell wrapper
+ use std::io::Write;
+ let mut stdout = std::io::stdout();
+
+ // Write CD directive
+ let _ = write!(stdout, "__WORKTRUNK_CD__{}\0", result.path().display());
+
+ // Write message
+ let _ = write!(stdout, "{}\0", result.format_message(&branch));
+
+ // If execute flag present, write EXEC directive
+ if let Some(cmd) = execute.as_deref() {
+ let _ = write!(stdout, "__WORKTRUNK_EXEC__{}\0", cmd);
+ }
+
+ // Final newline for readability in logs
+ let _ = stdout.write_all(b"\n");
+ Ok(())
+ } else {
+ // Non-internal mode: print message and execute command
+ println!("{}", result.format_message(&branch));
+
+ if let Some(cmd) = execute.as_deref() {
+ // Execute command after showing message
+ println!();
+ execute_command_in_worktree(result.path(), cmd)?;
+ } else {
+ // Show shell integration hint if no command to execute
+ println!("{}", shell_integration_hint());
}
- } else if let Some(output) = result.format_user_output(&branch) {
- println!("{}", output);
+ Ok(())
}
})
}),
Commands::Remove { internal } => handle_remove().map(|result| {
if internal {
if let Some(output) = result.format_internal_output() {
- println!("{}", output);
+ // Use write! to preserve NUL bytes
+ let _ = std::io::stdout().write_all(output.as_bytes());
+ let _ = std::io::stdout().write_all(b"\n");
}
} else if let Some(output) = result.format_user_output() {
println!("{}", output);
diff --git a/templates/bash.sh b/templates/bash.sh
index 3cf10540e..5ecffd204 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -2,22 +2,52 @@
# Only initialize if wt is available
if command -v wt >/dev/null 2>&1; then
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
+ _WORKTRUNK_CMD="${WORKTRUNK_BIN:-wt}"
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
-
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
+ local exec_cmd="" chunk exit_code
+ local exit_code_file
+ exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }
+
+ # Parse output directly from wt (command substitution strips NUL bytes!)
+ # Use process substitution to preserve NUL bytes
+ # Write exit code to temp file since it can't be captured from process substitution
+ # The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)
+ while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do
+ if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then
+ # CD directive - extract path and change directory
+ local path="${chunk#__WORKTRUNK_CD__}"
+ \cd "$path"
+ elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
+ # EXEC directive - extract command (may contain newlines)
+ exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- # Regular output - print it
- echo "$line"
+ # Regular output - print it (preserving newlines)
+ printf '%s' "$chunk"
+ fi
+ done < <(command "$_WORKTRUNK_CMD" "$@" 2>&1; echo "$?" > "$exit_code_file")
+
+ # Read exit code from temp file
+ exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)
+
+ # Cleanup temp file
+ \rm -f "$exit_code_file"
+
+ # Execute command if one was specified
+ # Security: Command is user-provided from -x flag; eval is intentional.
+ # NUL-termination allows multi-line commands.
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if [[ -n "$exec_cmd" ]]; then
+ if ! eval "$exec_cmd"; then
+ echo "Warning: Command execution failed (exit code $?)" >&2
fi
- done <<< "$output"
+ fi
return $exit_code
}
@@ -34,7 +64,7 @@ if command -v wt >/dev/null 2>&1; then
;;
*)
# All other commands pass through directly
- command wt "$@"
+ command "$_WORKTRUNK_CMD" "$@"
;;
esac
}
@@ -44,7 +74,7 @@ if command -v wt >/dev/null 2>&1; then
local cur="${COMP_WORDS[COMP_CWORD]}"
# Call wt complete with current command line
- local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)
COMPREPLY=($(compgen -W "$completions" -- "$cur"))
}
diff --git a/templates/elvish.elv b/templates/elvish.elv
index fa26b0e08..5bd4cf79a 100644
--- a/templates/elvish.elv
+++ b/templates/elvish.elv
@@ -2,32 +2,50 @@
# Only initialize if wt is available
if (has-external wt) {
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: set E:WORKTRUNK_BIN = ./target/debug/wt
+ var _WORKTRUNK_CMD = wt
+ if (has-env WORKTRUNK_BIN) {
+ set _WORKTRUNK_CMD = $E:WORKTRUNK_BIN
+ }
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
fn _wt_exec {|@args|
var exit-code = 0
var output = ""
+ var exec-cmd = ""
# Capture output and handle potential non-zero exit
+ # TODO: Capture actual exit code from wt command, not just success/failure
try {
- set output = (e:wt $@args 2>&1 | slurp)
+ set output = (e:$_WORKTRUNK_CMD $@args 2>&1 | slurp)
} catch e {
set exit-code = 1
set output = $e[reason][content]
}
- # Parse output line by line
- var lines = [(str:split "\n" $output)]
- for line $lines {
- if (str:has-prefix $line "__WORKTRUNK_CD__") {
- # Extract path and change directory
- var path = (str:trim-prefix $line "__WORKTRUNK_CD__")
+ # Split output on NUL bytes, process each chunk
+ var chunks = [(str:split "\x00" $output)]
+ for chunk $chunks {
+ if (str:has-prefix $chunk "__WORKTRUNK_CD__") {
+ # CD directive - extract path and change directory
+ var path = (str:trim-prefix $chunk "__WORKTRUNK_CD__")
cd $path
- } else {
- # Regular output - print it
- echo $line
+ } elif (str:has-prefix $chunk "__WORKTRUNK_EXEC__") {
+ # EXEC directive - extract command (may contain newlines)
+ set exec-cmd = (str:trim-prefix $chunk "__WORKTRUNK_EXEC__")
+ } elif (!=s $chunk "") {
+ # Regular output - print it (preserving newlines)
+ print $chunk
}
}
+ # Execute command if one was specified
+ if (!=s $exec-cmd "") {
+ eval $exec-cmd
+ }
+
# Return exit code (will throw exception if non-zero)
if (!=s $exit-code 0) {
fail "command failed with exit code "$exit-code
@@ -37,7 +55,7 @@ if (has-external wt) {
# Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
fn {{ cmd_prefix }} {|@args|
if (== (count $args) 0) {
- e:wt
+ e:$_WORKTRUNK_CMD
return
}
@@ -49,7 +67,7 @@ if (has-external wt) {
_wt_exec $subcommand --internal $@rest-args
} else {
# All other commands pass through directly
- e:wt $@args
+ e:$_WORKTRUNK_CMD $@args
}
}
}
diff --git a/templates/fish.fish b/templates/fish.fish
index 3eb1f77e5..1f5ee7b7a 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -2,19 +2,59 @@
# Only initialize if {{ cmd_prefix }} is available
if type -q {{ cmd_prefix }}
+ # Use WORKTRUNK_BIN if set, otherwise default to '{{ cmd_prefix }}'
+ # This allows testing development builds: set -x WORKTRUNK_BIN ./target/debug/wt
+ if set -q WORKTRUNK_BIN
+ set -g _WORKTRUNK_CMD $WORKTRUNK_BIN
+ else
+ set -g _WORKTRUNK_CMD {{ cmd_prefix }}
+ end
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
+ #
+ # Note: Uses psub for process substitution to preserve NUL bytes.
+ # This is reliable for simple read-only cases but psub has known
+ # limitations in complex scenarios (see fish-shell issue #1040).
+ # Current usage is safe as we only read from psub output sequentially.
function _wt_exec
- set -l output (command {{ cmd_prefix }} $argv 2>&1)
- set -l exit_code $status
-
- # Parse output line by line
- for line in (string split \n -- $output)
- if string match -q '__WORKTRUNK_CD__*' -- $line
- # Extract path and change directory
- cd (string replace '__WORKTRUNK_CD__' '' -- $line)
- else
- # Regular output - print it
- echo $line
+ set -l exec_cmd ""
+ set -l exit_code_file (mktemp)
+ or begin
+ echo "Failed to create temp file" >&2
+ return 1
+ end
+
+ # Use psub (process substitution) to preserve NUL bytes
+ # Command substitution $(...) strips NUL bytes, but psub preserves them
+ # Redirect directly from psub output, and save exit code to temp file
+ while read -z chunk
+ if string match -q '__WORKTRUNK_CD__*' -- $chunk
+ # CD directive - extract path and change directory
+ set -l path (string replace '__WORKTRUNK_CD__' '' -- $chunk)
+ if not cd $path
+ echo "Error: Failed to change directory to $path" >&2
+ end
+ else if string match -q '__WORKTRUNK_EXEC__*' -- $chunk
+ # EXEC directive - extract command (may contain newlines)
+ set exec_cmd (string replace '__WORKTRUNK_EXEC__' '' -- $chunk)
+ else if test -n "$chunk"
+ # Regular output - print it (preserving newlines)
+ printf '%s' $chunk
+ end
+ end < (begin; command $_WORKTRUNK_CMD $argv 2>&1; echo $status > $exit_code_file; end | psub)
+
+ # Read exit code from temp file
+ set -l exit_code (cat $exit_code_file 2>/dev/null; or echo 0)
+ rm -f $exit_code_file
+
+ # Execute command if one was specified
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if test -n "$exec_cmd"
+ if not eval $exec_cmd
+ echo "Warning: Command execution failed (exit code $status)" >&2
end
end
@@ -31,7 +71,7 @@ if type -q {{ cmd_prefix }}
_wt_exec $subcommand --internal $argv[2..-1]
case '*'
# All other commands pass through directly
- command {{ cmd_prefix }} $argv
+ command $_WORKTRUNK_CMD $argv
end
end
@@ -39,7 +79,7 @@ if type -q {{ cmd_prefix }}
function __{{ cmd_prefix }}_complete
# Call {{ cmd_prefix }} complete with current command line
set -l cmd (commandline -opc)
- command {{ cmd_prefix }} complete $cmd 2>/dev/null
+ command $_WORKTRUNK_CMD complete $cmd 2>/dev/null
end
# Register dynamic completions
diff --git a/templates/nushell.nu b/templates/nushell.nu
index 7abdd935f..f50973948 100644
--- a/templates/nushell.nu
+++ b/templates/nushell.nu
@@ -2,23 +2,38 @@
# Only initialize if wt is available
if (which wt | is-not-empty) {
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: $env.WORKTRUNK_BIN = ./target/debug/wt
+ let _WORKTRUNK_CMD = (if ($env.WORKTRUNK_BIN? | is-not-empty) { $env.WORKTRUNK_BIN } else { "wt" })
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
export def --env _wt_exec [...args] {
- let result = (do { ^wt ...$args } | complete)
+ let result = (do { ^$_WORKTRUNK_CMD ...$args } | complete)
+ mut exec_cmd = ""
- # Parse output line by line
- let lines = ($result.stdout | lines)
- for line in $lines {
- if ($line | str starts-with "__WORKTRUNK_CD__") {
- # Extract path and change directory
- let path = ($line | str substring 16..)
+ # Split output on NUL bytes, process each chunk
+ for chunk in ($result.stdout | split row "\u{0000}") {
+ if ($chunk | str starts-with "__WORKTRUNK_CD__") {
+ # CD directive - extract path and change directory
+ # TODO: Use str replace instead of hard-coded offset (fragile if prefix changes)
+ let path = ($chunk | str substring 16..)
cd $path
- } else {
- # Regular output - print it
- print $line
+ } else if ($chunk | str starts-with "__WORKTRUNK_EXEC__") {
+ # EXEC directive - extract command (may contain newlines)
+ # TODO: Use str replace instead of hard-coded offset (fragile if prefix changes)
+ $exec_cmd = ($chunk | str substring 18..)
+ } else if ($chunk | str length) > 0 {
+ # Regular output - print it (preserving newlines)
+ print -n $chunk
}
}
+ # Execute command if one was specified
+ if ($exec_cmd != "") {
+ nu -c $exec_cmd
+ }
+
# Return the exit code
return $result.exit_code
}
@@ -38,7 +53,7 @@ if (which wt | is-not-empty) {
}
_ => {
# All other commands pass through directly
- ^wt ...$rest
+ ^$_WORKTRUNK_CMD ...$rest
}
}
}
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index f2ab20584..3101818c0 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -2,7 +2,12 @@
# Only initialize if wt is available
if (Get-Command wt -ErrorAction SilentlyContinue) {
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: $env:WORKTRUNK_BIN = "./target/debug/wt"
+ $script:_WORKTRUNK_CMD = if ($env:WORKTRUNK_BIN) { $env:WORKTRUNK_BIN } else { "wt" }
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
function _wt_exec {
param(
[Parameter(ValueFromRemainingArguments=$true)]
@@ -10,20 +15,31 @@ if (Get-Command wt -ErrorAction SilentlyContinue) {
)
# Capture output and exit code
- $output = & wt @Arguments 2>&1
+ $output = & $script:_WORKTRUNK_CMD @Arguments 2>&1 | Out-String
$exitCode = $LASTEXITCODE
+ $execCmd = ""
- # Parse output line by line
- foreach ($line in $output) {
- if ($line -match '^__WORKTRUNK_CD__(.+)$') {
- # Extract path and change directory
- Set-Location $matches[1]
- } else {
- # Regular output - write it
- Write-Output $line
+ # Split output on NUL bytes, process each chunk
+ foreach ($chunk in ($output -split "`0")) {
+ if ($chunk -match '^__WORKTRUNK_CD__') {
+ # CD directive - extract path and change directory
+ $path = $chunk -replace '^__WORKTRUNK_CD__', ''
+ Set-Location $path
+ } elseif ($chunk -match '^__WORKTRUNK_EXEC__') {
+ # EXEC directive - extract command (may contain newlines)
+ $execCmd = $chunk -replace '^__WORKTRUNK_EXEC__', ''
+ } elseif ($chunk) {
+ # Regular output - write it (preserving newlines)
+ # TODO: Use Write-Output instead of Write-Host for redirectable output
+ Write-Host -NoNewline $chunk
}
}
+ # Execute command if one was specified
+ if ($execCmd) {
+ Invoke-Expression $execCmd
+ }
+
# Return the exit code
return $exitCode
}
@@ -36,7 +52,7 @@ if (Get-Command wt -ErrorAction SilentlyContinue) {
)
if ($Arguments.Count -eq 0) {
- & wt
+ & $script:_WORKTRUNK_CMD
return $LASTEXITCODE
}
@@ -51,7 +67,7 @@ if (Get-Command wt -ErrorAction SilentlyContinue) {
}
default {
# All other commands pass through directly
- & wt @Arguments
+ & $script:_WORKTRUNK_CMD @Arguments
return $LASTEXITCODE
}
}
diff --git a/templates/xonsh.xsh b/templates/xonsh.xsh
index c60361360..da031239b 100644
--- a/templates/xonsh.xsh
+++ b/templates/xonsh.xsh
@@ -2,31 +2,48 @@
# Only initialize if wt is available
import shutil
+import os
if shutil.which("wt") is not None:
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: $WORKTRUNK_BIN = ./target/debug/wt
+ _WORKTRUNK_CMD = os.environ.get('WORKTRUNK_BIN', 'wt')
+
def _wt_exec(args):
- """Helper function to parse wt output and handle directives"""
+ """Helper function to parse wt output and handle directives
+ Directives are NUL-terminated to support multi-line commands"""
# Capture full output including return code
- result = !(wt @(args))
+ result = ![@(_WORKTRUNK_CMD) @(args)]
+ exec_cmd = ""
- # Parse output line by line
+ # Split output on NUL bytes, process each chunk
if result.out:
- for line in result.out.splitlines():
- if line.startswith("__WORKTRUNK_CD__"):
- # Extract path and change directory
- path = line[17:] # Remove prefix
+ for chunk in result.out.split("\0"):
+ if chunk.startswith("__WORKTRUNK_CD__"):
+ # CD directive - extract path and change directory
+ # TODO: Use str.replace instead of hard-coded offset (fragile if prefix changes)
+ path = chunk[16:] # Remove prefix
cd @(path)
- else:
- # Regular output - print it
- print(line)
+ elif chunk.startswith("__WORKTRUNK_EXEC__"):
+ # EXEC directive - extract command (may contain newlines)
+ # TODO: Use str.replace instead of hard-coded offset (fragile if prefix changes)
+ exec_cmd = chunk[18:] # Remove prefix
+ elif chunk:
+ # Regular output - print it (preserving newlines)
+ print(chunk, end='')
+
+ # Execute command if one was specified
+ if exec_cmd:
+ execx(exec_cmd)
# Return the exit code
+ # TODO: Add fallback for None: return result.returncode or 0
return result.returncode
def _{{ cmd_prefix }}_wrapper(args):
"""Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge"""
if not args:
# No arguments, just run wt
- wt
+ ![@(_WORKTRUNK_CMD)]
return
subcommand = args[0]
@@ -37,7 +54,7 @@ if shutil.which("wt") is not None:
return _wt_exec([subcommand, "--internal"] + rest_args)
else:
# All other commands pass through directly
- result = !(wt @(args))
+ result = ![@(_WORKTRUNK_CMD) @(args)]
return result.returncode
# Register the alias
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 574e2dbac..88863dae3 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -96,6 +96,29 @@ fn test_switch_existing_worktree_internal() {
);
}
+#[test]
+fn test_switch_internal_with_execute() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ #[cfg(not(target_os = "windows"))]
+ let execute_cmd = "echo 'line1'\necho 'line2'";
+ #[cfg(target_os = "windows")]
+ let execute_cmd = "echo line1 && echo line2";
+
+ snapshot_switch(
+ "switch_internal_with_execute",
+ &repo,
+ &[
+ "--create",
+ "--internal",
+ "exec-internal",
+ "--execute",
+ execute_cmd,
+ ],
+ );
+}
+
#[test]
fn test_switch_error_missing_worktree_directory() {
let mut repo = TestRepo::new();
@@ -173,3 +196,21 @@ fn test_switch_execute_with_existing_worktree() {
&["existing-exec", "--execute", create_file_cmd],
);
}
+
+#[test]
+fn test_switch_execute_multiline() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Test multi-line command execution
+ #[cfg(target_os = "windows")]
+ let multiline_cmd = "echo line1\r\necho line2\r\necho line3";
+ #[cfg(not(target_os = "windows"))]
+ let multiline_cmd = "echo 'line1'\necho 'line2'\necho 'line3'";
+
+ snapshot_switch(
+ "switch_execute_multiline",
+ &repo,
+ &["--create", "multiline-test", "--execute", multiline_cmd],
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 40b703b48..14df1811e 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -23,22 +23,52 @@ exit_code: 0
# Only initialize if wt is available
if command -v wt >/dev/null 2>&1; then
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
+ _WORKTRUNK_CMD="${WORKTRUNK_BIN:-wt}"
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
+ local exec_cmd="" chunk exit_code
+ local exit_code_file
+ exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
+ # Parse output directly from wt (command substitution strips NUL bytes!)
+ # Use process substitution to preserve NUL bytes
+ # Write exit code to temp file since it can't be captured from process substitution
+ # The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)
+ while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do
+ if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then
+ # CD directive - extract path and change directory
+ local path="${chunk#__WORKTRUNK_CD__}"
+ \cd "$path"
+ elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
+ # EXEC directive - extract command (may contain newlines)
+ exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- # Regular output - print it
- echo "$line"
+ # Regular output - print it (preserving newlines)
+ printf '%s' "$chunk"
+ fi
+ done < <(command "$_WORKTRUNK_CMD" "$@" 2>&1; echo "$?" > "$exit_code_file")
+
+ # Read exit code from temp file
+ exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)
+
+ # Cleanup temp file
+ \rm -f "$exit_code_file"
+
+ # Execute command if one was specified
+ # Security: Command is user-provided from -x flag; eval is intentional.
+ # NUL-termination allows multi-line commands.
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if [[ -n "$exec_cmd" ]]; then
+ if ! eval "$exec_cmd"; then
+ echo "Warning: Command execution failed (exit code $?)" >&2
fi
- done <<< "$output"
+ fi
return $exit_code
}
@@ -55,7 +85,7 @@ if command -v wt >/dev/null 2>&1; then
;;
*)
# All other commands pass through directly
- command wt "$@"
+ command "$_WORKTRUNK_CMD" "$@"
;;
esac
}
@@ -65,7 +95,7 @@ if command -v wt >/dev/null 2>&1; then
local cur="${COMP_WORDS[COMP_CWORD]}"
# Call wt complete with current command line
- local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)
COMPREPLY=($(compgen -W "$completions" -- "$cur"))
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
index 601f95e4a..c66ef9334 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
@@ -25,22 +25,52 @@ exit_code: 0
# Only initialize if wt is available
if command -v wt >/dev/null 2>&1; then
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
+ _WORKTRUNK_CMD="${WORKTRUNK_BIN:-wt}"
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
+ local exec_cmd="" chunk exit_code
+ local exit_code_file
+ exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
+ # Parse output directly from wt (command substitution strips NUL bytes!)
+ # Use process substitution to preserve NUL bytes
+ # Write exit code to temp file since it can't be captured from process substitution
+ # The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)
+ while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do
+ if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then
+ # CD directive - extract path and change directory
+ local path="${chunk#__WORKTRUNK_CD__}"
+ \cd "$path"
+ elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
+ # EXEC directive - extract command (may contain newlines)
+ exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- # Regular output - print it
- echo "$line"
+ # Regular output - print it (preserving newlines)
+ printf '%s' "$chunk"
+ fi
+ done < <(command "$_WORKTRUNK_CMD" "$@" 2>&1; echo "$?" > "$exit_code_file")
+
+ # Read exit code from temp file
+ exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)
+
+ # Cleanup temp file
+ \rm -f "$exit_code_file"
+
+ # Execute command if one was specified
+ # Security: Command is user-provided from -x flag; eval is intentional.
+ # NUL-termination allows multi-line commands.
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if [[ -n "$exec_cmd" ]]; then
+ if ! eval "$exec_cmd"; then
+ echo "Warning: Command execution failed (exit code $?)" >&2
fi
- done <<< "$output"
+ fi
return $exit_code
}
@@ -57,7 +87,7 @@ if command -v wt >/dev/null 2>&1; then
;;
*)
# All other commands pass through directly
- command wt "$@"
+ command "$_WORKTRUNK_CMD" "$@"
;;
esac
}
@@ -67,7 +97,7 @@ if command -v wt >/dev/null 2>&1; then
local cur="${COMP_WORDS[COMP_CWORD]}"
# Call wt complete with current command line
- local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)
COMPREPLY=($(compgen -W "$completions" -- "$cur"))
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 7eb0a0934..03d358b8f 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -23,19 +23,59 @@ exit_code: 0
# Only initialize if wt is available
if type -q wt
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: set -x WORKTRUNK_BIN ./target/debug/wt
+ if set -q WORKTRUNK_BIN
+ set -g _WORKTRUNK_CMD $WORKTRUNK_BIN
+ else
+ set -g _WORKTRUNK_CMD wt
+ end
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
+ #
+ # Note: Uses psub for process substitution to preserve NUL bytes.
+ # This is reliable for simple read-only cases but psub has known
+ # limitations in complex scenarios (see fish-shell issue #1040).
+ # Current usage is safe as we only read from psub output sequentially.
function _wt_exec
- set -l output (command wt $argv 2>&1)
- set -l exit_code $status
+ set -l exec_cmd ""
+ set -l exit_code_file (mktemp)
+ or begin
+ echo "Failed to create temp file" >&2
+ return 1
+ end
+
+ # Use psub (process substitution) to preserve NUL bytes
+ # Command substitution $(...) strips NUL bytes, but psub preserves them
+ # Redirect directly from psub output, and save exit code to temp file
+ while read -z chunk
+ if string match -q '__WORKTRUNK_CD__*' -- $chunk
+ # CD directive - extract path and change directory
+ set -l path (string replace '__WORKTRUNK_CD__' '' -- $chunk)
+ if not cd $path
+ echo "Error: Failed to change directory to $path" >&2
+ end
+ else if string match -q '__WORKTRUNK_EXEC__*' -- $chunk
+ # EXEC directive - extract command (may contain newlines)
+ set exec_cmd (string replace '__WORKTRUNK_EXEC__' '' -- $chunk)
+ else if test -n "$chunk"
+ # Regular output - print it (preserving newlines)
+ printf '%s' $chunk
+ end
+ end < (begin; command $_WORKTRUNK_CMD $argv 2>&1; echo $status > $exit_code_file; end | psub)
+
+ # Read exit code from temp file
+ set -l exit_code (cat $exit_code_file 2>/dev/null; or echo 0)
+ rm -f $exit_code_file
- # Parse output line by line
- for line in (string split \n -- $output)
- if string match -q '__WORKTRUNK_CD__*' -- $line
- # Extract path and change directory
- cd (string replace '__WORKTRUNK_CD__' '' -- $line)
- else
- # Regular output - print it
- echo $line
+ # Execute command if one was specified
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if test -n "$exec_cmd"
+ if not eval $exec_cmd
+ echo "Warning: Command execution failed (exit code $status)" >&2
end
end
@@ -52,7 +92,7 @@ if type -q wt
_wt_exec $subcommand --internal $argv[2..-1]
case '*'
# All other commands pass through directly
- command wt $argv
+ command $_WORKTRUNK_CMD $argv
end
end
@@ -60,7 +100,7 @@ if type -q wt
function __wt_complete
# Call wt complete with current command line
set -l cmd (commandline -opc)
- command wt complete $cmd 2>/dev/null
+ command $_WORKTRUNK_CMD complete $cmd 2>/dev/null
end
# Register dynamic completions
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index f972cc615..845605964 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -23,22 +23,52 @@ exit_code: 0
# Only initialize if wt is available
if command -v wt >/dev/null 2>&1; then
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
+ _WORKTRUNK_CMD="${WORKTRUNK_BIN:-wt}"
+
# Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
+ local exec_cmd="" chunk exit_code
+ local exit_code_file
+ exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
+ # Parse output directly from wt (command substitution strips NUL bytes!)
+ # Use process substitution to preserve NUL bytes
+ # Write exit code to temp file since it can't be captured from process substitution
+ # The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)
+ while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do
+ if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then
+ # CD directive - extract path and change directory
+ local path="${chunk#__WORKTRUNK_CD__}"
+ \cd "$path"
+ elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
+ # EXEC directive - extract command (may contain newlines)
+ exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
else
- # Regular output - print it
- echo "$line"
+ # Regular output - print it (preserving newlines)
+ printf '%s' "$chunk"
+ fi
+ done < <(command "$_WORKTRUNK_CMD" "$@" 2>&1; echo "$?" > "$exit_code_file")
+
+ # Read exit code from temp file
+ exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)
+
+ # Cleanup temp file
+ \rm -f "$exit_code_file"
+
+ # Execute command if one was specified
+ # Security: Command is user-provided from -x flag; eval is intentional.
+ # NUL-termination allows multi-line commands.
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if [[ -n "$exec_cmd" ]]; then
+ if ! eval "$exec_cmd"; then
+ echo "Warning: Command execution failed (exit code $?)" >&2
fi
- done <<< "$output"
+ fi
return $exit_code
}
@@ -55,7 +85,7 @@ if command -v wt >/dev/null 2>&1; then
;;
*)
# All other commands pass through directly
- command wt "$@"
+ command "$_WORKTRUNK_CMD" "$@"
;;
esac
}
@@ -65,7 +95,7 @@ if command -v wt >/dev/null 2>&1; then
local cur="${COMP_WORDS[COMP_CWORD]}"
# Call wt complete with current command line
- local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)
COMPREPLY=($(compgen -W "$completions" -- "$cur"))
}
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_empty_array.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_empty_array.snap
index 8c438a5fb..f7f86c151 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_empty_array.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_empty_array.snap
@@ -23,6 +23,7 @@ exit_code: 0
✅ Created new worktree for feature
Path: [REPO].feature
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap
index 6f33837ab..6e5fd1290 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap
@@ -13,7 +13,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUmUbSm
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpQrrlBo
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -24,6 +24,7 @@ exit_code: 0
✅ Created new worktree for feature
Path: [REPO].feature
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snap
index 64c63a665..6d96b1fe3 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snap
@@ -23,6 +23,7 @@ exit_code: 0
✅ Created new worktree for feature
Path: [REPO].feature
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snap
index c39f47f06..c64ca729e 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snap
@@ -13,7 +13,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpwTEnNd
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp5RmQcF
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -26,6 +26,7 @@ Second
✅ Created new worktree for feature
Path: [REPO].feature
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snap
index 8c438a5fb..f7f86c151 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snap
@@ -23,6 +23,7 @@ exit_code: 0
✅ Created new worktree for feature
Path: [REPO].feature
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap
index 961764fce..b7f0c7947 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap
@@ -13,7 +13,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIvjDOu
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpiJeZmq
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -24,6 +24,7 @@ exit_code: 0
✅ Created new worktree for feature/test
Path: [REPO].feature-test
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snap
index fa4951199..af794d2a8 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snap
@@ -13,7 +13,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpo8Mro1
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0AL9rq
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -25,6 +25,7 @@ Setup complete
✅ Created new worktree for feature
Path: [REPO].feature
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap
index b93f8f7ab..c8aacb5a9 100644
Binary files a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap and b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap differ
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_base_without_create.snap b/tests/snapshots/integration__integration_tests__switch__switch_base_without_create.snap
index edb3507bf..550d3c88e 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_base_without_create.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_base_without_create.snap
@@ -24,7 +24,6 @@ exit_code: 0
✅ Switched to worktree for main
-
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap b/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap
index bcc9a2884..c29020bed 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_create_new.snap
@@ -23,6 +23,7 @@ exit_code: 0
✅ Created new worktree for feature-x
Path: [REPO].feature-x
+
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snap
index 801fb76bc..6641981c7 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snap
@@ -25,6 +25,5 @@ exit_code: 0
✅ Created new worktree for file-test
Path: [REPO].file-test
-To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snap
index e2b59454f..cd0a72c3f 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snap
@@ -24,7 +24,4 @@ exit_code: 0
✅ Switched to worktree for existing-exec
-
-To enable automatic cd, run: wt configure-shell
-
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
index 90586b009..88f0be6c4 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
@@ -22,6 +22,9 @@ info:
success: false
exit_code: 1
----- stdout -----
+✅ Created new worktree for fail-test
+ Path: [REPO].fail-test
+
----- stderr -----
Command 'exit 1' failed with exit code 1
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_multiline.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_multiline.snap
new file mode 100644
index 000000000..79b57c68e
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_multiline.snap
@@ -0,0 +1,32 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - multiline-test
+ - "--execute"
+ - "echo 'line1'\necho 'line2'\necho 'line3'"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+✅ Created new worktree for multiline-test
+ Path: [REPO].multiline-test
+
+line1
+line2
+line3
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snap
index 59550d6d5..6d7e1a7db 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snap
@@ -22,10 +22,9 @@ info:
success: true
exit_code: 0
----- stdout -----
-test output
✅ Created new worktree for exec-test
Path: [REPO].exec-test
-To enable automatic cd, run: wt configure-shell
+test output
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_existing_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_existing_branch.snap
index 0167acb00..e1fd2feeb 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_existing_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_existing_branch.snap
@@ -22,7 +22,6 @@ exit_code: 0
✅ Switched to worktree for feature-z
-
To enable automatic cd, run: wt configure-shell
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap
index cb459b402..c18b6f2e8 100644
Binary files a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap and b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap differ
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap
index a371418dc..a2fcb0a37 100644
Binary files a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap and b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap differ
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap
new file mode 100644
index 000000000..60c0b09e8
Binary files /dev/null and b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap differ
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap
index 735428af2..4912b99e6 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_base.snap
@@ -25,6 +25,7 @@ exit_code: 0
✅ Created new worktree for feature-with-base
Path: [REPO].feature-with-base
+
To enable automatic cd, run: wt configure-shell
----- stderr -----