Skip to content

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

Fix stderr redirection in fish shell wrapper

Maximilian Roos0301d4bf1b3b
diff --git a/src/main.rs b/src/main.rs
index fa18e9eef..c21233889 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -56,6 +56,12 @@ fn maybe_handle_help_with_pager() -> bool {
let args: Vec<String> = std::env::args().collect();
+ // Skip pager in directive mode (--internal flag present)
+ // Fish's command substitution doesn't propagate stderr redirects, so
+ // `wt --help &>file` would output to terminal if pager is used.
+ // In directive mode, help should go to stderr without paging.
+ let is_internal = args.iter().any(|a| a == "--internal");
+
// Check for --help-page flag (output full doc page with frontmatter)
if args.iter().any(|a| a == "--help-page") {
handle_help_page(&args);
@@ -114,7 +120,11 @@ fn maybe_handle_help_with_pager() -> bool {
// Render markdown sections to ANSI
help = md_help::render_markdown_in_help(&help);
- if let Err(e) = help_pager::show_help_in_pager(&help) {
+ // In directive mode (--internal), skip pager - output to stderr directly.
+ // This fixes fish's command substitution not propagating stderr redirects.
+ if is_internal {
+ eprintln!("{}", help);
+ } else if let Err(e) = help_pager::show_help_in_pager(&help) {
log::debug!("Pager invocation failed: {}", e);
eprintln!("{}", help);
}
diff --git a/templates/fish.fish b/templates/fish.fish
index 3a6ca5962..876b5d84c 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -4,9 +4,17 @@
if type -q {{ cmd_prefix }}; or test -n "$WORKTRUNK_BIN"
# Capture stdout (shell script), eval in parent shell. stderr streams to terminal.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
+ #
+ # We use pipeline capture (`| read`) instead of command substitution (`(...)`)
+ # because fish's command substitution runs in its own pipeline where stderr
+ # doesn't inherit caller redirects. With pipeline capture, stderr flows through
+ # normally and respects redirects like `wt --help &>file`.
function wt_exec
test -n "$WORKTRUNK_BIN"; or set -l WORKTRUNK_BIN (type -P {{ cmd_prefix }})
- set -l script (command $WORKTRUNK_BIN $argv | string collect)
+
+ # Pipeline capture: stderr streams through, stdout captured via read
+ # -z (null delimiter) ensures we capture all lines, not just the first
+ command $WORKTRUNK_BIN $argv | string collect --allow-empty | read --local -z script
set -l exit_code $pipestatus[1]
if test -n "$script"
@@ -35,7 +43,7 @@ if type -q {{ cmd_prefix }}; or test -n "$WORKTRUNK_BIN"
# --source: use cargo run (builds from source)
if test $use_source = true
- set -l script (cargo run --quiet -- --internal $args | string collect)
+ cargo run --quiet -- --internal $args | string collect --allow-empty | read --local -z script
set -l exit_code $pipestatus[1]
if test -n "$script"
eval $script
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index fc83678e2..525213097 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -2960,4 +2960,210 @@ fi
output
);
}
+
+ // ========================================================================
+ // Stderr/Stdout Redirection Tests
+ // ========================================================================
+ //
+ // These tests verify that output redirection works correctly through the
+ // shell wrapper. When a user runs `wt --help &> file`, ALL output should
+ // go to the file - nothing should leak to the terminal.
+ //
+ // This is particularly important for fish where command substitution `(...)`
+ // doesn't propagate stderr redirects from the calling function.
+
+ /// Test that `wt --help &> file` redirects all output to the file.
+ ///
+ /// This test verifies that stderr redirection works correctly through the
+ /// shell wrapper. The issue being tested: in some shells (particularly fish),
+ /// command substitution doesn't propagate stderr redirects, causing help
+ /// output to appear on the terminal even when redirected.
+ #[rstest]
+ #[case("bash")]
+ #[case("zsh")]
+ #[case("fish")]
+ fn test_wrapper_help_redirect_captures_all_output(#[case] shell: &str) {
+ use portable_pty::{CommandBuilder, PtySize, native_pty_system};
+ use std::io::Read;
+
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ let wt_bin = get_cargo_bin("wt");
+ let wt_bin_dir = wt_bin.parent().unwrap();
+
+ // Create a temp file for the redirect target
+ let tmp_dir = tempfile::tempdir().unwrap();
+ let redirect_file = tmp_dir.path().join("output.log");
+ let redirect_path = redirect_file.display().to_string();
+
+ // Generate wrapper script
+ let output = std::process::Command::new(&wt_bin)
+ .args(["config", "shell", "init", shell])
+ .output()
+ .unwrap();
+ let wrapper_script = String::from_utf8_lossy(&output.stdout);
+
+ // Build shell script that:
+ // 1. Sources the wrapper
+ // 2. Runs `wt --help &> file`
+ // 3. Echoes a marker so we know the script completed
+ let script = match shell {
+ "fish" => format!(
+ r#"
+set -x WORKTRUNK_BIN '{wt_bin}'
+set -x CLICOLOR_FORCE 1
+
+# Source the shell integration
+{wrapper_script}
+
+# Run help with redirect - ALL output should go to file
+wt --help &>'{redirect_path}'
+
+# Marker to show script completed
+echo "SCRIPT_COMPLETED"
+"#,
+ wt_bin = wt_bin.display(),
+ wrapper_script = wrapper_script,
+ redirect_path = redirect_path,
+ ),
+ "zsh" => format!(
+ r#"
+autoload -Uz compinit && compinit -i 2>/dev/null
+export WORKTRUNK_BIN='{wt_bin}'
+export CLICOLOR_FORCE=1
+
+# Source the shell integration
+{wrapper_script}
+
+# Run help with redirect - ALL output should go to file
+wt --help &>'{redirect_path}'
+
+# Marker to show script completed
+echo "SCRIPT_COMPLETED"
+"#,
+ wt_bin = wt_bin.display(),
+ wrapper_script = wrapper_script,
+ redirect_path = redirect_path,
+ ),
+ _ => format!(
+ r#"
+export WORKTRUNK_BIN='{wt_bin}'
+export CLICOLOR_FORCE=1
+
+# Source the shell integration
+{wrapper_script}
+
+# Run help with redirect - ALL output should go to file
+wt --help &>'{redirect_path}'
+
+# Marker to show script completed
+echo "SCRIPT_COMPLETED"
+"#,
+ wt_bin = wt_bin.display(),
+ wrapper_script = wrapper_script,
+ redirect_path = redirect_path,
+ ),
+ };
+
+ // Execute in PTY
+ let pty_system = native_pty_system();
+ let pair = pty_system
+ .openpty(PtySize {
+ rows: 48,
+ cols: 200,
+ pixel_width: 0,
+ pixel_height: 0,
+ })
+ .unwrap();
+
+ let mut cmd = CommandBuilder::new(shell);
+ cmd.env_clear();
+ cmd.env(
+ "HOME",
+ home::home_dir().unwrap().to_string_lossy().to_string(),
+ );
+ cmd.env(
+ "PATH",
+ format!(
+ "{}:{}",
+ wt_bin_dir.display(),
+ std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string())
+ ),
+ );
+
+ // Shell-specific flags for isolation
+ match shell {
+ "zsh" => {
+ cmd.env("ZDOTDIR", "/dev/null");
+ cmd.arg("--no-rcs");
+ cmd.arg("-o");
+ cmd.arg("NO_GLOBAL_RCS");
+ cmd.arg("-o");
+ cmd.arg("NO_RCS");
+ }
+ "bash" => {
+ cmd.arg("--norc");
+ cmd.arg("--noprofile");
+ }
+ "fish" => {
+ cmd.arg("--no-config");
+ }
+ _ => {}
+ }
+
+ cmd.arg("-c");
+ cmd.arg(&script);
+ cmd.cwd(repo.root_path());
+
+ let mut child = pair.slave.spawn_command(cmd).unwrap();
+ drop(pair.slave);
+
+ let mut reader = pair.master.try_clone_reader().unwrap();
+ let mut buf = String::new();
+ reader.read_to_string(&mut buf).unwrap();
+
+ let _status = child.wait().unwrap();
+ let terminal_output = buf.replace("\r\n", "\n");
+
+ // Read the redirect file
+ let file_content = fs::read_to_string(&redirect_file).unwrap_or_else(|e| {
+ panic!(
+ "{}: Failed to read redirect file: {}\nTerminal output:\n{}",
+ shell, e, terminal_output
+ )
+ });
+
+ // Verify script completed
+ assert!(
+ terminal_output.contains("SCRIPT_COMPLETED"),
+ "{}: Script did not complete successfully.\nTerminal output:\n{}",
+ shell,
+ terminal_output
+ );
+
+ // Verify help content went to the file
+ assert!(
+ file_content.contains("Usage:") || file_content.contains("wt"),
+ "{}: Help content should be in the redirect file.\nFile content:\n{}\nTerminal output:\n{}",
+ shell,
+ file_content,
+ terminal_output
+ );
+
+ // Verify help content did NOT leak to the terminal
+ // We check for specific help markers that shouldn't appear on terminal
+ let help_markers = ["Usage:", "Commands:", "Options:", "USAGE:"];
+ for marker in help_markers {
+ if terminal_output.contains(marker) {
+ panic!(
+ "{}: Help output leaked to terminal (found '{}').\n\
+ This indicates stderr redirection is not working correctly.\n\
+ Terminal output:\n{}\n\
+ File content:\n{}",
+ shell, marker, terminal_output, file_content
+ );
+ }
+ }
+ }
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 8d71f358a..1db0d25a8 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -29,9 +29,17 @@ exit_code: 0
if type -q wt; or test -n "$WORKTRUNK_BIN"
# Capture stdout (shell script), eval in parent shell. stderr streams to terminal.
# WORKTRUNK_BIN can override the binary path (for testing dev builds).
+ #
+ # We use pipeline capture (`| read`) instead of command substitution (`(...)`)
+ # because fish's command substitution runs in its own pipeline where stderr
+ # doesn't inherit caller redirects. With pipeline capture, stderr flows through
+ # normally and respects redirects like `wt --help &>file`.
function wt_exec
test -n "$WORKTRUNK_BIN"; or set -l WORKTRUNK_BIN (type -P wt)
- set -l script (command $WORKTRUNK_BIN $argv | string collect)
+
+ # Pipeline capture: stderr streams through, stdout captured via read
+ # -z (null delimiter) ensures we capture all lines, not just the first
+ command $WORKTRUNK_BIN $argv | string collect --allow-empty | read --local -z script
set -l exit_code $pipestatus[1]
if test -n "$script"
@@ -60,7 +68,7 @@ if type -q wt; or test -n "$WORKTRUNK_BIN"
# --source: use cargo run (builds from source)
if test $use_source = true
- set -l script (cargo run --quiet -- --internal $args | string collect)
+ cargo run --quiet -- --internal $args | string collect --allow-empty | read --local -z script
set -l exit_code $pipestatus[1]
if test -n "$script"
eval $script