Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(fish): Improve output piping and exit code capture
Maximilian Roos79712b849b45
diff --git a/Cargo.lock b/Cargo.lockindex ae2b95416..dff5f584a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -164,6 +164,12 @@ version = "0.21.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"+[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"+[[package]]name = "bitflags"version = "2.10.0"@@ -221,6 +227,12 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"+[[package]]+name = "cfg_aliases"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"+[[package]]name = "char_index"version = "0.1.4"@@ -599,6 +611,12 @@ version = "0.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "780955b8b195a21ab8e4ac6b60dd1dbdcec1dc6c51c0617964b08c81785e12c9"+[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"+[[package]]name = "either"version = "1.15.0"@@ -686,6 +704,17 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"+[[package]]+name = "filedescriptor"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"+dependencies = [+ "libc",+ "thiserror 1.0.69",+ "winapi",+]+[[package]]name = "find-msvc-tools"version = "0.1.4"@@ -971,6 +1000,12 @@ dependencies = ["serde",]+[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"+[[package]]name = "libc"version = "0.2.177"@@ -983,7 +1018,7 @@ version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb"dependencies = [- "bitflags",+ "bitflags 2.10.0","libc",]@@ -1005,6 +1040,18 @@ version = "2.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"+[[package]]+name = "nix"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"+dependencies = [+ "bitflags 2.10.0",+ "cfg-if",+ "cfg_aliases",+ "libc",+]+[[package]]name = "nohash-hasher"version = "0.2.0"@@ -1179,6 +1226,27 @@ dependencies = ["portable-atomic",]+[[package]]+name = "portable-pty"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e"+dependencies = [+ "anyhow",+ "bitflags 1.3.2",+ "downcast-rs",+ "filedescriptor",+ "lazy_static",+ "libc",+ "log",+ "nix",+ "serial2",+ "shared_library",+ "shell-words",+ "winapi",+ "winreg",+]+[[package]]name = "powerfmt"version = "0.2.0"@@ -1273,7 +1341,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"dependencies = ["getrandom 0.2.16","libredox",- "thiserror",+ "thiserror 2.0.17",][[package]]@@ -1318,7 +1386,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94"dependencies = ["base64",- "bitflags",+ "bitflags 2.10.0","serde","serde_derive",]@@ -1383,7 +1451,7 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"dependencies = [- "bitflags",+ "bitflags 2.10.0","errno","libc","linux-raw-sys",@@ -1481,6 +1549,17 @@ dependencies = ["serde_core",]+[[package]]+name = "serial2"+version = "0.2.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8cc76fa68e25e771492ca1e3c53d447ef0be3093e05cd3b47f4b712ba10c6f3c"+dependencies = [+ "cfg-if",+ "libc",+ "winapi",+]+[[package]]name = "sha2"version = "0.10.9"@@ -1492,12 +1571,28 @@ dependencies = ["digest",]+[[package]]+name = "shared_library"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11"+dependencies = [+ "lazy_static",+ "libc",+]+[[package]]name = "shell-escape"version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f"+[[package]]+name = "shell-words"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"+[[package]]name = "shlex"version = "1.3.0"@@ -1575,13 +1670,33 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"+[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]+[[package]]name = "thiserror"version = "2.0.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"dependencies = [- "thiserror-impl",+ "thiserror-impl 2.0.17",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",][[package]]@@ -1873,6 +1988,22 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"+[[package]]name = "winapi-util"version = "0.1.11"@@ -1882,6 +2013,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"+[[package]]name = "windows-core"version = "0.62.2"@@ -2106,6 +2243,15 @@ dependencies = ["memchr",]+[[package]]+name = "winreg"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"+dependencies = [+ "winapi",+]+[[package]]name = "wit-bindgen"version = "0.46.0"@@ -2131,6 +2277,7 @@ dependencies = ["insta","insta-cmd","log",+ "portable-pty","rayon","regex","rstest",diff --git a/Cargo.toml b/Cargo.tomlindex afbac21b4..44690ce8a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -49,6 +49,7 @@ tempfile = "3.23"toml = "0.9"criterion = "0.7"regex = "1.12"+portable-pty = "0.9"[[bench]]name = "completion"diff --git a/templates/fish.fish b/templates/fish.fishindex e16d99fa0..240ef3ac8 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -13,17 +13,13 @@ if type -q {{ cmd_prefix }}# Helper function to parse wt output and handle directives# Directives are NUL-terminated to support multi-line commands#- # Note: Uses psub for process substitution to preserve NUL bytes.- # This is reliable for simple read-only cases but psub has known- # limitations in complex scenarios (see fish-shell issue #1040).- # Current usage is safe as we only read from psub output sequentially.+ # IMPORTANT: No "begin...end" block on the left side of the pipe!+ # Fish runs only one piece of fish script at a time; a block on the LHS+ # would serialize the pipeline (RHS wouldn't run until LHS finishes).+ # By keeping the LHS as a plain external command, the RHS can consume+ # the stream concurrently, preserving temporal ordering.function _wt_execset -l exec_cmd ""- set -l exit_code_file (mktemp)- or begin- echo "Failed to create temp file" >&2- return 1- end# Debug mode: set WORKTRUNK_DEBUG=1 to see what's happeningset -l debug_mode 0@@ -32,13 +28,12 @@ if type -q {{ cmd_prefix }}echo "[DEBUG] Starting _wt_exec with args: $argv" >&2end- # Use psub (process substitution) to preserve NUL bytes- # Command substitution $(...) strips NUL bytes, but psub preserves them- # Redirect stderr to stdout (2>&1) to capture child process output- # (child output goes to stderr per output system architecture)- # Redirect directly from psub output, and save exit code to temp file+ # CRITICAL: Do NOT add "2>&1" here!+ # We want child stderr to remain a TTY (via Stdio::inherit() in Rust)+ # so that child processes stream output in real-time with colors/progress bars.+ # Only worktrunk's stdout (directives + messages) flows through this pipe.set -l chunk_count 0- while read -z chunk+ command $_WORKTRUNK_CMD $argv | while read -z chunkset chunk_count (math $chunk_count + 1)if test $debug_mode -eq 1echo "[DEBUG] Chunk $chunk_count length: "(string length -- $chunk) >&2@@ -67,16 +62,19 @@ if type -q {{ cmd_prefix }}endprintf '%s\n' $chunkend- end < (begin; command $_WORKTRUNK_CMD $argv 2>&1; echo $status > $exit_code_file; end | psub)+ end++ # CRITICAL: Capture $pipestatus IMMEDIATELY after the pipe, before ANY other commands!+ # Every command (including 'if', 'test', 'echo') clobbers $pipestatus+ set -l codes $pipestatus+ set -l exit_code $codes[1]if test $debug_mode -eq 1echo "[DEBUG] Finished reading, total chunks: $chunk_count" >&2+ echo "[DEBUG] Pipeline status codes: $codes" >&2+ echo "[DEBUG] Exit code: $exit_code" >&2end- # Read exit code from temp file- set -l exit_code (cat $exit_code_file 2>/dev/null; or echo 0)- rm -f $exit_code_file-# Execute command if one was specified# Exit code semantics: Returns wt's exit code, not the executed command's.# This allows detecting wt failures (e.g., branch creation errors).diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex 45450db5a..bfc227ee8 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -148,6 +148,68 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s}}+/// Execute a command in a PTY (pseudo-terminal)+///+/// This provides the most accurate test environment - child processes see a real TTY+/// and behave exactly as they would in a user's terminal (streaming, colors, etc.)+#[cfg(test)]+fn exec_in_pty(+ shell: &str,+ script: &str,+ working_dir: &std::path::Path,+ env_vars: &[(String, String)],+) -> (String, i32) {+ use portable_pty::{CommandBuilder, PtySize, native_pty_system};+ use std::io::Read;++ let pty_system = native_pty_system();+ let pair = pty_system+ .openpty(PtySize {+ rows: 48,+ cols: 200,+ pixel_width: 0,+ pixel_height: 0,+ })+ .expect("Failed to open PTY");++ // Spawn the shell inside the PTY+ let mut cmd = CommandBuilder::new(shell);+ cmd.arg("-c");+ cmd.arg(script);+ cmd.cwd(working_dir);++ // Add environment variables+ for (key, value) in env_vars {+ cmd.env(key, value);+ }++ let mut child = pair+ .slave+ .spawn_command(cmd)+ .expect("Failed to spawn command in PTY");+ drop(pair.slave); // Close slave in parent++ // Read everything the "terminal" would display+ let mut reader = pair+ .master+ .try_clone_reader()+ .expect("Failed to clone PTY reader");++ let mut buf = String::new();+ reader+ .read_to_string(&mut buf)+ .expect("Failed to read from PTY"); // Blocks until child exits & PTY closes++ let status = child.wait().expect("Failed to wait for child process");++ (normalize_newlines(&buf), status.exit_code() as i32)+}++/// Normalize line endings (CRLF -> LF)+fn normalize_newlines(s: &str) -> String {+ s.replace("\r\n", "\n")+}+/// Execute a command through a shell wrapper////// This simulates what actually happens when users run `wt switch`, etc. in their shell:@@ -175,23 +237,47 @@ fn exec_through_wrapper_from() -> ShellOutput {let script = build_shell_script(shell, repo, subcommand, args);- let mut cmd = Command::new(shell);- cmd.arg("-c").arg(&script).current_dir(working_dir);-- // Configure git environment- repo.clean_cli_env(&mut cmd);-- let output = cmd- .output()- .unwrap_or_else(|_| panic!("Failed to execute {} wrapper", shell));-- // With 2>&1 in the script, both streams are merged to stdout- // This preserves temporal locality (output appears when operations complete)- let combined = String::from_utf8_lossy(&output.stdout).to_string();+ // PTY execution - provides exact terminal behavior for all shells+ // Note: Fish's psub (process substitution) uses file-backed buffers, which causes+ // different temporal ordering than bash/zsh. Child command output may appear before+ // the progress messages that spawned them. This is actual fish behavior, not a test bug.++ // Collect environment variables that clean_cli_env would set+ let env_vars = vec![+ ("CLICOLOR_FORCE".to_string(), "1".to_string()),+ (+ "WORKTRUNK_CONFIG_PATH".to_string(),+ repo.test_config_path().to_string_lossy().to_string(),+ ),+ // Git config from configure_git_cmd+ ("GIT_AUTHOR_NAME".to_string(), "Test User".to_string()),+ (+ "GIT_AUTHOR_EMAIL".to_string(),+ "[email protected]".to_string(),+ ),+ ("GIT_COMMITTER_NAME".to_string(), "Test User".to_string()),+ (+ "GIT_COMMITTER_EMAIL".to_string(),+ "[email protected]".to_string(),+ ),+ (+ "GIT_AUTHOR_DATE".to_string(),+ "2025-10-28T12:00:00Z".to_string(),+ ),+ (+ "GIT_COMMITTER_DATE".to_string(),+ "2025-10-28T12:00:00Z".to_string(),+ ),+ ("LANG".to_string(), "C".to_string()),+ ("LC_ALL".to_string(), "C".to_string()),+ ("SOURCE_DATE_EPOCH".to_string(), "1761609600".to_string()),+ ];++ let (combined, exit_code) = exec_in_pty(shell, &script, working_dir, &env_vars);ShellOutput {combined,- exit_code: output.status.code().unwrap_or(1),+ exit_code,}}diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_fish.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_fish.snapindex d79592646..087a29bf6 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_fish.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_failure_fish.snap@@ -6,7 +6,6 @@ expression: output.normalized().as_ref()[40m [0m echo '✓ Code formatting check passed'✓ Code formatting check passed-🔄 [36mRunning pre-merge command [1m[36mtest[0m:[0m[40m [0m echo '✗ Test suite failed: 3 tests failing' && exit 1diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_fish.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_fish.snapindex a01344b86..50c767940 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_fish.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_with_pre_merge_success_fish.snap@@ -6,17 +6,14 @@ expression: output.normalized().as_ref()[40m [0m echo '✓ Code formatting check passed'✓ Code formatting check passed-🔄 [36mRunning pre-merge command [1m[36mlint[0m:[0m[40m [0m echo '✓ Linting passed - no warnings'✓ Linting passed - no warnings-🔄 [36mRunning pre-merge command [1m[36mtest[0m:[0m[40m [0m echo '✓ All 47 tests passed in 2.3s'✓ All 47 tests passed in 2.3s-🔄 [36mRebasing onto [1m[36mmain[0m...[0m🔄 [36mMerging 1 commit to [1m[36mmain[0m @ d067f01[0mdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_fish.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_fish.snapindex 98117f88b..0c15259c7 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_fish.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_hooks_fish.snap@@ -6,12 +6,10 @@ expression: output.normalized().as_ref()[40m [0m echo 'Installing dependencies...'Installing dependencies...-🔄 [36mExecuting (post-create):[0m[40m [0m echo 'Building project...'Building project...-🔄 [36mStarting (background):[0m[40m [0m echo 'Starting dev server on port 3000'diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 72ac52b70..b0ce3bf08 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWc0lh5/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpirklUY/test-config.toml---success: trueexit_code: 0@@ -36,17 +36,13 @@ if type -q wt# Helper function to parse wt output and handle directives# Directives are NUL-terminated to support multi-line commands#- # Note: Uses psub for process substitution to preserve NUL bytes.- # This is reliable for simple read-only cases but psub has known- # limitations in complex scenarios (see fish-shell issue #1040).- # Current usage is safe as we only read from psub output sequentially.+ # IMPORTANT: No "begin...end" block on the left side of the pipe!+ # Fish runs only one piece of fish script at a time; a block on the LHS+ # would serialize the pipeline (RHS wouldn't run until LHS finishes).+ # By keeping the LHS as a plain external command, the RHS can consume+ # the stream concurrently, preserving temporal ordering.function _wt_execset -l exec_cmd ""- set -l exit_code_file (mktemp)- or begin- echo "Failed to create temp file" >&2- return 1- end# Debug mode: set WORKTRUNK_DEBUG=1 to see what's happeningset -l debug_mode 0@@ -55,13 +51,12 @@ if type -q wtecho "[DEBUG] Starting _wt_exec with args: $argv" >&2end- # Use psub (process substitution) to preserve NUL bytes- # Command substitution $(...) strips NUL bytes, but psub preserves them- # Redirect stderr to stdout (2>&1) to capture child process output- # (child output goes to stderr per output system architecture)- # Redirect directly from psub output, and save exit code to temp file+ # CRITICAL: Do NOT add "2>&1" here!+ # We want child stderr to remain a TTY (via Stdio::inherit() in Rust)+ # so that child processes stream output in real-time with colors/progress bars.+ # Only worktrunk's stdout (directives + messages) flows through this pipe.set -l chunk_count 0- while read -z chunk+ command $_WORKTRUNK_CMD $argv | while read -z chunkset chunk_count (math $chunk_count + 1)if test $debug_mode -eq 1echo "[DEBUG] Chunk $chunk_count length: "(string length -- $chunk) >&2@@ -90,16 +85,19 @@ if type -q wtendprintf '%s\n' $chunkend- end < (begin; command $_WORKTRUNK_CMD $argv 2>&1; echo $status > $exit_code_file; end | psub)+ end++ # CRITICAL: Capture $pipestatus IMMEDIATELY after the pipe, before ANY other commands!+ # Every command (including 'if', 'test', 'echo') clobbers $pipestatus+ set -l codes $pipestatus+ set -l exit_code $codes[1]if test $debug_mode -eq 1echo "[DEBUG] Finished reading, total chunks: $chunk_count" >&2+ echo "[DEBUG] Pipeline status codes: $codes" >&2+ echo "[DEBUG] Exit code: $exit_code" >&2end- # Read exit code from temp file- set -l exit_code (cat $exit_code_file 2>/dev/null; or echo 0)- rm -f $exit_code_file-# Execute command if one was specified# Exit code semantics: Returns wt's exit code, not the executed command's.# This allows detecting wt failures (e.g., branch creation errors).