Files
worktrunk/templates/bash.sh
Maximilian Roos cd6732e93a fix: preserve native foreground job control (#4400)
Foreground hooks could hang when they changed terminal settings:
Worktrunk created a separate process group without giving it the
terminal, so the kernel stopped the child with SIGTTOU. Foreground
commands now stay in the caller's native job group, consistently for
single and concurrent commands. Terminal access, Ctrl-C and job
suspension follow the shell's native behavior.

### Design

- `signal_forwarder` owns foreground cancellation and child admission.
Native SIGINT/SIGTERM deaths stop later hooks and worktree steps; a
child that catches Ctrl-C keeps its ordinary exit semantics, including
exit code 130. SIGTERM addressed to wt cancels its owned work even when
a child catches it.
- `shell_exec` and concurrent output share that lifecycle. Output drains
stop on cancellation; complete buffered stdin uses an anonymous
temporary file instead of writer threads. Real process pipelines remain
pipes. Buffered stdin therefore requires temporary storage and is
seekable.
- Help and preview pagers use Git's pager selection and the same process
primitives. Interactive pager cancellation propagates silently, and
preview deadlines cover output and child waits.
- Shell wrappers apply directory directives and clean temporary files
while preserving native interrupt behavior. Nushell integration now
requires 0.113 or newer and uses native `finally` cleanup.

Nushell 0.116's `finally` itself can abort a noninteractive script after
Ctrl-C even when the child catches it and exits successfully.
Worktrunk's directory change and cleanup still complete; the same
script-continuation difference reproduces in a minimal Nushell
`try/finally` without Worktrunk.

Bash applies aborted-line cleanup through a writable `PROMPT_COMMAND`.
With a readonly prompt command or `set -a`, it applies ordinary cleanup
while preserving that configuration; Ctrl-C can leave the pending
directory directive unapplied.

The main behavioral coverage uses real children and PTYs: terminal
ownership/settings, raw and caught Ctrl-C, PID-targeted cancellation,
stopped jobs, concurrent output, pagers, and generated shell wrappers.
Module contracts describe ownership and platform differences.

### Validation

The complete project pre-merge gate passes locally, including the
real-shell/PTY suite, Clippy, formatting, locked dependencies, and
documentation checks. The change also received an independent Opus
correctness and simplicity review, with fixes reviewed through
convergence. macOS runtime validation is local; Linux and Windows run in
CI.

Closes #4389. Thanks to @user753 for the reproduction.

> _This was written by Codex on behalf of max-sixty_
2026-10-08 16:31:37 -07:00

120 lines
6.6 KiB
Bash

# worktrunk shell integration for {{ shell_name }}
# 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 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
local args=()
for arg in "$@"; do
if [[ "$arg" == --source ]]; then use_source=true; else args+=("$arg"); fi
done
# Completion mode: call binary directly, no directive files needed.
# This check MUST be here (not in the binary) because clap's completion
# handler runs before argument parsing.
if [[ -n "${COMPLETE:-}" ]]; then
command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}"
return
fi
# Native SIGINT can unwind this body before ordinary cleanup. Capture one
# cleanup function for both the next prompt and a noninteractive shell exit.
local cd_file owner cleanup_body exit_trap owns_exit=false prompt_provider prompt_armed=true
local prompt_value="${PROMPT_COMMAND-}" prompt_present="${PROMPT_COMMAND+x}" prompt_declared=false
local prompt_declaration prompt_flags
if builtin declare -p PROMPT_COMMAND >/dev/null 2>&1; then prompt_declared=true; fi
# Readonly prompts cannot be replaced; allexport would export our callback.
if [[ $- == *a* ]] || ! (PROMPT_COMMAND="$prompt_value") 2>/dev/null; then prompt_armed=false; fi
cd_file="$(mktemp)" || return
owner="_{{ cmd_ident }}_cleanup_${cd_file##*/}"
owner="${owner//[^a-zA-Z0-9_]/_}"
exit_trap="$(builtin trap -p EXIT)"
# trap -p may expose an inherited but inactive EXIT handler in a subshell.
# Reinstalling it would activate the parent's handler there.
if [[ ( $BASH_SUBSHELL -eq 0 || -z "$exit_trap" ) && ( $- != *i* || "$prompt_armed" == true ) ]]; then owns_exit=true; fi
builtin printf -v prompt_provider 'if %s prompt "$?"; then builtin eval %q; else builtin eval %q; fi' "$owner" "$prompt_value" "$prompt_value"
# %q captures the state after the caller's local variables have unwound.
builtin printf -v cleanup_body '
local cd_file=%q owner=%q exit_trap=%q owns_exit=%q
local prompt_value=%q prompt_present=%q prompt_declared=%q prompt_provider=%q
' "$cd_file" "$owner" "$exit_trap" "$owns_exit" "$prompt_value" "$prompt_present" "$prompt_declared" "$prompt_provider"
# `builtin cd` bypasses any user `cd` alias or function (e.g. zoxide's
# `alias cd=__zoxide_z`) that would otherwise be substituted into the
# function body when it's defined. See #2643.
cleanup_body+='
local event=$1 status=$2 cd_status=0
if [[ "$owns_exit" == true ]]; then builtin trap - EXIT; fi
if [[ -s "$cd_file" ]]; then
builtin cd -- "$(<"$cd_file")" || cd_status=$?
fi
command rm -f "$cd_file"
if [[ ${PROMPT_COMMAND-} == "$prompt_provider" ]]; then
if [[ -n "$prompt_present" ]]; then
PROMPT_COMMAND="$prompt_value"
else
local prompt_flags
prompt_flags="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_flags=
prompt_flags=${prompt_flags#declare }
prompt_flags=${prompt_flags%% *}
if [[ "$prompt_declared" == true ]]; then
builtin unset "PROMPT_COMMAND[0]"
else
builtin unset PROMPT_COMMAND
fi
if [[ "$prompt_flags" == *x* ]]; then builtin export PROMPT_COMMAND; fi
fi
fi
if [[ "$owns_exit" == true && -n "$exit_trap" ]]; then builtin eval "$exit_trap"; fi
builtin unset -f "$owner"
if [[ "$event" == normal && $status -eq 0 ]]; then
return "$cd_status"
else
return "$status"
fi
'
builtin eval "$owner() { $cleanup_body }"
if [[ "$prompt_armed" == true ]]; then PROMPT_COMMAND="$prompt_provider"; fi
# Bash 3.2 only reports an exported, unset variable after assignment.
prompt_declaration="$(builtin declare -p PROMPT_COMMAND 2>/dev/null)" || prompt_declaration=
prompt_flags=${prompt_declaration#declare }
prompt_flags=${prompt_flags%% *}
local exit_code=0
local execution=("${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}")
if [[ "$use_source" == true ]]; then execution=(cargo run --bin {{ cmd }} --quiet -- "${args[@]}"); fi
if [[ "$owns_exit" == true ]]; then
local exit_provider="$owner exit \"\$?\""
if [[ -n "$exit_trap" ]]; then
local exit_callback=${exit_trap#trap -- }
exit_callback=${exit_callback% EXIT}
builtin printf -v exit_provider 'if %s exit "$?"; then builtin eval %s; else builtin eval %s; fi' "$owner" "$exit_callback" "$exit_callback"
fi
builtin trap "$exit_provider" EXIT
fi
case "$prompt_armed:$prompt_flags" in
true:*x*) PROMPT_COMMAND="$prompt_value" WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;
*) WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" command "${execution[@]}" || exit_code=$? ;;
esac
if "$owner" normal "$exit_code"; then return 0; else return $?; fi
}
# Lazy completions - generate on first TAB, then delegate to clap's completer
_{{ cmd }}_lazy_complete() {
# Generate completions function once (check if clap's function exists)
if ! declare -F _clap_complete_{{ cmd_ident }} >/dev/null; then
# Use `command` to bypass the shell function and call the binary directly.
# Without this, `{{ cmd }}` would call the shell function which evals
# the completion script internally but doesn't re-emit it.
# WORKTRUNK_COMPLETE_NAME emits the registration under the name bound
# below; clap would otherwise name everything after its own command
# name and the call below would hit an undefined function (#3816).
eval "$(WORKTRUNK_COMPLETE_NAME="{{ cmd }}" COMPLETE=bash command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || return
fi
_clap_complete_{{ cmd_ident }} "$@"
}
complete -o nospace -o bashdefault -F _{{ cmd }}_lazy_complete {{ cmd }}
fi