Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(zsh): Advise on compinit if missing during install
Maximilian Roos0fe75642eddd
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 785b1da1f..1b3da76be 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -2,7 +2,7 @@ use std::fs::{self, OpenOptions};use std::io::{self, BufRead, BufReader, Write};use std::path::{Path, PathBuf};use worktrunk::path::format_path_for_display;-use worktrunk::shell::Shell;+use worktrunk::shell::{self, Shell};use worktrunk::styling::{INFO_EMOJI, PROGRESS_EMOJI, SUCCESS_EMOJI, format_bash_with_gutter};use crate::completion;@@ -146,6 +146,44 @@ pub fn handle_configure_shell(let result = scan_shell_configs(shell_filter, false)?;let completion_results = process_shell_completions(&shells, false)?;+ // Zsh completions require compinit to be enabled. Unlike bash/fish, zsh doesn't+ // enable its completion system by default - users must explicitly call compinit.+ // We detect this and show an advisory hint to help users get completions working.+ //+ // We only show this advisory during `install`, not `init`, because:+ // - `init` outputs a script that gets eval'd - advisory would pollute that+ // - `install` is the user-facing command where hints are appropriate+ //+ // We show the advisory when:+ // - User explicitly runs `install zsh` (they clearly want zsh integration)+ // - User runs `install` (all shells) AND their $SHELL is zsh (they use zsh daily)+ //+ // We skip if:+ // - User runs `install` but their $SHELL is bash/fish (they may be configuring+ // zsh for occasional use; don't nag about their non-primary shell)+ // - Zsh was already configured (AlreadyExists) - they've seen this before+ let zsh_was_configured = result+ .configured+ .iter()+ .any(|r| r.shell == Shell::Zsh && !matches!(r.action, ConfigAction::AlreadyExists));+ let should_check_compinit = zsh_was_configured+ && (shell_filter == Some(Shell::Zsh)+ || (shell_filter.is_none() && shell::is_current_shell_zsh()));++ if should_check_compinit {+ // Probe user's zsh to check if compinit is enabled.+ // Only show advisory if we positively detect it's missing (Some(false)).+ // If detection fails (None), stay silent - we can't be sure.+ if shell::detect_zsh_compinit() == Some(false) {+ use worktrunk::styling::{WARNING, WARNING_EMOJI, eprintln};+ eprintln!(+ "{WARNING_EMOJI} {WARNING}Completions won't work: zsh's compinit is not enabled.{WARNING:#}"+ );+ eprintln!("{WARNING} Add this to ~/.zshrc before the wt line:{WARNING:#}");+ eprintln!("{WARNING} autoload -Uz compinit && compinit{WARNING:#}");+ }+ }+Ok(ScanResult {configured: result.configured,completion_results,diff --git a/src/shell.rs b/src/shell.rsindex 70ff365f4..40a85dc69 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -418,6 +418,76 @@ struct FishTemplate<'a> {// cmd_prefix: &'a str,// }+/// Detect if user's zsh has compinit enabled by probing for the compdef function.+///+/// Zsh's completion system (compinit) must be explicitly enabled - it's not on by default.+/// When compinit runs, it defines the `compdef` function. We probe for this function+/// by spawning an interactive zsh that sources the user's config, then checking if+/// compdef exists.+///+/// This approach matches what other CLI tools (hugo, podman, dvc) recommend: detect+/// the state and advise users, rather than trying to auto-enable compinit.+///+/// Returns:+/// - `Some(true)` if compinit is enabled (compdef function exists)+/// - `Some(false)` if compinit is NOT enabled+/// - `None` if detection failed (zsh not installed, timeout, error)+pub fn detect_zsh_compinit() -> Option<bool> {+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};++ // Probe command: check if compdef function exists (proof compinit ran).+ // We use unique markers (__WT_COMPINIT_*) to avoid false matches from any+ // output the user's zshrc might produce during startup.+ let probe_cmd =+ r#"(( $+functions[compdef] )) && echo __WT_COMPINIT_YES__ || echo __WT_COMPINIT_NO__"#;++ let mut child = Command::new("zsh")+ .arg("-ic")+ .arg(probe_cmd)+ .stdout(Stdio::piped())+ .stderr(Stdio::null()) // Suppress user's zsh startup messages+ .spawn()+ .ok()?;++ let start = Instant::now();+ let timeout = Duration::from_secs(2);++ loop {+ match child.try_wait() {+ Ok(Some(_status)) => {+ // Process finished (exit status is always 0 due to || fallback in probe)+ // wait_with_output() collects remaining stdout even after try_wait() succeeds+ let output = child.wait_with_output().ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Some(stdout.contains("__WT_COMPINIT_YES__"));+ }+ Ok(None) => {+ // Still running - check timeout+ if start.elapsed() > timeout {+ let _ = child.kill();+ let _ = child.wait(); // Reap zombie process+ return None;+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ Err(_) => return None,+ }+ }+}++/// Check if the current shell is zsh (based on $SHELL environment variable).+///+/// Used to determine if the user's primary shell is zsh when running `install`+/// without a specific shell argument. If they're a zsh user, we show compinit+/// hints; if they're using bash/fish, we skip the hint since zsh isn't their+/// daily driver.+pub fn is_current_shell_zsh() -> bool {+ std::env::var("SHELL")+ .map(|s| s.ends_with("/zsh") || s.ends_with("/zsh-"))+ .unwrap_or(false)+}+#[cfg(test)]mod tests {use super::*;diff --git a/templates/zsh.zsh b/templates/zsh.zshindex 1e57e576a..991e6f48a 100644--- a/templates/zsh.zsh+++ b/templates/zsh.zsh@@ -1,4 +1,7 @@# worktrunk shell integration for zsh+#+# Completions require zsh's completion system (compinit). If completions don't work:+# autoload -Uz compinit && compinit # add before this line in your .zshrc# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then@@ -54,7 +57,6 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];}# Lazy completions - generate on first TAB, then delegate to clap's completer- # NOTE: This must come AFTER compinit in your .zshrc_{{ cmd_prefix }}_lazy_complete() {# Generate completions function once (check if clap's function exists)if ! (( $+functions[_clap_dynamic_completer_{{ cmd_prefix }}] )); then@@ -63,11 +65,11 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];_clap_dynamic_completer_{{ cmd_prefix }} "$@"}- # Register completion (requires compinit to have run first)+ # Register completion (silently skip if compinit hasn't run yet).+ # We don't warn here because this script runs on every shell startup - users+ # shouldn't see warnings every time they open a terminal. Instead, `wt config+ # shell install` detects missing compinit and shows a one-time advisory.if (( $+functions[compdef] )); thencompdef _{{ cmd_prefix }}_lazy_complete {{ cmd_prefix }}- else- echo "{{ cmd_prefix }}: completions disabled (compinit not loaded yet)" >&2- echo "{{ cmd_prefix }}: move 'eval \"\$({{ cmd_prefix }} config shell init zsh)\"' after compinit in your .zshrc" >&2fifidiff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rsindex 0f84cc9d5..26f8ffd4e 100644--- a/tests/integration_tests/configure_shell.rs+++ b/tests/integration_tests/configure_shell.rs@@ -37,6 +37,9 @@ fn test_configure_shell_with_yes() {π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----+ π‘ [33mCompletions won't work: zsh's compinit is not enabled.[0m+ [33m Add this to ~/.zshrc before the wt line:[0m+ [33m autoload -Uz compinit && compinit[0m");});@@ -78,6 +81,9 @@ fn test_configure_shell_specific_shell() {π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----+ π‘ [33mCompletions won't work: zsh's compinit is not enabled.[0m+ [33m Add this to ~/.zshrc before the wt line:[0m+ [33m autoload -Uz compinit && compinit[0m");});@@ -298,6 +304,9 @@ fn test_configure_shell_multiple_configs() {π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----+ π‘ [33mCompletions won't work: zsh's compinit is not enabled.[0m+ [33m Add this to ~/.zshrc before the wt line:[0m+ [33m autoload -Uz compinit && compinit[0m");});@@ -357,6 +366,9 @@ fn test_configure_shell_mixed_states() {π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----+ π‘ [33mCompletions won't work: zsh's compinit is not enabled.[0m+ [33m Add this to ~/.zshrc before the wt line:[0m+ [33m autoload -Uz compinit && compinit[0m");});@@ -639,3 +651,87 @@ fn test_install_uninstall_roundtrip() {"PATH export should be preserved");}++/// Test that compinit warning does NOT show when .zshrc has compinit enabled+#[test]+fn test_configure_shell_no_warning_when_compinit_enabled() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create a .zshrc that enables compinit - detection should find it+ let zshrc_path = temp_home.path().join(".zshrc");+ fs::write(+ &zshrc_path,+ "# Existing config\nautoload -Uz compinit && compinit\n",+ )+ .unwrap();++ let settings = setup_home_snapshot_settings(&temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.env("ZDOTDIR", temp_home.path()); // Point zsh to our test home for config+ cmd.arg("config")+ .arg("shell")+ .arg("install")+ .arg("zsh")+ .arg("--force")+ .current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd, @r"+ success: true+ exit_code: 0+ ----- stdout -----+ β Added shell extension & completions for [1mzsh[0m @ [1m~/.zshrc[0m++ β Configured 1 shell+ π‘ [2mRestart shell or run: source ~/.zshrc[0m++ ----- stderr -----+ ");+ });+}++/// Test that compinit warning does NOT show when $SHELL is bash (not a zsh user)+/// Even when installing all shells, we don't warn bash users about zsh compinit+#[test]+fn test_configure_shell_no_warning_for_bash_user() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create config files for both shells (no compinit in zshrc)+ let zshrc_path = temp_home.path().join(".zshrc");+ let bashrc_path = temp_home.path().join(".bashrc");+ fs::write(&zshrc_path, "# Existing zsh config\n").unwrap();+ fs::write(&bashrc_path, "# Existing bash config\n").unwrap();++ let settings = setup_home_snapshot_settings(&temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/bash"); // User's primary shell is bash+ cmd.arg("config")+ .arg("shell")+ .arg("install")+ .arg("--force")+ .current_dir(repo.root_path());++ // Should NOT show compinit warning - user is a bash user, not zsh+ assert_cmd_snapshot!(cmd, @r"+ success: true+ exit_code: 0+ ----- stdout -----+ β Added shell extension & completions for [1mbash[0m @ [1m~/.bashrc[0m+ β Added shell extension & completions for [1mzsh[0m @ [1m~/.zshrc[0m+ π‘ [2mSkipped [1mfish[0m; ~/.config/fish/conf.d not found[0m++ β Configured 2 shells+ π‘ [2mRestart shell or run: source ~/.bashrc[0m++ ----- stderr -----+ ");+ });+}diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 1a3aea6ee..07236e0b3 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -24,6 +24,9 @@ success: trueexit_code: 0----- stdout -----# worktrunk shell integration for zsh+#+# Completions require zsh's completion system (compinit). If completions don't work:+# autoload -Uz compinit && compinit # add before this line in your .zshrc# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then@@ -211,7 +214,6 @@ wt_exec() {}# Lazy completions - generate on first TAB, then delegate to clap's completer- # NOTE: This must come AFTER compinit in your .zshrc_wt_lazy_complete() {# Generate completions function once (check if clap's function exists)if ! (( $+functions[_clap_dynamic_completer_wt] )); then@@ -220,12 +222,12 @@ wt_exec() {_clap_dynamic_completer_wt "$@"}- # Register completion (requires compinit to have run first)+ # Register completion (silently skip if compinit hasn't run yet).+ # We don't warn here because this script runs on every shell startup - users+ # shouldn't see warnings every time they open a terminal. Instead, `wt config+ # shell install` detects missing compinit and shows a one-time advisory.if (( $+functions[compdef] )); thencompdef _wt_lazy_complete wt- else- echo "wt: completions disabled (compinit not loaded yet)" >&2- echo "wt: move 'eval \"\$(wt config shell init zsh)\"' after compinit in your .zshrc" >&2fifi