Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: Improve shell integration exit code handling and error checking
Maximilian Roos3d36c0127045
diff --git a/templates/elvish.elv b/templates/elvish.elvindex 2059128dc..750edf9d6 100644--- a/templates/elvish.elv+++ b/templates/elvish.elv@@ -11,6 +11,9 @@ if (or (has-external wt) (has-env WORKTRUNK_BIN)) {# Helper function to parse wt output and handle directives# Directives are NUL-terminated to support multi-line commands+ # NOTE: Uses 'slurp' which buffers output. Elvish's I/O model doesn't provide+ # good primitives for byte-level streaming of process output while also capturing+ # it for directive processing. Exit codes are now captured correctly.fn _wt_exec {|@args|var exit-code = 0var output = ""@@ -18,12 +21,18 @@ if (or (has-external wt) (has-env WORKTRUNK_BIN)) {# Capture stdout for directives, let stderr pass through to terminal# This preserves TTY for color detection- # TODO: Capture actual exit code from wt command, not just success/failuretry {set output = (e:$_WORKTRUNK_CMD $@args | slurp)} catch e {+ # Extract exit code, defaulting to 1 if unavailableset exit-code = 1- set output = $e[reason][content]+ if (has-key $e[reason] exit-status) {+ set exit-code = $e[reason][exit-status]+ }+ # Capture any error content+ if (has-key $e[reason] content) {+ set output = $e[reason][content]+ }}# Split output on NUL bytes, process each chunk@@ -32,7 +41,11 @@ if (or (has-external wt) (has-env WORKTRUNK_BIN)) {if (str:has-prefix $chunk "__WORKTRUNK_CD__") {# CD directive - extract path and change directoryvar path = (str:trim-prefix $chunk "__WORKTRUNK_CD__")- cd $path+ if (path:is-dir $path) {+ cd $path+ } else {+ echo "Error: Not a directory: "$path >&2+ }} elif (str:has-prefix $chunk "__WORKTRUNK_EXEC__") {# EXEC directive - extract command (may contain newlines)set exec-cmd = (str:trim-prefix $chunk "__WORKTRUNK_EXEC__")@@ -47,11 +60,15 @@ if (or (has-external wt) (has-env WORKTRUNK_BIN)) {# If wt succeeds but command fails, returns the command's exit code.if (!=s $exec-cmd "") {try {+ # Security: Command comes from wt --internal output; eval is intentionaleval $exec-cmdset exit-code = 0} catch e {- # Command failed - set exit code to 1 (elvish exceptions don't always preserve exit codes)+ # Extract exit code, defaulting to 1 if unavailableset exit-code = 1+ if (has-key $e[reason] exit-status) {+ set exit-code = $e[reason][exit-status]+ }}}diff --git a/templates/nushell.nu b/templates/nushell.nuindex 3e9aaa865..d36034ea4 100644--- a/templates/nushell.nu+++ b/templates/nushell.nu@@ -8,8 +8,14 @@ if (which wt | is-not-empty) or ($env.WORKTRUNK_BIN? | is-not-empty) {# Helper function to parse wt output and handle directives# Directives are NUL-terminated to support multi-line commands+ # NOTE: Uses 'complete' which buffers output. Nushell's streaming model doesn't+ # provide primitives for byte-level reading of process output, so real-time+ # streaming is not currently possible. Exit codes are captured correctly.export def --env _wt_exec [cmd?: string, ...args] {let command = (if ($cmd | is-empty) { $_WORKTRUNK_CMD } else { $cmd })++ # Run command and capture result+ # stderr passes through to terminal for TTY detectionlet result = (do { ^$command ...$args } | complete)mut exec_cmd = ""@@ -18,12 +24,16 @@ if (which wt | is-not-empty) or ($env.WORKTRUNK_BIN? | is-not-empty) {if ($chunk | str starts-with "__WORKTRUNK_CD__") {# CD directive - extract path and change directorylet path = ($chunk | str replace --regex '^__WORKTRUNK_CD__' '')- cd $path+ if ($path | path exists) and ($path | path type) == "dir" {+ cd $path+ } else {+ print $"Error: Not a directory: ($path)" | str trim+ }} else if ($chunk | str starts-with "__WORKTRUNK_EXEC__") {# EXEC directive - extract command (may contain newlines)$exec_cmd = ($chunk | str replace --regex '^__WORKTRUNK_EXEC__' '')} else if ($chunk | str length) > 0 {- # Regular output - print it with newline+ # Regular output - print itprint $chunk}}@@ -32,11 +42,12 @@ if (which wt | is-not-empty) or ($env.WORKTRUNK_BIN? | is-not-empty) {# Exit code semantics: If wt fails, returns wt's exit code (command never executes).# If wt succeeds but command fails, returns the command's exit code.if ($exec_cmd != "") {+ # Security: Command comes from wt --internal output; eval is intentionallet cmd_result = (do { nu -c $exec_cmd } | complete)return $cmd_result.exit_code}- # Return the exit code+ # Return the actual exit code from the commandreturn $result.exit_code}diff --git a/templates/powershell.ps1 b/templates/powershell.ps1index b8a6de670..45e236b42 100644--- a/templates/powershell.ps1+++ b/templates/powershell.ps1@@ -18,31 +18,75 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {# Use provided command or default to _WORKTRUNK_CMD$cmd = if ($Command) { $Command } else { $script:_WORKTRUNK_CMD }- # Capture stdout for directives, let stderr pass through to terminal- # This preserves TTY for color detection- $output = & $cmd @Arguments | Out-String- $exitCode = $LASTEXITCODE+ # Set up process with stdout redirection for real-time streaming+ # stderr passes through to terminal for TTY detection+ $psi = New-Object System.Diagnostics.ProcessStartInfo+ $psi.FileName = $cmd+ $psi.Arguments = ($Arguments | ForEach-Object {+ if ($_ -match '\s') { "`"$_`"" } else { $_ }+ }) -join ' '+ $psi.RedirectStandardOutput = $true+ $psi.RedirectStandardError = $false+ $psi.UseShellExecute = $false++ $process = New-Object System.Diagnostics.Process+ $process.StartInfo = $psi+ $process.Start() | Out-Null++ # Read stdout character by character for real-time processing+ $reader = $process.StandardOutput+ $buffer = New-Object System.Text.StringBuilder$execCmd = ""- # Split output on NUL bytes, process each chunk- foreach ($chunk in ($output -split "`0")) {- if ($chunk -match '^__WORKTRUNK_CD__') {- # CD directive - extract path and change directory- $path = $chunk -replace '^__WORKTRUNK_CD__', ''- Set-Location $path- } elseif ($chunk -match '^__WORKTRUNK_EXEC__') {- # EXEC directive - extract command (may contain newlines)- $execCmd = $chunk -replace '^__WORKTRUNK_EXEC__', ''- } elseif ($chunk) {- # Regular output - write it with newline+ # Read and process output as it arrives+ while (-not $reader.EndOfStream) {+ $charCode = $reader.Read()+ if ($charCode -eq -1) { break } # Explicit EOF check+ $char = [char]$charCode++ if ($char -eq "`0") {+ # NUL byte - process the buffered chunk immediately+ $chunk = $buffer.ToString()++ if ($chunk -match '^__WORKTRUNK_CD__') {+ # CD directive - extract path and change directory+ $path = $chunk -replace '^__WORKTRUNK_CD__', ''+ if (Test-Path -Path $path -PathType Container) {+ Set-Location $path+ } else {+ Write-Error "Error: Not a directory: $path"+ }+ } elseif ($chunk -match '^__WORKTRUNK_EXEC__') {+ # EXEC directive - extract command (may contain newlines)+ $execCmd = $chunk -replace '^__WORKTRUNK_EXEC__', ''+ } elseif ($chunk) {+ # Regular output - write it immediately+ Write-Output $chunk+ }++ $buffer.Clear()+ } else {+ $buffer.Append($char) | Out-Null+ }+ }++ # Process any remaining buffer (shouldn't happen with NUL-terminated protocol)+ if ($buffer.Length -gt 0) {+ $chunk = $buffer.ToString()+ if ($chunk) {Write-Output $chunk}}+ # Wait for process and get actual exit code+ $process.WaitForExit()+ $exitCode = $process.ExitCode+# Execute command if one was specified# Exit code semantics: If wt fails, returns wt's exit code (command never executes).# If wt succeeds but command fails, returns the command's exit code.if ($execCmd) {+ # Security: Command comes from wt --internal output; eval is intentionalInvoke-Expression $execCmd$exitCode = $LASTEXITCODE}diff --git a/templates/xonsh.xsh b/templates/xonsh.xshindex 8c4d122a1..3869a002e 100644--- a/templates/xonsh.xsh+++ b/templates/xonsh.xsh@@ -12,36 +12,72 @@ if shutil.which("wt") is not None or os.environ.get('WORKTRUNK_BIN'):def _wt_exec(args, cmd=None):"""Helper function to parse wt output and handle directivesDirectives are NUL-terminated to support multi-line commands"""+ import subprocess+# Use provided command or default to _WORKTRUNK_CMDcommand = cmd if cmd is not None else _WORKTRUNK_CMD- # Capture full output including return code- result = ![@(command) @(args)]++ # Start process with stdout redirection for real-time streaming+ # stderr passes through to terminal for TTY detection+ proc = subprocess.Popen(+ [command] + args,+ stdout=subprocess.PIPE,+ stderr=None, # Let stderr pass through+ text=True,+ bufsize=0 # Unbuffered for real-time streaming+ )++ # Read stdout character by character for real-time processing+ buffer = ""exec_cmd = ""- # Split output on NUL bytes, process each chunk- if result.out:- for chunk in result.out.split("\0"):- if chunk.startswith("__WORKTRUNK_CD__"):- # CD directive - extract path and change directory- path = chunk.replace("__WORKTRUNK_CD__", "", 1)- cd @(path)- elif chunk.startswith("__WORKTRUNK_EXEC__"):- # EXEC directive - extract command (may contain newlines)- exec_cmd = chunk.replace("__WORKTRUNK_EXEC__", "", 1)- elif chunk:- # Regular output - print it with newline- print(chunk)+ # Read and process output as it arrives+ try:+ while True:+ char = proc.stdout.read(1)+ if not char:+ break++ if char == '\0':+ # NUL byte - process the buffered chunk immediately+ if buffer.startswith("__WORKTRUNK_CD__"):+ # CD directive - extract path and change directory+ path = buffer.replace("__WORKTRUNK_CD__", "", 1)+ if os.path.isdir(path):+ cd @(path)+ else:+ print(f"Error: Not a directory: {path}", file=sys.stderr)+ elif buffer.startswith("__WORKTRUNK_EXEC__"):+ # EXEC directive - extract command (may contain newlines)+ exec_cmd = buffer.replace("__WORKTRUNK_EXEC__", "", 1)+ elif buffer:+ # Regular output - print it immediately+ print(buffer)++ buffer = ""+ else:+ buffer += char+ except IOError as e:+ print(f"Error reading command output: {e}", file=sys.stderr)++ # Process any remaining buffer (shouldn't happen with NUL-terminated protocol)+ if buffer:+ print(buffer)++ # Wait for process and get actual exit code+ exit_code = proc.wait()# Execute command if one was specified# Exit code semantics: If wt fails, returns wt's exit code (command never executes).# If wt succeeds but command fails, returns the command's exit code.if exec_cmd:+ # Security: Command comes from wt --internal output; eval is intentionalexecx(exec_cmd)# execx() sets __xonsh__.env['LASTRETURNCODE'] to the exit codereturn __xonsh__.env.get('LASTRETURNCODE', 0)- # Return the exit code, defaulting to 0 if the subprocess did not set one- return result.returncode if result.returncode is not None else 0+ # Return the actual exit code from the command+ return exit_codedef _{{ cmd_prefix }}_wrapper(args):"""Override {{ cmd_prefix }} command to add --internal flag"""