Skip to content

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

feat: Add native Zsh shell integration

Maximilian Roosbc65b13fa0a8
diff --git a/src/shell.rs b/src/shell.rs
index 6c7ac9e16..fd7fec59b 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -310,13 +310,19 @@ impl ShellInit {
/// Generate shell integration code
pub fn generate(&self, cli_cmd: &clap::Command) -> Result<String, askama::Error> {
match self.shell {
- Shell::Bash | Shell::Zsh | Shell::Oil => {
+ Shell::Bash | Shell::Oil => {
let template = BashTemplate {
shell_name: self.shell.to_string(),
cmd_prefix: &self.cmd_prefix,
};
template.render()
}
+ Shell::Zsh => {
+ let template = ZshTemplate {
+ cmd_prefix: &self.cmd_prefix,
+ };
+ template.render()
+ }
Shell::Fish => {
let dynamic_completions =
generate_fish_dynamic_completions(cli_cmd, &self.cmd_prefix);
@@ -354,7 +360,7 @@ impl ShellInit {
}
}
-/// Bash/Zsh shell template
+/// Bash shell template
#[derive(Template)]
#[template(path = "bash.sh", escape = "none")]
struct BashTemplate<'a> {
@@ -362,6 +368,13 @@ struct BashTemplate<'a> {
cmd_prefix: &'a str,
}
+/// Zsh shell template
+#[derive(Template)]
+#[template(path = "zsh.zsh", escape = "none")]
+struct ZshTemplate<'a> {
+ cmd_prefix: &'a str,
+}
+
/// Fish shell template
#[derive(Template)]
#[template(path = "fish.fish", escape = "none")]
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
new file mode 100644
index 000000000..c09bb5809
--- /dev/null
+++ b/templates/zsh.zsh
@@ -0,0 +1,97 @@
+# worktrunk shell integration for zsh
+
+# Only initialize if wt is available
+if command -v wt >/dev/null 2>&1; then
+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'
+ # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
+ _WORKTRUNK_CMD="${WORKTRUNK_BIN:-wt}"
+
+ # Helper function to parse wt output and handle directives
+ # Directives are NUL-terminated to support multi-line commands
+ _wt_exec() {
+ local exec_cmd="" chunk exit_code
+ local exit_code_file stdout_file
+ exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }
+ stdout_file=$(mktemp) || { /bin/rm -f "$exit_code_file" 2>/dev/null; echo "Failed to create temp file" >&2; return 1; }
+
+ # Run command and capture output to file to avoid process substitution issues
+ # Process substitution in zsh can hang in non-interactive mode
+ # Let stderr pass through to terminal (preserves TTY for color detection)
+ command "$_WORKTRUNK_CMD" "$@" > "$stdout_file"
+ echo "$?" > "$exit_code_file"
+
+ # Parse stdout for directives (NUL-delimited)
+ # The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)
+ while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do
+ if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then
+ # CD directive - extract path and change directory
+ local path="${chunk#__WORKTRUNK_CD__}"
+ \cd "$path"
+ elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then
+ # EXEC directive - extract command (may contain newlines)
+ exec_cmd="${chunk#__WORKTRUNK_EXEC__}"
+ else
+ # Regular output - print it with newline
+ printf '%s\n' "$chunk"
+ fi
+ done < "$stdout_file"
+
+ # Read exit code from temp file
+ exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)
+
+ # Cleanup temp files (use absolute path for --no-rcs compatibility)
+ /bin/rm -f "$exit_code_file" "$stdout_file" 2>/dev/null || true
+
+ # Execute command if one was specified
+ # Security: Command is user-provided from -x flag; eval is intentional.
+ # NUL-termination allows multi-line commands.
+ # Exit code semantics: Returns wt's exit code, not the executed command's.
+ # This allows detecting wt failures (e.g., branch creation errors).
+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.
+ if [[ -n "$exec_cmd" ]]; then
+ if ! eval "$exec_cmd"; then
+ echo "Warning: Command execution failed (exit code $?)" >&2
+ fi
+ fi
+
+ return $exit_code
+ }
+
+ # Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
+ {{ cmd_prefix }}() {
+ local subcommand="$1"
+
+ case "$subcommand" in
+ switch|remove|merge)
+ # Commands that need --internal for directory change support
+ shift
+ _wt_exec --internal "$subcommand" "$@"
+ ;;
+ *)
+ # All other commands pass through directly
+ command "$_WORKTRUNK_CMD" "$@"
+ ;;
+ esac
+ }
+
+ # Dynamic completion function for zsh
+ _{{ cmd_prefix }}_complete() {
+ local -a completions
+ local -a words
+
+ # Get current command line as array
+ words=("${(@)words}")
+
+ # Call wt complete with current command line
+ completions=(${(f)"$(command "$_WORKTRUNK_CMD" complete "${words[@]}" 2>/dev/null)"})
+
+ # Add completions
+ compadd -a completions
+ }
+
+ # Register dynamic completion (only if compdef is available)
+ # In non-interactive shells or test environments, the completion system may not be loaded
+ if (( $+functions[compdef] )); then
+ compdef _{{ cmd_prefix }}_complete {{ cmd_prefix }}
+ fi
+fi
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index bfc227ee8..4130ee5c3 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -174,6 +174,26 @@ fn exec_in_pty(
// Spawn the shell inside the PTY
let mut cmd = CommandBuilder::new(shell);
+
+ // For zsh, isolate from user rc files to prevent TTY access issues
+ // User startup files (~/.zshenv, ~/.zshrc) can touch /dev/tty (e.g., stty, zle,
+ // compinit, GPG_TTY=$(tty)) which causes SIGTTIN/TTOU/TSTP signals when the
+ // process tries to access the controlling terminal.
+ // See: https://zsh.sourceforge.io/Doc/Release/Files.html
+ if shell == "zsh" {
+ // Set ZDOTDIR to /dev/null so ~/.zshenv is not found
+ cmd.env("ZDOTDIR", "/dev/null");
+
+ // Prevent loading any other rc files
+ cmd.arg("--no-rcs");
+ cmd.arg("-o");
+ cmd.arg("NO_GLOBAL_RCS");
+ cmd.arg("-o");
+ cmd.arg("NO_RCS");
+ cmd.arg("-o");
+ cmd.arg("NO_MONITOR");
+ }
+
cmd.arg("-c");
cmd.arg(script);
cmd.cwd(working_dir);
@@ -285,24 +305,20 @@ mod tests {
use super::*;
use rstest::rstest;
- // TODO: Add zsh support
- // Zsh currently uses the bash template (src/shell.rs:313), which includes bash-specific
- // commands like `complete -F` and `COMP_WORDS` that don't exist in zsh.
- // This causes zsh tests to hang waiting for the wrapper to execute.
- // Need to create templates/zsh.zsh with proper zsh syntax:
- // - Use `compdef` instead of `complete` for completions
- // - Use zsh-specific completion system
- // - Fix temp file cleanup (currently tries `\rm` which fails in test environment)
-
// ========================================================================
// Cross-Shell Error Handling Tests
// ========================================================================
//
// These tests use parametrized testing to verify consistent behavior
- // across all supported shells (bash, fish).
+ // across all supported shells (bash, zsh, fish).
+ //
+ // Note: Zsh tests run in isolated mode (--no-rcs, ZDOTDIR=/dev/null) to prevent
+ // user startup files from touching /dev/tty, which would cause SIGTTIN/TTOU/TSTP
+ // signals. This isolation ensures tests are deterministic across all environments.
#[rstest]
#[case("bash")]
+ #[case("zsh")]
#[case("fish")]
fn test_wrapper_handles_command_failure(#[case] shell: &str) {
let mut repo = TestRepo::new();
@@ -337,6 +353,7 @@ mod tests {
#[rstest]
#[case("bash")]
+ #[case("zsh")]
#[case("fish")]
fn test_wrapper_switch_create(#[case] shell: &str) {
let repo = TestRepo::new();
@@ -363,6 +380,7 @@ mod tests {
#[rstest]
#[case("bash")]
+ #[case("zsh")]
#[case("fish")]
fn test_wrapper_remove(#[case] shell: &str) {
let mut repo = TestRepo::new();
@@ -383,6 +401,7 @@ mod tests {
#[rstest]
#[case("bash")]
+ #[case("zsh")]
#[case("fish")]
fn test_wrapper_merge(#[case] shell: &str) {
let mut repo = TestRepo::new();
@@ -403,6 +422,7 @@ mod tests {
#[rstest]
#[case("bash")]
+ #[case("zsh")]
#[case("fish")]
fn test_wrapper_switch_with_execute(#[case] shell: &str) {
let repo = TestRepo::new();
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__command_failure_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__command_failure_zsh.snap
new file mode 100644
index 000000000..ce8b21c1b
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__command_failure_zsh.snap
@@ -0,0 +1,8 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+expression: output.normalized().as_ref()
+---
+zsh:365: command not found: compdef
+❌ Branch existing already exists
+
+πŸ’‘ Remove --create flag to switch to it
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_zsh.snap
new file mode 100644
index 000000000..e96b53264
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__merge_zsh.snap
@@ -0,0 +1,6 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+expression: output.normalized().as_ref()
+---
+zsh:365: command not found: compdef
+βœ… Already on main, nothing to merge
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__remove_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__remove_zsh.snap
new file mode 100644
index 000000000..53e9e9543
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__remove_zsh.snap
@@ -0,0 +1,7 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+expression: output.normalized().as_ref()
+---
+zsh:365: command not found: compdef
+πŸ”„ Removing worktree for to-remove...
+βœ… Removed worktree for to-remove
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_create_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_create_zsh.snap
new file mode 100644
index 000000000..4039cc3a7
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_create_zsh.snap
@@ -0,0 +1,6 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+expression: output.normalized().as_ref()
+---
+zsh:365: command not found: compdef
+βœ… Created new worktree for feature at [TMPDIR]/test-repo.feature
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_execute_zsh.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_execute_zsh.snap
new file mode 100644
index 000000000..aabd3606d
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__switch_with_execute_zsh.snap
@@ -0,0 +1,10 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+expression: output.normalized().as_ref()
+---
+zsh:365: command not found: compdef
+βœ… Created new worktree for test-exec at [TMPDIR]/test-repo.test-exec
+πŸ”„ Executing (--execute):
+  echo executed
+
+executed
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index f1c1fea56..6fe1c7735 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpreSuwI/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpelDWZF/test-config.toml
---
success: true
exit_code: 0
@@ -33,12 +33,17 @@ if command -v wt >/dev/null 2>&1; then
# Directives are NUL-terminated to support multi-line commands
_wt_exec() {
local exec_cmd="" chunk exit_code
- local exit_code_file
+ local exit_code_file stdout_file
exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }
+ stdout_file=$(mktemp) || { /bin/rm -f "$exit_code_file" 2>/dev/null; echo "Failed to create temp file" >&2; return 1; }
- # Parse stdout for directives (NUL-delimited)
+ # Run command and capture output to file to avoid process substitution issues
+ # Process substitution in zsh can hang in non-interactive mode
# Let stderr pass through to terminal (preserves TTY for color detection)
- # Write exit code to temp file since it can't be captured from process substitution
+ command "$_WORKTRUNK_CMD" "$@" > "$stdout_file"
+ echo "$?" > "$exit_code_file"
+
+ # Parse stdout for directives (NUL-delimited)
# The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)
while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do
if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then
@@ -52,13 +57,13 @@ if command -v wt >/dev/null 2>&1; then
# Regular output - print it with newline
printf '%s\n' "$chunk"
fi
- done < <(command "$_WORKTRUNK_CMD" "$@"; echo "$?" > "$exit_code_file")
+ done < "$stdout_file"
# Read exit code from temp file
exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)
- # Cleanup temp file
- \rm -f "$exit_code_file"
+ # Cleanup temp files (use absolute path for --no-rcs compatibility)
+ /bin/rm -f "$exit_code_file" "$stdout_file" 2>/dev/null || true
# Execute command if one was specified
# Security: Command is user-provided from -x flag; eval is intentional.
@@ -77,65 +82,41 @@ if command -v wt >/dev/null 2>&1; then
# Override wt command to add --internal flag for switch, remove, and merge
wt() {
- local use_dev=false
- local args=()
- local saved_cmd="$_WORKTRUNK_CMD"
-
- # Check for --dev flag and strip it
- for arg in "$@"; do
- if [[ "$arg" == "--dev" ]]; then
- use_dev=true
- else
- args+=("$arg")
- fi
- done
-
- # If --dev was specified, build and use local debug binary
- if [[ "$use_dev" == true ]]; then
- if ! cargo build --quiet >/dev/null 2>&1; then
- echo "Error: cargo build failed" >&2
- _WORKTRUNK_CMD="$saved_cmd"
- return 1
- fi
- _WORKTRUNK_CMD="./target/debug/wt"
- fi
-
- # Dispatch based on subcommand
- if [[ ${#args[@]} -gt 0 ]]; then
- local subcommand="${args[0]}"
-
- case "$subcommand" in
- switch|remove|merge)
- # Commands that need --internal for directory change support
- _wt_exec --internal "${args[@]}"
- ;;
- *)
- # All other commands pass through directly
- command "$_WORKTRUNK_CMD" "${args[@]}"
- ;;
- esac
- else
- # No arguments, just run the command
- command "$_WORKTRUNK_CMD"
- fi
+ local subcommand="$1"
- # Restore original command
- local result=$?
- _WORKTRUNK_CMD="$saved_cmd"
- return $result
+ case "$subcommand" in
+ switch|remove|merge)
+ # Commands that need --internal for directory change support
+ shift
+ _wt_exec --internal "$subcommand" "$@"
+ ;;
+ *)
+ # All other commands pass through directly
+ command "$_WORKTRUNK_CMD" "$@"
+ ;;
+ esac
}
- # Dynamic completion function
+ # Dynamic completion function for zsh
_wt_complete() {
- local cur="${COMP_WORDS[COMP_CWORD]}"
+ local -a completions
+ local -a words
+
+ # Get current command line as array
+ words=("${(@)words}")
# Call wt complete with current command line
- local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)
- COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+ completions=(${(f)"$(command "$_WORKTRUNK_CMD" complete "${words[@]}" 2>/dev/null)"})
+
+ # Add completions
+ compadd -a completions
}
- # Register dynamic completion
- complete -F _wt_complete wt
+ # Register dynamic completion (only if compdef is available)
+ # In non-interactive shells or test environments, the completion system may not be loaded
+ if (( $+functions[compdef] )); then
+ compdef _wt_complete wt
+ fi
fi
# Static completions (commands and flags)