Skip to content

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

Run switch --execute as literal argv (#3977)

Maximilian Roosbaf161bf60a5
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.md
index e71878ffd..38d55bfbd 100644
--- a/.claude/skills/writing-user-outputs/SKILL.md
+++ b/.claude/skills/writing-user-outputs/SKILL.md
@@ -9,16 +9,15 @@ metadata:
## Shell Integration
-Worktrunk uses split file-based directive passing for shell integration:
+Worktrunk uses one file-based directive for shell integration:
-1. Shell wrapper creates two temp files via `mktemp` (cd and exec)
-2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
-3. wt writes a raw path to the CD file; shell commands to the EXEC file (for `--execute`)
-4. Shell wrapper reads the CD file with `cd -- "$(< file)"` (no shell parsing)
-5. Shell wrapper sources the EXEC file if non-empty
+1. Shell wrapper creates a temp file via `mktemp`
+2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_CD_FILE`
+3. wt writes a raw path to the file
+4. Shell wrapper changes directory to that path after wt exits
-When neither directive env var is set (direct binary call), commands execute
-directly and shell integration hints are shown.
+`--execute` always launches its external program directly from wt, with the
+selected worktree as its working directory. It does not use a directive.
## Output Functions
@@ -110,7 +109,7 @@ is what a shell loop reads.
| Function | Purpose |
|----------|---------|
| `change_directory(path)` | Shell cd after wt exits (writes to directive file if set) |
-| `execute(command)` | Shell command after wt exits |
+| `execute(argv)` | Run an external program in the selected worktree |
| `terminate_output()` | Reset ANSI state on stderr |
| `is_shell_integration_active()` | Check if directive file set (rarely needed) |
| `pre_hook_display_path(path)` | Compute display path for pre-hooks |
@@ -147,7 +146,7 @@ format_heading("USER CONFIG", Some("@ ~/.config/wt.toml"))
- **stdout** → the answer, in whatever format the user selected. Data (tables, JSON, shell code, an expanded template) and `--dry-run` previews both qualify: a preview is the whole answer when nothing mutates. Human-formatted output belongs here too. Color strips automatically on a pipe (anstream), so `wt list | grep` stays safe.
- **stderr** → narration about doing it: progress, success/warning/error messages, hints, interactive prompts, and `-v`/`-vv` diagnostics.
-- **directive file** → shell commands executed after wt exits (cd, exec).
+- **directive file** → the raw cd path consumed after wt exits.
The same line can flip streams between modes. `wt config shell uninstall` deletes the file, so `✓ Removed … @ ~/.zshrc` only narrates a side effect that already happened → stderr (the edited file is the answer; stdout is empty). `wt config shell uninstall --dry-run` mutates nothing, so `○ Will remove … @ ~/.zshrc` is the only answer there is → stdout. What flips isn't the wording, it's whether a side effect exists to be the answer.
@@ -179,18 +178,13 @@ pager fails.
## Security
-The split-trust design enforces two trust levels:
-
- `WORKTRUNK_DIRECTIVE_CD_FILE` holds a raw path (no shell parsing), so it's
safe to pass through to alias/hook child processes — a body that writes to it
can at worst redirect `cd`.
-- `WORKTRUNK_DIRECTIVE_EXEC_FILE` holds arbitrary shell that the wrapper
- sources verbatim, so wt scrubs this env var from alias/hook child processes.
- A hook body writing to it would inject shell into the parent session.
All directive env vars are removed from spawned subprocesses by default via
`shell_exec::scrub_directive_env_vars()`. `DirectivePassthrough::inherit_from_env()`
-re-adds only the CD file for trusted contexts.
+re-adds the CD file where a nested command may redirect the parent shell.
## Windows Compatibility (Git Bash / MSYS2)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9543d0815..8198c2d75 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@
### Improved
+- **`wt switch --execute` launches argv directly instead of parsing a shell command**: `-x` now names one external program and arguments after `--` go directly to it without Worktrunk shell parsing. Program lookup and argument decoding follow the operating system; on Windows, shell shims such as `code` need their `.cmd` extension or an explicit `cmd.exe /C`. Shell syntax remains available explicitly with `-x sh -- -c '…'`. Worktrunk starts the program in the selected worktree, so wrappers need no exec channel and Nushell needs no implicit `sh`. A live shell whose old exec-file wrapper buffers `--execute` output now warns to rerun `wt config shell install`; Nushell requires that update because its wrapper is a static file. (Breaking: pass a program name to `-x`; existing shell command strings must opt into a shell.) ([#2860](https://github.com/max-sixty/worktrunk/issues/2860), fixes [#3944](https://github.com/max-sixty/worktrunk/issues/3944))
+
- **Established automation and LLM customization interfaces are now stable**: `wt step eval`, `wt step for-each`, `wt step prune`, LLM branch summaries, `wt config state vars`, and `commit.generation.template-append` are no longer marked experimental. ([#3949](https://github.com/max-sixty/worktrunk/pull/3949))
- **Deprecated config compatibility has been removed**: `commit.generation.template-file` and `squash-template-file` are no longer supported; put the file contents in `template` or `squash-template` instead. `switch.picker.timeout-ms` now follows the generic unknown-field path instead of being removed by `wt config update`. (Breaking.) ([#3949](https://github.com/max-sixty/worktrunk/pull/3949))
@@ -24,7 +26,7 @@
- **JSON list output ignores display-column gates**: `[list] columns` no longer makes `wt list --format json` contact a forge or generate summaries. CI requires `--full`; summaries also require `[list] summary = true` and a configured generator. (Breaking: schema 1 loses config-driven `ci` and `summary` fields.) ([#3812](https://github.com/max-sixty/worktrunk/pull/3812), thanks @emeren for the request)
-- **The nushell wrapper propagates exit codes without a POSIX shell**: `wt config shell install` writes the nushell wrapper on any platform where `nu` is on PATH, but the wrapper reported a failing `wt` by spawning `sh`. On Windows, where `sh` doesn't exist, every failing command printed a nushell ``Command `sh` not found`` trace over the wrapper's own source and reported exit 1 whatever the real code was. It now re-invokes nushell itself. `--execute` bodies still need `sh`, since they are POSIX snippets by construction. ([#3945](https://github.com/max-sixty/worktrunk/pull/3945), fixes [#3944](https://github.com/max-sixty/worktrunk/issues/3944))
+- **The nushell wrapper propagates command failures without a POSIX shell**: `wt config shell install` writes the nushell wrapper on any platform where `nu` is on PATH, but the wrapper reported a failing `wt` by spawning `sh`. On Windows, where `sh` doesn't exist, every failing command printed a nushell ``Command `sh` not found`` trace over the wrapper's own source and reported exit 1 whatever the real code was. It now re-invokes nushell itself. ([#3945](https://github.com/max-sixty/worktrunk/pull/3945))
- **Long Windows paths compare consistently**: paths beyond 260 characters could retain a `\\?\` prefix and appear to be on another drive. `copy-ignored` then refused them, while switch, remove, merge, and relocate landed at the worktree root instead of the original subdirectory. ([#3899](https://github.com/max-sixty/worktrunk/pull/3899), fixes [#3898](https://github.com/max-sixty/worktrunk/issues/3898), thanks @Persedes for reporting and verifying the fix)
diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.md
index e9961a34b..b0a22c9e6 100644
--- a/docs/src/content/docs/config.md
+++ b/docs/src/content/docs/config.md
@@ -667,9 +667,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge
| `WORKTRUNK_PROJECT_CONFIG_PATH` | Override project config file location (defaults to `.config/wt.toml`); relative paths resolve from the worktree root |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
-| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory |
-| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |
diff --git a/docs/src/content/docs/extending.md b/docs/src/content/docs/extending.md
index 7e7482d30..4d16da16f 100644
--- a/docs/src/content/docs/extending.md
+++ b/docs/src/content/docs/extending.md
@@ -130,11 +130,11 @@ show-branches = "wt step for-each -- sh -c 'echo {% raw %}{{ branch }}{% endraw
`wt show-branches` prints each worktree's own branch.
-`wt switch --execute` defers the same way, without the extra wrapper: its `--execute '…'` argument is already a single quoted string, so only `{% raw %}` is needed. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:
+`wt switch --execute` defers the same way. `-x` names the program and arguments after `--` stay separate, so quote the deferred template as one alias-body token. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:
```toml
[aliases]
-echo-target = "wt switch {{ args }} --no-cd --execute 'echo {% raw %}{{ worktree_path }}{% endraw %}'"
+echo-target = "wt switch {{ args }} --no-cd --execute echo -- '{% raw %}{{ worktree_path }}{% endraw %}'"
```
A repo-level variable like `{{ default_branch }}` needs no deferral: it is identical in every worktree, so a bare `{{ default_branch }}` is already correct everywhere.
@@ -174,15 +174,17 @@ So the sweep exits non-zero only when it leaves a worktree needing attention —
[aliases]
move-changes = '''
if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then
- wt switch --create {{ to }} --execute="{{ args }}"
+ wt switch --create {{ to }} --execute sh -- -c \
+ 'if [ "$#" -gt 0 ]; then exec "$@"; fi' worktrunk-move {{ args }}
else
git stash push --include-untracked --quiet
- wt switch --create {{ to }} --execute="git stash pop --index; {{ args }}"
+ wt switch --create {{ to }} --execute sh -- -c \
+ 'git stash pop --index; if [ "$#" -gt 0 ]; then exec "$@"; fi' worktrunk-move {{ args }}
fi
'''
```
-Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and `--execute` pops it in the new worktree with the staged/unstaged split intact. Anything after `--` runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.
+Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and the explicit `sh -c` step pops it in the new worktree with the staged/unstaged split intact. Anything after `--` is forwarded as argv and runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.
To copy instead of move, add `git stash apply --index --quiet` right after the push.
diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.md
index cff324c8a..fb562678a 100644
--- a/docs/src/content/docs/switch.md
+++ b/docs/src/content/docs/switch.md
@@ -188,8 +188,7 @@ Arguments:
[EXECUTE_ARGS]...
Additional arguments for --execute command (after --)
- Arguments after -- are appended to the execute command. Each argument is expanded for
- templates, then POSIX shell-escaped.
+ Each argument is expanded for templates and passed directly to the program.
Options:
-c, --create
@@ -202,14 +201,17 @@ Options:
pr:{N}, mr:{N}.
-x, --execute <EXECUTE>
- Command to run after switch
+ Program to run after switch
- Replaces the wt process with the command after switching, giving it full terminal control.
- Useful for launching editors, AI agents, or other interactive tools.
+ Runs one external program after switching, with full terminal control. Arguments after --
+ go directly to that program without Worktrunk shell parsing. Program lookup and argument
+ decoding follow the operating system. Shell syntax requires an explicit shell, for example
+ -x sh -- -c 'npm install && npm test'. On Windows, shell shims need their extension (-x
+ code.cmd) or an explicit shell such as -x cmd.exe -- /C code.
Without a branch argument, the interactive picker opens and the command runs against the
selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
- there.
+ there. With --no-cd, the program starts in the invoking directory instead.
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} describe the source: the selected base with --create,
@@ -234,7 +236,7 @@ Options:
Skip directory change after switching
Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or
- for CI/automation. Use --cd to override.
+ for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.md
index fb3cd8f62..297177fb1 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/config.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md
@@ -659,9 +659,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge
| `WORKTRUNK_PROJECT_CONFIG_PATH` | Override project config file location (defaults to `.config/wt.toml`); relative paths resolve from the worktree root |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
-| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory |
-| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |
diff --git a/plugins/worktrunk/skills/worktrunk/reference/extending.md b/plugins/worktrunk/skills/worktrunk/reference/extending.md
index e2ea6a99b..e07d479a5 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/extending.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/extending.md
@@ -126,11 +126,11 @@ show-branches = "wt step for-each -- sh -c 'echo {% raw %}{{ branch }}{% endraw
`wt show-branches` prints each worktree's own branch.
-`wt switch --execute` defers the same way, without the extra wrapper: its `--execute '…'` argument is already a single quoted string, so only `{% raw %}` is needed. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:
+`wt switch --execute` defers the same way. `-x` names the program and arguments after `--` stay separate, so quote the deferred template as one alias-body token. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:
```toml
[aliases]
-echo-target = "wt switch {{ args }} --no-cd --execute 'echo {% raw %}{{ worktree_path }}{% endraw %}'"
+echo-target = "wt switch {{ args }} --no-cd --execute echo -- '{% raw %}{{ worktree_path }}{% endraw %}'"
```
A repo-level variable like `{{ default_branch }}` needs no deferral: it is identical in every worktree, so a bare `{{ default_branch }}` is already correct everywhere.
@@ -170,15 +170,17 @@ So the sweep exits non-zero only when it leaves a worktree needing attention —
[aliases]
move-changes = '''
if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then
- wt switch --create {{ to }} --execute="{{ args }}"
+ wt switch --create {{ to }} --execute sh -- -c \
+ 'if [ "$#" -gt 0 ]; then exec "$@"; fi' worktrunk-move {{ args }}
else
git stash push --include-untracked --quiet
- wt switch --create {{ to }} --execute="git stash pop --index; {{ args }}"
+ wt switch --create {{ to }} --execute sh -- -c \
+ 'git stash pop --index; if [ "$#" -gt 0 ]; then exec "$@"; fi' worktrunk-move {{ args }}
fi
'''
```
-Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and `--execute` pops it in the new worktree with the staged/unstaged split intact. Anything after `--` runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.
+Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and the explicit `sh -c` step pops it in the new worktree with the staged/unstaged split intact. Anything after `--` is forwarded as argv and runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.
To copy instead of move, add `git stash apply --index --quiet` right after the push.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md
index 615cc8fa1..1f4600db1 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md
@@ -8,11 +8,9 @@ Subprocesses cannot change the parent shell's current directory. When
`wt switch feature` runs, the `wt` binary runs as a child process and cannot
`cd` the terminal.
-Worktrunk solves this with **split directive file passing**: the shell wrapper
-creates two temp files, `wt` writes a raw path to one (cd) and shell commands
-to the other (`--execute` payloads), and the wrapper applies both after `wt`
-exits. The split design eliminates shell injection from cd directives — the CD
-file holds a raw path that is never parsed as shell. The wrapper's steps and a
+Worktrunk solves this with a file directive: the shell wrapper creates one temp
+file, `wt` writes the target directory to it, and the wrapper changes directory
+after `wt` exits. `--execute` runs directly inside wt. The wrapper's steps and a
simplified implementation: [How the Shell Wrapper
Works](#how-the-shell-wrapper-works).
@@ -55,12 +53,12 @@ When shell integration isn't working, `wt switch` shows warnings explaining why.
### "shell wrapper is out of date"
-**Meaning**: The active shell still has a pre-split wrapper loaded. Current
-versions no longer write shell commands to that wrapper's single directive
-file, because it mixes trusted directory paths with arbitrary shell.
+**Meaning**: The active shell still has a retired wrapper loaded. Current
+versions no longer write to that wrapper's single directive file, so the
+parent shell cannot follow a directory change.
**Fix**: Run `wt config shell install`, then restart the shell (or reload its
-config) to activate the current split-file wrapper.
+config) to activate the current wrapper.
### "shell integration not installed"
@@ -130,44 +128,29 @@ suggested fix.
The shell wrapper (installed by `wt config shell install`) defines a shell
function that:
-1. Creates two temp files (cd and exec)
-2. Sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
+1. Creates a temp file
+2. Sets `WORKTRUNK_DIRECTIVE_CD_FILE`
3. Runs the real `wt` binary
4. Reads the CD file with `cd -- "$(< file)"` (raw path, no shell parsing)
-5. Sources the EXEC file if non-empty (for `--execute` payloads)
-6. Cleans up both temp files
+5. Cleans up the temp file
Simplified example (actual wrapper handles completions and edge cases):
```bash
wt() {
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command wt "$@" || exit_code=$?
if [[ -s "$cd_file" ]]; then
cd -- "$(<"$cd_file")"
fi
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- fi
-
- rm -f "$cd_file" "$exec_file"
+ rm -f "$cd_file"
return "$exit_code"
}
```
-### Directive trust boundary
-
-The CD file contains only a raw path, so Worktrunk can pass it through to
-alias and hook subprocesses. The EXEC file contains shell code that the parent
-wrapper sources, so Worktrunk removes it from project-defined aliases and
-hooks. User-config aliases are the intentional exception: because their
-commands are authored by the user, they retain the EXEC file and can run a
-nested `wt switch --execute`.
-
## Debugging Checklist
### 1. Check if wrapper is installed
@@ -218,9 +201,8 @@ Should show the `eval` line with line number.
### 3. Check if directive files are set
```bash
-# After running any wt command, these should be unset (temp files deleted)
+# After running any wt command, this should be unset (temp file deleted)
echo $WORKTRUNK_DIRECTIVE_CD_FILE
-echo $WORKTRUNK_DIRECTIVE_EXEC_FILE
# During wt execution, these would be set to temp file paths
```
@@ -230,11 +212,10 @@ echo $WORKTRUNK_DIRECTIVE_EXEC_FILE
```bash
# Create temp files and test
export WORKTRUNK_DIRECTIVE_CD_FILE=$(mktemp)
-export WORKTRUNK_DIRECTIVE_EXEC_FILE=$(mktemp)
command wt switch feature
cat $WORKTRUNK_DIRECTIVE_CD_FILE # Should contain: /path/to/worktree (raw path)
cd -- "$(<$WORKTRUNK_DIRECTIVE_CD_FILE)" # Should cd you there
-rm -f $WORKTRUNK_DIRECTIVE_CD_FILE $WORKTRUNK_DIRECTIVE_EXEC_FILE
+rm -f $WORKTRUNK_DIRECTIVE_CD_FILE
```
## Common Issues
@@ -270,9 +251,7 @@ If you see path issues, ensure you're using a recent Git for Windows version.
| Variable | Purpose |
|----------|---------|
| `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 the PowerShell (`powershell`) and fish (`fish`) wrappers; selects how wt escapes the EXEC directive payload for that shell |
| `WORKTRUNK_COMPLETE_NAME` | Set by the bash, zsh, and PowerShell wrappers when they load completions; names the command the registration binds to, so `--cmd` integrations complete |
## See Also
diff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.md
index 89ecaa813..9fb48317d 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/switch.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md
@@ -162,8 +162,7 @@ Arguments:
[EXECUTE_ARGS]...
Additional arguments for --execute command (after --)
- Arguments after -- are appended to the execute command. Each argument is expanded for
- templates, then POSIX shell-escaped.
+ Each argument is expanded for templates and passed directly to the program.
Options:
-c, --create
@@ -176,14 +175,17 @@ Options:
pr:{N}, mr:{N}.
-x, --execute <EXECUTE>
- Command to run after switch
+ Program to run after switch
- Replaces the wt process with the command after switching, giving it full terminal control.
- Useful for launching editors, AI agents, or other interactive tools.
+ Runs one external program after switching, with full terminal control. Arguments after --
+ go directly to that program without Worktrunk shell parsing. Program lookup and argument
+ decoding follow the operating system. Shell syntax requires an explicit shell, for example
+ -x sh -- -c 'npm install && npm test'. On Windows, shell shims need their extension (-x
+ code.cmd) or an explicit shell such as -x cmd.exe -- /C code.
Without a branch argument, the interactive picker opens and the command runs against the
selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
- there.
+ there. With --no-cd, the program starts in the invoking directory instead.
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} describe the source: the selected base with --create,
@@ -208,7 +210,7 @@ Options:
Skip directory change after switching
Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or
- for CI/automation. Use --cd to override.
+ for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index fb3cd8f62..297177fb1 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -659,9 +659,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge
| `WORKTRUNK_PROJECT_CONFIG_PATH` | Override project config file location (defaults to `.config/wt.toml`); relative paths resolve from the worktree root |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
-| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory |
-| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |
diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.md
index e2ea6a99b..e07d479a5 100644
--- a/skills/worktrunk/reference/extending.md
+++ b/skills/worktrunk/reference/extending.md
@@ -126,11 +126,11 @@ show-branches = "wt step for-each -- sh -c 'echo {% raw %}{{ branch }}{% endraw
`wt show-branches` prints each worktree's own branch.
-`wt switch --execute` defers the same way, without the extra wrapper: its `--execute '…'` argument is already a single quoted string, so only `{% raw %}` is needed. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:
+`wt switch --execute` defers the same way. `-x` names the program and arguments after `--` stay separate, so quote the deferred template as one alias-body token. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:
```toml
[aliases]
-echo-target = "wt switch {{ args }} --no-cd --execute 'echo {% raw %}{{ worktree_path }}{% endraw %}'"
+echo-target = "wt switch {{ args }} --no-cd --execute echo -- '{% raw %}{{ worktree_path }}{% endraw %}'"
```
A repo-level variable like `{{ default_branch }}` needs no deferral: it is identical in every worktree, so a bare `{{ default_branch }}` is already correct everywhere.
@@ -170,15 +170,17 @@ So the sweep exits non-zero only when it leaves a worktree needing attention —
[aliases]
move-changes = '''
if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then
- wt switch --create {{ to }} --execute="{{ args }}"
+ wt switch --create {{ to }} --execute sh -- -c \
+ 'if [ "$#" -gt 0 ]; then exec "$@"; fi' worktrunk-move {{ args }}
else
git stash push --include-untracked --quiet
- wt switch --create {{ to }} --execute="git stash pop --index; {{ args }}"
+ wt switch --create {{ to }} --execute sh -- -c \
+ 'git stash pop --index; if [ "$#" -gt 0 ]; then exec "$@"; fi' worktrunk-move {{ args }}
fi
'''
```
-Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and `--execute` pops it in the new worktree with the staged/unstaged split intact. Anything after `--` runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.
+Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and the explicit `sh -c` step pops it in the new worktree with the staged/unstaged split intact. Anything after `--` is forwarded as argv and runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.
To copy instead of move, add `git stash apply --index --quiet` right after the push.
diff --git a/skills/worktrunk/reference/shell-integration.md b/skills/worktrunk/reference/shell-integration.md
index 615cc8fa1..1f4600db1 100644
--- a/skills/worktrunk/reference/shell-integration.md
+++ b/skills/worktrunk/reference/shell-integration.md
@@ -8,11 +8,9 @@ Subprocesses cannot change the parent shell's current directory. When
`wt switch feature` runs, the `wt` binary runs as a child process and cannot
`cd` the terminal.
-Worktrunk solves this with **split directive file passing**: the shell wrapper
-creates two temp files, `wt` writes a raw path to one (cd) and shell commands
-to the other (`--execute` payloads), and the wrapper applies both after `wt`
-exits. The split design eliminates shell injection from cd directives — the CD
-file holds a raw path that is never parsed as shell. The wrapper's steps and a
+Worktrunk solves this with a file directive: the shell wrapper creates one temp
+file, `wt` writes the target directory to it, and the wrapper changes directory
+after `wt` exits. `--execute` runs directly inside wt. The wrapper's steps and a
simplified implementation: [How the Shell Wrapper
Works](#how-the-shell-wrapper-works).
@@ -55,12 +53,12 @@ When shell integration isn't working, `wt switch` shows warnings explaining why.
### "shell wrapper is out of date"
-**Meaning**: The active shell still has a pre-split wrapper loaded. Current
-versions no longer write shell commands to that wrapper's single directive
-file, because it mixes trusted directory paths with arbitrary shell.
+**Meaning**: The active shell still has a retired wrapper loaded. Current
+versions no longer write to that wrapper's single directive file, so the
+parent shell cannot follow a directory change.
**Fix**: Run `wt config shell install`, then restart the shell (or reload its
-config) to activate the current split-file wrapper.
+config) to activate the current wrapper.
### "shell integration not installed"
@@ -130,44 +128,29 @@ suggested fix.
The shell wrapper (installed by `wt config shell install`) defines a shell
function that:
-1. Creates two temp files (cd and exec)
-2. Sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
+1. Creates a temp file
+2. Sets `WORKTRUNK_DIRECTIVE_CD_FILE`
3. Runs the real `wt` binary
4. Reads the CD file with `cd -- "$(< file)"` (raw path, no shell parsing)
-5. Sources the EXEC file if non-empty (for `--execute` payloads)
-6. Cleans up both temp files
+5. Cleans up the temp file
Simplified example (actual wrapper handles completions and edge cases):
```bash
wt() {
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command wt "$@" || exit_code=$?
if [[ -s "$cd_file" ]]; then
cd -- "$(<"$cd_file")"
fi
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- fi
-
- rm -f "$cd_file" "$exec_file"
+ rm -f "$cd_file"
return "$exit_code"
}
```
-### Directive trust boundary
-
-The CD file contains only a raw path, so Worktrunk can pass it through to
-alias and hook subprocesses. The EXEC file contains shell code that the parent
-wrapper sources, so Worktrunk removes it from project-defined aliases and
-hooks. User-config aliases are the intentional exception: because their
-commands are authored by the user, they retain the EXEC file and can run a
-nested `wt switch --execute`.
-
## Debugging Checklist
### 1. Check if wrapper is installed
@@ -218,9 +201,8 @@ Should show the `eval` line with line number.
### 3. Check if directive files are set
```bash
-# After running any wt command, these should be unset (temp files deleted)
+# After running any wt command, this should be unset (temp file deleted)
echo $WORKTRUNK_DIRECTIVE_CD_FILE
-echo $WORKTRUNK_DIRECTIVE_EXEC_FILE
# During wt execution, these would be set to temp file paths
```
@@ -230,11 +212,10 @@ echo $WORKTRUNK_DIRECTIVE_EXEC_FILE
```bash
# Create temp files and test
export WORKTRUNK_DIRECTIVE_CD_FILE=$(mktemp)
-export WORKTRUNK_DIRECTIVE_EXEC_FILE=$(mktemp)
command wt switch feature
cat $WORKTRUNK_DIRECTIVE_CD_FILE # Should contain: /path/to/worktree (raw path)
cd -- "$(<$WORKTRUNK_DIRECTIVE_CD_FILE)" # Should cd you there
-rm -f $WORKTRUNK_DIRECTIVE_CD_FILE $WORKTRUNK_DIRECTIVE_EXEC_FILE
+rm -f $WORKTRUNK_DIRECTIVE_CD_FILE
```
## Common Issues
@@ -270,9 +251,7 @@ If you see path issues, ensure you're using a recent Git for Windows version.
| Variable | Purpose |
|----------|---------|
| `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 the PowerShell (`powershell`) and fish (`fish`) wrappers; selects how wt escapes the EXEC directive payload for that shell |
| `WORKTRUNK_COMPLETE_NAME` | Set by the bash, zsh, and PowerShell wrappers when they load completions; names the command the registration binds to, so `--cmd` integrations complete |
## See Also
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index 89ecaa813..9fb48317d 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -162,8 +162,7 @@ Arguments:
[EXECUTE_ARGS]...
Additional arguments for --execute command (after --)
- Arguments after -- are appended to the execute command. Each argument is expanded for
- templates, then POSIX shell-escaped.
+ Each argument is expanded for templates and passed directly to the program.
Options:
-c, --create
@@ -176,14 +175,17 @@ Options:
pr:{N}, mr:{N}.
-x, --execute <EXECUTE>
- Command to run after switch
+ Program to run after switch
- Replaces the wt process with the command after switching, giving it full terminal control.
- Useful for launching editors, AI agents, or other interactive tools.
+ Runs one external program after switching, with full terminal control. Arguments after --
+ go directly to that program without Worktrunk shell parsing. Program lookup and argument
+ decoding follow the operating system. Shell syntax requires an explicit shell, for example
+ -x sh -- -c 'npm install && npm test'. On Windows, shell shims need their extension (-x
+ code.cmd) or an explicit shell such as -x cmd.exe -- /C code.
Without a branch argument, the interactive picker opens and the command runs against the
selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code
- there.
+ there. With --no-cd, the program starts in the invoking directory instead.
Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{
base }} and {{ base_worktree_path }} describe the source: the selected base with --create,
@@ -208,7 +210,7 @@ Options:
Skip directory change after switching
Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or
- for CI/automation. Use --cd to override.
+ for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index ea53d0a6f..9e8fd3abf 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -372,15 +372,20 @@ pub(crate) struct SwitchArgs {
#[arg(short = 'b', long, requires = "branch", add = crate::completion::branch_value_completer(), value_parser = crate::cli::non_empty_branch)]
pub(crate) base: Option<String>,
- /// Command to run after switch
+ /// Program to run after switch
///
- /// Replaces the wt process with the command after switching, giving
- /// it full terminal control. Useful for launching editors, AI agents,
- /// or other interactive tools.
+ /// Runs one external program after switching, with full terminal control.
+ /// Arguments after `--` go directly to that program without Worktrunk shell
+ /// parsing. Program lookup and argument decoding follow the operating system.
+ /// Shell syntax requires an explicit shell, for example
+ /// `-x sh -- -c 'npm install && npm test'`. On Windows, shell shims need
+ /// their extension (`-x code.cmd`) or an explicit shell such as
+ /// `-x cmd.exe -- /C code`.
///
/// Without a branch argument, the interactive picker opens and the
/// command runs against the selected worktree — so `wt switch -x claude`
- /// picks a worktree, then launches Claude Code there.
+ /// picks a worktree, then launches Claude Code there. With `--no-cd`, the
+ /// program starts in the invoking directory instead.
///
/// Supports [hook template variables](https://worktrunk.dev/hook/#template-variables)
/// (`{{ branch }}`, `{{ worktree_path }}`, etc.) and filters.
@@ -403,13 +408,12 @@ pub(crate) struct SwitchArgs {
/// Template example: `-x code -- '{{ worktree_path }}'` opens VS Code
/// at the worktree, `-x tmux -- new -s '{{ branch | sanitize }}'` starts
/// a tmux session named after the branch.
- #[arg(short = 'x', long)]
+ #[arg(short = 'x', long, value_parser = clap::builder::NonEmptyStringValueParser::new())]
pub(crate) execute: Option<String>,
/// Additional arguments for --execute command (after --)
///
- /// Arguments after `--` are appended to the execute command.
- /// Each argument is expanded for templates, then POSIX shell-escaped.
+ /// Each argument is expanded for templates and passed directly to the program.
#[arg(last = true, requires = "execute")]
pub(crate) execute_args: Vec<String>,
@@ -420,7 +424,8 @@ pub(crate) struct SwitchArgs {
/// Skip directory change after switching
///
/// Hooks still run normally. Useful when hooks handle navigation
- /// (e.g., tmux workflows) or for CI/automation. Use --cd to override.
+ /// (e.g., tmux workflows) or for CI/automation. `--execute` also starts in
+ /// the invoking directory. Use --cd to override.
#[arg(long, overrides_with = "cd")]
pub(crate) no_cd: bool,
@@ -2556,9 +2561,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge
| `WORKTRUNK_PROJECT_CONFIG_PATH` | Override project config file location (defaults to `.config/wt.toml`); relative paths resolve from the worktree root |
| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |
| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |
-| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |
| `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory |
-| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |
| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) |
| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |
| `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index cbd374f02..ca3098b2b 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -35,13 +35,8 @@
//! merging into a single `CommandConfig`, so per-source policy can be applied
//! step-by-step without un-merging. Steps are tagged with their source
//! (`HookSource::User` / `Project`), and `sourced_steps_to_foreground`
-//! applies per-step `DirectivePassthrough`: the CD directive file is passed
-//! through to every step so inner `wt` invocations can redirect the parent
-//! shell's cwd; the EXEC directive file passes through user-source steps but
-//! is scrubbed for project-source steps. When the same name is defined in
-//! both configs, the user's own steps still get the EXEC relaxation — the
-//! decision is per-step, so the project side scrubbing doesn't bleed back
-//! into the user steps. See issue #2101.
+//! applies `DirectivePassthrough`: the CD directive file is passed through so
+//! inner `wt` invocations can redirect the parent shell's cwd.
use std::collections::{BTreeMap, BTreeSet};
diff --git a/src/commands/custom.rs b/src/commands/custom.rs
index be7f5024d..076a8c4f9 100644
--- a/src/commands/custom.rs
+++ b/src/commands/custom.rs
@@ -30,7 +30,7 @@ use std::process::Command;
use anyhow::{Context, Result};
use worktrunk::git::WorktrunkError;
-use worktrunk::shell_exec::RETIRED_DIRECTIVE_FILE_ENV_VAR;
+use worktrunk::shell_exec::{DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR};
use worktrunk::trace::CommandTrace;
use crate::cli::build_command;
@@ -132,8 +132,9 @@ fn unrecognized_subcommand_error(name: &str) -> clap::Error {
fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Result<()> {
let mut cmd = Command::new(path);
cmd.args(args);
- // Explicitly invoked extensions remain trusted with split CD/EXEC; only
- // the retired sourceable single-file capability is forbidden.
+ // Preserve the raw CD directive, but never expose a file that an older
+ // parent wrapper will source as shell code after this process exits.
+ cmd.env_remove(DIRECTIVE_EXEC_FILE_ENV_VAR);
cmd.env_remove(RETIRED_DIRECTIVE_FILE_ENV_VAR);
if let Some(dir) = working_dir {
cmd.current_dir(dir);
diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rs
index b81cded34..4cab5b825 100644
--- a/src/commands/hook_filter.rs
+++ b/src/commands/hook_filter.rs
@@ -6,9 +6,7 @@
/// Whether a hook or alias body came from user config or project config.
///
-/// Drives the per-step trust model: user-source bodies skip approval and
-/// pass EXEC through (the config is the user's own); project-source bodies
-/// require approval at the gate (command entry point) and scrub EXEC.
+/// Drives approval and source-qualified filtering.
#[derive(
Clone,
Copy,
@@ -25,11 +23,9 @@
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum HookSource {
- /// User config (~/.config/worktrunk/config.toml). No approval required;
- /// EXEC directives pass through (alias steps).
+ /// User config (~/.config/worktrunk/config.toml). No approval required.
User,
- /// Project config (.config/wt.toml). Approval is handled at the gate;
- /// EXEC directives are scrubbed.
+ /// Project config (.config/wt.toml). Approval is handled at the gate.
Project,
}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 6723869ba..9a4f4bbe4 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -530,16 +530,8 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: PendingPipeline) -> an
/// the `source` field on each step drives the per-step trust model
/// (`DirectivePassthrough`).
///
-/// Trust model:
-/// - User-source alias steps pass EXEC through. The body lives in the user's
-/// own config, so a nested `wt switch --execute …` is no different from the
-/// user typing it at the top level. See issue #2101.
-/// - Project-source alias steps and all hook steps scrub EXEC (they can still
-/// emit CD directives via `inherit_from_env`).
-///
-/// In a merged user+project alias body, the user's steps still get the
-/// relaxation — the decision is per-step, so the project side scrubbing
-/// doesn't bleed back into the user steps.
+/// Every foreground step inherits the CD directive so a nested switch can
+/// still move the parent shell.
pub(crate) fn sourced_steps_to_foreground(
sourced_steps: Vec<SourcedStep>,
kind: &PipelineKind,
@@ -547,12 +539,7 @@ pub(crate) fn sourced_steps_to_foreground(
sourced_steps
.into_iter()
.map(|sourced| {
- let directives = match (kind, sourced.source) {
- (PipelineKind::Alias { .. }, HookSource::User) => {
- DirectivePassthrough::inherit_from_env_with_exec()
- }
- _ => DirectivePassthrough::inherit_from_env(),
- };
+ let directives = DirectivePassthrough::inherit_from_env();
let (pipe_stdin, redirect_stdout_to_stderr, error_wrapper) = match kind {
PipelineKind::Hook { hook_type, .. } => {
(true, true, hook_error_wrapper(*hook_type))
diff --git a/src/commands/step/tether.rs b/src/commands/step/tether.rs
index 7d76d854c..0fb8dab10 100644
--- a/src/commands/step/tether.rs
+++ b/src/commands/step/tether.rs
@@ -61,8 +61,8 @@ pub(crate) fn step_tether(command: &[String], working_dir: Option<&Path>) -> Res
cmd.current_dir(dir);
}
// Direct exec, no implicit shell, same as `wt step for-each`; scrub the
- // directive env vars so a long-lived child can't write to the parent
- // shell's cd/exec directive files.
+ // directive env vars so a long-lived child can't redirect the parent
+ // shell's directory.
worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);
set_new_process_group(&mut cmd);
let mut trace = CommandTrace::new(None, &command.join(" "));
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 2ea621aa3..b7b821e3e 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -10,17 +10,15 @@
//! The binary can change *its own* working directory, but when it exits, the parent shell remains
//! in the original directory.
//!
-//! # Solution: Split File-Based Directive Passing
+//! # Solution: File-Based Directory Passing
//!
-//! Shell wrappers create two temp files and set `WORKTRUNK_DIRECTIVE_CD_FILE`
-//! and `WORKTRUNK_DIRECTIVE_EXEC_FILE` to their paths:
+//! Shell wrappers create a temp file and set `WORKTRUNK_DIRECTIVE_CD_FILE` to
+//! its path:
//!
-//! 1. Shell wrapper creates two temp files via `mktemp` (cd and exec)
-//! 2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`
-//! 3. wt binary writes a raw path to the CD file (no shell escaping)
-//! 4. wt writes arbitrary shell to the EXEC file (only for `--execute`)
-//! 5. Shell wrapper reads the CD file with `cd -- "$(< file)"` (no shell parsing)
-//! 6. Shell wrapper sources the EXEC file if non-empty
+//! 1. Shell wrapper creates a temp file via `mktemp`
+//! 2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_CD_FILE`
+//! 3. wt binary writes a raw path to the file
+//! 4. Shell wrapper changes directory to that path
//!
//! ## Without Shell Integration (Direct Binary Call)
//!
@@ -49,7 +47,7 @@
//!
//! When shell integration is enabled (`eval "$(wt config shell init bash)"`), the shell wrapper:
//!
-//! 1. Creates two temp files and sets the CD and EXEC directive env vars
+//! 1. Creates a temp file and sets the CD directive env var
//! 2. Runs the wt binary (which writes a raw path to the CD file)
//! 3. Reads the CD file with `cd -- "$(< file)"` after wt exits
//!
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index aff2ee25c..db76b77e3 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -21,9 +21,7 @@ use worktrunk::git::{
ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,
SwitchSuggestionCtx, WorktreeId, branch_tracks_ref, current_or_recover,
};
-use worktrunk::shell_exec::{
- ShellEscapeMode, directive_shell_escape_mode, shell_cwd, shell_escape_for,
-};
+use worktrunk::shell_exec::{ShellEscapeMode, shell_cwd};
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, println, progress_message,
suggest_command, warning_message,
@@ -1874,10 +1872,10 @@ impl SwitchPipeline<'_> {
);
// Compute only the vars the command actually names. The map is
// consumed by `expand_template` and nothing else — the child
- // receives a shell string through the EXEC directive file (or
- // `sh -c`), never the context as JSON on stdin, and `--execute`
- // renders no `-v` variables table. So a var the templates don't
- // reference is a git subprocess whose result is thrown away.
+ // receives argv, never the context as JSON on stdin, and
+ // `--execute` renders no `-v` variables table. So a var the
+ // templates don't reference is a git subprocess whose result is
+ // thrown away.
//
// The union is complete: `validate_switch_templates` already
// parsed both positions against `ValidationScope::SwitchExecute`
@@ -1891,41 +1889,18 @@ impl SwitchPipeline<'_> {
let template_vars =
build_hook_context(&ctx, &extra_vars, VarScope::Referenced(&referenced))?;
- // 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();
-
- // Expand template variables in command, escaped for the directive shell.
- let expanded_cmd = template_vars.expand(cmd, 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| {
- template_vars.expand(
- arg,
- ShellEscapeMode::Literal,
- repo,
- "--execute argument",
- )
- })
- .collect();
- let escaped_args: Vec<_> = expanded_args?
- .iter()
- .map(|arg| shell_escape_for(escape_mode, arg))
- .collect();
- format!("{} {}", expanded_cmd, escaped_args.join(" "))
- };
- execute_user_command(&full_cmd, hooks_display_path.as_deref())?;
+ // Every position is one argv element. Literal expansion preserves
+ // spaces, quotes, and shell metacharacters as data.
+ let program =
+ template_vars.expand(cmd, ShellEscapeMode::Literal, repo, "--execute command")?;
+ let args: Result<Vec<_>, _> = execute_args
+ .iter()
+ .map(|arg| {
+ template_vars.expand(arg, ShellEscapeMode::Literal, repo, "--execute argument")
+ })
+ .collect();
+ let argv: Vec<String> = std::iter::once(program).chain(args?).collect();
+ execute_user_command(&argv, hooks_display_path.as_deref())?;
}
Ok(())
@@ -2041,86 +2016,6 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>
})
}
-/// Whether `value` is a single clean program-name token — the form `--execute`
-/// keeps accepting unchanged once it switches to the argv input model.
-///
-/// First character `[A-Za-z0-9._/@]`, the rest additionally `+`/`-`. On
-/// Windows, `\` and `:` are also allowed so native paths (`C:\dir\tool`) are
-/// not flagged; on POSIX they are shell metacharacters and stay excluded.
-/// This rejects a leading `-`/`+` (an option-like `argv[0]` resolves
-/// differently), whitespace, `{{ }}` template markup, and every shell
-/// metacharacter — any of which means the value is not a bare program name.
-fn is_clean_program_token(value: &str) -> bool {
- let mut chars = value.chars();
- let Some(first) = chars.next() else {
- return false;
- };
- let first_ok = first.is_ascii_alphanumeric()
- || matches!(first, '.' | '_' | '/' | '@')
- || (cfg!(windows) && first == '\\');
- first_ok
- && chars.all(|c| {
- c.is_ascii_alphanumeric()
- || matches!(c, '.' | '_' | '/' | '@' | '+' | '-')
- || (cfg!(windows) && matches!(c, '\\' | ':'))
- })
-}
-
-/// Warn when a `--execute` value will change behavior under the upcoming argv
-/// input model.
-///
-/// A future release runs `-x` as a single program (with arguments after `--`),
-/// not a shell command line. Warn now for any value that is not a single
-/// program token — shell syntax, multiple words, or `{{ }}` markup (flagged
-/// conservatively, even when it would expand to a clean name).
-///
-/// A single program token — including a path — is unaffected and stays silent.
-/// A bare name that is really a shell alias/function/builtin is not detectable
-/// here without the user's shell, so it is left to fail loudly at the cutover
-/// rather than guessed at. Informational only — it never blocks the switch.
-///
-/// The hint reconstructs the command line that runs today — the `-x` value
-/// with its trailing args appended, the way `run_switch` joins them — and
-/// wraps it for whichever shell the active wrapper evaluates the payload
-/// with (`sh` / `fish` / `pwsh`), so the suggestion is behavior-preserving
-/// on fish/PowerShell, not just POSIX sh, and complete when trailing args
-/// are present. It also links the tracking issue (#2860) so anyone whose
-/// workflow the argv model would regress can report the case before the
-/// cutover.
-fn warn_if_execute_form_deprecated(cmd: &str, execute_args: &[String]) {
- if is_clean_program_token(cmd) {
- return;
- }
- let mode = directive_shell_escape_mode();
- let (shell, flag) = match mode {
- ShellEscapeMode::PowerShell => ("pwsh", "-Command"),
- ShellEscapeMode::Fish => ("fish", "-c"),
- _ => ("sh", "-c"),
- };
- let command_line = if execute_args.is_empty() {
- cmd.to_string()
- } else {
- let escaped: Vec<String> = execute_args
- .iter()
- .map(|arg| shell_escape_for(mode, arg))
- .collect();
- format!("{} {}", cmd, escaped.join(" "))
- };
- let suggested = shell_escape_for(mode, &command_line);
- eprintln!(
- "{}",
- warning_message(cformat!(
- "<bold>--execute</> will change in a future release: it will run a single program, with arguments after <bold>--</>, not a shell command line"
- ))
- );
- eprintln!(
- "{}",
- hint_message(cformat!(
- "Comment at <underline>https://github.com/max-sixty/worktrunk/issues/2860</> if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: <underline>--execute {shell} -- {flag} {suggested}</>"
- ))
- );
-}
-
/// Validate all templates that will be expanded after worktree creation.
///
/// Catches syntax errors and undefined variable references *before* the
@@ -2178,7 +2073,6 @@ fn validate_switch_templates(
"--execute argument",
)?;
}
- warn_if_execute_form_deprecated(cmd, execute_args);
}
// Validate hook templates only when hooks will actually run
@@ -2259,45 +2153,6 @@ mod tests {
);
}
- #[test]
- fn is_clean_program_token_matches_only_bare_names() {
- // Bare program names — unchanged under the argv input model.
- for ok in [
- "git",
- "claude",
- "node18",
- "my-tool",
- "tool.sh",
- "/usr/bin/env",
- "./build",
- "_x",
- "@scope/pkg",
- ] {
- assert!(is_clean_program_token(ok), "expected clean token: {ok:?}");
- }
- // Not bare names — empty, whitespace, shell syntax, template markup,
- // or an option-like leading character.
- for bad in [
- "",
- "npm run dev",
- "a && b",
- "echo $HOME",
- "code {{ worktree_path }}",
- "a|b",
- "-flag",
- "+x",
- ] {
- assert!(!is_clean_program_token(bad), "expected non-token: {bad:?}");
- }
- // A native Windows path is a clean token only when targeting Windows;
- // on POSIX, `\` and `:` are shell metacharacters.
- assert_eq!(
- is_clean_program_token(r"C:\Tools\foo.exe"),
- cfg!(windows),
- "Windows path classification should follow the target OS"
- );
- }
-
#[test]
fn capture_switch_source_returns_empty_when_recovered() {
// When recovered from a deleted CWD, post-switch hooks must see empty
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index a2d789733..a84d1c0f4 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -4,8 +4,6 @@
//! [`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.
@@ -429,7 +427,7 @@ pub fn alias_context_filter(mut referenced: BTreeSet<String>) -> BTreeSet<String
///
/// `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.
+/// independent of the user's interactive shell.
#[derive(Debug)]
struct ShellArgs(Vec<String>);
@@ -1068,13 +1066,10 @@ pub fn validate_template(
/// * `template` - Template string using Jinja2 syntax (e.g., `{{ branch }}`)
/// * `vars` - Variables to substitute
/// * `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::Posix`] — escape for safe splicing into a command
+/// line passed to `Cmd::shell` (hooks and aliases).
/// - [`ShellEscapeMode::Literal`] — substitute values verbatim (filesystem
-/// paths).
+/// paths and `--execute` argv elements).
/// * `repo` - Repository for looking up worktree paths
///
/// # Filters
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index e1687956c..2c1a27106 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -174,7 +174,6 @@ const DIAGNOSTIC_ENV_VARS: &[&str] = &[
// Worktrunk's own runtime knobs and logging.
"RUST_LOG",
"WORKTRUNK_VERBOSE",
- "WORKTRUNK_SHELL",
"WORKTRUNK_FOREGROUND",
"WORKTRUNK_MAX_CONCURRENT_COMMANDS",
];
diff --git a/src/output/concurrent.rs b/src/output/concurrent.rs
index 6a8f13e2b..f2c5e5011 100644
--- a/src/output/concurrent.rs
+++ b/src/output/concurrent.rs
@@ -46,8 +46,7 @@ use anyhow::Context;
use worktrunk::command_log::log_command;
use worktrunk::git::WorktrunkError;
use worktrunk::shell_exec::{
- DIRECTIVE_EXEC_FILE_ENV_VAR, ShellConfig, apply_cd_directive_env, scrub_directive_env_vars,
- scrub_git_discovery_env_vars,
+ ShellConfig, apply_cd_directive_env, scrub_directive_env_vars, scrub_git_discovery_env_vars,
};
#[cfg(unix)]
use worktrunk::signal_forwarder::ForegroundSignals;
@@ -302,14 +301,11 @@ fn spawn_child(
scrub_git_discovery_env_vars(&mut command);
}
- // Scrub all directive env vars, then re-add the passthroughs.
+ // Scrub all directive env vars, then re-add the CD passthrough.
scrub_directive_env_vars(&mut command);
if let Some(path) = &cmd.directives.cd_file {
apply_cd_directive_env(&mut command, path);
}
- if let Some(path) = &cmd.directives.exec_file {
- command.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);
- }
#[cfg(unix)]
{
@@ -482,7 +478,7 @@ mod tests {
//! Unit tests that exercise the executor's option-bearing code paths which
//! aren't reachable through the alias integration tests today: every child
//! currently has `log_label=None` (aliases skip per-child logging) and the
- //! CD/EXEC directive env vars are usually unset. Driving these branches
+ //! CD directive env vars are usually unset. Driving these branches
//! with a direct call proves they behave correctly when a future caller
//! (concurrent foreground hooks, once their deprecation completes) uses them.
use super::*;
@@ -523,9 +519,7 @@ mod tests {
// passing a log_label doesn't panic and the command still runs.
}
- /// `DirectivePassthrough` with `cd_file` and `exec_file` set must propagate
- /// both env vars to the child. The child script writes to each named file;
- /// we assert both values are delivered.
+ /// `DirectivePassthrough` with `cd_file` set must propagate it to the child.
///
/// Unix-only: the script uses POSIX `sh` redirect syntax and relies on
/// native temp paths that don't need escaping. Git Bash on Windows would
@@ -535,25 +529,14 @@ mod tests {
fn test_directive_env_vars_passed_through() {
use tempfile::NamedTempFile;
let cd = NamedTempFile::new().unwrap();
- let exec = NamedTempFile::new().unwrap();
let directives = DirectivePassthrough {
cd_file: Some(cd.path().to_path_buf()),
- exec_file: Some(exec.path().to_path_buf()),
};
- // Write each env var's value to its matching temp file. If the child
- // didn't receive the env var, the redirect would fail or write an
- // empty file.
- let script = format!(
- "printf CD > {} && printf EXEC > {}",
- cd.path().display(),
- exec.path().display(),
- );
- let outcomes = run_one_with_directives("job", &script, None, &directives);
+ let script = "printf CD > \"$WORKTRUNK_DIRECTIVE_CD_FILE\"";
+ let outcomes = run_one_with_directives("job", script, None, &directives);
assert!(outcomes[0].is_ok(), "child should exit 0");
let cd_contents = std::fs::read_to_string(cd.path()).unwrap();
- let exec_contents = std::fs::read_to_string(exec.path()).unwrap();
assert_eq!(cd_contents, "CD");
- assert_eq!(exec_contents, "EXEC");
}
/// An empty `cmds` slice must return an empty outcomes vec without
diff --git a/src/output/global.rs b/src/output/global.rs
index 57160b28b..e16255e0e 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -1,76 +1,37 @@
//! Global output context with file-based directive passing
//!
-//! Shell integration directives (cd, exec) travel from wt to the parent shell
-//! through files named by environment variables. This module chooses the right
-//! file for each directive and escalates a warning when a trusted directive is
-//! refused. Regular output still uses `eprintln!`/`println!` directly (from
-//! `worktrunk::styling` for color support).
+//! The shell wrapper passes a file where wt can write the directory that the
+//! parent shell should enter. Regular output still uses
+//! `eprintln!`/`println!` directly (from `worktrunk::styling` for color support).
//!
//! # Protocol
//!
-//! Shell integration uses two separate files with different trust levels:
-//!
-//! - `WORKTRUNK_DIRECTIVE_CD_FILE` holds a single raw path. The wrapper runs
-//! `cd -- "$(< file)"` after wt exits. There is no shell parsing, no
-//! escaping, and no injection surface, so the env var is safe to pass
-//! through to alias/hook shell bodies — a body that appends to it can at
-//! worst redirect `cd`.
-//!
-//! - `WORKTRUNK_DIRECTIVE_EXEC_FILE` holds arbitrary shell that the wrapper
-//! sources after the `cd`. This is how `wt switch --execute <cmd>` runs its
-//! payload in the user's interactive shell, inheriting functions and env.
-//! Because the contents are sourced verbatim, wt scrubs this env var from
-//! project-alias and foreground-hook child processes so a body authored in
-//! shared config cannot inject shell into the parent session.
-//!
-//! # Conservative scrub
-//!
-//! User-source aliases pass the EXEC env var through (issue #2101): the body
-//! lives in the user's own config, so `wt step my-alias` running
-//! `wt switch main --execute claude` is no different from the user typing
-//! the same command at the top level.
-//!
-//! Project aliases and foreground hooks keep the scrub. A nested `wt
-//! --execute …` inside one of those bodies sees no EXEC file and refuses to
-//! run the payload, emitting a warning and a link to
-//! <https://github.com/max-sixty/worktrunk/issues/2101> so users can report
-//! whether to relax the restriction further.
+//! `WORKTRUNK_DIRECTIVE_CD_FILE` holds one raw path. The wrapper changes to it
+//! after wt exits. `--execute` needs no directive: wt starts the external
+//! program directly with its working directory set to the switch target. The
+//! retired exec-file variable is recognized only to warn when an old wrapper
+//! redirects `--execute` output away from the terminal.
//!
//! The retired single-file protocol is never written. If an old wrapper still
//! sets only `WORKTRUNK_DIRECTIVE_FILE`, switch output diagnoses the outdated
//! wrapper and tells the user to reinstall shell integration.
use std::fs::OpenOptions;
-use std::io::{self, Write};
-#[cfg(unix)]
-use std::os::unix::process::CommandExt;
+use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
-use std::process::Stdio;
use anyhow::Context as _;
use color_print::cformat;
use std::sync::{Mutex, OnceLock};
-#[cfg(not(unix))]
use worktrunk::git::WorktrunkError;
-#[cfg(not(unix))]
use worktrunk::shell_exec::Cmd;
-#[cfg(unix)]
-use worktrunk::shell_exec::ShellConfig;
-// The std-`Command` scrub helper is only needed by the unix `exec` variant of
-// `execute_command`; the non-unix variant scrubs via `Cmd`'s builder method.
-#[cfg(unix)]
-use worktrunk::shell_exec::scrub_git_discovery_env_vars;
use worktrunk::shell_exec::{
DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,
+ ShellEscapeMode, shell_escape_for,
};
use worktrunk::styling::{eprintln, hint_message, stderr, warning_message};
-/// Issue tracking whether to relax the EXEC scrub further for project aliases
-/// and hooks. (User aliases already pass EXEC through.) Emitted in the warning
-/// so users can report use cases.
-pub const EXEC_SCRUB_ISSUE_URL: &str = "https://github.com/max-sixty/worktrunk/issues/2101";
-
// Re-export set_verbosity from the library's styling module.
// This ensures the binary and library share the same global state.
// Library code (like expansion.rs) accesses verbosity() directly from styling.
@@ -90,35 +51,26 @@ static OUTPUT_STATE: OnceLock<Mutex<OutputState>> = OnceLock::new();
/// Ensures output shows the retired wrapper's reinstall action at most once.
static RETIRED_REPAIR_HINT_SHOWN: OnceLock<()> = OnceLock::new();
-/// Selects which directive files wt writes to based on environment.
+/// Selects how wt communicates a directory change to the parent shell.
///
/// Computed once during `state()` initialization from the process environment.
#[derive(Debug, Clone, Default)]
enum DirectiveMode {
- /// Shell integration not active. `execute()` runs commands directly;
- /// `change_directory()` is a no-op beyond updating the buffered target
- /// dir used by `execute()`.
+ /// Shell integration not active.
#[default]
Interactive,
- /// Split protocol. `cd_file` is always a real path; `exec_file` is
- /// `None` when the EXEC var was scrubbed from this process (we're
- /// running inside an alias/hook shell body). `--execute` in the scrubbed
- /// case warns and drops the command.
- Split {
- cd_file: PathBuf,
- exec_file: Option<PathBuf>,
- },
- /// A retired pre-split wrapper is active. This state is diagnostic-only:
- /// wt never reads or writes the retired directive file, and `--execute`
- /// is refused rather than run directly.
+ /// A shell wrapper supplied a CD directive file.
+ ShellIntegration { cd_file: PathBuf },
+ /// A retired single-file wrapper is active. This state is diagnostic-only:
+ /// wt never reads or writes the retired directive file.
Retired,
}
#[derive(Default)]
struct OutputState {
- /// Which directive files wt writes to.
+ /// How directory changes are communicated.
mode: DirectiveMode,
- /// Buffered target directory for execute() in interactive mode
+ /// Target directory for a subsequent `execute()` call.
target_dir: Option<PathBuf>,
/// Mapping from canonical path prefix to logical (symlink) prefix.
/// Computed once at init from `$PWD` vs `std::env::current_dir()`.
@@ -259,9 +211,9 @@ fn read_env_path(var: &str) -> Option<PathBuf> {
.map(PathBuf::from)
}
-/// Whether this invocation came through a retired pre-split shell wrapper.
+/// Whether this invocation came through a retired single-file shell wrapper.
///
-/// A split-protocol CD file always wins over a leftover single-file variable.
+/// A current CD file always wins over a leftover single-file variable.
/// The old variable is recognized only to produce a targeted repair message;
/// wt never writes to it.
pub(crate) fn retired_shell_wrapper_active() -> bool {
@@ -273,20 +225,16 @@ pub(crate) fn retired_shell_wrapper_active() -> bool {
fn compute_directive_mode() -> DirectiveMode {
let cd = read_env_path(DIRECTIVE_CD_FILE_ENV_VAR);
- let exec = read_env_path(DIRECTIVE_EXEC_FILE_ENV_VAR);
let retired = read_env_path(RETIRED_DIRECTIVE_FILE_ENV_VAR);
match cd {
- Some(cd_file) => DirectiveMode::Split {
- cd_file,
- exec_file: exec,
- },
+ Some(cd_file) => DirectiveMode::ShellIntegration { cd_file },
None if retired.is_some() => DirectiveMode::Retired,
None => DirectiveMode::Interactive,
}
}
-/// Print the canonical repair action for the retired pre-split wrapper once.
+/// Print the canonical repair action for the retired single-file wrapper once.
pub(crate) fn print_outdated_shell_wrapper_hint_once() {
if RETIRED_REPAIR_HINT_SHOWN.set(()).is_ok() {
eprintln!(
@@ -298,65 +246,17 @@ pub(crate) fn print_outdated_shell_wrapper_hint_once() {
}
}
-/// Refuse `--execute` from a retired wrapper. Fires at most once per process,
-/// and supplies the reinstall action when no earlier directory warning did.
-fn warn_retired_exec_once(command: &str) {
- static WARNED: OnceLock<()> = OnceLock::new();
- if WARNED.set(()).is_err() {
- return;
- }
- eprintln!(
- "{}",
- warning_message(cformat!(
- "<bold>--execute</> disabled because the shell wrapper is out of date; skipping <bold>{command}</>"
- ))
- );
- print_outdated_shell_wrapper_hint_once();
-}
-
-/// Warn that `--execute` was refused because we're running inside an alias or
-/// hook body with the EXEC file scrubbed. Fires at most once per process so
-/// repeated refusals don't spam the terminal.
-fn warn_exec_scrubbed_once(command: &str) {
- static WARNED: OnceLock<()> = OnceLock::new();
- if WARNED.set(()).is_err() {
- return;
- }
- eprintln!(
- "{}",
- warning_message(cformat!(
- "<bold>--execute</> disabled inside project alias / hook bodies for safety; skipping <bold>{command}</>"
- ))
- );
- eprintln!(
- "{}",
- hint_message(cformat!(
- "User-source aliases allow it. Comment at <underline>{EXEC_SCRUB_ISSUE_URL}</> if you need it for project aliases or hooks"
- ))
- );
-}
-
-/// Append a line to a directive file.
-///
-/// `what` names the payload for the failure message ("the command", "the cd
-/// command"). The raw `io::Error` names neither the file nor what didn't get
-/// written, and this write runs *last* — after the operation the user asked for
-/// has already landed — so `✗ No such file or directory (os error 2)` on its own
-/// reads as if the command or the worktree were the thing that's missing. These
-/// files belong to the shell wrapper, so the message has to point there.
-fn append_line(path: &Path, line: &str, what: &str) -> anyhow::Result<()> {
- append_line_io(path, line).with_context(|| {
- format!(
- "Failed to write {what} to the directive file {}",
- path.display()
- )
- })
-}
-
-fn append_line_io(path: &Path, line: &str) -> io::Result<()> {
- let mut file = OpenOptions::new().append(true).open(path)?;
- writeln!(file, "{}", line)?;
- file.flush()
+/// Warn when a retired exec-file wrapper has redirected stdout from the terminal.
+pub(crate) fn print_outdated_execute_wrapper_warning() {
+ if read_env_path(DIRECTIVE_EXEC_FILE_ENV_VAR).is_some() && !io::stdout().is_terminal() {
+ eprintln!(
+ "{}",
+ warning_message(
+ "Shell wrapper is out of date — --execute output may be buffered instead of using the terminal"
+ )
+ );
+ print_outdated_shell_wrapper_hint_once();
+ }
}
/// Truncate-write the given path to the CD directive file. The file holds one
@@ -365,7 +265,8 @@ fn append_line_io(path: &Path, line: &str) -> io::Result<()> {
/// `change_directory()` calls should resolve (hook emits a cd after switch
/// emits its own → hook wins).
///
-/// A failure names the file, for the reason [`append_line`] does.
+/// A failure names the file because the operation has already completed by the
+/// time the directive write runs.
fn write_cd_path(file: &Path, path: &Path) -> anyhow::Result<()> {
write_cd_path_io(file, path)
.with_context(|| format!("Failed to write the cd directive file {}", file.display()))
@@ -386,11 +287,10 @@ fn write_cd_path_io(file: &Path, path: &Path) -> io::Result<()> {
/// Request directory change (for shell integration).
///
-/// Writes the target path to the CD directive file. In interactive mode (no
-/// current wrapper), just buffers the target so that a later `execute()` can
-/// use it as the child's working directory.
+/// Stores the target for a later `execute()` call and, when shell integration
+/// is active, also writes it to the CD directive file.
///
-/// A write failure names the file it couldn't write — see [`append_line`].
+/// A write failure names the file it couldn't write.
pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
let path = path.as_ref();
let mode = {
@@ -401,7 +301,9 @@ pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
match mode {
DirectiveMode::Interactive | DirectiveMode::Retired => Ok(()),
- DirectiveMode::Split { cd_file, .. } => write_cd_path(&cd_file, &to_logical_path(path)),
+ DirectiveMode::ShellIntegration { cd_file } => {
+ write_cd_path(&cd_file, &to_logical_path(path))
+ }
}
}
@@ -425,98 +327,39 @@ pub fn was_cwd_removed() -> bool {
.cwd_removed
}
-/// Request command execution.
-///
-/// Dispatches by directive mode:
-/// - Interactive: runs the command directly (replacing this process on Unix).
-/// - Split protocol with EXEC file: appends the command to the EXEC file; the
-/// wrapper sources it after wt exits, so it runs in the user's interactive
-/// shell.
-/// - Split protocol without EXEC file: refuses the command with a warning. We
-/// land here when running inside an alias or hook body, where `Cmd` scrubbed
-/// the EXEC var to keep arbitrary shell from reaching the parent session.
-/// - Retired wrapper: refuses the command and points to the reinstall action.
-///
-/// A failed append names the file it couldn't write — see [`append_line`].
-pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
- let command = command.into();
-
- let (mode, target_dir) = {
- let guard = state().lock().expect("OUTPUT_STATE lock poisoned");
- (guard.mode.clone(), guard.target_dir.clone())
- };
-
- match mode {
- DirectiveMode::Interactive => execute_command(command, target_dir.as_deref()),
- DirectiveMode::Split {
- exec_file: Some(file),
- ..
- } => append_line(&file, &command, "the command"),
- DirectiveMode::Split {
- exec_file: None, ..
- } => {
- warn_exec_scrubbed_once(&command);
- Ok(())
- }
- DirectiveMode::Retired => {
- warn_retired_exec_once(&command);
- Ok(())
- }
- }
+/// Render an argv as a copyable command line for messages and diagnostics.
+pub(crate) fn format_exec_argv(argv: &[String]) -> String {
+ argv.iter()
+ .map(|arg| shell_escape_for(ShellEscapeMode::Posix, arg))
+ .collect::<Vec<_>>()
+ .join(" ")
}
-/// Whether a call to `execute()` with a non-empty command would be refused
-/// by the conservative scrub or a retired wrapper. Callers can use this to
-/// suppress pre-exec output (e.g. "Executing (--execute):" headers) so the
-/// warning stands alone.
-pub fn exec_would_be_refused() -> bool {
- let guard = state().lock().expect("OUTPUT_STATE lock poisoned");
- matches!(
- guard.mode,
- DirectiveMode::Split {
- exec_file: None,
- ..
- } | DirectiveMode::Retired
- )
-}
-
-/// Execute a command in the given directory (Unix: exec, non-Unix: spawn)
-#[cfg(unix)]
-fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
- let exec_dir = target_dir.unwrap_or_else(|| Path::new("."));
- let shell = ShellConfig::get()?;
-
- // Use exec() to replace wt process with the command.
- // This gives the command full TTY access (stdin, stdout, stderr all inherited),
- // enabling interactive programs like `claude` to work properly.
- let mut cmd = shell.command(&command);
- cmd.current_dir(exec_dir)
- .stdin(Stdio::inherit())
- .stdout(Stdio::inherit())
- .stderr(Stdio::inherit());
- // A buffered target means wt relocated the payload into a worktree it
- // selected, so the payload's `git` calls must discover that worktree from
- // the cwd, not an inherited `GIT_DIR` (issue #3373; see
- // `scrub_git_discovery_env_vars`). With no target the payload runs where
- // the user invoked wt, and keeps their context.
- if target_dir.is_some() {
- scrub_git_discovery_env_vars(&mut cmd);
- }
- let err = cmd.exec();
-
- // exec() only returns on error
- Err(anyhow::anyhow!(cformat!(
- "Failed to exec <bold>{}</> with {}: {}",
- command,
- shell.name,
- err
- )))
+/// Run an external program in the directory selected by the preceding switch.
+pub fn execute(argv: Vec<String>) -> anyhow::Result<()> {
+ if argv.first().is_none_or(String::is_empty) {
+ anyhow::bail!("--execute requires a non-empty program");
+ }
+ let target_dir = state()
+ .lock()
+ .expect("OUTPUT_STATE lock poisoned")
+ .target_dir
+ .clone();
+ execute_command(argv, target_dir.as_deref())
}
-/// Execute a command in the given directory (non-Unix: spawn and wait)
-#[cfg(not(unix))]
-fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
- let mut cmd = Cmd::shell(&command).stdin(Stdio::inherit());
+/// Execute an argv in the given directory, with the terminal attached.
+fn execute_command(argv: Vec<String>, target_dir: Option<&Path>) -> anyhow::Result<()> {
+ let mut argv = argv.into_iter();
+ let program = argv.next().context("--execute requires a program")?;
+ let mut cmd = Cmd::new(program)
+ .args(argv)
+ .inherit_stdin()
+ .forward_signals();
+ #[cfg(unix)]
+ {
+ cmd = cmd.propagate_sigpipe();
+ }
if let Some(dir) = target_dir {
// wt relocated the payload into a worktree it selected; its `git`
// calls must discover that worktree from the cwd, not an inherited
@@ -524,14 +367,16 @@ fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result
cmd = cmd.current_dir(dir).scrub_git_discovery_env();
}
- if let Err(err) = cmd.stream() {
- // If the command failed with an exit code, just exit with that code.
- // This matches Unix behavior where exec() replaces the process and
- // the shell's exit code becomes the process exit code (no error message).
+ suppress_child_exit_message(cmd.stream())
+}
+
+/// Preserve a user program's status without printing wt's own error afterward.
+fn suppress_child_exit_message(result: anyhow::Result<()>) -> anyhow::Result<()> {
+ if let Err(err) = result {
if let Some(WorktrunkError::ChildProcessExited { code, .. }) =
err.downcast_ref::<WorktrunkError>()
{
- std::process::exit(*code);
+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: *code }.into());
}
return Err(err);
}
@@ -555,11 +400,11 @@ pub fn terminate_output() -> io::Result<()> {
stderr.flush()
}
-/// Check whether the split directive-file protocol is active.
+/// Check whether a shell wrapper supplied a CD directive file.
pub fn is_shell_integration_active() -> bool {
matches!(
state().lock().expect("OUTPUT_STATE lock poisoned").mode,
- DirectiveMode::Split { .. }
+ DirectiveMode::ShellIntegration { .. }
)
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 6f0667652..558cc4b19 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1096,15 +1096,9 @@ pub fn handle_switch_output(
/// directory (shell integration not active). This helps users understand where
/// the command runs.
///
-/// When execution will be refused (the conservative EXEC scrub or a retired
-/// wrapper), no `Executing` header is printed — `execute()` emits its own
-/// warning explaining the skip, and a contradictory header would read as a
-/// broken promise.
-pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyhow::Result<()> {
- if super::exec_would_be_refused() {
- // execute() will emit the refusal warning and return Ok.
- return super::execute(command);
- }
+pub fn execute_user_command(argv: &[String], display_path: Option<&Path>) -> anyhow::Result<()> {
+ super::global::print_outdated_execute_wrapper_warning();
+ let command = super::global::format_exec_argv(argv);
// Show what command is being executed (section header + gutter content)
// Include path when user's shell won't be there (shell integration not active)
@@ -1116,9 +1110,9 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho
None => "Executing (--execute):".to_string(),
};
eprintln!("{}", progress_message(header));
- eprintln!("{}", format_bash_with_gutter(command));
+ eprintln!("{}", format_bash_with_gutter(&command));
- super::execute(command)?;
+ super::execute(argv.to_vec())?;
Ok(())
}
@@ -2046,25 +2040,18 @@ fn remove_removed_worktree_silently(
///
/// Capabilities: optional stdout→stderr redirect for deterministic ordering,
/// SIGINT/SIGTERM forwarding to child process group, ANSI reset before child
-/// runs, `Cmd` tracing/logging, and directive file control.
+/// runs, `Cmd` tracing/logging, and CD directive control.
///
/// ## Directive files
///
/// `directives` controls whether the child can write shell-integration
-/// directives back to the parent shell. The CD file is always safe to pass
-/// through (raw path, no injection surface); the EXEC file is normally scrubbed
-/// because alias/hook bodies must not inject arbitrary shell into the parent
-/// session — see [`DirectivePassthrough::inherit_from_env_with_exec`] for the
-/// one exception.
+/// directives back to the parent shell. The CD file holds a raw path and is
+/// safe to pass through.
///
/// - `DirectivePassthrough::default()` — scrubs all directive env vars from
/// the child. Used by background hooks (outlive the parent shell).
-/// - `DirectivePassthrough::inherit_from_env()` — re-adds CD but scrubs EXEC.
-/// Used by project aliases and foreground hooks, which may emit `cd`
-/// directives but must not be able to inject shell.
-/// - `DirectivePassthrough::inherit_from_env_with_exec()` — also re-adds EXEC.
-/// Used only for user-source aliases, where the alias body is already user-
-/// authored just like a top-level `wt switch --execute` invocation.
+/// - `DirectivePassthrough::inherit_from_env()` — re-adds CD. Used by aliases
+/// and foreground hooks, which may emit `cd` directives.
///
/// ## Stdout routing
///
@@ -2145,9 +2132,6 @@ pub fn execute_shell_command(
if let Some(path) = directives.cd_file {
cmd = cmd.directive_cd_file(path);
}
- if let Some(path) = directives.exec_file {
- cmd = cmd.directive_exec_file(path);
- }
cmd.stream()?;
@@ -2161,39 +2145,20 @@ pub fn execute_shell_command(
///
/// `Default` (no fields set) scrubs all directive env vars from the child;
/// [`DirectivePassthrough::inherit_from_env`] reads the current process
-/// environment and re-adds CD only; [`DirectivePassthrough::inherit_from_env_with_exec`]
-/// re-adds CD and EXEC. The EXEC file is only included by the `_with_exec`
-/// variant — every other path scrubs it so alias/hook shell bodies cannot
-/// inject arbitrary shell into the parent session.
+/// environment and re-adds CD.
#[derive(Debug, Default, Clone)]
pub struct DirectivePassthrough {
pub cd_file: Option<std::path::PathBuf>,
- pub exec_file: Option<std::path::PathBuf>,
}
impl DirectivePassthrough {
/// Pass the CD directive file through to the child, reading the current
/// process environment. Used by project aliases and foreground hooks that
- /// may legitimately emit a `cd` directive. The EXEC file is deliberately
- /// omitted — a project-config body could otherwise inject arbitrary shell
- /// into the parent session.
+ /// may legitimately emit a `cd` directive.
pub fn inherit_from_env() -> Self {
use worktrunk::shell_exec::DIRECTIVE_CD_FILE_ENV_VAR;
Self {
cd_file: read_directive_env(DIRECTIVE_CD_FILE_ENV_VAR),
- exec_file: None,
- }
- }
-
- /// Like [`Self::inherit_from_env`] but also passes the EXEC directive
- /// file through. Used only for user-source aliases: the body lives in the
- /// user's own config, so a nested `wt --execute` is no different from the
- /// user typing the same command at the top level. See issue #2101.
- pub fn inherit_from_env_with_exec() -> Self {
- use worktrunk::shell_exec::DIRECTIVE_EXEC_FILE_ENV_VAR;
- Self {
- exec_file: read_directive_env(DIRECTIVE_EXEC_FILE_ENV_VAR),
- ..Self::inherit_from_env()
}
}
}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 41617b974..2c113f4ca 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -4,8 +4,8 @@
//!
//! For regular output, use `eprintln!`/`println!` directly (from `worktrunk::styling`
//! for color support); [`print_json`] serializes a `--format=json` answer to stdout.
-//! This module handles shell integration directives (cd, exec) that need to be
-//! communicated to the parent shell.
+//! This module handles the cd directive that must be communicated to the
+//! parent shell.
//!
//! ## Usage
//!
@@ -14,18 +14,16 @@
//!
//! eprintln!("{}", success_message("Operation complete"));
//! output::change_directory(&path);
-//! output::execute("git pull");
+//! output::execute(vec!["git".into(), "pull".into()]);
//! ```
//!
//! ## Shell Integration
//!
-//! Two split directive files, one for each trust level:
+//! Shell integration uses one directive file:
//! - `WORKTRUNK_DIRECTIVE_CD_FILE` — raw path; the wrapper `cd`s to it.
-//! - `WORKTRUNK_DIRECTIVE_EXEC_FILE` — arbitrary shell; the wrapper sources it.
//!
-//! When no directive env vars are set (direct binary call):
-//! - Commands execute directly.
-//! - Shell hints are shown for missing integration.
+//! `--execute` programs always run directly. Without the CD directive, shell
+//! hints explain why the parent shell cannot follow the directory change.
//!
//! See [`shell_integration`] module for the complete spec of warning messages.
@@ -39,10 +37,10 @@ pub(crate) mod shell_integration;
// Re-export the public API
pub(crate) use global::{
- change_directory, exec_would_be_refused, execute, is_shell_integration_active,
- mark_cwd_removed, post_hook_display_path, pre_hook_display_path,
- print_outdated_shell_wrapper_hint_once, retired_shell_wrapper_active, set_verbosity,
- terminate_output, to_logical_path, was_cwd_removed,
+ change_directory, execute, is_shell_integration_active, mark_cwd_removed,
+ post_hook_display_path, pre_hook_display_path, print_outdated_shell_wrapper_hint_once,
+ retired_shell_wrapper_active, set_verbosity, terminate_output, to_logical_path,
+ was_cwd_removed,
};
// Re-export output handlers
pub(crate) use handlers::{
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
index 5cd32aa25..36cbb09ff 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
@@ -7,8 +7,7 @@ expression: output
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override wt command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -26,16 +25,15 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
@@ -51,16 +49,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
index e9f0d871c..eb8577266 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
@@ -7,8 +7,7 @@ expression: output
# This is the full function definition, output by `wt config shell init fish`.
# It's sourced at runtime by the wrapper in ~/.config/fish/functions/wt.fish.
-# Override wt command with split directive passing.
-# Creates two temp files: one for cd (raw path) and one for exec (shell).
+# Override wt command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
function wt
set -l use_source false
@@ -24,18 +23,13 @@ function wt
return 127
end
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 \
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \
cargo run --bin wt --quiet -- $args
else
- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
- WORKTRUNK_SHELL=fish \
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \
$WORKTRUNK_BIN $args
end
set -l exit_code $status
@@ -54,17 +48,7 @@ function wt
end
end
- # exec file holds arbitrary shell (e.g. from --execute)
- if test -s "$exec_file"
- set -l directive (string collect < "$exec_file")
- eval $directive
- set -l src_exit $status
- if test $exit_code -eq 0
- set exit_code $src_exit
- end
- end
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return $exit_code
end
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
index 747051051..a5bafff0f 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
@@ -32,8 +32,7 @@ export def "nu-complete wt" [spans: list<string>] {
}
}
-# Override wt command with split directive passing.
-# Creates two temp files: one for cd (raw path) and one for exec (shell).
+# Override wt so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
#
# Nushell pipeline workaround (nushell/nushell#12643):
@@ -54,11 +53,10 @@ export def "nu-complete wt" [spans: list<string>] {
# (`wt list --format json | from json`). No directive processing — `list`
# never emits directives. No directive env vars are set.
#
-# - Everything else: Stdout is redirected to a temp file via `o>`, then
-# returned as the function's last expression after directive processing.
-# Stderr flows to the terminal in real-time. The binary sees non-TTY stdout
-# and uses buffered mode, but commands other than `list` don't benefit from
-# progressive rendering anyway.
+# - Everything else: Stdout is normally redirected to a temp file via `o>`,
+# then returned as the function's last expression after directive processing.
+# `--execute` is the exception: wt's child needs the terminal, so stdout
+# streams directly and is not available to an outer nushell pipeline.
#
# Completer wired via `@complete` attribute on an untyped `[...args]` rest.
# The parameter-level `string@"completer"` form keeps tokens literal, which
@@ -95,15 +93,22 @@ export def --env --wrapped wt [...args] {
^$worktrunk_bin ...$args
} else {
let cd_file = (mktemp --tmpdir)
- let exec_file = (mktemp --tmpdir)
let stdout_file = (mktemp --tmpdir)
+ let wt_args = ($args | take until {|arg| $arg == "--" })
+ # Before `-x`, `c`, `v`, and `y` are boolean flags clap may cluster with it.
+ let has_execute = ($wt_args | any {|arg| $arg == "--execute" or ($arg | str starts-with "--execute=") or ($arg =~ '^-[cvy]*x') })
- # Capture stdout to file for pipeline passthrough; stderr flows to terminal.
+ # Capture stdout for pipeline passthrough unless wt will launch an
+ # interactive child, which must inherit the terminal.
# Nushell 0.98+ throws ShellError on non-zero exit (like bash `set -e`).
# `try` catches it so directive processing and temp file cleanup still run.
let exit_code = (try {
- with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file, WORKTRUNK_DIRECTIVE_EXEC_FILE: $exec_file } {
- ^$worktrunk_bin ...$args o> $stdout_file
+ with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file } {
+ if $has_execute {
+ ^$worktrunk_bin ...$args
+ } else {
+ ^$worktrunk_bin ...$args o> $stdout_file
+ }
}
0
} catch {
@@ -116,38 +121,9 @@ export def --env --wrapped wt [...args] {
cd $target_dir
}
- # exec file holds arbitrary shell (e.g. from --execute).
- # Execute the whole file as one sh invocation so multi-line payloads
- # share a single shell session (matching bash/zsh/fish `source` semantics:
- # variables persist, `cd` affects later commands, etc.).
- # Env changes (export) won't persist in the nushell session, but no
- # worktrunk code emits export directives.
- #
- # This path still requires `sh`, unlike the exit propagation below: an
- # exec body is a POSIX snippet by construction (`ShellEscapeMode::Posix`),
- # so there is no nushell-native command to hand it to. It only fires for
- # `--execute`, and which shell should run those bodies on Windows is an
- # open question — see issue #3944.
- #
- # `try` for the same reason as the binary call above: a body that exits
- # non-zero raises a ShellError that would unwind the whole `def`, skipping
- # cleanup (leaking all three temp files) and discarding the stdout this
- # function still has to return. Catching it also makes the body's exit code
- # a value we can fold in, rather than one the unwind happens to carry out.
- let exec_exit = if ($exec_file | path exists) and (open $exec_file --raw | str trim | is-not-empty) {
- let script = open $exec_file --raw
- try { ^sh -c $script; 0 } catch { $env.LAST_EXIT_CODE }
- } else {
- 0
- }
-
- # First non-zero wins, wt before the body — the precedence the bash, zsh
- # and fish wrappers apply to their `src_exit`.
- let exit_code = if $exit_code != 0 { $exit_code } else { $exec_exit }
-
- let output = (open $stdout_file --raw)
+ let output = if $has_execute { "" } else { open $stdout_file --raw }
- # Clean up all three temp files at once, after the last read of any of them.
+ # Clean up the temp files after their final reads.
#
# A bare `rm` here is shadowable by the user's own `alias rm = ...`:
# nushell resolves aliases at parse time, and `config.nu` runs before the
@@ -163,9 +139,9 @@ export def --env --wrapped wt [...args] {
# option: it's a parse-time keyword that leaks out of this function into
# the user's session, silently unbinding their alias.
if $nu.os-info.family == "windows" {
- try { rm -f $cd_file $exec_file $stdout_file }
+ try { rm -f $cd_file $stdout_file }
} else {
- try { ^rm -f $cd_file $exec_file $stdout_file }
+ try { ^rm -f $cd_file $stdout_file }
}
# Return stdout or propagate failure as the function's last expression.
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
index 10782b384..45572d75c 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
@@ -12,7 +12,7 @@ expression: output
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
- # wt wrapper function - uses split temp files for directives
+ # wt wrapper function - uses a temp file for the parent-shell cd directive
#
# IMPORTANT: This function must remain a "simple function" (no [CmdletBinding()] or
# [Parameter()] attributes). Advanced functions add common parameters like -Debug,
@@ -30,25 +30,18 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
}
$cdFile = [System.IO.Path]::GetTempFileName()
- $execFile = [System.IO.Path]::GetTempFileName()
try {
- # Run wt with split directive env vars
- # WORKTRUNK_SHELL selects PowerShell escaping for the EXEC directive payload
+ # Run wt with the parent-shell cd directive
$env:WORKTRUNK_DIRECTIVE_CD_FILE = $cdFile
- $env:WORKTRUNK_DIRECTIVE_EXEC_FILE = $execFile
- $env:WORKTRUNK_SHELL = "powershell"
& $wtBin @args
$exitCode = $LASTEXITCODE
}
finally {
Remove-Item Env:\WORKTRUNK_DIRECTIVE_CD_FILE -ErrorAction SilentlyContinue
- Remove-Item Env:\WORKTRUNK_DIRECTIVE_EXEC_FILE -ErrorAction SilentlyContinue
- Remove-Item Env:\WORKTRUNK_SHELL -ErrorAction SilentlyContinue
}
- # Process directive files and clean up in a single try/finally so both
- # temp files are removed even if cd or exec throws.
+ # Process the directive and clean it up even if cd throws.
try {
# cd file holds a raw path (no shell escaping needed)
if ((Test-Path $cdFile) -and (Get-Item $cdFile).Length -gt 0) {
@@ -61,20 +54,9 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
}
}
- # exec file holds arbitrary shell (e.g. from --execute)
- if ((Test-Path $execFile) -and (Get-Item $execFile).Length -gt 0) {
- $script = Get-Content -Path $execFile -Raw
- if ($script.Trim()) {
- Invoke-Expression $script
- if ($exitCode -eq 0) {
- $exitCode = $LASTEXITCODE
- }
- }
- }
}
finally {
Remove-Item $cdFile -ErrorAction SilentlyContinue
- Remove-Item $execFile -ErrorAction SilentlyContinue
}
# Propagate the exit code so scripts/CI can read $LASTEXITCODE.
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
index 0c9b69413..6f2df7899 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
@@ -10,8 +10,7 @@ expression: output
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override wt command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -29,16 +28,15 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
@@ -54,16 +52,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
index 5db2aad6b..3f5a7dd6b 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
@@ -7,8 +7,7 @@ expression: "init.generate().expect(\"Should generate with custom prefix\")"
# Only initialize if custom is available (in PATH or via WORKTRUNK_BIN)
if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override custom command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override custom command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
custom() {
local use_source=false
@@ -26,16 +25,15 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin custom --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-custom}" "${args[@]}" || exit_code=$?
fi
@@ -51,16 +49,7 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 154078bc6..3982aca03 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -524,18 +524,15 @@ fn find_git_bash() -> Option<PathBuf> {
/// injection surface — this is safe to pass through to alias/hook shell bodies.
pub const DIRECTIVE_CD_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_CD_FILE";
-/// Environment variable naming the directive file for arbitrary exec commands.
+/// Retired shell-command directive variable.
///
-/// Shell wrappers set this to a temp file; wt writes shell commands (e.g. the
-/// body of `wt switch --execute`) to it and the wrapper sources the file after
-/// wt exits, so the command runs in the user's interactive shell. Because the
-/// file contents are arbitrary shell, wt scrubs this from project-alias and
-/// hook child environments — a body authored in shared config could inject
-/// shell into the parent shell. User-source aliases re-add it (issue #2101)
-/// since the body is user-authored just like a top-level `wt --execute`.
+/// Current wrappers no longer set it. Its presence tells `--execute` that the
+/// live shell still has an old wrapper loaded, and subprocesses must not
+/// inherit it: an older parent wrapper would source anything written there
+/// after wt exits.
pub const DIRECTIVE_EXEC_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_EXEC_FILE";
-/// Retired pre-split directive file env var.
+/// Retired single-file directive env var.
///
/// wt never writes to or passes this file through, but still removes the
/// variable from child environments so an old wrapper cannot expose a file
@@ -629,10 +626,9 @@ pub fn apply_cd_directive_env(cmd: &mut std::process::Command, cd_file: &std::pa
///
/// - **`wt` relocated a user command into a worktree it selected** — hooks
/// (run in the operation's worktree), `wt step for-each` (run in each
-/// worktree in turn), and the `--execute` no-integration fallback (run in
-/// the switch target when `wt` itself executes the payload) — the cwd
-/// carries `wt`'s intent, so the inherited context is scrubbed and the
-/// command's `git` calls discover the worktree from the cwd. The inherited
+/// worktree in turn), and the `--execute` program (run in the switch target)
+/// — the cwd carries `wt`'s intent, so the inherited context is scrubbed and
+/// the command's `git` calls discover the worktree from the cwd. The inherited
/// context is common, not exotic: `git` exports an absolute `GIT_DIR`
/// pinned to the invoking worktree's private gitdir when `wt` runs as a
/// `!wt` alias from a **linked worktree**, and git itself exports discovery
@@ -645,14 +641,7 @@ pub fn apply_cd_directive_env(cmd: &mut std::process::Command, cd_file: &std::pa
/// - **The child runs where the user already was** — aliases (the user's own
/// top-level command, run from the invoking worktree) and `commit.generation`
/// commands (spawned with no `current_dir`) — the inherited context *is* the
-/// user's context, so it is forwarded untouched. Under shell integration the
-/// `--execute` payload also lands here: the wrapper shell evaluates it, so
-/// it sees that shell's own environment (which never contains the vars a
-/// `!wt` git alias exports — git's exports die with `wt`'s process tree).
-/// Scrubbing the fallback therefore *converges* the two `--execute` paths
-/// for the alias case; only a `GIT_DIR` the user globally exported in their
-/// interactive shell still differs, and such an env misdirects every plain
-/// `git` command they run anyway.
+/// user's context, so it is forwarded untouched.
///
/// - **`wt`'s own git plumbing** ([`Cmd`] via `Repository::run_command`) keeps
/// the inherited context on purpose (relative values absolutized, see issue
@@ -716,81 +705,20 @@ pub fn apply_hermetic_test_env(cmd: &mut std::process::Command) {
}
// ============================================================================
-// Directive-Payload Shell Escaping
+// Shell Escaping
// ============================================================================
-/// Environment variable a shell wrapper sets to identify itself.
+/// How to expand a value into a command template.
///
-/// 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.
+/// Hooks and aliases are POSIX shell command lines. Filesystem paths and
+/// `--execute` argv elements use literal expansion because no shell parses
+/// them.
#[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 single-quoting (`'it'\''s'`) for hooks and 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 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`].
@@ -802,8 +730,6 @@ pub fn shell_escape_for(mode: ShellEscapeMode, s: &str) -> String {
ShellEscapeMode::Posix => {
shell_escape::unix::escape(std::borrow::Cow::Borrowed(s)).into_owned()
}
- ShellEscapeMode::PowerShell => powershell_escape(s),
- ShellEscapeMode::Fish => fish_escape(s),
}
}
@@ -1149,6 +1075,10 @@ pub struct Cmd {
share_parent_pgroup: bool,
/// If true, forward signals to child process group (for stream(), Unix only)
forward_signals: bool,
+ /// If true, treat a SIGPIPE exit as success. This is the default for pager
+ /// producers, where the consumer closing early is expected. Direct user
+ /// programs can opt out with [`Cmd::propagate_sigpipe`].
+ ignore_sigpipe: bool,
/// When set, log this command to the command log after execution.
/// The label identifies what triggered the command (e.g., "pre-merge user:lint").
external_label: Option<String>,
@@ -1157,12 +1087,6 @@ pub struct Cmd {
/// shell bodies may emit cd directives (the file holds a raw path, no shell
/// injection surface).
directive_cd_file: Option<std::path::PathBuf>,
- /// When set, re-adds `WORKTRUNK_DIRECTIVE_EXEC_FILE` after the security
- /// scrub. Set only by user-source aliases (issue #2101): the body is the
- /// user's own config, so a nested `wt --execute` is no different from the
- /// user typing it at the top level. Project aliases and hooks must NEVER
- /// set this — they could inject arbitrary shell into the parent session.
- directive_exec_file: Option<std::path::PathBuf>,
}
struct ExternalCommandLog {
@@ -1301,9 +1225,9 @@ impl Cmd {
stdin_cfg: None,
share_parent_pgroup: false,
forward_signals: false,
+ ignore_sigpipe: true,
external_label: None,
directive_cd_file: None,
- directive_exec_file: None,
}
}
@@ -1384,8 +1308,7 @@ impl Cmd {
// Prevent subprocesses from writing shell directives (security).
// Applied last so it can't be re-added by user-provided envs.
// `stream()` selectively re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` for
- // trusted contexts, and `WORKTRUNK_DIRECTIVE_EXEC_FILE` only for
- // trusted user-source aliases.
+ // trusted contexts.
scrub_directive_env_vars(cmd);
}
@@ -1559,6 +1482,17 @@ impl Cmd {
self
}
+ /// Preserve SIGPIPE as exit status 141 instead of treating it as pager
+ /// completion.
+ ///
+ /// `Cmd::stream()` historically ignores SIGPIPE because many callers feed
+ /// a pager that may quit before consuming all output. Use this for a child
+ /// whose status belongs to the user, such as `wt switch --execute`.
+ pub fn propagate_sigpipe(mut self) -> Self {
+ self.ignore_sigpipe = false;
+ self
+ }
+
/// Mark this command as an external (user-configured) command for logging.
///
/// When set, the command execution is logged to `.git/wt/logs/commands.jsonl`
@@ -1580,20 +1514,6 @@ impl Cmd {
self
}
- /// Pass the EXEC directive file through to the child process.
- ///
- /// Re-adds `WORKTRUNK_DIRECTIVE_EXEC_FILE`, allowing the child to request
- /// arbitrary shell execution in the parent shell (the wrapper sources the
- /// file after wt exits). This is only safe when the child's command body
- /// is itself trusted user-authored input — currently just user-source
- /// aliases, where the alias body lives in the user's own config and
- /// nesting `wt --execute` is no different from the user typing it. Project
- /// aliases and hooks must not call this — see issue #2101.
- pub fn directive_exec_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
- self.directive_exec_file = Some(path.into());
- self
- }
-
/// Execute the command and return its output.
///
/// Captures stdout/stderr and returns them in `Output`. For interactive
@@ -1610,7 +1530,7 @@ impl Cmd {
"Cmd::shell() commands must use .stream(), not .run()"
);
debug_assert!(
- self.directive_cd_file.is_none() && self.directive_exec_file.is_none(),
+ self.directive_cd_file.is_none(),
"directive_*_file is only applied by .stream(), not .run()"
);
@@ -1747,10 +1667,7 @@ impl Cmd {
"pipe_into does not support external() logging"
);
debug_assert!(
- self.directive_cd_file.is_none()
- && self.directive_exec_file.is_none()
- && next.directive_cd_file.is_none()
- && next.directive_exec_file.is_none(),
+ self.directive_cd_file.is_none() && next.directive_cd_file.is_none(),
"directive_*_file is only applied by .stream(), not pipe_into"
);
@@ -1960,16 +1877,10 @@ impl Cmd {
self.apply_common_settings(&mut cmd);
// Re-add directive files after security scrub for trusted contexts.
- // CD file is always safe to pass through (raw path, no shell). EXEC
- // file is only re-added for user-source aliases (issue #2101); project
- // aliases and hooks leave it scrubbed so their bodies cannot inject
- // shell into the parent session.
+ // The CD file is safe to pass through because it contains a raw path.
if let Some(ref path) = self.directive_cd_file {
apply_cd_directive_env(&mut cmd, path);
}
- if let Some(ref path) = self.directive_exec_file {
- cmd.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);
- }
if let Err(e) = self.check_spawn_preconditions() {
// Nothing spawned yet — emit a one-shot failed record (the trace
@@ -2106,7 +2017,7 @@ impl Cmd {
if let Some(sig) = std::os::unix::process::ExitStatusExt::signal(&status) {
// SIGPIPE (13) is expected when a pager (less, bat) exits before the
// child finishes writing — not an error from the user's perspective.
- if sig == SIGPIPE {
+ if sig == SIGPIPE && self.ignore_sigpipe {
trace.complete(true);
external_log.record(Some(0));
return Ok(());
@@ -2174,8 +2085,7 @@ impl Cmd {
self.stdin_data.is_none()
&& self.timeout.is_none()
&& self.external_label.is_none()
- && self.directive_cd_file.is_none()
- && self.directive_exec_file.is_none(),
+ && self.directive_cd_file.is_none(),
"delayed_stream does not support stdin/timeout/external/directive options"
);
@@ -2388,6 +2298,7 @@ mod tests {
#[test]
fn test_scrub_directive_env_vars_covers_every_directive_variable() {
assert_eq!(RETIRED_DIRECTIVE_FILE_ENV_VAR, "WORKTRUNK_DIRECTIVE_FILE");
+ assert_eq!(DIRECTIVE_EXEC_FILE_ENV_VAR, "WORKTRUNK_DIRECTIVE_EXEC_FILE");
let mut cmd = std::process::Command::new("child");
for var in [
@@ -2459,45 +2370,6 @@ mod tests {
assert!(!from_spawned);
}
- #[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.
@@ -2507,16 +2379,6 @@ mod tests {
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]
@@ -2862,6 +2724,27 @@ mod tests {
);
}
+ #[test]
+ #[cfg(unix)]
+ fn test_cmd_stream_can_propagate_sigpipe() {
+ use crate::git::WorktrunkError;
+
+ let err = Cmd::new("sh")
+ .args(["-c", "kill -PIPE $$"])
+ .propagate_sigpipe()
+ .stream()
+ .unwrap_err();
+ let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();
+ assert!(matches!(
+ wt_err,
+ WorktrunkError::ChildProcessExited {
+ code: 141,
+ signal: Some(13),
+ ..
+ }
+ ));
+ }
+
#[test]
#[cfg(unix)]
fn test_cmd_stream_other_signals_are_errors() {
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index eb250d5c9..ef0218ef5 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -1124,20 +1124,14 @@ pub trait TestRepoBase {
}
}
-/// Create a pair of temporary files for directive output (cd + exec), in a
-/// directory of their own.
+/// Create a temporary CD directive file for a shell-integration test.
///
-/// The shell wrapper creates temp files and sets `WORKTRUNK_DIRECTIVE_CD_FILE`
-/// and `WORKTRUNK_DIRECTIVE_EXEC_FILE` before running wt. Use
-/// `configure_directive_files()` to set these on a Command for testing.
-///
-/// Returns `(cd_path, exec_path, guard)`. The guard must be kept alive for the
-/// duration of the test — dropping it removes the directory and both files.
-pub fn directive_files() -> (PathBuf, PathBuf, TempDir) {
+/// The guard must be kept alive for the duration of the test — dropping it
+/// removes the directory and file.
+pub fn directive_file() -> (PathBuf, TempDir) {
let dir = directive_temp_dir();
let cd_path = create_empty(dir.path().join("cd"));
- let exec_path = create_empty(dir.path().join("exec"));
- (cd_path, exec_path, dir)
+ (cd_path, dir)
}
/// A private directory for a test's directive files.
@@ -1157,28 +1151,14 @@ fn directive_temp_dir() -> TempDir {
TempDir::new().expect("failed to create directive temp dir")
}
-/// Create `path` as an empty file, as the shell wrapper's `mktemp` would, and
-/// return it. wt appends to the exec file rather than creating it, so it has to
-/// exist before wt runs.
+/// Create `path` as an empty file and return it.
fn create_empty(path: PathBuf) -> PathBuf {
std::fs::File::create(&path).expect("failed to create a directive file in its own temp dir");
path
}
-/// Configure a Command to use the new split directive-file protocol.
-///
-/// Sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE` env
-/// vars so the wt binary writes a raw path to the cd file and arbitrary shell
-/// to the exec file.
-pub fn configure_directive_files(cmd: &mut Command, cd_path: &Path, exec_path: &Path) {
- cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", cd_path);
- cmd.env("WORKTRUNK_DIRECTIVE_EXEC_FILE", exec_path);
-}
-
-/// Configure a Command to use the split directive-file protocol with only the
-/// CD file (EXEC scrubbed). This simulates running inside an alias/hook body
-/// where the EXEC env var was stripped.
-pub fn configure_directive_cd_only(cmd: &mut Command, cd_path: &Path) {
+/// Configure a Command with the shell wrapper's CD directive file.
+pub fn configure_directive_file(cmd: &mut Command, cd_path: &Path) {
cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", cd_path);
}
diff --git a/templates/bash.sh b/templates/bash.sh
index 8cef38d9e..9f4958ef7 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -3,8 +3,7 @@
# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)
if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override {{ cmd }} command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override {{ cmd }} command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
{{ cmd }}() {
local use_source=false
@@ -22,16 +21,15 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?
fi
@@ -47,16 +45,7 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/templates/fish.fish b/templates/fish.fish
index 13ee6abf0..011dd158e 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -3,8 +3,7 @@
# This is the full function definition, output by `{{ cmd }} config shell init fish`.
# It's sourced at runtime by the wrapper in ~/.config/fish/functions/{{ cmd }}.fish.
-# Override {{ cmd }} command with split directive passing.
-# Creates two temp files: one for cd (raw path) and one for exec (shell).
+# Override {{ cmd }} command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
function {{ cmd }}
set -l use_source false
@@ -20,18 +19,13 @@ function {{ cmd }}
return 127
end
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 \
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \
cargo run --bin {{ cmd }} --quiet -- $args
else
- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
- WORKTRUNK_SHELL=fish \
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \
$WORKTRUNK_BIN $args
end
set -l exit_code $status
@@ -50,17 +44,7 @@ function {{ cmd }}
end
end
- # exec file holds arbitrary shell (e.g. from --execute)
- if test -s "$exec_file"
- set -l directive (string collect < "$exec_file")
- eval $directive
- set -l src_exit $status
- if test $exit_code -eq 0
- set exit_code $src_exit
- end
- end
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return $exit_code
end
diff --git a/templates/nushell.nu b/templates/nushell.nu
index 49b79ba0b..43e7edab7 100644
--- a/templates/nushell.nu
+++ b/templates/nushell.nu
@@ -28,8 +28,7 @@ export def "nu-complete {{ cmd }}" [spans: list<string>] {
}
}
-# Override {{ cmd }} command with split directive passing.
-# Creates two temp files: one for cd (raw path) and one for exec (shell).
+# Override {{ cmd }} so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
#
# Nushell pipeline workaround (nushell/nushell#12643):
@@ -50,11 +49,10 @@ export def "nu-complete {{ cmd }}" [spans: list<string>] {
# (`{{ cmd }} list --format json | from json`). No directive processing — `list`
# never emits directives. No directive env vars are set.
#
-# - Everything else: Stdout is redirected to a temp file via `o>`, then
-# returned as the function's last expression after directive processing.
-# Stderr flows to the terminal in real-time. The binary sees non-TTY stdout
-# and uses buffered mode, but commands other than `list` don't benefit from
-# progressive rendering anyway.
+# - Everything else: Stdout is normally redirected to a temp file via `o>`,
+# then returned as the function's last expression after directive processing.
+# `--execute` is the exception: wt's child needs the terminal, so stdout
+# streams directly and is not available to an outer nushell pipeline.
#
# Completer wired via `@complete` attribute on an untyped `[...args]` rest.
# The parameter-level `string@"completer"` form keeps tokens literal, which
@@ -91,15 +89,22 @@ export def --env --wrapped {{ cmd }} [...args] {
^$worktrunk_bin ...$args
} else {
let cd_file = (mktemp --tmpdir)
- let exec_file = (mktemp --tmpdir)
let stdout_file = (mktemp --tmpdir)
+ let wt_args = ($args | take until {|arg| $arg == "--" })
+ # Before `-x`, `c`, `v`, and `y` are boolean flags clap may cluster with it.
+ let has_execute = ($wt_args | any {|arg| $arg == "--execute" or ($arg | str starts-with "--execute=") or ($arg =~ '^-[cvy]*x') })
- # Capture stdout to file for pipeline passthrough; stderr flows to terminal.
+ # Capture stdout for pipeline passthrough unless wt will launch an
+ # interactive child, which must inherit the terminal.
# Nushell 0.98+ throws ShellError on non-zero exit (like bash `set -e`).
# `try` catches it so directive processing and temp file cleanup still run.
let exit_code = (try {
- with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file, WORKTRUNK_DIRECTIVE_EXEC_FILE: $exec_file } {
- ^$worktrunk_bin ...$args o> $stdout_file
+ with-env { WORKTRUNK_DIRECTIVE_CD_FILE: $cd_file } {
+ if $has_execute {
+ ^$worktrunk_bin ...$args
+ } else {
+ ^$worktrunk_bin ...$args o> $stdout_file
+ }
}
0
} catch {
@@ -112,38 +117,9 @@ export def --env --wrapped {{ cmd }} [...args] {
cd $target_dir
}
- # exec file holds arbitrary shell (e.g. from --execute).
- # Execute the whole file as one sh invocation so multi-line payloads
- # share a single shell session (matching bash/zsh/fish `source` semantics:
- # variables persist, `cd` affects later commands, etc.).
- # Env changes (export) won't persist in the nushell session, but no
- # worktrunk code emits export directives.
- #
- # This path still requires `sh`, unlike the exit propagation below: an
- # exec body is a POSIX snippet by construction (`ShellEscapeMode::Posix`),
- # so there is no nushell-native command to hand it to. It only fires for
- # `--execute`, and which shell should run those bodies on Windows is an
- # open question — see issue #3944.
- #
- # `try` for the same reason as the binary call above: a body that exits
- # non-zero raises a ShellError that would unwind the whole `def`, skipping
- # cleanup (leaking all three temp files) and discarding the stdout this
- # function still has to return. Catching it also makes the body's exit code
- # a value we can fold in, rather than one the unwind happens to carry out.
- let exec_exit = if ($exec_file | path exists) and (open $exec_file --raw | str trim | is-not-empty) {
- let script = open $exec_file --raw
- try { ^sh -c $script; 0 } catch { $env.LAST_EXIT_CODE }
- } else {
- 0
- }
-
- # First non-zero wins, wt before the body — the precedence the bash, zsh
- # and fish wrappers apply to their `src_exit`.
- let exit_code = if $exit_code != 0 { $exit_code } else { $exec_exit }
-
- let output = (open $stdout_file --raw)
+ let output = if $has_execute { "" } else { open $stdout_file --raw }
- # Clean up all three temp files at once, after the last read of any of them.
+ # Clean up the temp files after their final reads.
#
# A bare `rm` here is shadowable by the user's own `alias rm = ...`:
# nushell resolves aliases at parse time, and `config.nu` runs before the
@@ -159,9 +135,9 @@ export def --env --wrapped {{ cmd }} [...args] {
# option: it's a parse-time keyword that leaks out of this function into
# the user's session, silently unbinding their alias.
if $nu.os-info.family == "windows" {
- try { rm -f $cd_file $exec_file $stdout_file }
+ try { rm -f $cd_file $stdout_file }
} else {
- try { ^rm -f $cd_file $exec_file $stdout_file }
+ try { ^rm -f $cd_file $stdout_file }
}
# Return stdout or propagate failure as the function's last expression.
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index 1dad924c2..7d322fd89 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -8,7 +8,7 @@
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
- # wt wrapper function - uses split temp files for directives
+ # wt wrapper function - uses a temp file for the parent-shell cd directive
#
# IMPORTANT: This function must remain a "simple function" (no [CmdletBinding()] or
# [Parameter()] attributes). Advanced functions add common parameters like -Debug,
@@ -26,25 +26,18 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN
}
$cdFile = [System.IO.Path]::GetTempFileName()
- $execFile = [System.IO.Path]::GetTempFileName()
try {
- # Run wt with split directive env vars
- # WORKTRUNK_SHELL selects PowerShell escaping for the EXEC directive payload
+ # Run wt with the parent-shell cd directive
$env:WORKTRUNK_DIRECTIVE_CD_FILE = $cdFile
- $env:WORKTRUNK_DIRECTIVE_EXEC_FILE = $execFile
- $env:WORKTRUNK_SHELL = "powershell"
& $wtBin @args
$exitCode = $LASTEXITCODE
}
finally {
Remove-Item Env:\WORKTRUNK_DIRECTIVE_CD_FILE -ErrorAction SilentlyContinue
- Remove-Item Env:\WORKTRUNK_DIRECTIVE_EXEC_FILE -ErrorAction SilentlyContinue
- Remove-Item Env:\WORKTRUNK_SHELL -ErrorAction SilentlyContinue
}
- # Process directive files and clean up in a single try/finally so both
- # temp files are removed even if cd or exec throws.
+ # Process the directive and clean it up even if cd throws.
try {
# cd file holds a raw path (no shell escaping needed)
if ((Test-Path $cdFile) -and (Get-Item $cdFile).Length -gt 0) {
@@ -57,20 +50,9 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN
}
}
- # exec file holds arbitrary shell (e.g. from --execute)
- if ((Test-Path $execFile) -and (Get-Item $execFile).Length -gt 0) {
- $script = Get-Content -Path $execFile -Raw
- if ($script.Trim()) {
- Invoke-Expression $script
- if ($exitCode -eq 0) {
- $exitCode = $LASTEXITCODE
- }
- }
- }
}
finally {
Remove-Item $cdFile -ErrorAction SilentlyContinue
- Remove-Item $execFile -ErrorAction SilentlyContinue
}
# Propagate the exit code so scripts/CI can read $LASTEXITCODE.
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
index cbdc44a0f..e1d5716ce 100644
--- a/templates/zsh.zsh
+++ b/templates/zsh.zsh
@@ -6,8 +6,7 @@
# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)
if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override {{ cmd }} command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override {{ cmd }} command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
{{ cmd }}() {
local use_source=false
@@ -25,16 +24,15 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin {{ cmd }} --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}" || exit_code=$?
fi
@@ -50,16 +48,7 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index 1e6c87d25..ba7710bd6 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -393,7 +393,7 @@ Tests run once. Worktrunk configures no nextest `retries`, and no test re-runs i
- A kill at the 180s slow-timeout is a duration symptom with two causes, told apart by the durations around it: many stretched durations alongside high machine load is CPU starvation, usually a sibling worktree's concurrent build; one test pinned at the timeout in an otherwise-normal run is a blocked call inside it, usually network. Starvation's only lever here would be nextest `threads-required` bounds on the heavy PTY tests, deliberately unset while these stay rare one-offs: the bound taxes every healthy run, and can't see the sibling build that caused the starvation.
- A shared channel with more than one producer is an attribution bug. Counting events drained from a channel between steps only measures the step that produced them if nothing *else* can produce them: a background task's event landing after its step's drain is charged to the next step, so the assertion that fails names the wrong step and the wrong cause. The events are usually indistinguishable (skim's `Event::RunPreview` carries no payload), so identity assertions aren't available — quiesce the other producers instead, before the step sequence arms whatever they'd match. `on_update_pokes_run_preview_only_when_the_visible_pane_changes` is the worked example: `PreviewOrchestrator::wait_for_idle()` before each `note_awaiting`, so the skeleton precompute lands while no key matches it.
- A spawn that fails `NotFound` is a concurrent-build bug. Cargo uplifts `target/debug/wt` by removing the path and recreating it, so a second `cargo` against the same target directory leaves the binary absent for a fraction of a millisecond per rebuild, failing whatever spawn is in flight with `Os { code: 2, kind: NotFound }` — anywhere: an `insta_cmd` snapshot, a PTY wrapper's `wt config shell init`, a hook whose marker file then never appears — and passing on re-run, which is the signature. `wt_bin()` closes the window by spawning a hardlink pinned under `target/debug/wt-test-bin/` instead of the uplifted path (`testing::pin_test_binary`), so route every `wt` spawn through it or a helper that does; `test_wt_spawns_are_pinned` makes a direct `CARGO_BIN_EXE_wt` spawn fail the suite.
-- A shared namespace is a collision bug. **Never `NamedTempFile::new()`** for a file a test needs by name: `tempfile` retries a name collision only when it surfaces as `AlreadyExists`, and on Windows `create_new` against a name already held by a *directory* — or by a file in delete-pending state — comes back `PermissionDenied`, which it hands straight back to the caller. A full suite run leaves the temp directory full of `.tmpXXXXXX` entries (every `TestRepo` makes one), and under that load the call fails ~1% of the time with `Access is denied.` — a panic that has nothing to do with what the test asserts. Take a `TempDir` and give the files fixed names inside it (`worktrunk::testing::directive_files` is the pattern); a directory collision surfaces as `AlreadyExists`, which tempfile retries.
+- A shared namespace is a collision bug. **Never `NamedTempFile::new()`** for a file a test needs by name: `tempfile` retries a name collision only when it surfaces as `AlreadyExists`, and on Windows `create_new` against a name already held by a *directory* — or by a file in delete-pending state — comes back `PermissionDenied`, which it hands straight back to the caller. A full suite run leaves the temp directory full of `.tmpXXXXXX` entries (every `TestRepo` makes one), and under that load the call fails ~1% of the time with `Access is denied.` — a panic that has nothing to do with what the test asserts. Take a `TempDir` and give the files fixed names inside it (`worktrunk::testing::directive_file` is the pattern); a directory collision surfaces as `AlreadyExists`, which tempfile retries.
A bounded poll that rides out one identified `ErrorKind` whose window is understood is itself a root fix, and the doctrine leaves it alone: `pin_test_binary` polls `NotFound` across cargo's uplift window, and `forward_with_etxtbsy_retry` (`src/completion.rs`) polls `ExecutableFileBusy` while a concurrently-forked child holds the just-written script's write fd open. Both fail immediately on any other error, which is what keeps a poll from drifting into a retry.
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index ef4423ff1..d45d4b378 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -1,6 +1,6 @@
use crate::common::{
BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, canonicalize,
- configure_directive_files, configure_git_cmd, configure_git_env, directive_files, repo,
+ configure_directive_file, configure_git_cmd, configure_git_env, directive_file, repo,
setup_temp_snapshot_settings, wait_for_file, wait_for_file_content, wait_for_worktree_removed,
wt_command,
};
@@ -64,10 +64,10 @@ fn test_bare_repo_switch_creates_worktree() {
// Run wt switch --create to create a new worktree
// Config uses {{ branch }} template, so worktrees are created inside bare repo
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
@@ -111,10 +111,10 @@ fn test_bare_repo_switch_with_configured_naming() {
test.commit_in(&main_worktree, "Initial commit");
// Config uses "{{ branch }}" template, so worktrees are created inside bare repo
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
@@ -149,10 +149,10 @@ fn test_bare_repo_remove_worktree() {
test.commit_in(&feature_worktree, "Feature work");
// Remove feature worktree from main worktree
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["remove", "feature", "--foreground"])
.current_dir(&main_worktree);
@@ -208,10 +208,10 @@ fn test_bare_repo_path_used_for_worktree_paths() {
// Create new worktree - config uses {{ branch }} template
// Worktrees are created inside the bare repo directory
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "dev"])
.current_dir(&main_worktree);
@@ -252,10 +252,10 @@ fn test_bare_repo_with_repo_path_variable() {
test.commit_in(&main_worktree, "Initial commit");
// Create new worktree using wt switch
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature/auth"])
.current_dir(&main_worktree);
@@ -608,10 +608,10 @@ fn test_bare_repo_merge_workflow() {
// Create feature branch worktree using wt switch
// Config uses {{ branch }} template, so worktrees are inside bare repo
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -624,10 +624,10 @@ fn test_bare_repo_merge_workflow() {
test.commit_in(&feature_worktree, "Feature work");
// Merge feature into main (explicitly specify target)
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args([
"merge",
"main", // Explicitly specify target branch
@@ -686,10 +686,10 @@ fn test_bare_repo_background_logs_location() {
test.commit_in(&feature_worktree, "Feature work");
// Run remove in background to test log file location
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["remove", "feature"]).current_dir(&main_worktree);
let output = cmd.output().unwrap();
@@ -765,10 +765,10 @@ fn test_bare_repo_project_config_found_from_bare_root() {
// Now run `wt switch --create feature` from the bare repo root (NOT from main worktree)
// This is the scenario described in #1691
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature", "--yes"])
.current_dir(test.bare_repo_path());
@@ -864,10 +864,10 @@ fn test_bare_repo_project_config_found_when_primary_on_non_default_branch() {
.unwrap();
// Now run `wt switch --create test-repro` from the bare repo root.
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "test-repro", "--yes"])
.current_dir(test.bare_repo_path());
@@ -929,10 +929,10 @@ fn test_bare_repo_no_project_config_when_primary_off_branch_and_none_present() {
// Run `wt switch --create foo` from the bare repo root. With no project
// config anywhere, it should still succeed.
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "foo", "--yes"])
.current_dir(test.bare_repo_path());
@@ -1084,10 +1084,10 @@ fn test_bare_repo_project_config_found_from_linked_worktree_when_primary_off_bra
);
// Run `wt switch --create` from *inside* the `other` worktree (HEAD = other).
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "test-repro", "--yes"])
.current_dir(&other_worktree);
@@ -1247,10 +1247,10 @@ fn test_bare_repo_project_config_found_with_dash_c_flag() {
// Run from a completely unrelated directory using -C to point at the bare repo
let unrelated_dir = tempfile::tempdir().unwrap();
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args([
"-C",
test.bare_repo_path().to_str().unwrap(),
@@ -1305,10 +1305,10 @@ fn test_bare_repo_ignores_config_in_bare_root() {
.unwrap();
// Run `wt switch --create feature` from the bare repo root
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature", "--yes"])
.current_dir(test.bare_repo_path());
@@ -1346,10 +1346,10 @@ fn test_bare_repo_slashed_branch_with_sanitize() {
test.commit_in(&main_worktree, "Initial commit");
// Create feature branch with slash using wt switch
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature/auth"])
.current_dir(&main_worktree);
@@ -1481,10 +1481,10 @@ fn test_nested_bare_repo_worktree_path() {
let test = NestedBareRepoTest::new();
// Create first worktree using wt switch --create
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
@@ -1519,10 +1519,10 @@ fn test_nested_bare_repo_full_workflow() {
let test = NestedBareRepoTest::new();
// Create main worktree
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
cmd.output().unwrap();
@@ -1532,10 +1532,10 @@ fn test_nested_bare_repo_full_workflow() {
test.commit_in(&main_worktree, "Initial");
// Create feature worktree
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -1558,10 +1558,10 @@ fn test_nested_bare_repo_full_workflow() {
assert!(stdout.contains("feature"), "Should list feature worktree");
// Remove feature worktree
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["remove", "feature", "--foreground"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -1578,10 +1578,10 @@ fn test_nested_bare_repo_list_snapshot() {
let test = NestedBareRepoTest::new();
// Create main worktree
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
cmd.output().unwrap();
@@ -1590,10 +1590,10 @@ fn test_nested_bare_repo_list_snapshot() {
test.commit_in(&main_worktree, "Initial");
// Create feature worktree
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature"])
.current_dir(&main_worktree);
cmd.output().unwrap();
@@ -1619,10 +1619,10 @@ fn test_bare_repo_bootstrap_first_worktree() {
// Unlike other tests, we do NOT create any worktrees first.
// We run wt switch --create directly on the bare repo.
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "main"])
.current_dir(test.bare_repo_path());
@@ -1763,10 +1763,10 @@ fn test_bare_repo_merge_preserves_default_branch_worktree() {
// Run `wt merge feature` from the main (default branch) worktree.
// This attempts to merge main into feature — the important thing is that
// the main worktree must NOT be removed even though is_linked() returns true.
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args([
"merge",
"feature", // Target = feature branch
@@ -1808,10 +1808,10 @@ fn setup_unconfigured_nested_bare_repo() -> NestedBareRepoTest {
.unwrap();
// Create main worktree with a commit (needed as a starting point for switch)
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "main", "--yes"])
.current_dir(test.bare_repo_path());
let output = cmd.output().unwrap();
@@ -1837,10 +1837,10 @@ fn test_bare_repo_worktree_path_prompt_auto_accept() {
let settings = setup_temp_snapshot_settings(test.temp_path());
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "feature", "--yes"])
.current_dir(&main_worktree);
@@ -1871,10 +1871,10 @@ fn test_bare_repo_worktree_path_prompt_non_interactive_warning() {
let settings = setup_temp_snapshot_settings(test.temp_path());
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
test.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
// No --yes, but stdin is piped (non-interactive) since assert_cmd_snapshot
// doesn't attach a TTY
cmd.args(["switch", "--create", "feature"])
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 68edae431..e49817e21 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -1042,9 +1042,9 @@ fn test_complete_switch_execute_all_formats(repo: TestRepo) {
// Test all execute flag formats: --execute with space, --execute=, -xvalue
// All should complete branches after the execute value is provided
let test_cases: &[&[&str]] = &[
- &["wt", "switch", "--execute", "code .", ""], // --execute with space
- &["wt", "switch", "--execute=code .", ""], // --execute= with equals
- &["wt", "switch", "-xcode", ""], // -x fused short form
+ &["wt", "switch", "--execute", "code", ""], // --execute with space
+ &["wt", "switch", "--execute=code", ""], // --execute= with equals
+ &["wt", "switch", "-xcode", ""], // -x fused short form
];
for args in test_cases {
diff --git a/tests/integration_tests/custom.rs b/tests/integration_tests/custom.rs
index 2f724b2b5..a3cb55a7d 100644
--- a/tests/integration_tests/custom.rs
+++ b/tests/integration_tests/custom.rs
@@ -96,7 +96,7 @@ fn custom_subcommand_accepts_non_utf8_forwarded_arg() {
#[cfg(unix)]
#[test]
-fn custom_subcommand_scrubs_retired_directive_and_preserves_split_files() {
+fn custom_subcommand_scrubs_shell_exec_directives_and_preserves_cd() {
use std::os::unix::fs::PermissionsExt;
use worktrunk::shell_exec::{
DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,
@@ -142,10 +142,7 @@ printf 'retired=%s\ncd=%s\nexec=%s\n' "${WORKTRUNK_DIRECTIVE_FILE-unset}" "${WOR
stdout.contains(&format!("cd={}", cd_file.display())),
"{stdout}"
);
- assert!(
- stdout.contains(&format!("exec={}", exec_file.display())),
- "{stdout}"
- );
+ assert!(stdout.contains("exec=unset"), "{stdout}");
assert_eq!(
std::fs::read_to_string(&retired_file).unwrap(),
"",
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index 105ec9208..a235cae4f 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -1,7 +1,6 @@
use crate::common::{
- TestRepo, configure_directive_cd_only, configure_directive_files, directive_files, repo,
- repo_with_feature_worktree, repo_with_remote, repo_with_remote_and_feature,
- setup_snapshot_settings, wt_command,
+ TestRepo, configure_directive_file, directive_file, repo, repo_with_feature_worktree,
+ repo_with_remote, repo_with_remote_and_feature, setup_snapshot_settings, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -11,16 +10,14 @@ use std::os::unix::fs as unix_fs;
use std::path::Path;
// ============================================================================
-// Directive File Tests (split protocol)
+// CD Directive File Tests
// ============================================================================
-// These tests verify the split directive-file protocol:
+// These tests verify the directive-file protocol:
// - WORKTRUNK_DIRECTIVE_CD_FILE: wt writes a raw path (no `cd ` prefix, no quotes).
// The shell wrapper runs `cd -- "$(< file)"`.
-// - WORKTRUNK_DIRECTIVE_EXEC_FILE: wt writes arbitrary shell (e.g. from --execute).
-// The shell wrapper sources the file.
#[rstest]
-fn test_switch_retired_directive_file_refuses_execute_after_switch(
+fn test_switch_retired_directive_file_does_not_block_execute(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
let feature_wt = repo.add_worktree("feature");
@@ -37,15 +34,13 @@ fn test_switch_retired_directive_file_refuses_execute_after_switch(
cmd.arg("switch")
.arg("feature")
.arg("--execute")
- .arg("echo spawned > retired-execute-ran")
+ .arg("sh")
+ .args(["--", "-c", "echo spawned > retired-execute-ran"])
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- assert!(
- !execute_marker.exists(),
- "wt must never spawn an --execute payload from the retired wrapper"
- );
+ assert!(execute_marker.exists(), "--execute should run directly");
assert_eq!(
fs::read_to_string(&directive_path).unwrap(),
"",
@@ -54,128 +49,76 @@ fn test_switch_retired_directive_file_refuses_execute_after_switch(
});
}
+/// A current wrapper may inherit retired variables from an older parent shell.
+/// The current CD file stays active, execution stays direct, and the stale
+/// execute wrapper gets a migration warning.
#[rstest]
-fn test_switch_retired_directive_file_refuses_execute_when_already_at(
+fn test_current_wrapper_wins_retired_variables_and_warns(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
- let feature_wt = repo.add_worktree("feature");
- let directive_dir = tempfile::TempDir::new().unwrap();
- let directive_path = directive_dir.path().join("directive");
- let execute_marker = feature_wt.join("retired-execute-ran");
- fs::write(&directive_path, "").unwrap();
+ let _feature_wt = repo.add_worktree("feature");
+ let (cd_path, _guard) = directive_file();
+ let retired_dir = tempfile::TempDir::new().unwrap();
+ let retired_path = retired_dir.path().join("directive");
+ let retired_exec_path = retired_dir.path().join("execute");
+ fs::write(&retired_path, "").unwrap();
+ fs::write(&retired_exec_path, "").unwrap();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_path);
- cmd.arg("switch")
- .arg("feature")
- .arg("--execute")
- .arg("echo spawned > retired-execute-ran")
- .current_dir(&feature_wt);
+ let mut cmd = repo.wt_command();
+ configure_directive_file(&mut cmd, &cd_path);
+ cmd.env("WORKTRUNK_DIRECTIVE_FILE", &retired_path)
+ .env("WORKTRUNK_DIRECTIVE_EXEC_FILE", &retired_exec_path)
+ .args([
+ "switch",
+ "feature",
+ "--execute",
+ "git",
+ "--",
+ "rev-parse",
+ "--abbrev-ref",
+ "HEAD",
+ ])
+ .current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
assert!(
- !execute_marker.exists(),
- "wt must never spawn an --execute payload from the retired wrapper"
+ !fs::read_to_string(&cd_path)
+ .unwrap_or_default()
+ .trim()
+ .is_empty(),
+ "the current wrapper's CD directive should remain active"
);
assert_eq!(
- fs::read_to_string(&directive_path).unwrap(),
+ fs::read_to_string(&retired_path).unwrap(),
"",
"wt must never write to the retired directive file"
);
- });
-}
-
-/// A current split wrapper may inherit the retired variable from an older
-/// parent shell. The split files still take precedence: both directives land
-/// in their dedicated files, and the retired file remains untouched.
-#[rstest]
-fn test_split_directive_files_win_over_retired_variable(
- #[from(repo_with_remote)] mut repo: TestRepo,
-) {
- let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
- let retired_dir = tempfile::TempDir::new().unwrap();
- let retired_path = retired_dir.path().join("directive");
- fs::write(&retired_path, "").unwrap();
-
- let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- let output = cmd
- .env("WORKTRUNK_DIRECTIVE_FILE", &retired_path)
- .args(["switch", "feature", "--execute", "echo through-split"])
- .current_dir(repo.root_path())
- .output()
- .unwrap();
-
- assert!(
- output.status.success(),
- "split directives must remain active when the retired variable is also set.\nstderr:\n{}",
- String::from_utf8_lossy(&output.stderr)
- );
- assert!(
- !fs::read_to_string(&cd_path)
- .unwrap_or_default()
- .trim()
- .is_empty(),
- "the split CD file must receive the target path"
- );
- assert_eq!(
- fs::read_to_string(&exec_path).unwrap(),
- "echo through-split\n",
- "the split EXEC file must receive the command"
- );
- assert_eq!(
- fs::read_to_string(&retired_path).unwrap(),
- "",
- "wt must never write to the retired directive file"
- );
-}
-
-/// When only the CD file is set (EXEC scrubbed — running inside an alias/hook),
-/// --execute commands are refused with a warning.
-#[rstest]
-fn test_switch_exec_scrubbed_warns(#[from(repo_with_remote)] repo: TestRepo) {
- let (cd_path, _exec_path, _guard) = directive_files();
-
- let settings = setup_snapshot_settings(&repo);
-
- settings.bind(|| {
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- // Only set CD file, not EXEC — simulates running inside alias/hook body
- configure_directive_cd_only(&mut cmd, &cd_path);
- cmd.args([
- "switch",
- "--create",
- "scrub-test",
- "--execute",
- "echo should-not-run",
- ])
- .current_dir(repo.root_path());
-
- assert_cmd_snapshot!(cmd);
+ assert_eq!(
+ fs::read_to_string(&retired_exec_path).unwrap(),
+ "",
+ "wt must never write to the retired execute directive file"
+ );
});
}
// ============================================================================
-// Split Protocol Tests
+// Directive Protocol Tests
// ============================================================================
#[rstest]
fn test_switch_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("feature")
.current_dir(repo.root_path());
@@ -197,49 +140,15 @@ fn test_switch_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
});
}
-/// A failed EXEC-directive write names the file and the write.
-///
-/// This write is the last thing a `--switch --execute` does, after the switch
-/// has already landed and after `◎ Executing (--execute):`, so the bare
-/// `io::Error` it used to propagate (`✗ No such file or directory (os error 2)`)
-/// read as if the *command* were missing. The paths come from the shell wrapper,
-/// so the message has to point there.
-#[rstest]
-fn test_exec_directive_write_failure_names_the_file(#[from(repo_with_remote)] mut repo: TestRepo) {
- let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
- // A path under a directory that doesn't exist: the open fails, and nothing
- // about it depends on platform or timing.
- let unwritable_exec = exec_path.parent().unwrap().join("no-such-dir").join("exec");
-
- let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &unwritable_exec);
- let output = cmd
- .args(["switch", "feature", "--execute", "echo hi"])
- .current_dir(repo.root_path())
- .output()
- .unwrap();
-
- let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- !output.status.success(),
- "an unwritable exec directive file must fail the command.\nstderr:\n{stderr}"
- );
- assert!(
- stderr.contains("Failed to write the command to the directive file"),
- "the error must name the write and the file.\nstderr:\n{stderr}"
- );
-}
-
/// A failed CD-directive write names the file too, for the same reason.
#[rstest]
fn test_cd_directive_write_failure_names_the_file(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let unwritable_cd = cd_path.parent().unwrap().join("no-such-dir").join("cd");
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &unwritable_cd, &exec_path);
+ configure_directive_file(&mut cmd, &unwritable_cd);
let output = cmd
.args(["switch", "feature"])
.current_dir(repo.root_path())
@@ -261,14 +170,14 @@ fn test_cd_directive_write_failure_names_the_file(#[from(repo_with_remote)] mut
fn test_merge_directive_file(mut repo_with_remote_and_feature: TestRepo) {
let repo = &mut repo_with_remote_and_feature;
let feature_wt = &repo.worktrees["feature"];
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("merge").arg("main").current_dir(feature_wt);
assert_cmd_snapshot!(cmd);
@@ -291,14 +200,14 @@ fn test_merge_directive_file(mut repo_with_remote_and_feature: TestRepo) {
#[rstest]
fn test_remove_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("remove").current_dir(&feature_wt);
assert_cmd_snapshot!(cmd);
@@ -326,7 +235,7 @@ fn test_remove_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
#[rstest]
fn test_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create the same subdirectory in both worktrees
let subdir = "apps/gateway";
@@ -335,7 +244,7 @@ fn test_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("feature")
.current_dir(repo.root_path().join(subdir));
@@ -361,7 +270,7 @@ fn test_switch_falls_back_to_root_when_subdir_missing(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
let feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create subdirectory only in the source worktree, not in the target
let subdir = "apps/gateway";
@@ -370,7 +279,7 @@ fn test_switch_falls_back_to_root_when_subdir_missing(
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("feature")
.current_dir(repo.root_path().join(subdir));
@@ -401,7 +310,7 @@ fn test_switch_falls_back_to_root_when_subdir_missing(
#[rstest]
fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create a subdirectory in the source worktree and commit it so it appears in the new branch
let subdir = "apps/gateway";
@@ -412,7 +321,7 @@ fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo)
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "new-feature"])
.current_dir(repo.root_path().join(subdir));
@@ -434,7 +343,7 @@ fn test_switch_create_preserves_subdir(#[from(repo_with_remote)] repo: TestRepo)
#[rstest]
fn test_remove_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create the same subdirectory in both the feature worktree (where the
// user is) and the main worktree (where removal lands).
@@ -444,7 +353,7 @@ fn test_remove_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("remove").current_dir(feature_wt.join(subdir));
let output = cmd.output().unwrap();
@@ -468,7 +377,7 @@ fn test_remove_falls_back_to_root_when_subdir_missing(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
let feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create the subdirectory only in the feature worktree (where the user
// is), not in the main worktree where removal lands.
@@ -478,7 +387,7 @@ fn test_remove_falls_back_to_root_when_subdir_missing(
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("remove").current_dir(feature_wt.join(subdir));
let output = cmd.output().unwrap();
@@ -512,14 +421,14 @@ fn test_remove_falls_back_to_root_when_subdir_missing(
#[rstest]
fn test_switch_no_cd_suppresses_directive(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "feature", "--no-cd"])
.current_dir(repo.root_path());
@@ -537,14 +446,14 @@ fn test_switch_no_cd_suppresses_directive(#[from(repo_with_remote)] mut repo: Te
#[rstest]
fn test_switch_no_cd_create_suppresses_directive(#[from(repo_with_remote)] repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "--create", "new-feature", "--no-cd"])
.current_dir(repo.root_path());
@@ -562,7 +471,7 @@ fn test_switch_no_cd_create_suppresses_directive(#[from(repo_with_remote)] repo:
#[rstest]
fn test_switch_no_cd_hooks_show_path_annotation(#[from(repo_with_remote)] repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create project config with a post-switch hook
let config_dir = repo.root_path().join(".config");
@@ -580,7 +489,7 @@ fn test_switch_no_cd_hooks_show_path_annotation(#[from(repo_with_remote)] repo:
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
// Use --yes to auto-approve the hook command
cmd.args(["switch", "--create", "hook-test", "--no-cd", "--yes"])
.current_dir(repo.root_path());
@@ -598,16 +507,17 @@ fn test_switch_no_cd_hooks_show_path_annotation(#[from(repo_with_remote)] repo:
}
#[rstest]
-fn test_switch_no_cd_execute_runs_in_target_worktree(#[from(repo_with_remote)] repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
+fn test_switch_no_cd_execute_does_not_emit_cd(#[from(repo_with_remote)] repo: TestRepo) {
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- // pwd should print the target worktree path, even with --no-cd
+ configure_directive_file(&mut cmd, &cd_path);
+ // The wrapper will launch pwd from the invoking directory because
+ // --no-cd deliberately leaves its shell there.
cmd.args([
"switch",
"--create",
@@ -634,7 +544,7 @@ fn test_switch_no_cd_execute_runs_in_target_worktree(#[from(repo_with_remote)] r
#[rstest]
fn test_switch_no_cd_config_suppresses_directive(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Set up config with cd = false
repo.write_test_config(
@@ -650,7 +560,7 @@ cd = false
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["switch", "feature"])
.current_dir(repo.root_path());
@@ -667,7 +577,7 @@ cd = false
}
// ============================================================================
-// Non-Directive Mode Tests (no split directive env vars)
+// Non-Directive Mode Tests (no CD directive env var)
// ============================================================================
#[rstest]
@@ -689,14 +599,14 @@ fn test_switch_without_directive_file(repo: TestRepo) {
fn test_merge_directive_no_remove(mut repo_with_feature_worktree: TestRepo) {
let repo = &mut repo_with_feature_worktree;
let feature_wt = &repo.worktrees["feature"];
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("merge")
.arg("main")
.arg("--no-remove")
@@ -710,14 +620,14 @@ fn test_merge_directive_no_remove(mut repo_with_feature_worktree: TestRepo) {
fn test_merge_directive_remove(mut repo_with_feature_worktree: TestRepo) {
let repo = &mut repo_with_feature_worktree;
let feature_wt = &repo.worktrees["feature"];
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let settings = setup_snapshot_settings(repo);
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("merge").arg("main").current_dir(feature_wt);
assert_cmd_snapshot!(cmd);
@@ -747,7 +657,7 @@ fn test_merge_directive_remove(mut repo_with_feature_worktree: TestRepo) {
#[rstest]
fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRepo) {
let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create a symlink to the repo's parent directory
let real_parent = repo.root_path().parent().unwrap();
@@ -761,7 +671,7 @@ fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRe
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
// Set PWD to the logical (symlink) path — this is what the shell sets
cmd.env("PWD", &logical_cwd);
cmd.arg("switch").arg("feature").current_dir(&logical_cwd);
@@ -813,7 +723,7 @@ fn test_switch_preserves_symlink_path(#[from(repo_with_remote)] mut repo: TestRe
#[cfg(unix)]
#[rstest]
fn test_switch_create_preserves_symlink_path(#[from(repo_with_remote)] repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create a symlink to the repo's parent directory
let real_parent = repo.root_path().parent().unwrap();
@@ -826,7 +736,7 @@ fn test_switch_create_preserves_symlink_path(#[from(repo_with_remote)] repo: Tes
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.env("PWD", &logical_cwd);
cmd.args(["switch", "--create", "new-feature"])
.current_dir(&logical_cwd);
@@ -870,7 +780,7 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
#[from(repo_with_remote)] mut repo: TestRepo,
) {
let feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create subdirectory in both worktrees
let subdir = "apps/gateway";
@@ -888,7 +798,7 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.env("PWD", &logical_cwd);
cmd.arg("switch").arg("feature").current_dir(&logical_cwd);
@@ -925,13 +835,13 @@ fn test_switch_preserves_symlink_path_from_subdirectory(
fn test_switch_no_symlink_uses_canonical(#[from(repo_with_remote)] mut repo: TestRepo) {
// When PWD matches current_dir (no symlink), canonical path is used as before
let _feature_wt = repo.add_worktree("feature");
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let canonical_cwd = dunce::canonicalize(repo.root_path()).unwrap();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
// Set PWD to canonical (same as current_dir — no symlink)
cmd.env("PWD", &canonical_cwd);
cmd.arg("switch").arg("feature").current_dir(&canonical_cwd);
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 2ee07c2f4..8438fa624 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -500,7 +500,7 @@ fn rejects_git_older_than_the_supported_minimum() {
cmd.arg("list");
let output = cmd.output().unwrap();
- assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"\u{1b}[31m✗\u{1b}[39m \u{1b}[31mGit 2.42.4 is unsupported; Worktrunk requires Git 2.43.0 or newer\u{1b}[39m\n");
+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✗ Git 2.42.4 is unsupported; Worktrunk requires Git 2.43.0 or newer");
assert_eq!(output.status.code(), Some(1));
assert!(output.stdout.is_empty());
}
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index bfc3e983b..262d5fa2d 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -1090,6 +1090,9 @@ approved-commands = ["echo 'Background task' > background.txt"]
"--create",
"feature",
"--execute",
+ "sh",
+ "--",
+ "-c",
"echo 'Execute flag' > execute.txt",
],
);
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index b2883f345..fa4c4515f 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1,6 +1,6 @@
use crate::common::{
- BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, configure_directive_files,
- directive_files, make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
+ BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, configure_directive_file,
+ directive_file, make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
setup_temp_snapshot_settings, wt_command,
};
use ansi_str::AnsiStr;
@@ -212,10 +212,10 @@ fn test_remove_internal_mode(mut repo: TestRepo) {
let worktree_path = repo.add_worktree("feature-internal");
// Directive file guards must live through command execution
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
assert_cmd_snapshot!({
let mut cmd = make_snapshot_cmd(&repo, "remove", &[], Some(&worktree_path));
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd
});
}
@@ -2490,13 +2490,13 @@ approved-commands = ["exit 1"]
let worktree_path = repo.add_worktree("feature-cd-test");
// Set up directive files
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Run remove from within the worktree (which would trigger cd to main if it worked)
let mut cmd = repo.wt_command();
cmd.args(["remove", "--foreground"]);
cmd.current_dir(&worktree_path);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
let output = cmd.output().unwrap();
// Command should have failed (hook failure)
diff --git a/tests/integration_tests/security.rs b/tests/integration_tests/security.rs
index 35ad8256c..6508d1217 100644
--- a/tests/integration_tests/security.rs
+++ b/tests/integration_tests/security.rs
@@ -1,24 +1,13 @@
//! Security tests for shell injection vulnerabilities
//!
-//! # Security Model: Split Directive Protocol
+//! # Security Model
//!
-//! Worktrunk uses two directive files with different trust levels:
+//! The CD directive (`WORKTRUNK_DIRECTIVE_CD_FILE`) contains a raw path. The shell
+//! wrapper changes to that path without evaluating it. `--execute` starts one
+//! external program directly; no shell parses its argv.
//!
-//! - **CD file** (`WORKTRUNK_DIRECTIVE_CD_FILE`): Contains a raw path. The shell
-//! wrapper runs `cd -- "$(< file)"`. Because the file is never sourced as
-//! shell, there is **no injection surface** — even a malicious path cannot
-//! inject commands. This file is safe to pass through to alias/hook bodies.
-//!
-//! - **EXEC file** (`WORKTRUNK_DIRECTIVE_EXEC_FILE`): Contains arbitrary shell
-//! (from `--execute`). The wrapper sources it. Only wt-internal Rust code
-//! writes to this file — it is scrubbed from alias/hook child environments.
-//!
-//! ## Defense in Depth
-//!
-//! Multiple layers prevent injection even if one layer fails:
-//!
-//! 1. **Protocol separation**: CD file is a raw path (no shell parsing); EXEC
-//! file is only written by Rust code, never by external content.
+//! 1. **Structured inputs**: CD is a raw path and execute is argv; neither is
+//! parsed as shell.
//!
//! 2. **Channel separation**: User messages go to stderr; directive files are
//! separate. Malicious content in stderr cannot reach the directive files.
@@ -36,18 +25,17 @@
//!
//! 1. Branch names with shell metacharacters don't corrupt the cd path
//! 2. Malicious branch names don't create unexpected files
-//! 3. The EXEC file only contains user-provided `--execute` content
-//! 4. Git's ref-name validation rejects the most dangerous characters
+//! 3. Git's ref-name validation rejects the most dangerous characters
//!
//! ## Testing Limitations
//!
//! These tests run the Rust binary, not the shell wrapper. They verify that
-//! directive file contents are safe, but they don't test that the wrapper
-//! handles the files correctly. Full end-to-end tests with the shell wrapper
+//! the direct execution input is safe, but they don't test the wrapper. Full
+//! end-to-end tests with the shell wrapper
//! are in `tests/integration_tests/shell_wrapper.rs`.
use crate::common::{
- TestRepo, configure_directive_files, directive_files, repo, setup_snapshot_settings, wt_command,
+ TestRepo, configure_directive_file, directive_file, repo, setup_snapshot_settings, wt_command,
};
use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
@@ -152,10 +140,10 @@ fn test_branch_name_is_directive_not_executed(repo: TestRepo) {
settings.set_snapshot_path("../snapshots");
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
@@ -189,10 +177,10 @@ fn test_branch_name_with_newline_directive_not_executed(repo: TestRepo) {
settings.set_snapshot_path("../snapshots");
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
@@ -260,10 +248,10 @@ fn test_branch_name_with_cd_directive_not_executed(repo: TestRepo) {
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
@@ -284,10 +272,10 @@ fn test_error_message_with_directive_not_executed(repo: TestRepo) {
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg(malicious_branch)
.current_dir(repo.root_path());
@@ -303,9 +291,8 @@ fn test_error_message_with_directive_not_executed(repo: TestRepo) {
}
///
-/// The -x flag is SUPPOSED to execute commands, so this tests that:
-/// 1. Commands from -x are written to the directive file
-/// 2. User content in branch names that looks like old directives doesn't cause injection
+/// User content in branch names that looks like old directives must not become
+/// part of the explicitly requested command.
#[rstest]
fn test_execute_flag_with_directive_like_branch_name(repo: TestRepo) {
// Branch name that looks like a directive
@@ -326,24 +313,21 @@ fn test_execute_flag_with_directive_like_branch_name(repo: TestRepo) {
settings.set_snapshot_path("../snapshots");
settings.bind(|| {
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.arg("switch")
.arg("--create")
.arg(malicious_branch)
.arg("-x")
- .arg("echo legitimate command")
+ .arg("echo")
+ .args(["--", "legitimate command"])
.current_dir(repo.root_path());
- // The -x command should be written to directive file
- // The branch name should NOT inject additional commands
assert_cmd_snapshot!(cmd);
});
- // The legitimate command would execute (we're not actually running the shell wrapper),
- // but the injected command should NOT
assert!(
!std::path::Path::new("/tmp/hacked7").exists(),
"Malicious code was executed alongside legitimate -x command!"
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index 5437afc74..6f69a4f24 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -33,12 +33,9 @@ fn test_switch_with_active_shell_integration_no_prompt(repo: TestRepo) {
// Now switch with shell integration "active" (CD directive file set)
// The file must exist (shell wrapper creates it before calling wt)
let cd_file = repo.root_path().join("directive_cd.txt");
- let exec_file = repo.root_path().join("directive_exec.txt");
fs::write(&cd_file, "").unwrap();
- fs::write(&exec_file, "").unwrap();
let mut cmd = repo.wt_command();
cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &cd_file);
- cmd.env("WORKTRUNK_DIRECTIVE_EXEC_FILE", &exec_file);
let output = cmd.args(["switch", "feature"]).output().unwrap();
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 525ece505..9ece8a0c3 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -164,7 +164,7 @@ complete --keep-order --exclusive --command wt --arguments "(COMPLETE=fish \$WOR
/// Quote a shell argument if it contains special characters
fn quote_arg(arg: &str) -> String {
- if arg.contains(' ') || arg.contains(';') || arg.contains('\'') {
+ if arg.is_empty() || arg.contains(' ') || arg.contains(';') || arg.contains('\'') {
shell_quote(arg)
} else {
arg.to_string()
@@ -177,6 +177,13 @@ fn shell_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
+/// Always quote a Nushell string. Nushell does not support the POSIX `\''`
+/// concatenation idiom, while ordinary double-quoted strings accept `\\` and
+/// `\"` escapes without interpolation (`$"…"` is the interpolation form).
+fn nushell_quote(s: &str) -> String {
+ format!("\"{}\"", s.replace('\\', r"\\").replace('"', r#"\""#))
+}
+
/// Quote a path for PowerShell (escape backticks and single quotes)
fn powershell_quote(s: &str) -> String {
// PowerShell string escaping: use single quotes and escape embedded single quotes by doubling
@@ -265,6 +272,17 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
script.push_str(arg);
}
}
+ "nu" | "nushell" => {
+ if arg.is_empty()
+ || arg
+ .chars()
+ .any(|c| c.is_whitespace() || matches!(c, ';' | '\'' | '"' | '$' | '\\'))
+ {
+ script.push_str(&nushell_quote(arg));
+ } else {
+ script.push_str(arg);
+ }
+ }
_ => {
script.push_str(&quote_arg(arg));
}
@@ -614,8 +632,8 @@ fn exec_bash_truly_interactive(
///
/// This simulates what actually happens when users run `wt switch`, etc. in their shell:
/// 1. The `wt` function is defined (from shell integration)
-/// 2. It calls `wt_exec` which sets WORKTRUNK_DIRECTIVE_CD_FILE + WORKTRUNK_DIRECTIVE_EXEC_FILE
-/// 3. The wrapper reads the cd file and sources the exec file after wt exits
+/// 2. It sets WORKTRUNK_DIRECTIVE_CD_FILE
+/// 3. The wrapper reads the cd path after wt exits
/// 4. Users see stdout/stderr output in real-time
///
/// Now uses PTY interactive mode for consistent behavior and potential input echoing.
@@ -824,18 +842,18 @@ mod unix_tests {
/// that this path depends on — no POSIX shell to spawn — so the regression is
/// covered on the Unix runners where the nushell wrapper is actually tested.
#[rstest]
- fn test_nushell_wrapper_failure_needs_no_posix_shell(mut repo: TestRepo) {
+ fn test_nushell_wrapper_needs_no_posix_shell(mut repo: TestRepo) {
repo.add_worktree("existing");
- // A PATH with no `sh`/`bash`/`dash`: just the shell under test, the git
- // that `wt switch` shells out to, and the `rm` the wrapper's own Unix
- // cleanup branch calls externally (`^rm`). Dropping `rm` would leak every
+ // A PATH with no `sh`/`bash`/`dash`: just nushell, git, the command run
+ // by `--execute`, and the `rm` used by the wrapper's Unix cleanup branch.
+ // Dropping `rm` would leak every
// `mktemp` file, silently — the branch is wrapped in `try` — and would
// also make the test less faithful to the platform it stands in for:
// Windows takes the `$nu.os-info.family` branch, where cleanup uses the
// nushell builtin and does run.
let bin_dir = tempfile::tempdir().unwrap();
- for tool in ["nu", "git", "rm"] {
+ for tool in ["nu", "git", "rm", "printf"] {
let resolved = which::which(tool)
.unwrap_or_else(|e| panic!("{tool} must be installed to run tests: {e}"));
std::os::unix::fs::symlink(resolved, bin_dir.path().join(tool)).unwrap();
@@ -899,6 +917,37 @@ mod unix_tests {
"wrapper leaked a nushell external-command error.\nOutput:\n{}",
output.combined
);
+
+ // `--execute` uses the same shell-free path.
+ let output = exec_through_wrapper_with_env(
+ "nu",
+ &repo,
+ "switch",
+ &[
+ "--create",
+ "nu-exec-no-sh",
+ "--execute",
+ "printf",
+ "--",
+ "NU_EXEC_OK",
+ ],
+ repo.root_path(),
+ &[],
+ &[("PATH", &sanitized_path)],
+ );
+
+ assert_eq!(output.exit_code, 0, "Output:\n{}", output.combined);
+ assert!(
+ output.combined.contains("NU_EXEC_OK"),
+ "directly executed program output is missing.\nOutput:\n{}",
+ output.combined
+ );
+ assert!(
+ !output.combined.contains("Command `sh` not found"),
+ "wrapper tried to introduce an implicit POSIX shell.\nOutput:\n{}",
+ output.combined
+ );
+ output.assert_no_directive_leaks();
}
#[rstest]
@@ -986,42 +1035,90 @@ mod unix_tests {
);
}
+ #[rstest]
+ fn test_nu_wrapper_ignores_execute_flags_after_argument_boundary(repo: TestRepo) {
+ let mut script = String::new();
+ append_wrapper_setup(&mut script, "nu", &repo);
+ script.push_str(
+ "let out = (wt step for-each --format=json -- printf -- -x)\n\
+ print $\"PIPELINE_CAPTURED:(not ($out | is-empty))\"\n",
+ );
+
+ let config_path = repo.test_config_path().to_string_lossy().to_string();
+ let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
+ let env_vars = build_test_env_vars(&config_path, &approvals_path);
+ let (combined, exit_code) =
+ exec_in_pty_interactive("nu", &script, repo.root_path(), &env_vars, &[]);
+
+ assert_eq!(exit_code, 0, "Output:\n{combined}");
+ assert!(
+ combined.contains("PIPELINE_CAPTURED:true"),
+ "-x after -- should not disable Nushell pipeline capture.\nOutput:\n{combined}"
+ );
+ }
+
#[rstest]
#[case("bash")]
#[case("zsh")]
#[case("fish")]
#[case("nu")]
fn test_wrapper_switch_with_execute(#[case] shell: &str, repo: TestRepo) {
- // `echo` with `executed` as a trailing arg, run through each wrapper.
- // `--yes` skips the approval prompt.
- let output = exec_through_wrapper(
- shell,
- &repo,
- "switch",
- &[
+ let args = if shell == "nu" {
+ vec![
+ "-cx",
+ "sh",
+ "test-exec",
+ "--yes",
+ "--",
+ "-c",
+ "test -t 1 && printf 'EXEC_STDOUT_TTY:true\\n'",
+ ]
+ } else {
+ vec![
"--create",
"test-exec",
"--yes",
"--execute",
- "echo",
+ "sh",
"--",
- "executed",
- ],
+ "-c",
+ "test -t 1 && printf 'EXEC_STDOUT_TTY:true\\n'",
+ ]
+ };
+
+ // The child must inherit a real terminal, including through Nushell's
+ // normally-buffered wrapper path. Its case uses the valid `-cx`
+ // cluster so execute detection follows clap's short-option parsing.
+ let output = exec_through_wrapper_with_env(
+ shell,
+ &repo,
+ "switch",
+ &args,
+ repo.root_path(),
+ &[],
+ &[("WORKTRUNK_DIRECTIVE_EXEC_FILE", "retired")],
);
// Shell-agnostic assertions
- assert_eq!(output.exit_code, 0, "{}: Command should succeed", shell);
+ assert_eq!(
+ output.exit_code, 0,
+ "{}: Command should succeed\nOutput:\n{}",
+ shell, output.combined
+ );
output.assert_no_directive_leaks();
assert!(
- output.combined.contains("executed"),
- "{}: Execute command output missing",
+ output.combined.contains("EXEC_STDOUT_TTY:true"),
+ "{}: execute child did not inherit terminal stdout",
shell
);
+ assert!(
+ !output.combined.contains("Shell wrapper is out of date"),
+ "{shell}: a stale wrapper with terminal stdout should not warn"
+ );
- // Per-shell snapshot: the `Executing (--execute):` line escapes the
- // trailing arg for the directive shell, so fish differs from the
- // POSIX wrappers — output is no longer identical across shells.
+ // Keep one snapshot per wrapper implementation: all consume the same
+ // argv protocol, but their PTY echo can still differ.
shell_wrapper_settings().bind(|| {
assert_snapshot!(format!("switch_with_execute_{shell}"), &output.combined);
});
@@ -1045,9 +1142,12 @@ mod unix_tests {
&[
"--create",
"test-exit-code",
+ "--yes",
"--execute",
+ "sh",
+ "--",
+ "-c",
"exit 42",
- "--yes",
],
);
@@ -1070,9 +1170,9 @@ mod unix_tests {
/// A failing `--execute` body must not abort the nushell wrapper before its
/// cleanup runs.
///
- /// Nushell 0.98+ raises a `ShellError` on a non-zero external exit, so the
- /// wrapper's `^sh -c $script` used to unwind the whole `def` — the three
- /// `mktemp` files leaked and the stdout the function still had to return was
+ /// Nushell 0.98+ raises a `ShellError` on a non-zero external exit, so a
+ /// failing program can unwind the whole `def` unless the wrapper catches
+ /// it before cleanup — the temp files leaked and the stdout the function still had to return was
/// discarded. `test_wrapper_execute_exit_code_propagation` covers the same
/// command and passes either way: the unwind *happens* to carry exit 42 out
/// to the shell, which is all that test asserts. So the leak sat on a path
@@ -1093,7 +1193,7 @@ mod unix_tests {
let mut script = String::new();
append_wrapper_setup(&mut script, "nu", &repo);
script.push_str(
- "let code = (try { wt switch --create exec-abort --yes --execute \"exit 42\"; 0 } catch { $env.LAST_EXIT_CODE })\n",
+ "let code = (try { wt switch --create exec-abort --yes --execute sh -- -c \"exit 42\"; 0 } catch { $env.LAST_EXIT_CODE })\n",
);
script.push_str("print $\"WT_EXIT:($code)\"\n");
@@ -1414,9 +1514,11 @@ approved-commands = ["echo 'test command executed'"]
&[
"--create",
"test-exec",
- "--execute",
- "echo executed",
"--yes",
+ "--execute",
+ "echo",
+ "--",
+ "executed",
],
);
@@ -1586,9 +1688,7 @@ approved-commands = ["echo 'fish background task'"]
#[rstest]
fn test_fish_multiline_command_execution(repo: TestRepo) {
- // Test that Fish wrapper handles multi-line commands correctly
- // This tests Fish's NUL-byte parsing with embedded newlines
- // Use actual newlines in the command string
+ // Shell behavior remains available when requested explicitly.
let multiline_cmd = "echo 'line 1'; echo 'line 2'; echo 'line 3'";
// Use --yes to skip approval prompt in tests
@@ -1599,9 +1699,12 @@ approved-commands = ["echo 'fish background task'"]
&[
"--create",
"fish-multiline",
+ "--yes",
"--execute",
+ "fish",
+ "--",
+ "-c",
multiline_cmd,
- "--yes",
],
);
@@ -3748,7 +3851,16 @@ mod windows_tests {
"powershell",
&repo,
"switch",
- &["--create", "feature", "--execute", "exit 42"],
+ &[
+ "--create",
+ "feature",
+ "--execute",
+ "pwsh",
+ "--",
+ "-NoProfile",
+ "-Command",
+ "exit 42",
+ ],
);
// The wrapper should propagate the exit code from the executed command
@@ -4006,9 +4118,13 @@ mod windows_tests {
&[
"--create",
"test-exec",
+ "--yes",
"--execute",
+ "pwsh",
+ "--",
+ "-NoProfile",
+ "-Command",
"Write-Host 'executed'",
- "--yes",
],
);
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
index 7974d73ac..8fcce9fb5 100644
--- a/tests/integration_tests/statusline.rs
+++ b/tests/integration_tests/statusline.rs
@@ -418,12 +418,6 @@ fn test_statusline_claude_code_missing_context_window(repo: TestRepo) {
});
}
-// --- Directive Mode Tests ---
-// Note: With the split directive file architecture, data output (like statusline)
-// still goes to stdout. The directive files are only used for cd paths and exec
-// commands. So this test is no longer needed - statusline behavior is the same
-// regardless of whether directive env vars are set.
-
// --- Branch Display Tests ---
///
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 3922b1eee..71a2e7f17 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -1,7 +1,7 @@
//! Integration tests for `wt step <alias>`
use crate::common::{
- TestRepo, configure_directive_files, directive_files, make_snapshot_cmd,
+ TestRepo, configure_directive_file, directive_file, make_snapshot_cmd,
make_snapshot_cmd_with_global_flags, repo, repo_with_remote, setup_snapshot_settings, wt_bin,
};
// Used only by the `#[cfg(unix)]` signal tests below; gate the import to match,
@@ -796,10 +796,10 @@ fn test_alias_passes_directive_file_to_subprocess(repo: TestRepo) {
"switch --create alias-created",
));
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["step", "new-branch"]);
let output = cmd.output().unwrap();
@@ -873,10 +873,10 @@ fn test_alias_wrapping_switch_preserves_subdir(#[from(repo_with_remote)] mut rep
repo.write_test_config(&wt_alias_config("go", "switch feature"));
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["step", "go"])
.current_dir(repo.root_path().join(&subdir));
let output = cmd.output().unwrap();
@@ -913,10 +913,10 @@ fn test_alias_wrapping_remove_preserves_subdir(#[from(repo_with_remote)] mut rep
repo.write_test_config(&wt_alias_config("finish", "remove -y"));
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["step", "finish"])
.current_dir(feature_wt.join(&subdir));
let output = cmd.output().unwrap();
@@ -936,140 +936,33 @@ fn test_alias_wrapping_remove_preserves_subdir(#[from(repo_with_remote)] mut rep
);
}
-/// User-source aliases pass the EXEC directive file through to the body, so a
-/// nested `wt switch --execute X` writes the payload back to the parent
-/// shell's EXEC file the same as a top-level `wt switch --execute X` would.
-///
-/// Regression test for #2101: the conservative scrub used to refuse `--execute`
-/// inside any alias body, breaking workflows like `issue = "wt switch --create
-/// {{ args[0] }} --execute claude"` even when the alias lived in user config.
+/// A nested switch runs `--execute` directly rather than depending on a
+/// directive inherited through the alias shell.
#[rstest]
-fn test_user_alias_passes_exec_directive(repo: TestRepo) {
+fn test_alias_runs_execute_directly(repo: TestRepo) {
repo.commit("initial");
repo.write_test_config(&wt_alias_config(
"exec-passthrough",
- "switch --create user-alias-target --execute 'echo from-user-alias'",
+ "switch --create user-alias-target --execute echo -- from-user-alias",
));
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["step", "exec-passthrough"]);
let output = cmd.output().unwrap();
- let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- output.status.success(),
- "wt step exec-passthrough failed: stdout={}\nstderr={stderr}",
- String::from_utf8_lossy(&output.stdout),
- );
- assert!(
- !stderr.contains("disabled inside"),
- "user alias should not trip the EXEC scrub warning, got: {stderr}"
- );
-
- let exec_content = std::fs::read_to_string(&exec_path).unwrap_or_default();
- assert!(
- exec_content.contains("echo from-user-alias"),
- "EXEC file should contain the alias's --execute payload, got: {exec_content:?}"
- );
-}
-
-/// Project-source aliases keep the conservative EXEC scrub: a nested
-/// `wt switch --execute X` is refused with a warning pointing at the tracking
-/// issue. The body is shared config, so allowing it would let the project
-/// inject arbitrary shell into every contributor's interactive session.
-#[rstest]
-fn test_project_alias_scrubs_exec_directive(repo: TestRepo) {
- repo.commit("initial");
-
- repo.write_project_config(&wt_alias_config(
- "exec-blocked",
- "switch --create project-alias-target --execute 'echo should-not-pass'",
- ));
-
- let (cd_path, exec_path, _guard) = directive_files();
-
- let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- // -y skips the project-alias approval prompt.
- cmd.args(["-y", "step", "exec-blocked"]);
- let output = cmd.output().unwrap();
-
- let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
- "wt -y step exec-blocked failed: stdout={}\nstderr={stderr}",
+ "wt step exec-passthrough failed: stdout={}\nstderr={}",
String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
);
assert!(
- stderr.contains("disabled inside project alias"),
- "project alias should warn that --execute is disabled, got: {stderr}"
- );
- assert!(
- stderr.contains("issues/2101"),
- "warning should link the tracking issue, got: {stderr}"
- );
-
- let exec_content = std::fs::read_to_string(&exec_path).unwrap_or_default();
- assert!(
- !exec_content.contains("should-not-pass"),
- "EXEC file should NOT contain the scrubbed payload, got: {exec_content:?}"
- );
-}
-
-/// Same alias name in both user and project configs: EXEC passes through for
-/// the user-source step but is scrubbed for the project-source step.
-///
-/// EXEC passthrough is a per-step decision driven by `HookSource` on each
-/// `SourcedStep`, not a per-pipeline scrub. When both sources define the
-/// alias, both run (user first, then project) — the user's own step still
-/// gets the relaxation, and the project-authored step keeps the conservative
-/// scrub even though it's part of the same merged body.
-#[rstest]
-fn test_user_and_project_alias_collision_scrubs_only_project_step(repo: TestRepo) {
- repo.commit("initial");
-
- repo.write_test_config(&wt_alias_config(
- "shared",
- "switch --create user-step-target --execute 'echo from-user-step'",
- ));
- // Project step also tries `--execute` so we can assert its payload is
- // scrubbed even though the user step's payload passes through.
- repo.write_project_config(&wt_alias_config(
- "shared",
- "switch --create project-step-target --execute 'echo from-project-step'",
- ));
-
- let (cd_path, exec_path, _guard) = directive_files();
-
- let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- // -y skips the project-alias approval prompt.
- cmd.args(["-y", "step", "shared"]);
- let output = cmd.output().unwrap();
-
- let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- output.status.success(),
- "wt -y step shared failed: stdout={}\nstderr={stderr}",
- String::from_utf8_lossy(&output.stdout),
- );
- assert!(
- stderr.contains("disabled inside project alias"),
- "project-source step should still warn that --execute is disabled, got: {stderr}"
- );
-
- let exec_content = std::fs::read_to_string(&exec_path).unwrap_or_default();
- assert!(
- exec_content.contains("from-user-step"),
- "EXEC file should contain the user step's payload (per-step relaxation), got: {exec_content:?}"
- );
- assert!(
- !exec_content.contains("from-project-step"),
- "EXEC file should NOT contain the project step's payload (per-step scrub), got: {exec_content:?}"
+ String::from_utf8_lossy(&output.stdout).contains("from-user-alias"),
+ "nested --execute output missing"
);
}
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
index 952cb0406..9375b3ba6 100644
--- a/tests/integration_tests/step_relocate.rs
+++ b/tests/integration_tests/step_relocate.rs
@@ -1,8 +1,6 @@
//! Integration tests for `wt step relocate`
-use crate::common::{
- TestRepo, configure_directive_files, directive_files, make_snapshot_cmd, repo,
-};
+use crate::common::{TestRepo, configure_directive_file, directive_file, make_snapshot_cmd, repo};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
@@ -1388,7 +1386,7 @@ worktree-path = "../{{ undefined_var }}.{{ branch }}"
#[cfg_attr(windows, ignore)]
fn test_relocate_preserves_subdir(repo: TestRepo) {
let parent = worktree_parent(&repo);
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
// Create a worktree at a non-standard location, with a subdirectory the
// user is working in.
@@ -1404,7 +1402,7 @@ fn test_relocate_preserves_subdir(repo: TestRepo) {
fs::create_dir_all(wrong_path.join(&subdir)).unwrap();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.args(["step", "relocate"])
.current_dir(wrong_path.join(&subdir));
@@ -1425,7 +1423,7 @@ fn test_relocate_preserves_subdir(repo: TestRepo) {
);
}
-/// A shell started before the split directive protocol cannot follow a
+/// A shell using the retired single-file protocol cannot follow a
/// relocated current worktree. The relocation still succeeds, but it must
/// explain that the wrapper is stale and how to repair it rather than silently
/// leaving the shell in the renamed-away directory.
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index b52767920..f06503cd7 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1,8 +1,8 @@
use crate::common::{
- SLEEP_FOR_ABSENCE_CHECK, TestRepo, configure_directive_files, directive_files,
- make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,
- set_temp_home_env, setup_home_snapshot_settings, setup_snapshot_settings, temp_home,
- wait_for_file_content, wt_command,
+ SLEEP_FOR_ABSENCE_CHECK, TestRepo, configure_directive_file, directive_file, make_snapshot_cmd,
+ make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,
+ setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wait_for_file_content,
+ wt_command,
};
use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
@@ -42,14 +42,14 @@ fn snapshot_switch_impl(
settings.bind(|| {
// Directive file guards - declared at closure scope to live through command execution
let maybe_directive = if with_directive_file {
- Some(directive_files())
+ Some(directive_file())
} else {
None
};
let mut cmd = make_snapshot_cmd(repo, "switch", args, cwd);
- if let Some((ref cd_path, ref exec_path, ref _guard)) = maybe_directive {
- configure_directive_files(&mut cmd, cd_path, exec_path);
+ if let Some((ref cd_path, ref _guard)) = maybe_directive {
+ configure_directive_file(&mut cmd, cd_path);
}
if let Some(shell_path) = shell {
cmd.env("SHELL", shell_path);
@@ -883,24 +883,30 @@ fn test_switch_internal_with_execute(repo: TestRepo) {
snapshot_switch_with_directive_file(
"switch_internal_with_execute",
&repo,
- &["--create", "exec-internal", "--execute", execute_cmd],
+ &[
+ "--create",
+ "exec-internal",
+ "--execute",
+ "sh",
+ "--",
+ "-c",
+ execute_cmd,
+ ],
);
}
-/// The `--execute` no-integration fallback relocates the payload into the
-/// switch target, so inherited git-discovery vars (`GIT_DIR`/`GIT_WORK_TREE`)
+/// `--execute` starts the program in the switch target, so inherited
+/// git-discovery vars (`GIT_DIR`/`GIT_WORK_TREE`)
/// must be scrubbed there like at the hook and for-each spawn sites — git
/// resolves them before the cwd, so a forwarded value would misdirect the
/// payload's `git` calls to the inherited repo while the "Executing @ …"
/// header names the target (issue #3373; classification in
/// `scrub_git_discovery_env_vars`).
///
-/// `repo.wt_command()` configures no directive files, so wt executes the
-/// payload itself (unix: exec, non-unix: spawn — each platform's CI drives
-/// its own variant). The relative marker path resolves in the payload's cwd,
-/// pinning the relocation at the same time.
+/// The relative marker path resolves in the payload's cwd, pinning the
+/// relocation at the same time.
#[rstest]
-fn test_switch_execute_fallback_does_not_inherit_git_discovery_vars(mut repo: TestRepo) {
+fn test_switch_execute_does_not_inherit_git_discovery_vars(mut repo: TestRepo) {
let feature_path = repo.add_worktree("feature");
let output = repo
@@ -909,6 +915,9 @@ fn test_switch_execute_fallback_does_not_inherit_git_discovery_vars(mut repo: Te
"switch",
"feature",
"--execute",
+ "sh",
+ "--",
+ "-c",
r#"printf '[%s][%s]' "$GIT_DIR" "$GIT_WORK_TREE" > git_env_seen.txt"#,
])
.env("GIT_DIR", repo.root_path().join(".git"))
@@ -933,8 +942,8 @@ fn test_switch_execute_fallback_does_not_inherit_git_discovery_vars(mut repo: Te
/// `--execute` computes only the template variables its command names.
///
/// The context map built at that call site feeds `expand_template` and nothing
-/// else — the payload reaches the child as a shell string, never as JSON on
-/// stdin, and `--execute` renders no `-v` variables table — so a var the
+/// else — the payload reaches the child as argv, never as JSON on stdin, and
+/// `--execute` renders no `-v` variables table — so a var the
/// templates don't reference is a git subprocess whose result is discarded.
/// `var_default_branch` is the one with teeth: on a clone with no
/// `refs/remotes/origin/HEAD` and no cached `worktrunk.default-branch` it falls
@@ -951,15 +960,26 @@ fn test_switch_execute_computes_only_referenced_vars(mut repo: TestRepo) {
let trace = repo.root_path().join(".git/wt/logs/trace.jsonl");
// Each `-vv` run replaces trace.jsonl, so the two cases don't accumulate.
- let var_spans = |execute: &str| -> Vec<String> {
+ let var_spans = |arg: &str| -> Vec<String> {
let output = repo
.wt_command()
- .args(["-vv", "switch", "exec-vars", "--execute", execute])
+ .args([
+ "-vv",
+ "switch",
+ "exec-vars",
+ "--execute",
+ "sh",
+ "--",
+ "-c",
+ "true",
+ "worktrunk-test",
+ arg,
+ ])
.output()
.unwrap();
assert!(
output.status.success(),
- "switch --execute '{execute}' failed:\nstderr: {}",
+ "switch --execute with {arg:?} failed:\nstderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let raw = fs::read_to_string(&trace).expect("-vv should write trace.jsonl");
@@ -974,28 +994,22 @@ fn test_switch_execute_computes_only_referenced_vars(mut repo: TestRepo) {
spans
};
- let none_referenced = var_spans("echo hi");
+ let none_referenced = var_spans("hi");
assert!(
none_referenced.is_empty(),
"a --execute command naming no variables should compute none, got {none_referenced:?}"
);
assert_eq!(
- var_spans("echo {{ commit }}"),
+ var_spans("{{ commit }}"),
["var_commit"],
"a --execute command naming commit should compute exactly that"
);
}
-/// `--execute` with trailing `-- args` containing shell metacharacters: the
-/// constructed command appended to the exec directive file must POSIX-escape
-/// each trailing arg so the user's shell wrapper (`sh -c`, `bash -c`, …)
-/// reads them as literal arguments — no command substitution, no $-expansion,
-/// embedded single quotes via the standard `'\''` idiom. Guards
-/// `run_switch`'s `escaped_args` map at `worktree/switch.rs` from regressing
-/// to platform-sensitive escaping.
+/// `--execute` preserves argv boundaries without shell parsing.
+#[cfg(unix)]
#[rstest]
-fn test_switch_with_execute_trailing_args_metachars(repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
+fn test_switch_with_execute_uses_literal_argv(repo: TestRepo) {
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
let mut cmd = make_snapshot_cmd(
@@ -1005,173 +1019,51 @@ fn test_switch_with_execute_trailing_args_metachars(repo: TestRepo) {
"--create",
"exec-trailing",
"--execute",
- "echo",
+ "sh",
"--",
+ "-c",
+ "printf '<%s>\\n' \"$@\"",
+ "_",
"$x's hello",
"with space",
+ "",
+ "café",
],
None,
);
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- assert_cmd_snapshot!("switch_with_execute_trailing_args_metachars_stderr", cmd);
-
- // The exec file is what the shell wrapper would source. It must contain
- // the trailing args POSIX-escaped — exactly the form a POSIX shell
- // parses back to the original literal values. (No command
- // substitution, no `$` expansion; embedded single quote uses the
- // standard `'\''` idiom.)
- let exec_contents = fs::read_to_string(&exec_path).unwrap();
- insta::assert_snapshot!(
- "switch_with_execute_trailing_args_metachars_exec",
- &exec_contents
- );
+ assert_cmd_snapshot!("switch_with_execute_literal_argv", cmd);
});
}
-/// 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`.
+/// Shell syntax in `-x` is a literal program name after the argv cutover.
#[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,
+fn test_switch_execute_does_not_parse_shell_syntax(repo: TestRepo) {
+ let mut cmd = repo.wt_command();
+ let output = cmd
+ .args([
"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
- );
- });
+ "--create",
+ "literal-program",
+ "--execute",
+ "echo hi && ls",
+ ])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("echo hi && ls"),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
}
-/// A `--execute` value that is a shell command line rather than a single
-/// program name gets a deprecation warning for the upcoming argv input model;
-/// a single program name stays silent.
#[rstest]
-fn test_switch_execute_argv_deprecation_warning(repo: TestRepo) {
- let (cd_path, exec_path, _guard) = directive_files();
- let settings = setup_snapshot_settings(&repo);
- settings.bind(|| {
- // Shell syntax / multiple words — not a single program name.
- let mut cmd = make_snapshot_cmd(
- &repo,
- "switch",
- &["--create", "dep-shell", "--execute", "echo hi && ls"],
- None,
- );
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- assert_cmd_snapshot!("switch_execute_deprecation_shell_syntax", cmd);
-
- // A single program name — unaffected, no warning.
- let mut cmd = make_snapshot_cmd(
- &repo,
- "switch",
- &["--create", "dep-ok", "--execute", "git"],
- None,
- );
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- assert_cmd_snapshot!("switch_execute_deprecation_compatible", cmd);
-
- // Trailing args are folded into the suggested command line, not dropped.
- let mut cmd = make_snapshot_cmd(
- &repo,
- "switch",
- &["--create", "dep-args", "--execute", "npm run", "--", "test"],
- None,
- );
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- assert_cmd_snapshot!("switch_execute_deprecation_trailing_args", cmd);
-
- // Under a fish wrapper the suggestion wraps in `fish`, not POSIX `sh`.
- let mut cmd = make_snapshot_cmd(
- &repo,
- "switch",
- &[
- "--create",
- "dep-fish",
- "--execute",
- "set -lx FOO bar; echo $FOO",
- ],
- None,
- );
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
- cmd.env("WORKTRUNK_SHELL", "fish");
- assert_cmd_snapshot!("switch_execute_deprecation_fish_wrapper", cmd);
- });
+fn test_switch_execute_rejects_empty_program(repo: TestRepo) {
+ snapshot_switch(
+ "switch_execute_rejects_empty_program",
+ &repo,
+ &["--create", "empty-program", "--execute", ""],
+ );
}
// Error tests
#[rstest]
@@ -1241,7 +1133,15 @@ fn test_switch_execute_creates_file(repo: TestRepo) {
snapshot_switch(
"switch_execute_creates_file",
&repo,
- &["--create", "file-test", "--execute", create_file_cmd],
+ &[
+ "--create",
+ "file-test",
+ "--execute",
+ "sh",
+ "--",
+ "-c",
+ create_file_cmd,
+ ],
);
// Query Git rather than reconstructing the configured path template: this
@@ -1277,14 +1177,22 @@ fn test_switch_execute_failure(repo: TestRepo) {
snapshot_switch(
"switch_execute_failure",
&repo,
- &["--create", "fail-test", "--execute", "exit 1"],
+ &[
+ "--create",
+ "fail-test",
+ "--execute",
+ "sh",
+ "--",
+ "-c",
+ "exit 1",
+ ],
);
}
// Execute template expansion tests
#[rstest]
fn test_switch_execute_template_branch(repo: TestRepo) {
- // Test that {{ branch }} is expanded in --execute command
+ // Test that {{ branch }} is expanded in an --execute argument.
snapshot_switch(
"switch_execute_template_branch",
&repo,
@@ -1292,7 +1200,9 @@ fn test_switch_execute_template_branch(repo: TestRepo) {
"--create",
"template-test",
"--execute",
- "echo 'branch={{ branch }}'",
+ "echo",
+ "--",
+ "branch={{ branch }}",
],
);
}
@@ -1311,7 +1221,9 @@ fn test_switch_execute_template_base(repo: TestRepo) {
"--base",
"release-base",
"--execute",
- "echo 'base={{ base }}'",
+ "echo",
+ "--",
+ "base={{ base }}",
],
);
}
@@ -1324,18 +1236,24 @@ fn test_switch_execute_template_base_for_existing_worktree_uses_source(mut repo:
snapshot_switch(
"switch_execute_template_base_without_create",
&repo,
- &["existing", "--execute", "echo 'base={{ base }}'"],
+ &["existing", "--execute", "echo", "--", "base={{ base }}"],
);
}
#[rstest]
-fn test_switch_execute_template_shell_escape(repo: TestRepo) {
- // Test that shell metacharacters in branch names are escaped
- // Without escaping, this would execute `id` as a separate command
+fn test_switch_execute_template_metacharacters_stay_literal(repo: TestRepo) {
+ // Template output remains one argv element; `;id` is never parsed as shell.
snapshot_switch(
"switch_execute_template_shell_escape",
&repo,
- &["--create", "feat;id", "--execute", "echo {{ branch }}"],
+ &[
+ "--create",
+ "feat;id",
+ "--execute",
+ "echo",
+ "--",
+ "{{ branch }}",
+ ],
);
}
@@ -1363,7 +1281,14 @@ fn test_switch_execute_template_error(repo: TestRepo) {
snapshot_switch(
"switch_execute_template_error",
&repo,
- &["--create", "error-test", "--execute", "echo {{ unclosed"],
+ &[
+ "--create",
+ "error-test",
+ "--execute",
+ "echo",
+ "--",
+ "{{ unclosed",
+ ],
);
}
@@ -1389,13 +1314,17 @@ fn test_switch_execute_arg_template_error(repo: TestRepo) {
#[rstest]
fn test_switch_execute_verbose_multiline_template(repo: TestRepo) {
// Test that -v shows multiline template expansion with proper formatting
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+ MockConfig::new("multiline-target")
+ .command("_default", MockResponse::output("executed\n"))
+ .write(&mock_bin);
+
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- // Multiline template with conditional
- let multiline_template = r#"{% if branch %}
-echo 'branch={{ branch }}'
-echo 'repo={{ repo }}'
-{% endif %}"#;
+ // Multiline template in a single argv element.
+ let multiline_template = r#"{% if branch %}branch={{ branch }}
+repo={{ repo }}{% endif %}"#;
let mut cmd = make_snapshot_cmd_with_global_flags(
&repo,
@@ -1404,11 +1333,14 @@ echo 'repo={{ repo }}'
"--create",
"multiline-test",
"--execute",
+ "multiline-target",
+ "--",
multiline_template,
],
None,
&["-v"],
);
+ configure_mock_cli_env(&mut cmd, &mock_bin);
assert_cmd_snapshot!("switch_execute_verbose_multiline_template", cmd);
});
}
@@ -1422,9 +1354,11 @@ fn test_switch_no_config_commands_execute_still_runs(repo: TestRepo) {
&[
"--create",
"no-hooks-test",
- "--execute",
- "echo 'execute command runs'",
"--no-hooks",
+ "--execute",
+ "echo",
+ "--",
+ "execute command runs",
],
);
}
@@ -1496,9 +1430,11 @@ fn test_switch_no_config_commands_with_existing_worktree(mut repo: TestRepo) {
&repo,
&[
"existing-no-hooks",
- "--execute",
- "echo 'execute still runs'",
"--no-hooks",
+ "--execute",
+ "echo",
+ "--",
+ "execute still runs",
],
);
}
@@ -2005,9 +1941,9 @@ fn test_switch_detached_worktree_by_relative_path_honors_directory_flag(mut repo
let outside = repo.root_path().parent().unwrap().to_path_buf();
let root = repo.root_path().to_string_lossy().to_string();
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
cmd.current_dir(&outside)
.args(["-C", &root, "switch", "../repo.feature-detached"]);
@@ -2063,21 +1999,26 @@ fn test_switch_default_branch_from_feature_worktree(mut repo: TestRepo) {
);
}
-// Execute tests with directive file
-/// The shell wrapper sources this file and propagates the exit code.
+// Execute tests with a CD directive file
+/// wt launches this argv and propagates the exit code.
#[rstest]
fn test_switch_internal_execute_exit_code(repo: TestRepo) {
- // wt succeeds (exit 0), but shell script contains "exit 42"
- // Shell wrapper will eval and return 42
snapshot_switch_with_directive_file(
"switch_internal_execute_exit_code",
&repo,
- &["--create", "exit-code-test", "--execute", "exit 42"],
+ &[
+ "--create",
+ "exit-code-test",
+ "--execute",
+ "sh",
+ "--",
+ "-c",
+ "exit 42",
+ ],
);
}
-/// When wt succeeds but the execute script would fail, wt still exits 0.
-/// The shell wrapper handles the execute command's exit code.
+/// The execute program's exit code becomes wt's exit code.
#[rstest]
fn test_switch_internal_execute_with_output_before_exit(repo: TestRepo) {
// Execute command outputs then exits with code
@@ -2086,7 +2027,15 @@ fn test_switch_internal_execute_with_output_before_exit(repo: TestRepo) {
snapshot_switch_with_directive_file(
"switch_internal_execute_output_then_exit",
&repo,
- &["--create", "output-exit-test", "--execute", cmd],
+ &[
+ "--create",
+ "output-exit-test",
+ "--execute",
+ "sh",
+ "--",
+ "-c",
+ cmd,
+ ],
);
}
// History and ping-pong tests
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index ec911d480..539809a7c 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -1558,17 +1558,13 @@ fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {
// Create a worktree to switch to
let target_path = repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
+ let (cd_path, _guard) = worktrunk::testing::directive_file();
let mut env_vars = repo.test_env_vars();
env_vars.push((
"WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
cd_path.display().to_string(),
));
- env_vars.push((
- "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
- exec_path.display().to_string(),
- ));
// Run `wt switch` (without --no-cd), select "target-branch" via picker
let result = exec_in_pty_with_input_expectations(
@@ -1615,17 +1611,13 @@ fn test_switch_picker_no_cd_switches_without_cd_directive(mut repo: TestRepo) {
// Create a worktree to switch to
repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
+ let (cd_path, _guard) = worktrunk::testing::directive_file();
let mut env_vars = repo.test_env_vars();
env_vars.push((
"WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
cd_path.display().to_string(),
));
- env_vars.push((
- "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
- exec_path.display().to_string(),
- ));
// `wt switch --no-cd` opens the picker and switches identically to
// `wt switch <branch> --no-cd` — it only suppresses the cd directive.
@@ -1679,22 +1671,18 @@ fn test_switch_picker_execute_base_resolves_to_source(mut repo: TestRepo) {
repo.run_git(&["remote", "remove", "origin"]);
repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
+ let (cd_path, _guard) = worktrunk::testing::directive_file();
let mut env_vars = repo.test_env_vars();
env_vars.push((
"WORKTRUNK_DIRECTIVE_CD_FILE".to_string(),
cd_path.display().to_string(),
));
- env_vars.push((
- "WORKTRUNK_DIRECTIVE_EXEC_FILE".to_string(),
- exec_path.display().to_string(),
- ));
// Run from the `main` worktree so the captured source branch is `main`.
let result = exec_in_pty_with_input_expectations(
wt_bin().to_str().unwrap(),
- &["switch", "--execute", "echo {{ base }}"],
+ &["switch", "--execute", "echo", "--", "{{ base }}"],
repo.root_path(),
&env_vars,
&[
@@ -1712,11 +1700,10 @@ fn test_switch_picker_execute_base_resolves_to_source(mut repo: TestRepo) {
result.screen()
);
- let exec_contents = std::fs::read_to_string(&exec_path).unwrap_or_default();
assert!(
- exec_contents.contains("echo main"),
- "EXEC file should contain the expanded `{{{{ base }}}}` (the source \
- branch `main`), got: {exec_contents}"
+ result.screen().contains("main"),
+ "Screen:\n{}",
+ result.screen()
);
}
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 8acfa97e5..e1931274e 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -3800,7 +3800,7 @@ cleanup = "echo done"
/// parent shell via the CD directive file.
#[rstest]
fn test_foreground_hook_passes_directive_file(repo: TestRepo) {
- use crate::common::{configure_directive_files, directive_files, wt_bin};
+ use crate::common::{configure_directive_file, directive_file, wt_bin};
repo.commit("initial");
@@ -3823,10 +3823,10 @@ setup = "'{wt_toml}' switch --create hook-created --no-hooks"
"#,
));
- let (cd_path, exec_path, _guard) = directive_files();
+ let (cd_path, _guard) = directive_file();
let mut cmd = repo.wt_command();
- configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ configure_directive_file(&mut cmd, &cd_path);
// Run the pre-start hook manually in foreground
cmd.args(["hook", "pre-start", "setup"]);
let output = cmd.output().unwrap();
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap
index 3bf0189d9..da64fd45d 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap
@@ -21,7 +21,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap
index 0e60ad60c..e4058b701 100644
--- a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap
+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap
@@ -20,7 +20,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_when_already_at.snap b/tests/snapshots/integration__integration_tests__directives__current_wrapper_wins_retired_variables_and_warns.snap
similarity index 62%
rename from tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_when_already_at.snap
rename to tests/snapshots/integration__integration_tests__directives__current_wrapper_wins_retired_variables_and_warns.snap
index f0be7ff69..7e07e8948 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_when_already_at.snap
+++ b/tests/snapshots/integration__integration_tests__directives__current_wrapper_wins_retired_variables_and_warns.snap
@@ -6,7 +6,11 @@ info:
- switch
- feature
- "--execute"
- - echo spawned > retired-execute-ran
+ - git
+ - "--"
+ - rev-parse
+ - "--abbrev-ref"
+ - HEAD
env:
APPDATA: "[TEST_CONFIG_HOME]"
CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
@@ -14,9 +18,18 @@ info:
COLUMNS: "500"
GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -28,6 +41,8 @@ info:
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_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
@@ -43,6 +58,7 @@ info:
WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -50,10 +66,12 @@ info:
success: true
exit_code: 0
----- stdout -----
+feature
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo spawned > retired-execute-ran'
-○ Already on worktree for feature @ _REPO_.feature
-▲ --execute disabled because the shell wrapper is out of date; skipping echo spawned > retired-execute-ran
+○ Switched to worktree for feature @ _REPO_.feature
+▲ Shell wrapper is out of date — --execute output may be buffered instead of using the terminal
↳ To update the shell wrapper, run wt config shell install
+◎ Executing (--execute):
+  git rev-parse --abbrev-ref HEAD
+
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap
index 5da72e058..7108a4b37 100644
--- a/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__directives__merge_directive_file.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap b/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap
index faf681542..33b8cc8c7 100644
--- a/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap
+++ b/tests/snapshots/integration__integration_tests__directives__merge_directive_no_remove.snap
@@ -26,7 +26,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap b/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap
index 5da72e058..7108a4b37 100644
--- a/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap
+++ b/tests/snapshots/integration__integration_tests__directives__merge_directive_remove.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap
index 91e381320..57b9473c5 100644
--- a/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__directives__remove_directive_file.snap
@@ -24,7 +24,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap b/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap
index f41d10633..77c3c7290 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_directive_file.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap b/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap
deleted file mode 100644
index 92d60c251..000000000
--- a/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap
+++ /dev/null
@@ -1,59 +0,0 @@
----
-source: tests/integration_tests/directives.rs
-info:
- program: wt
- args:
- - switch
- - "--create"
- - scrub-test
- - "--execute"
- - echo should-not-run
- 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
- WORKTRUNK_TEST_BASH_INSTALLED: "0"
- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
- WORKTRUNK_TEST_CODEX_INSTALLED: "0"
- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
- WORKTRUNK_TEST_EPOCH: "1735776000"
- WORKTRUNK_TEST_FISH_INSTALLED: "0"
- WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
- WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- 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 -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo should-not-run'
-✓ Created branch scrub-test from main and worktree @ _REPO_.scrub-test
-↳ To customize worktree locations, run wt config create
-▲ --execute disabled inside project alias / hook bodies for safety; skipping echo should-not-run
-↳ User-source aliases allow it. Comment at https://github.com/max-sixty/worktrunk/issues/2101 if you need it for project aliases or hooks
-
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap
index f41d10633..77c3c7290 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_config_suppresses_directive.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
index fb7efd342..2cf614d0a 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_create_suppresses_directive.snap
@@ -27,7 +27,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
similarity index 75%
rename from tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
rename to tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
index 05f695e25..c2d3f4350 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_runs_in_target_worktree.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_execute_does_not_emit_cd.snap
@@ -11,12 +11,23 @@ info:
- pwd
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -29,7 +40,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -41,8 +51,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -50,6 +62,7 @@ info:
success: true
exit_code: 0
----- stdout -----
+_REPO_
----- stderr -----
✓ Created branch exec-test from main and worktree @ _REPO_.exec-test
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
index 0bc29e239..347e6302c 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_hooks_show_path_annotation.snap
@@ -28,7 +28,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
index 06437c6bd..3486da987 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_no_cd_suppresses_directive.snap
@@ -26,7 +26,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_after_switch.snap b/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_does_not_block_execute.snap
similarity index 72%
rename from tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_after_switch.snap
rename to tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_does_not_block_execute.snap
index b8e13eba6..87f1def02 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_after_switch.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_does_not_block_execute.snap
@@ -6,6 +6,9 @@ info:
- switch
- feature
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- echo spawned > retired-execute-ran
env:
APPDATA: "[TEST_CONFIG_HOME]"
@@ -14,9 +17,18 @@ info:
COLUMNS: "500"
GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -43,6 +55,7 @@ info:
WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -52,8 +65,7 @@ exit_code: 0
----- stdout -----
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo spawned > retired-execute-ran'
▲ Worktree for feature @ _REPO_.feature, but cannot change directory — shell wrapper is out of date
↳ To update the shell wrapper, run wt config shell install
-▲ --execute disabled because the shell wrapper is out of date; skipping echo spawned > retired-execute-ran
+◎ Executing (--execute) @ _REPO_.feature:
+  sh -c 'echo spawned > retired-execute-ran'
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index af726a349..febf0e5d6 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -644,9 +644,7 @@ Override the LLM command in CI to use a mock:
WORKTRUNK_PROJECT_CONFIG_PATH Override project config file location (defaults to .config/wt.toml); relative paths resolve from the worktree root
XDG_CONFIG_DIRS Colon-separated system config directories (default: /etc/xdg)
WORKTRUNK_DIRECTIVE_CD_FILE Internal: set by shell wrappers. wt writes a raw path; the wrapper cds to it
- WORKTRUNK_DIRECTIVE_EXEC_FILE Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file
WORKTRUNK_SHELL_CWD Internal: set by wt on alias and hook bodies, so a nested wt preserves the user's subdirectory
- WORKTRUNK_SHELL Internal: set by shell wrappers to indicate shell type (e.g., powershell)
WORKTRUNK_COMPLETE_NAME Internal: set by shell wrappers to the command name completions register under (defaults to the binary name)
WORKTRUNK_MAX_CONCURRENT_COMMANDS Max parallel git commands (default: 32). Lower if hitting file descriptor limits.
WORKTRUNK_VERBOSE Verbosity level (0/1/2), like -v/-vv but applied everywhere — including shell completion, which no flag can reach
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index f2ba35bc9..8e7b1c787 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -55,7 +55,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
[EXECUTE_ARGS]...
Additional arguments for --execute command (after --)
- Arguments after -- are appended to the execute command. Each argument is expanded for templates, then POSIX shell-escaped.
+ Each argument is expanded for templates and passed directly to the program.
Options:
-c, --create
@@ -67,11 +67,11 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Defaults to default branch. Supports the same shortcuts as the branch argument: ^, @, -, pr:{N}, mr:{N}.
-x, --execute <EXECUTE>
- Command to run after switch
+ Program to run after switch
- Replaces the wt process with the command after switching, giving it full terminal control. Useful for launching editors, AI agents, or other interactive tools.
+ Runs one external program after switching, with full terminal control. Arguments after -- go directly to that program without Worktrunk shell parsing. Program lookup and argument decoding follow the operating system. Shell syntax requires an explicit shell, for example -x sh -- -c 'npm install && npm test'. On Windows, shell shims need their extension (-x code.cmd) or an explicit shell such as -x cmd.exe -- /C code.
- Without a branch argument, the interactive picker opens and the command runs against the selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code there.
+ Without a branch argument, the interactive picker opens and the command runs against the selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code there. With --no-cd, the program starts in the invoking directory instead.
Supports ]8;;https://worktrunk.dev/hook/#template-variables\hook template variables]8;;\ ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{ base }} and {{ base_worktree_path }} describe the source: the selected base with --create, or the invoking worktree when switching to an existing worktree.
@@ -90,7 +90,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--no-cd
Skip directory change after switching
- Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or for CI/automation. Use --cd to override.
+ Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or for CI/automation. --execute also starts in the invoking directory. Use --cd to override.
-h, --help
Print help (see a summary with '-h')
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
index 8437f1fe8..89a903008 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
@@ -9,6 +9,13 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "500"
GIT_ALLOW_PROTOCOL: file
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
LANG: C
LC_ALL: C
LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
@@ -28,6 +35,7 @@ info:
WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
---
@@ -45,7 +53,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Options:
-c, --create Create a new branch
-b, --base <BASE> Base branch
- -x, --execute <EXECUTE> Command to run after switch
+ -x, --execute <EXECUTE> Program to run after switch
--clobber Remove stale paths at target
--no-cd Skip directory change after switching
-h, --help Print help (see more with '--help')
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index a55299e4d..a913b9e69 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -9,12 +9,23 @@ info:
- bash
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -37,8 +48,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -51,8 +64,7 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override wt command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -70,16 +82,15 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
@@ -95,16 +106,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 882525097..ec0125a34 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -9,12 +9,23 @@ info:
- fish
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -37,8 +48,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -51,8 +64,7 @@ exit_code: 0
# This is the full function definition, output by `wt config shell init fish`.
# It's sourced at runtime by the wrapper in ~/.config/fish/functions/wt.fish.
-# Override wt command with split directive passing.
-# Creates two temp files: one for cd (raw path) and one for exec (shell).
+# Override wt command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
function wt
set -l use_source false
@@ -68,18 +80,13 @@ function wt
return 127
end
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 \
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \
cargo run --bin wt --quiet -- $args
else
- env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file WORKTRUNK_DIRECTIVE_EXEC_FILE=$exec_file \
- WORKTRUNK_SHELL=fish \
+ env WORKTRUNK_DIRECTIVE_CD_FILE=$cd_file \
$WORKTRUNK_BIN $args
end
set -l exit_code $status
@@ -98,17 +105,7 @@ function wt
end
end
- # exec file holds arbitrary shell (e.g. from --execute)
- if test -s "$exec_file"
- set -l directive (string collect < "$exec_file")
- eval $directive
- set -l src_exit $status
- if test $exit_code -eq 0
- set exit_code $src_exit
- end
- end
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return $exit_code
end
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 8d2b8ef50..780afff72 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -9,12 +9,23 @@ info:
- zsh
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -37,8 +48,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -54,8 +67,7 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Override wt command with split directive passing.
- # Creates two temp files: one for cd (raw path) and one for exec (shell).
+ # Override wt command so it can change the parent shell's directory.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
wt() {
local use_source=false
@@ -73,16 +85,15 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
return
fi
- local cd_file exec_file exit_code=0
+ local cd_file exit_code=0
cd_file="$(mktemp)"
- exec_file="$(mktemp)"
# --source: use cargo run (builds from source)
if [[ "$use_source" == true ]]; then
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
cargo run --bin wt --quiet -- "${args[@]}" || exit_code=$?
else
- WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \
+ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" \
command "${WORKTRUNK_BIN:-wt}" "${args[@]}" || exit_code=$?
fi
@@ -98,16 +109,7 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
fi
fi
- # exec file holds arbitrary shell (e.g. from --execute)
- if [[ -s "$exec_file" ]]; then
- source "$exec_file"
- local src_exit=$?
- if [[ $exit_code -eq 0 ]]; then
- exit_code=$src_exit
- fi
- fi
-
- command rm -f "$cd_file" "$exec_file"
+ command rm -f "$cd_file"
return "$exit_code"
}
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snap b/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snap
index d5891d3e1..2017b0058 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snap
@@ -7,15 +7,29 @@ info:
- "--create"
- feature
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- "echo 'Execute flag' > execute.txt"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +52,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -49,12 +65,10 @@ exit_code: 0
----- stdout -----
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''Execute flag'\'' > execute.txt'
✓ Created branch feature from main and worktree @ _REPO_.feature
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Running post-start: project @ _REPO_.feature
◎ Executing (--execute) @ _REPO_.feature:
-  echo 'Execute flag' > execute.txt
+  sh -c 'echo '\''Execute flag'\'' > execute.txt'
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 70279c12f..a056c7c18 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap
@@ -24,7 +24,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap
index a992b52f6..d64278ba9 100644
--- a/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__branch_name_with_cd_directive_not_executed.snap
@@ -26,7 +26,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
index b9578a036..c4f6fc27e 100644
--- a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
+++ b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap
@@ -36,7 +36,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__fish_multiline_command_execution.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__fish_multiline_command_execution.snap
index 5ea1fb837..2a6c00481 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__fish_multiline_command_execution.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__fish_multiline_command_execution.snap
@@ -3,12 +3,11 @@ source: tests/integration_tests/shell_wrapper.rs
expression: "&output.combined"
---
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute fish -- -c 'echo \'line 1\'; echo \'line 2\'; echo \'line 3\''
✓ Created branch fish-multiline from main and worktree @ _REPO_.fish-multiline
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo 'line 1'; echo 'line 2'; echo 'line 3'
-line 1
+  fish -c 'echo '\''line 1'\''; echo '\''line 2'\''; echo '\''line 3'\'''
+line 1
line 2
line 3
+
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_bash.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_bash.snap
index 17799a3d3..e43f53644 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_bash.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_bash.snap
@@ -6,5 +6,6 @@ expression: "&output.combined"
✓ Created branch test-exec from main and worktree @ _REPO_.test-exec
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo executed
-executed
+  sh -c 'test -t 1 && printf '\''EXEC_STDOUT_TTY:true\n'\'''
+EXEC_STDOUT_TTY:true
+
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_fish.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_fish.snap
index 4e9f1eca2..e43f53644 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_fish.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_fish.snap
@@ -6,5 +6,6 @@ expression: "&output.combined"
✓ Created branch test-exec from main and worktree @ _REPO_.test-exec
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo 'executed'
-executed
+  sh -c 'test -t 1 && printf '\''EXEC_STDOUT_TTY:true\n'\'''
+EXEC_STDOUT_TTY:true
+
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_nu.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_nu.snap
index 17799a3d3..e43f53644 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_nu.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_nu.snap
@@ -6,5 +6,6 @@ expression: "&output.combined"
✓ Created branch test-exec from main and worktree @ _REPO_.test-exec
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo executed
-executed
+  sh -c 'test -t 1 && printf '\''EXEC_STDOUT_TTY:true\n'\'''
+EXEC_STDOUT_TTY:true
+
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_through_wrapper.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_through_wrapper.snap
index 6fa944248..d16fd6d32 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_through_wrapper.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_through_wrapper.snap
@@ -3,10 +3,9 @@ source: tests/integration_tests/shell_wrapper.rs
expression: "&output.combined"
---
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo executed'
✓ Created branch test-exec from main and worktree @ _REPO_.test-exec
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
  echo executed
-executed
+executed
+
diff --git a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_zsh.snap b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_zsh.snap
index 17799a3d3..e43f53644 100644
--- a/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__shell_wrapper__unix_tests__switch_with_execute_zsh.snap
@@ -6,5 +6,6 @@ expression: "&output.combined"
✓ Created branch test-exec from main and worktree @ _REPO_.test-exec
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo executed
-executed
+  sh -c 'test -t 1 && printf '\''EXEC_STDOUT_TTY:true\n'\'''
+EXEC_STDOUT_TTY:true
+
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch.snap b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch.snap
index 3cc699565..c37015e59 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_branch_worktree_mismatch.snap
@@ -26,7 +26,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap b/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap
index cfcbf4121..70fc9df4a 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_detached_worktree_by_relative_path.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
index 2047ddf25..1903d77c7 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_detached.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
index ca1f53c2c..8a0a7eb51 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_different_branch.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
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 35bf4ec80..9850385f4 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
@@ -7,15 +7,29 @@ info:
- "--create"
- file-test
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- "echo 'test content' > test.txt"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +52,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -49,11 +65,9 @@ exit_code: 0
----- stdout -----
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''test content'\'' > test.txt'
✓ Created branch file-test from main and worktree @ _REPO_.file-test
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Executing (--execute) @ _REPO_.file-test:
-  echo 'test content' > test.txt
+  sh -c 'echo '\''test content'\'' > test.txt'
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_fish_wrapper.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_fish_wrapper.snap
deleted file mode 100644
index 1f251ec50..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_fish_wrapper.snap
+++ /dev/null
@@ -1,60 +0,0 @@
----
-source: tests/integration_tests/switch.rs
-info:
- program: wt
- args:
- - switch
- - "--create"
- - dep-fish
- - "--execute"
- - set -lx FOO bar; echo $FOO
- 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_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_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- 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 -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute fish -- -c 'set -lx FOO bar; echo $FOO'
-✓ Created branch dep-fish from main and worktree @ _REPO_.dep-fish
-◎ Executing (--execute):
-  set -lx FOO bar; echo $FOO
-
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_shell_syntax.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_shell_syntax.snap
deleted file mode 100644
index 7264bff0a..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_shell_syntax.snap
+++ /dev/null
@@ -1,60 +0,0 @@
----
-source: tests/integration_tests/switch.rs
-info:
- program: wt
- args:
- - switch
- - "--create"
- - dep-shell
- - "--execute"
- - echo hi && ls
- 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
- WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
- WORKTRUNK_TEST_BASH_INSTALLED: "0"
- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
- WORKTRUNK_TEST_CODEX_INSTALLED: "0"
- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
- WORKTRUNK_TEST_EPOCH: "1735776000"
- WORKTRUNK_TEST_FISH_INSTALLED: "0"
- WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
- WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- 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 -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo hi && ls'
-✓ Created branch dep-shell from main and worktree @ _REPO_.dep-shell
-↳ To customize worktree locations, run wt config create
-◎ Executing (--execute):
-  echo hi && ls
-
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_trailing_args.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_trailing_args.snap
deleted file mode 100644
index 517a8c89e..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_trailing_args.snap
+++ /dev/null
@@ -1,61 +0,0 @@
----
-source: tests/integration_tests/switch.rs
-info:
- program: wt
- args:
- - switch
- - "--create"
- - dep-args
- - "--execute"
- - npm run
- - "--"
- - test
- 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
- WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
- WORKTRUNK_TEST_BASH_INSTALLED: "0"
- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
- WORKTRUNK_TEST_CODEX_INSTALLED: "0"
- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
- WORKTRUNK_TEST_EPOCH: "1735776000"
- WORKTRUNK_TEST_FISH_INSTALLED: "0"
- WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
- WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- 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 -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'npm run test'
-✓ Created branch dep-args from main and worktree @ _REPO_.dep-args
-◎ Executing (--execute):
-  npm run test
-
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 8efadf9b4..b51ee9108 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap
@@ -7,15 +7,29 @@ info:
- "--create"
- fail-test
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- exit 1
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +52,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -49,11 +65,9 @@ exit_code: 1
----- stdout -----
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'exit 1'
✓ Created branch fail-test from main and worktree @ _REPO_.fail-test
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Executing (--execute) @ _REPO_.fail-test:
-  exit 1
+  sh -c 'exit 1'
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_compatible.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_rejects_empty_program.snap
similarity index 63%
rename from tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_compatible.snap
rename to tests/snapshots/integration__integration_tests__switch__switch_execute_rejects_empty_program.snap
index 2acb67fe1..43405da97 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_deprecation_compatible.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_rejects_empty_program.snap
@@ -5,17 +5,28 @@ info:
args:
- switch
- "--create"
- - dep-ok
+ - empty-program
- "--execute"
- - git
+ - ""
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -27,8 +38,6 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -40,18 +49,19 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
-success: true
-exit_code: 0
+success: false
+exit_code: 2
----- stdout -----
----- stderr -----
-✓ Created branch dep-ok from main and worktree @ _REPO_.dep-ok
-◎ Executing (--execute):
-  git
-
+error: a value is required for '--execute <EXECUTE>' but none was supplied
+
+For more information, try '--help'.
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base.snap
index 73faef7ac..c146bd40d 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base.snap
@@ -9,7 +9,9 @@ info:
- "--base"
- release-base
- "--execute"
- - "echo 'base={{ base }}'"
+ - echo
+ - "--"
+ - "base={{ base }}"
env:
APPDATA: "[TEST_CONFIG_HOME]"
CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
@@ -17,9 +19,18 @@ info:
COLUMNS: "500"
GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -45,6 +56,7 @@ info:
WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -55,11 +67,9 @@ exit_code: 0
base=release-base
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''base={{ base }}'\'''
✓ Created branch from-release-base from release-base and worktree @ _REPO_.from-release-base
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Executing (--execute) @ _REPO_.from-release-base:
-  echo 'base=release-base'
+  echo base=release-base
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap
index 3be9a4713..459c47947 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_base_without_create.snap
@@ -6,15 +6,28 @@ info:
- switch
- existing
- "--execute"
- - "echo 'base={{ base }}'"
+ - echo
+ - "--"
+ - "base={{ base }}"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -37,8 +50,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -49,9 +64,7 @@ exit_code: 0
base=main
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''base={{ base }}'\'''
▲ Worktree for existing @ _REPO_.existing, but cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Executing (--execute) @ _REPO_.existing:
-  echo 'base=main'
+  echo base=main
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_branch.snap
index a6e8b0b5a..be4d79141 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_branch.snap
@@ -7,15 +7,28 @@ info:
- "--create"
- template-test
- "--execute"
- - "echo 'branch={{ branch }}'"
+ - echo
+ - "--"
+ - "branch={{ branch }}"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +51,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -50,11 +65,9 @@ exit_code: 0
branch=template-test
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''branch={{ branch }}'\'''
✓ Created branch template-test from main and worktree @ _REPO_.template-test
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Executing (--execute) @ _REPO_.template-test:
-  echo 'branch=template-test'
+  echo branch=template-test
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap
index 49de6f742..24f1ebb63 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_error.snap
@@ -7,15 +7,28 @@ info:
- "--create"
- error-test
- "--execute"
- - "echo {{ unclosed"
+ - echo
+ - "--"
+ - "{{ unclosed"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +51,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -49,5 +64,5 @@ exit_code: 1
----- stdout -----
----- stderr -----
-✗ Failed to expand --execute command: syntax error: unexpected end of input, expected end of variable block @ line 1
-  echo {{ unclosed
+✗ Failed to expand --execute argument: syntax error: unexpected end of input, expected end of variable block @ line 1
+  {{ unclosed
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap
index d0e78cf1d..1c39c63a3 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_template_shell_escape.snap
@@ -7,15 +7,28 @@ info:
- "--create"
- feat;id
- "--execute"
- - "echo {{ branch }}"
+ - echo
+ - "--"
+ - "{{ branch }}"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +51,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -50,8 +65,6 @@ exit_code: 0
feat;id
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo {{ branch }}'
✓ Created branch feat;id from main and worktree @ '_REPO_.feat;id'
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snap
index cca35efbf..733e46414 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_verbose_multiline_template.snap
@@ -8,15 +8,28 @@ info:
- "--create"
- multiline-test
- "--execute"
- - "{% if branch %}\necho 'branch={{ branch }}'\necho 'repo={{ repo }}'\n{% endif %}"
+ - multiline-target
+ - "--"
+ - "{% if branch %}branch={{ branch }}\nrepo={{ repo }}{% endif %}"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -39,8 +52,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -48,33 +63,27 @@ info:
success: true
exit_code: 0
----- stdout -----
-branch=multiline-test
-repo=repo
+executed
----- stderr -----
○ worktree-path source
  {{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}
○ worktree-path result
  _REPO_/../repo.multiline-test
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c '{% if branch %}
-echo '\''branch={{ branch }}'\''
-echo '\''repo={{ repo }}'\''
-{% endif %}'
✓ Created branch multiline-test from main and worktree @ _REPO_.multiline-test
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
○ --execute command source
-  {% if branch %}
-  echo 'branch={{ branch }}'
-  echo 'repo={{ repo }}'
-  {% endif %}
+  multiline-target
○ --execute command result
-  
-  echo 'branch=multiline-test'
-  echo 'repo=repo'
+  multiline-target
+○ --execute argument source
+  {% if branch %}branch={{ branch }}
+  repo={{ repo }}{% endif %}
+○ --execute argument result
+  branch=multiline-test
+  repo=repo
◎ Executing (--execute) @ _REPO_.multiline-test:
-  
-  echo 'branch=multiline-test'
-  echo 'repo=repo'
+  multiline-target 'branch=multiline-test
+  repo=repo'
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 03395eb77..ffe4bcdcc 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap
index 984f14aa1..abcbbab06 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap
@@ -7,15 +7,29 @@ info:
- "--create"
- exit-code-test
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- exit 42
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -28,7 +42,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -40,21 +53,21 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
-success: true
-exit_code: 0
+success: false
+exit_code: 42
----- stdout -----
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'exit 42'
✓ Created branch exit-code-test from main and worktree @ _REPO_.exit-code-test
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  exit 42
+  sh -c 'exit 42'

diff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap
index f41644bfe..03ac26773 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap
@@ -7,15 +7,29 @@ info:
- "--create"
- output-exit-test
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- "echo 'doing work'\nexit 7"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -28,7 +42,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -40,23 +53,23 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
-success: true
-exit_code: 0
+success: false
+exit_code: 7
----- stdout -----
+doing work
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''doing work'\''
-exit 7'
✓ Created branch output-exit-test from main and worktree @ _REPO_.output-exit-test
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo 'doing work'
-  exit 7
+  sh -c 'echo '\''doing work'\''
+  exit 7'

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 40bfe4d1a..a9f66ab54 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap
@@ -26,7 +26,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
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
index 99985b7a3..948ccd5d1 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap
@@ -7,15 +7,29 @@ info:
- "--create"
- exec-internal
- "--execute"
+ - sh
+ - "--"
+ - "-c"
- "echo 'line1'\necho 'line2'"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -28,7 +42,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -40,8 +53,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -49,14 +64,13 @@ info:
success: true
exit_code: 0
----- stdout -----
+line1
+line2
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''line1'\''
-echo '\''line2'\'''
✓ Created branch exec-internal from main and worktree @ _REPO_.exec-internal
↳ To customize worktree locations, run wt config create
◎ Executing (--execute):
-  echo 'line1'
-  echo 'line2'
+  sh -c 'echo '\''line1'\''
+  echo '\''line2'\'''

diff --git a/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
index 714d4b7ac..6511157f0 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_main_worktree_on_different_branch.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_execute_still_runs.snap b/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_execute_still_runs.snap
index 57344d302..bb4574a34 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_execute_still_runs.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_execute_still_runs.snap
@@ -6,17 +6,30 @@ info:
- switch
- "--create"
- no-hooks-test
- - "--execute"
- - "echo 'execute command runs'"
- "--no-hooks"
+ - "--execute"
+ - echo
+ - "--"
+ - execute command runs
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -39,8 +52,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -51,8 +66,6 @@ exit_code: 0
execute command runs
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''execute command runs'\'''
✓ Created branch no-hooks-test from main and worktree @ _REPO_.no-hooks-test
↳ To customize worktree locations, run wt config create
▲ Cannot change directory — shell integration not installed
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_existing.snap b/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_existing.snap
index ebb5b4178..bc01f505e 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_existing.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_no_hooks_existing.snap
@@ -5,17 +5,30 @@ info:
args:
- switch
- existing-no-hooks
- - "--execute"
- - "echo 'execute still runs'"
- "--no-hooks"
+ - "--execute"
+ - echo
+ - "--"
+ - execute still runs
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -38,8 +51,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -50,8 +65,6 @@ exit_code: 0
execute still runs
----- stderr -----
-▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo '\''execute still runs'\'''
▲ Worktree for existing-no-hooks @ _REPO_.existing-no-hooks, but cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Executing (--execute) @ _REPO_.existing-no-hooks:
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap b/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
index ff7911d47..9a19b7d94 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_no_warning_when_branch_matches.snap
@@ -25,7 +25,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap
index 696292c13..7a47658a1 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_post_hook_no_path_with_shell_integration.snap
@@ -27,7 +27,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_stderr.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_literal_argv.snap
similarity index 57%
rename from tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_stderr.snap
rename to tests/snapshots/integration__integration_tests__switch__switch_with_execute_literal_argv.snap
index a067bcbb2..a33f2e6d2 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_stderr.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_literal_argv.snap
@@ -7,18 +7,34 @@ info:
- "--create"
- exec-trailing
- "--execute"
- - echo
+ - sh
- "--"
+ - "-c"
+ - "printf '<%s>\\n' \"$@\""
+ - _
- "$x's hello"
- with space
+ - ""
+ - café
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -30,8 +46,6 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_CD_FILE: "[DIRECTIVE_CD_FILE]"
- WORKTRUNK_DIRECTIVE_EXEC_FILE: "[DIRECTIVE_EXEC_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -43,8 +57,10 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -52,10 +68,15 @@ info:
success: true
exit_code: 0
----- stdout -----
+<$x's hello>
+<with space>
+<>
+<café>
----- stderr -----
✓ Created branch exec-trailing from main and worktree @ _REPO_.exec-trailing
↳ To customize worktree locations, run wt config create
-◎ Executing (--execute):
-  echo '$x'\''s hello' 'with space'
-
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Executing (--execute) @ _REPO_.exec-trailing:
+  sh -c 'printf '\''<%s>\n'\'' "$@"' _ '$x'\''s hello' 'with space' '' 'café'
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_exec.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_exec.snap
deleted file mode 100644
index 5ff115ab9..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_exec.snap
+++ /dev/null
@@ -1,5 +0,0 @@
----
-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_fish_exec.snap b/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_exec.snap
deleted file mode 100644
index eb1f3bde6..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_exec.snap
+++ /dev/null
@@ -1,5 +0,0 @@
----
-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
deleted file mode 100644
index cb42334a9..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_fish_stderr.snap
+++ /dev/null
@@ -1,62 +0,0 @@
----
-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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_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_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- 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
deleted file mode 100644
index b82c3a6eb..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_exec.snap
+++ /dev/null
@@ -1,5 +0,0 @@
----
-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
deleted file mode 100644
index 4d5f6e096..000000000
--- a/tests/snapshots/integration__integration_tests__switch__switch_with_execute_trailing_args_metachars_powershell_stderr.snap
+++ /dev/null
@@ -1,62 +0,0 @@
----
-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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- GIT_TERMINAL_PROMPT: "0"
- HOME: "[TEST_HOME]"
- LANG: C
- LC_ALL: C
- LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
- OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
- PATH: "[PATH]"
- TERM: alacritty
- USERPROFILE: "[TEST_HOME]"
- WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_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_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
- 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'
-