Skip to content

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

feat: Enhance shell completion management and installation

Maximilian Roos3806b65d9b37
diff --git a/src/cli.rs b/src/cli.rs
index fbf3b523a..9af1b42e8 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -167,10 +167,6 @@ Use `wt config shell install` to automatically add to your shell config."#)]
/// Shell to generate code for
#[arg(value_enum)]
shell: Shell,
-
- /// Command name
- #[arg(long, default_value = DEFAULT_COMMAND_NAME)]
- command_name: String,
},
/// Write shell integration to config files
@@ -198,10 +194,6 @@ wt config shell install --force
/// Skip confirmation prompt
#[arg(short, long)]
force: bool,
-
- /// Command name
- #[arg(long, default_value = DEFAULT_COMMAND_NAME)]
- command_name: String,
},
/// Remove shell integration from config files
@@ -236,6 +228,24 @@ Detects various forms of the integration pattern regardless of:
#[arg(short, long)]
force: bool,
},
+
+ /// Generate shell completion script
+ #[command(after_long_help = r#"## Usage
+
+Generate completions for your shell:
+
+```bash
+wt config shell completions zsh > ~/.zfunc/_wt
+```
+
+This outputs a script that calls back to `wt` for dynamic completions
+(branch names, worktrees, etc.). The script is designed for fpath
+autoloading - zsh loads it only on first completion attempt."#)]
+ Completions {
+ /// Shell to generate completions for
+ #[arg(value_enum)]
+ shell: Shell,
+ },
}
#[derive(Subcommand)]
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index d8467eeab..2c2df4496 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -5,6 +5,8 @@ use worktrunk::path::format_path_for_display;
use worktrunk::shell::Shell;
use worktrunk::styling::{INFO_EMOJI, PROGRESS_EMOJI, SUCCESS_EMOJI, format_bash_with_gutter};
+use crate::completion;
+
pub struct ConfigureResult {
pub shell: Shell,
pub path: PathBuf,
@@ -16,19 +18,32 @@ pub struct UninstallResult {
pub shell: Shell,
pub path: PathBuf,
pub action: UninstallAction,
- pub removed_line: String,
}
pub struct UninstallScanResult {
pub results: Vec<UninstallResult>,
+ pub completion_results: Vec<CompletionUninstallResult>,
pub not_found: Vec<(Shell, PathBuf)>,
}
+pub struct CompletionUninstallResult {
+ pub shell: Shell,
+ pub path: PathBuf,
+ pub action: UninstallAction,
+}
+
pub struct ScanResult {
pub configured: Vec<ConfigureResult>,
+ pub completion_results: Vec<CompletionResult>,
pub skipped: Vec<(Shell, PathBuf)>, // Shell + first path that was checked
}
+pub struct CompletionResult {
+ pub shell: Shell,
+ pub path: PathBuf,
+ pub action: ConfigAction,
+}
+
#[derive(Debug, PartialEq)]
pub enum UninstallAction {
Removed,
@@ -38,8 +53,8 @@ pub enum UninstallAction {
impl UninstallAction {
pub fn description(&self) -> &str {
match self {
- UninstallAction::Removed => "Removed from",
- UninstallAction::WouldRemove => "Will remove from",
+ UninstallAction::Removed => "Removed",
+ UninstallAction::WouldRemove => "Will remove",
}
}
@@ -66,7 +81,7 @@ impl ConfigAction {
ConfigAction::Added => "Added",
ConfigAction::AlreadyExists => "Already configured",
ConfigAction::Created => "Created",
- ConfigAction::WouldAdd => "Will add to",
+ ConfigAction::WouldAdd => "Will add",
ConfigAction::WouldCreate => "Will create",
}
}
@@ -84,41 +99,58 @@ impl ConfigAction {
pub fn handle_configure_shell(
shell_filter: Option<Shell>,
skip_confirmation: bool,
- command_name: String,
) -> Result<ScanResult, String> {
// First, do a dry-run to see what would be changed
- let preview = scan_shell_configs(shell_filter, true, &command_name)?;
+ let preview = scan_shell_configs(shell_filter, true)?;
+
+ // Preview completions that would be written
+ let shells: Vec<_> = preview.configured.iter().map(|r| r.shell).collect();
+ let completion_preview = process_shell_completions(&shells, true)?;
// If nothing to do, return early
if preview.configured.is_empty() {
- return Ok(preview);
+ return Ok(ScanResult {
+ configured: preview.configured,
+ completion_results: completion_preview,
+ skipped: preview.skipped,
+ });
}
// Check if any changes are needed (not all are AlreadyExists)
- let needs_changes = preview
+ let needs_shell_changes = preview
.configured
.iter()
.any(|r| !matches!(r.action, ConfigAction::AlreadyExists));
+ let needs_completion_changes = completion_preview
+ .iter()
+ .any(|r| !matches!(r.action, ConfigAction::AlreadyExists));
// If nothing needs to be changed, just return the preview results
- if !needs_changes {
- return Ok(preview);
+ if !needs_shell_changes && !needs_completion_changes {
+ return Ok(ScanResult {
+ configured: preview.configured,
+ completion_results: completion_preview,
+ skipped: preview.skipped,
+ });
}
// Show what will be done and ask for confirmation (unless --force flag is used)
- if !skip_confirmation && !prompt_for_confirmation(&preview.configured)? {
+ if !skip_confirmation && !prompt_for_confirmation(&preview.configured, &completion_preview)? {
return Err("Cancelled by user".to_string());
}
// User confirmed (or --force flag was used), now actually apply the changes
- scan_shell_configs(shell_filter, false, &command_name)
+ let result = scan_shell_configs(shell_filter, false)?;
+ let completion_results = process_shell_completions(&shells, false)?;
+
+ Ok(ScanResult {
+ configured: result.configured,
+ completion_results,
+ skipped: result.skipped,
+ })
}
-fn scan_shell_configs(
- shell_filter: Option<Shell>,
- dry_run: bool,
- command_name: &str,
-) -> Result<ScanResult, String> {
+fn scan_shell_configs(shell_filter: Option<Shell>, dry_run: bool) -> Result<ScanResult, String> {
let shells = if let Some(shell) = shell_filter {
vec![shell]
} else {
@@ -135,9 +167,7 @@ fn scan_shell_configs(
let mut skipped = Vec::new();
for shell in shells {
- let paths = shell
- .config_paths(command_name)
- .map_err(|e| e.to_string())?;
+ let paths = shell.config_paths().map_err(|e| e.to_string())?;
// Find the first existing config file
let target_path = paths.iter().find(|p| p.exists());
@@ -161,13 +191,7 @@ fn scan_shell_configs(
if should_configure {
let path = target_path.or_else(|| paths.first());
if let Some(path) = path {
- match configure_shell_file(
- shell,
- path,
- dry_run,
- shell_filter.is_some(),
- command_name,
- ) {
+ match configure_shell_file(shell, path, dry_run, shell_filter.is_some()) {
Ok(Some(result)) => results.push(result),
Ok(None) => {} // No action needed
Err(e) => {
@@ -201,6 +225,7 @@ fn scan_shell_configs(
Ok(ScanResult {
configured: results,
+ completion_results: Vec::new(), // Completions handled separately in handle_configure_shell
skipped,
})
}
@@ -210,13 +235,12 @@ fn configure_shell_file(
path: &Path,
dry_run: bool,
explicit_shell: bool,
- command_name: &str,
) -> Result<Option<ConfigureResult>, String> {
// Get a summary of the shell integration for display
- let integration_summary = shell.integration_summary(command_name);
+ let integration_summary = shell.integration_summary();
// The actual line we write to the config file
- let config_content = shell.config_line(command_name);
+ let config_content = shell.config_line();
// For Fish, we write to a separate conf.d/ file
if matches!(shell, Shell::Fish) {
@@ -403,7 +427,10 @@ fn configure_fish_file(
}))
}
-fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String> {
+fn prompt_for_confirmation(
+ results: &[ConfigureResult],
+ completion_results: &[CompletionResult],
+) -> Result<bool, String> {
use anstyle::Style;
use worktrunk::styling::{eprint, eprintln};
@@ -412,20 +439,20 @@ fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String>
// In interactive mode, flushes both stdout and stderr
crate::output::flush_for_stderr_prompt().map_err(|e| e.to_string())?;
- // Interactive prompts go to stderr so they appear even when stdout is redirected
+ let bold = Style::new().bold();
+
+ // Show shell extension changes
for result in results {
// Skip items that are already configured
if matches!(result.action, ConfigAction::AlreadyExists) {
continue;
}
- // Format with bold shell and path
- let bold = Style::new().bold();
let shell = result.shell;
let path = format_path_for_display(&result.path);
eprintln!(
- "{} {} {bold}{shell}{bold:#} {bold}{path}{bold:#}",
+ "{} {} shell extension for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.emoji(),
result.action.description(),
);
@@ -435,6 +462,22 @@ fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String>
eprintln!(); // Blank line after each shell block
}
+ // Show completion changes
+ for result in completion_results {
+ if matches!(result.action, ConfigAction::AlreadyExists) {
+ continue;
+ }
+
+ let shell = result.shell;
+ let path = format_path_for_display(&result.path);
+
+ eprintln!(
+ "{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
+ result.action.emoji(),
+ result.action.description(),
+ );
+ }
+
prompt_yes_no()
}
@@ -459,6 +502,93 @@ fn prompt_yes_no() -> Result<bool, String> {
Ok(response == "y" || response == "yes")
}
+/// Process shell completions - either preview or write based on dry_run flag
+///
+/// Note: Zsh completions are handled via lazy `compdef` in the init script,
+/// so we skip writing static completion files for zsh.
+fn process_shell_completions(
+ shells: &[Shell],
+ dry_run: bool,
+) -> Result<Vec<CompletionResult>, String> {
+ let mut results = Vec::new();
+
+ for &shell in shells {
+ // Skip zsh - completions are handled via lazy compdef in the init script
+ if matches!(shell, Shell::Zsh) {
+ continue;
+ }
+ let completion_path = shell
+ .completion_path()
+ .map_err(|e| format!("Failed to get completion path: {}", e))?;
+
+ // Check if completion already exists with same content
+ let completion_content = generate_completion_content(shell)?;
+
+ if completion_path.exists() {
+ let existing = fs::read_to_string(&completion_path).unwrap_or_default();
+ if existing == completion_content {
+ results.push(CompletionResult {
+ shell,
+ path: completion_path,
+ action: ConfigAction::AlreadyExists,
+ });
+ continue;
+ }
+ }
+
+ // Determine action based on dry_run and whether file exists
+ let action = if dry_run {
+ if completion_path.exists() {
+ ConfigAction::WouldAdd
+ } else {
+ ConfigAction::WouldCreate
+ }
+ } else if completion_path.exists() {
+ ConfigAction::Added
+ } else {
+ ConfigAction::Created
+ };
+
+ if !dry_run {
+ // Create parent directory if needed
+ if let Some(parent) = completion_path.parent() {
+ fs::create_dir_all(parent).map_err(|e| {
+ format!(
+ "Failed to create directory {}: {}",
+ format_path_for_display(parent),
+ e
+ )
+ })?;
+ }
+
+ // Write completion file
+ fs::write(&completion_path, &completion_content).map_err(|e| {
+ format!(
+ "Failed to write {}: {}",
+ format_path_for_display(&completion_path),
+ e
+ )
+ })?;
+ }
+
+ results.push(CompletionResult {
+ shell,
+ path: completion_path,
+ action,
+ });
+ }
+
+ Ok(results)
+}
+
+/// Generate completion script content for a shell
+fn generate_completion_content(shell: Shell) -> Result<String, String> {
+ let mut buf = Vec::new();
+ completion::generate_completions_to_writer(shell, &mut buf)
+ .map_err(|e| format!("Failed to generate completions: {}", e))?;
+ String::from_utf8(buf).map_err(|e| format!("Invalid UTF-8 in completion script: {}", e))
+}
+
// Pattern detection for shell integration
fn has_integration_pattern(content: &str) -> bool {
let lower = content.to_lowercase();
@@ -480,12 +610,14 @@ pub fn handle_unconfigure_shell(
let preview = scan_for_uninstall(shell_filter, true)?;
// If nothing to do, return early
- if preview.results.is_empty() {
+ if preview.results.is_empty() && preview.completion_results.is_empty() {
return Ok(preview);
}
// Show what will be done and ask for confirmation (unless --force flag is used)
- if !skip_confirmation && !prompt_for_uninstall_confirmation(&preview.results)? {
+ if !skip_confirmation
+ && !prompt_for_uninstall_confirmation(&preview.results, &preview.completion_results)?
+ {
return Err("Cancelled by user".to_string());
}
@@ -506,9 +638,9 @@ fn scan_for_uninstall(
let mut results = Vec::new();
let mut not_found = Vec::new();
- for shell in shells {
+ for &shell in &shells {
let paths = shell
- .config_paths("wt")
+ .config_paths()
.map_err(|e| format!("Failed to get config paths for {}: {}", shell, e))?;
// For Fish, check for wt.fish specifically (delete entire file)
@@ -520,7 +652,6 @@ fn scan_for_uninstall(
shell,
path: fish_path.clone(),
action: UninstallAction::WouldRemove,
- removed_line: "wt.fish".to_string(),
});
} else {
fs::remove_file(fish_path).map_err(|e| {
@@ -534,7 +665,6 @@ fn scan_for_uninstall(
shell,
path: fish_path.clone(),
action: UninstallAction::Removed,
- removed_line: "wt.fish".to_string(),
});
}
} else {
@@ -568,7 +698,47 @@ fn scan_for_uninstall(
}
}
- Ok(UninstallScanResult { results, not_found })
+ // Also remove completion files
+ let mut completion_results = Vec::new();
+
+ for &shell in &shells {
+ // Skip zsh - completions are handled via lazy compdef in the init script
+ if matches!(shell, Shell::Zsh) {
+ continue;
+ }
+
+ let completion_path = shell
+ .completion_path()
+ .map_err(|e| format!("Failed to get completion path: {}", e))?;
+ if completion_path.exists() {
+ if dry_run {
+ completion_results.push(CompletionUninstallResult {
+ shell,
+ path: completion_path,
+ action: UninstallAction::WouldRemove,
+ });
+ } else {
+ fs::remove_file(&completion_path).map_err(|e| {
+ format!(
+ "Failed to remove {}: {}",
+ format_path_for_display(&completion_path),
+ e
+ )
+ })?;
+ completion_results.push(CompletionUninstallResult {
+ shell,
+ path: completion_path,
+ action: UninstallAction::Removed,
+ });
+ }
+ }
+ }
+
+ Ok(UninstallScanResult {
+ results,
+ completion_results,
+ not_found,
+ })
}
fn uninstall_from_file(
@@ -591,15 +761,11 @@ fn uninstall_from_file(
return Ok(None);
}
- // Use the first matching line for display
- let removed_line = integration_lines[0].1.trim().to_string();
-
if dry_run {
return Ok(Some(UninstallResult {
shell,
path: path.to_path_buf(),
action: UninstallAction::WouldRemove,
- removed_line,
}));
}
@@ -628,11 +794,13 @@ fn uninstall_from_file(
shell,
path: path.to_path_buf(),
action: UninstallAction::Removed,
- removed_line,
}))
}
-fn prompt_for_uninstall_confirmation(results: &[UninstallResult]) -> Result<bool, String> {
+fn prompt_for_uninstall_confirmation(
+ results: &[UninstallResult],
+ completion_results: &[CompletionUninstallResult],
+) -> Result<bool, String> {
use anstyle::Style;
use worktrunk::styling::eprintln;
@@ -644,7 +812,19 @@ fn prompt_for_uninstall_confirmation(results: &[UninstallResult]) -> Result<bool
let path = format_path_for_display(&result.path);
eprintln!(
- "{} {} {bold}{shell}{bold:#} {bold}{path}{bold:#}",
+ "{} {} shell extension for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
+ result.action.emoji(),
+ result.action.description(),
+ );
+ }
+
+ for result in completion_results {
+ let bold = Style::new().bold();
+ let shell = result.shell;
+ let path = format_path_for_display(&result.path);
+
+ eprintln!(
+ "{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.emoji(),
result.action.description(),
);
diff --git a/src/commands/init.rs b/src/commands/init.rs
index 89f298f38..ff041e5c9 100644
--- a/src/commands/init.rs
+++ b/src/commands/init.rs
@@ -1,8 +1,8 @@
use worktrunk::shell;
use worktrunk::styling::println;
-pub fn handle_init(shell: shell::Shell, command_name: String) -> Result<(), String> {
- let init = shell::ShellInit::new(shell, command_name);
+pub fn handle_init(shell: shell::Shell) -> Result<(), String> {
+ let init = shell::ShellInit::new(shell);
// Generate shell integration code (includes dynamic completion registration)
let integration_output = init
diff --git a/src/completion.rs b/src/completion.rs
index f459a64b7..a6b75ce3d 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -1,13 +1,15 @@
use std::cell::RefCell;
use std::ffi::{OsStr, OsString};
+use std::io;
use clap::Command;
use clap_complete::engine::{ArgValueCompleter, CompletionCandidate, ValueCompleter};
-use clap_complete::env::CompleteEnv;
+use clap_complete::env::{CompleteEnv, EnvCompleter};
use crate::cli;
use crate::display::format_relative_time_short;
use worktrunk::git::{BranchCategory, Repository};
+use worktrunk::shell::Shell;
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
pub fn maybe_handle_env_completion() -> bool {
@@ -27,6 +29,32 @@ pub fn maybe_handle_env_completion() -> bool {
handled
}
+/// Generate completion script for explicit `wt config shell completions <shell>` command
+pub fn generate_completions(shell: Shell) -> io::Result<()> {
+ generate_completions_to_writer(shell, &mut io::stdout())
+}
+
+/// Generate completion script to a writer (for writing to files)
+pub fn generate_completions_to_writer(shell: Shell, writer: &mut dyn io::Write) -> io::Result<()> {
+ let completer = std::env::current_exe()?;
+ let completer = completer.to_string_lossy();
+ let var = "COMPLETE";
+
+ // Use the shell-specific EnvCompleter to write the registration script
+ // Parameters: var, name (shell context), bin (user display - same as name), completer (binary path)
+ match shell {
+ Shell::Bash => {
+ clap_complete::env::Bash.write_registration(var, "wt", "wt", &completer, writer)
+ }
+ Shell::Zsh => {
+ clap_complete::env::Zsh.write_registration(var, "wt", "wt", &completer, writer)
+ }
+ Shell::Fish => {
+ clap_complete::env::Fish.write_registration(var, "wt", "wt", &completer, writer)
+ }
+ }
+}
+
/// Branch completion without additional context filtering (e.g., --base, merge target).
pub fn branch_value_completer() -> ArgValueCompleter {
ArgValueCompleter::new(BranchCompleter {
diff --git a/src/main.rs b/src/main.rs
index db6653f4c..e6461cc14 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -202,21 +202,15 @@ fn main() {
let result = match cli.command {
Commands::Config { action } => match action {
- ConfigCommand::Shell { action } => match action {
- ConfigShellCommand::Init {
- shell,
- command_name,
- } => {
- // Generate shell code to stdout
- handle_init(shell, command_name).map_err(|e| anyhow::anyhow!("{}", e))
- }
- ConfigShellCommand::Install {
- shell,
- force,
- command_name,
- } => {
- // Auto-write to shell config files
- handle_configure_shell(shell, force, command_name)
+ ConfigCommand::Shell { action } => {
+ match action {
+ ConfigShellCommand::Init { shell } => {
+ // Generate shell code to stdout
+ handle_init(shell).map_err(|e| anyhow::anyhow!("{}", e))
+ }
+ ConfigShellCommand::Install { shell, force } => {
+ // Auto-write to shell config files and completions
+ handle_configure_shell(shell, force)
.map_err(|e| anyhow::anyhow!("{}", e))
.and_then(|scan_result| {
use worktrunk::styling::format_bash_with_gutter;
@@ -227,13 +221,13 @@ fn main() {
.filter(|r| !matches!(r.action, ConfigAction::AlreadyExists))
.count();
- // Show configured shells
+ // Show configured shells grouped with their completions
+ let bold = Style::new().bold();
for result in &scan_result.configured {
- let bold = Style::new().bold();
let shell = result.shell;
let path = format_path_for_display(&result.path);
let message = format!(
- "{} {bold}{shell}{bold:#} {path}",
+ "{} shell extension for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.description()
);
@@ -250,20 +244,55 @@ fn main() {
}
}
- // Show config line only for new additions
- if changes_count > 0 {
+ // Show config line in preview (so user sees what will be added)
+ if matches!(
+ result.action,
+ ConfigAction::WouldAdd | ConfigAction::WouldCreate
+ ) {
crate::output::gutter(format_bash_with_gutter(
&result.config_line,
"",
))?;
- crate::output::blank()?;
+ }
+
+ // Show completion result for this shell
+ // TODO: Inconsistent that shell extensions show gutter but completions don't.
+ // Completions are dynamic stubs (~30 lines) that call back to `wt` - not
+ // as meaningful to show, but the asymmetry is confusing.
+ if let Some(comp_result) = scan_result.completion_results.iter().find(|r| r.shell == shell) {
+ let comp_path = format_path_for_display(&comp_result.path);
+ let comp_message = format!(
+ "{} completions for {bold}{shell}{bold:#} @ {bold}{comp_path}{bold:#}",
+ comp_result.action.description()
+ );
+ match comp_result.action {
+ ConfigAction::Added | ConfigAction::Created => {
+ crate::output::success(comp_message)?;
+ }
+ ConfigAction::AlreadyExists => {
+ crate::output::info(comp_message)?;
+ }
+ ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
+ crate::output::progress(comp_message)?;
+ }
+ }
+ } else if matches!(shell, worktrunk::shell::Shell::Zsh)
+ && !matches!(result.action, ConfigAction::AlreadyExists)
+ {
+ // Zsh completions are handled via lazy compdef in the init script
+ // Only show this message for new installations
+ crate::output::info(format!(
+ "Completions for {bold}zsh{bold:#} via lazy compdef (no file needed)"
+ ))?;
}
}
// Show skipped shells
for (shell, path) in &scan_result.skipped {
let path = format_path_for_display(path);
- crate::output::hint(format!("{shell} {path} (not found)"))?;
+ crate::output::hint(format!(
+ "Skipped {bold}{shell}{bold:#}; {path} not found"
+ ))?;
}
// Exit with error if no shells configured
@@ -271,15 +300,26 @@ fn main() {
return Err(anyhow::anyhow!("No shell config files found"));
}
+ // Count total changes (config + completions)
+ let completion_changes = scan_result.completion_results
+ .iter()
+ .filter(|r| !matches!(r.action, ConfigAction::AlreadyExists))
+ .count();
+ let total_changes = changes_count + completion_changes;
+
// Summary
- if changes_count > 0 {
- let plural = if changes_count == 1 { "" } else { "s" };
+ if total_changes > 0 {
+ crate::output::blank()?;
+ let plural = if total_changes == 1 { "" } else { "s" };
crate::output::success(format!(
- "Configured {changes_count} shell{plural}"
+ "Configured {total_changes} shell{plural}"
))?;
- crate::output::blank()?;
+ } else {
+ crate::output::success("All shells already configured")?;
+ }
- // Find the config file for the current shell
+ // Restart hint for current shell (only if config files changed, not just completions)
+ if changes_count > 0 {
let current_shell = std::env::var("SHELL")
.ok()
.and_then(|s| s.rsplit('/').next().map(String::from));
@@ -303,80 +343,114 @@ fn main() {
"Restart shell or run: source {path}"
))?;
}
- } else {
- crate::output::success("All shells already configured")?;
}
Ok(())
})
- }
- ConfigShellCommand::Uninstall { shell, force } => {
- let explicit_shell = shell.is_some();
- handle_unconfigure_shell(shell, force)
- .map_err(|e| anyhow::anyhow!("{}", e))
- .and_then(|scan_result| {
- use worktrunk::styling::format_bash_with_gutter;
+ }
+ ConfigShellCommand::Uninstall { shell, force } => {
+ let explicit_shell = shell.is_some();
+ handle_unconfigure_shell(shell, force)
+ .map_err(|e| anyhow::anyhow!("{}", e))
+ .and_then(|scan_result| {
+ let shell_count = scan_result.results.len();
+ let completion_count = scan_result.completion_results.len();
+ let total_changes = shell_count + completion_count;
+
+ // Show shell extension results
+ for result in &scan_result.results {
+ let bold = Style::new().bold();
+ let shell = result.shell;
+ let path = format_path_for_display(&result.path);
+
+ crate::output::success(format!(
+ "{} shell extension for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
+ result.action.description(),
+ ))?;
+ }
- let changes_count = scan_result.results.len();
+ // Show completion results
+ for result in &scan_result.completion_results {
+ let bold = Style::new().bold();
+ let shell = result.shell;
+ let path = format_path_for_display(&result.path);
- // Show results
- for result in &scan_result.results {
+ crate::output::success(format!(
+ "{} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
+ result.action.description(),
+ ))?;
+ }
+
+ // Show zsh lazy compdef message if zsh shell extension was removed
+ // but no completion file was removed (because zsh uses lazy compdef)
let bold = Style::new().bold();
- let shell = result.shell;
- let path = format_path_for_display(&result.path);
+ let zsh_shell_removed = scan_result.results.iter().any(|r| {
+ matches!(r.shell, worktrunk::shell::Shell::Zsh)
+ });
+ let zsh_completion_removed = scan_result.completion_results.iter().any(|r| {
+ matches!(r.shell, worktrunk::shell::Shell::Zsh)
+ });
+ if zsh_shell_removed && !zsh_completion_removed {
+ crate::output::info(format!(
+ "Completions for {bold}zsh{bold:#} were via lazy compdef (no file to remove)"
+ ))?;
+ }
+
+ // Show not found - warning if explicit shell, hint if auto-scan
+ for (shell, path) in &scan_result.not_found {
+ let path = format_path_for_display(path);
+ if explicit_shell {
+ crate::output::warning(format!(
+ "No shell integration found in {path}"
+ ))?;
+ } else {
+ crate::output::hint(format!(
+ "No {shell} integration in {path}"
+ ))?;
+ }
+ }
+
+ // Exit with info if nothing was found
+ if total_changes == 0 {
+ if scan_result.not_found.is_empty() {
+ crate::output::blank()?;
+ crate::output::hint(
+ "No shell integration found to remove",
+ )?;
+ }
+ return Ok(());
+ }
+ // Summary
+ crate::output::blank()?;
+ let plural = if shell_count == 1 { "" } else { "s" };
crate::output::success(format!(
- "{} {bold}{shell}{bold:#} {path}",
- result.action.description(),
+ "Removed integration from {shell_count} shell{plural}"
))?;
- crate::output::gutter(format_bash_with_gutter(
- &result.removed_line,
- "",
- ))?;
- }
- // Show not found - warning if explicit shell, hint if auto-scan
- for (shell, path) in &scan_result.not_found {
- let path = format_path_for_display(path);
- if explicit_shell {
- crate::output::warning(format!(
- "No shell integration found in {path}"
- ))?;
- } else {
- crate::output::hint(format!(
- "No {shell} integration in {path}"
- ))?;
- }
- }
+ // Hint about restarting shell (only if current shell was affected)
+ let current_shell = std::env::var("SHELL")
+ .ok()
+ .and_then(|s| s.rsplit('/').next().map(String::from));
- // Exit with info if nothing was found
- if changes_count == 0 {
- if scan_result.not_found.is_empty() {
- crate::output::blank()?;
- crate::output::hint("No shell integration found to remove")?;
- }
- return Ok(());
- }
+ let current_shell_affected = current_shell.as_ref().is_some_and(|shell_name| {
+ scan_result.results.iter().any(|r| {
+ r.shell.to_string().eq_ignore_ascii_case(shell_name)
+ })
+ });
- // Summary
- crate::output::blank()?;
- let plural = if changes_count == 1 { "" } else { "s" };
- crate::output::success(format!(
- "Removed shell integration from {changes_count} shell{plural}"
- ))?;
- crate::output::blank()?;
-
- // Hint about restarting shell
- let current_shell = std::env::var("SHELL")
- .ok()
- .and_then(|s| s.rsplit('/').next().map(String::from));
-
- if current_shell.is_some() {
- crate::output::hint("Restart shell to complete uninstall")?;
- }
- Ok(())
- })
+ if current_shell_affected {
+ crate::output::hint("Restart shell to complete uninstall")?;
+ }
+ Ok(())
+ })
+ }
+ ConfigShellCommand::Completions { shell } => {
+ // Generate completion script to stdout
+ completion::generate_completions(shell)
+ .map_err(|e| anyhow::anyhow!("Failed to generate completions: {}", e))
+ }
}
- },
+ }
ConfigCommand::Create => handle_config_create(),
ConfigCommand::List => handle_config_list(),
ConfigCommand::RefreshCache => handle_config_refresh_cache(),
diff --git a/src/shell.rs b/src/shell.rs
index 71886972b..1ce329b2d 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -1,4 +1,5 @@
use askama::Template;
+use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use std::path::PathBuf;
/// Get the user's home directory or return an error
@@ -14,7 +15,7 @@ fn home_dir() -> Result<PathBuf, std::io::Error> {
/// Supported shells
///
/// Currently supported: bash, fish, zsh
-#[derive(Debug, Clone, Copy, clap::ValueEnum, strum::Display, strum::EnumString)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display, strum::EnumString)]
#[strum(serialize_all = "lowercase", ascii_case_insensitive)]
pub enum Shell {
Bash,
@@ -43,8 +44,7 @@ impl Shell {
/// Returns the standard config file paths for this shell
///
/// Returns paths in order of preference. The first existing file should be used.
- /// For Fish, the cmd_prefix is used to name the conf.d file.
- pub fn config_paths(&self, cmd_prefix: &str) -> Result<Vec<PathBuf>, std::io::Error> {
+ pub fn config_paths(&self) -> Result<Vec<PathBuf>, std::io::Error> {
let home = home_dir()?;
Ok(match self {
@@ -60,12 +60,11 @@ impl Shell {
}
Self::Fish => {
// For fish, we write to conf.d/ which is auto-sourced
- // Use cmd_prefix in the filename
vec![
home.join(".config")
.join("fish")
.join("conf.d")
- .join(format!("{}.fish", cmd_prefix)),
+ .join("wt.fish"),
]
} // Disabled shells - uncomment when ready to support
// Self::Nushell => {
@@ -102,21 +101,57 @@ impl Shell {
})
}
+ /// Returns the path to the native completion directory for this shell
+ ///
+ /// These are the standard locations where shells look for lazy-loaded completions:
+ /// - Bash: `~/.local/share/bash-completion/completions/`
+ /// - Zsh: `~/.zfunc/` (for manual setup only; install uses lazy compdef)
+ /// - Fish: `~/.config/fish/completions/`
+ pub fn completion_path(&self) -> Result<PathBuf, std::io::Error> {
+ let home = home_dir()?;
+
+ // Use etcetera for XDG-compliant paths when available
+ let strategy = choose_base_strategy().ok();
+
+ Ok(match self {
+ Self::Bash => {
+ // XDG_DATA_HOME defaults to ~/.local/share
+ let data_home = strategy
+ .as_ref()
+ .map(|s| s.data_dir())
+ .unwrap_or_else(|| home.join(".local").join("share"));
+ data_home
+ .join("bash-completion")
+ .join("completions")
+ .join("wt")
+ }
+ Self::Zsh => home.join(".zfunc").join("_wt"),
+ Self::Fish => {
+ // XDG_CONFIG_HOME defaults to ~/.config
+ let config_home = strategy
+ .as_ref()
+ .map(|s| s.config_dir())
+ .unwrap_or_else(|| home.join(".config"));
+ config_home.join("fish").join("completions").join("wt.fish")
+ }
+ })
+ }
+
/// Returns the line to add to the config file for shell integration
///
/// All shells use a conditional wrapper to avoid errors when the command doesn't exist.
- pub fn config_line(&self, cmd_prefix: &str) -> String {
+ pub fn config_line(&self) -> String {
match self {
Self::Bash | Self::Zsh => {
format!(
- "if command -v {} >/dev/null 2>&1; then eval \"$(command {} config shell init {})\"; fi",
- cmd_prefix, cmd_prefix, self
+ "if command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init {})\"; fi",
+ self
)
}
Self::Fish => {
format!(
- "if type -q {}; command {} config shell init {} | source; end",
- cmd_prefix, cmd_prefix, self
+ "if type -q wt; command wt config shell init {} | source; end",
+ self
)
} // Disabled shells - uncomment when ready to support
// Self::Oil => {
@@ -237,52 +272,43 @@ impl Shell {
/// Returns a summary of what the shell integration does for display in confirmation
///
/// This just returns the same as config_line since we want to show the exact wrapper
- pub fn integration_summary(&self, cmd_prefix: &str) -> String {
- self.config_line(cmd_prefix)
+ pub fn integration_summary(&self) -> String {
+ self.config_line()
}
}
/// Shell integration configuration
pub struct ShellInit {
pub shell: Shell,
- pub cmd_prefix: String,
}
impl ShellInit {
- pub fn new(shell: Shell, cmd_prefix: String) -> Self {
- Self { shell, cmd_prefix }
+ pub fn new(shell: Shell) -> Self {
+ Self { shell }
}
/// Generate shell integration code
pub fn generate(&self) -> Result<String, askama::Error> {
match self.shell {
Shell::Bash => {
- let posix_shim = PosixDirectivesTemplate {
- cmd_prefix: &self.cmd_prefix,
- }
- .render()?;
+ let posix_shim = PosixDirectivesTemplate { cmd_prefix: "wt" }.render()?;
let template = BashTemplate {
shell_name: self.shell.to_string(),
- cmd_prefix: &self.cmd_prefix,
+ cmd_prefix: "wt",
posix_shim: &posix_shim,
};
template.render()
}
Shell::Zsh => {
- let posix_shim = PosixDirectivesTemplate {
- cmd_prefix: &self.cmd_prefix,
- }
- .render()?;
+ let posix_shim = PosixDirectivesTemplate { cmd_prefix: "wt" }.render()?;
let template = ZshTemplate {
- cmd_prefix: &self.cmd_prefix,
+ cmd_prefix: "wt",
posix_shim: &posix_shim,
};
template.render()
}
Shell::Fish => {
- let template = FishTemplate {
- cmd_prefix: &self.cmd_prefix,
- };
+ let template = FishTemplate { cmd_prefix: "wt" };
template.render()
} // Disabled shells - uncomment when ready to support
// Shell::Oil => {
diff --git a/templates/bash.sh b/templates/bash.sh
index 9fca97087..63cfe3871 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -53,30 +53,6 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
return $result
}
- # Lazy completion loader - loads real completions on first tab-press
- # This avoids ~11ms binary invocation at shell startup
- _wt_lazy_complete() {
- # Only try to install completions once
- if [[ -z "${_WT_COMPLETION_LOADED:-}" ]]; then
- _WT_COMPLETION_LOADED=1
- if completion_script=$(COMPLETE=bash "${_WORKTRUNK_CMD:-{{ cmd_prefix }}}" 2>/dev/null); then
- eval "$completion_script"
- else
- # Failed to load - remove completion registration
- complete -r {{ cmd_prefix }} 2>/dev/null || true
- return 1
- fi
- fi
-
- # Delegate to real completion function if it was installed
- if declare -F _clap_complete_{{ cmd_prefix }} >/dev/null 2>&1; then
- _clap_complete_{{ cmd_prefix }}
- fi
- }
- # nosort requires Bash 4.4+ (macOS ships with 3.2)
- if [[ ${BASH_VERSINFO[0]} -gt 4 || (${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -ge 4) ]]; then
- complete -o nospace -o bashdefault -o nosort -F _wt_lazy_complete {{ cmd_prefix }}
- else
- complete -o nospace -o bashdefault -F _wt_lazy_complete {{ cmd_prefix }}
- fi
+ # Completions are loaded from ~/.local/share/bash-completion/completions/wt
+ # Install with: wt config shell install
fi
diff --git a/templates/fish.fish b/templates/fish.fish
index 13e99e4fd..348b25419 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -127,9 +127,6 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN
return $result
end
- # Register Clap-based completions (auto-updates after wt upgrades)
- set -l _wt_completion_script (COMPLETE=fish $_WORKTRUNK_CMD 2>/dev/null | string collect)
- if test -n "$_wt_completion_script"
- eval $_wt_completion_script
- end
+ # Completions are loaded from ~/.config/fish/completions/wt.fish
+ # Install with: wt config shell install
end
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
index decb5e0a3..6cb68e27a 100644
--- a/templates/zsh.zsh
+++ b/templates/zsh.zsh
@@ -53,43 +53,24 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
return $result
}
- # Lazy completion loader - loads real completions on first tab-press
- # This avoids ~11ms binary invocation at shell startup
- _wt_lazy_complete() {
- # Only try to install completions once
- if [[ -z "${_WT_COMPLETION_LOADED:-}" ]]; then
- typeset -g _WT_COMPLETION_LOADED=1
- local completion_script
- if completion_script=$(COMPLETE=zsh "${_WORKTRUNK_CMD:-{{ cmd_prefix }}}" 2>/dev/null); then
- eval "$completion_script"
- else
- # Failed to load - unregister to prevent future silent failures
- compdef -d {{ cmd_prefix }} 2>/dev/null
- return 1
- fi
- fi
+ # Lazy completions via compdef - no fpath setup needed
+ # Regenerates on first TAB in each shell session
+ if (( $+functions[compdef] )); then
+ _{{ cmd_prefix }}_lazy_complete() {
+ # Load dynamic completion script once
+ unfunction _{{ cmd_prefix }}_lazy_complete 2>/dev/null || true
- # Delegate to real completion function if it was installed
- if (( $+functions[_clap_dynamic_completer_{{ cmd_prefix }}] )); then
- _clap_dynamic_completer_{{ cmd_prefix }}
- fi
- }
+ # Generate & eval the real completer from the binary
+ local _script
+ _script="$(COMPLETE=zsh "$_WORKTRUNK_CMD" 2>/dev/null)" || return
+ eval "$_script"
- # Register completion - either now or deferred until compinit runs
- _wt_register_completion() {
- if (( $+functions[compdef] )); then
- compdef _wt_lazy_complete {{ cmd_prefix }}
- # Remove hook once registered
- precmd_functions=(${precmd_functions:#_wt_register_completion})
- unfunction _wt_register_completion 2>/dev/null
- return 0
- fi
- return 1
- }
+ # Delegate to clap's generated function
+ if (( $+functions[_clap_dynamic_completer_{{ cmd_prefix }}] )); then
+ _clap_dynamic_completer_{{ cmd_prefix }} "$@"
+ fi
+ }
- # Try immediate registration, otherwise defer via precmd hook
- if ! _wt_register_completion; then
- # Add to hook only if not already present (handles re-sourcing .zshrc)
- (( ${precmd_functions[(I)_wt_register_completion]} )) || precmd_functions+=(_wt_register_completion)
+ compdef _{{ cmd_prefix }}_lazy_complete {{ cmd_prefix }}
fi
fi
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 742adc34a..c16bf3b57 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -294,8 +294,8 @@ fn test_complete_list_command() {
}
#[test]
-fn test_init_fish_includes_no_file_flag() {
- // Test that fish init wires Clap-based completions into the template
+fn test_init_fish_references_completion_location() {
+ // Test that fish init references the completion file location
let mut cmd = wt_command();
let output = cmd
.arg("config")
@@ -308,14 +308,14 @@ fn test_init_fish_includes_no_file_flag() {
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
- // Ensure we embed the COMPLETE=fish registration snippet
+ // Verify completions are loaded from native fish completions directory
assert!(
- stdout.contains("COMPLETE=fish $_WORKTRUNK_CMD"),
- "Fish template should call wt with COMPLETE=fish"
+ stdout.contains("~/.config/fish/completions/wt.fish"),
+ "Fish template should reference native completion location"
);
assert!(
- stdout.contains("eval $_wt_completion_script"),
- "Fish template should eval the Clap completion script"
+ stdout.contains("wt config shell install"),
+ "Fish template should mention install command"
);
}
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
index 68a581525..1be03f2ab 100644
--- a/tests/integration_tests/configure_shell.rs
+++ b/tests/integration_tests/configure_shell.rs
@@ -25,21 +25,20 @@ fn test_configure_shell_with_yes() {
.arg("--force")
.current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd, @r#"
+ assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
----- stdout -----
- ✅ Added zsh ~/.zshrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
+ ✅ Added shell extension for zsh @ ~/.zshrc
+ ⚪ Completions for zsh via lazy compdef (no file needed)
+ 💡 Skipped bash; ~/.bashrc not found
+ 💡 Skipped fish; ~/.config/fish/conf.d not found
- 💡 bash ~/.bashrc (not found)
- 💡 fish ~/.config/fish/conf.d (not found)
✅ Configured 1 shell
-
💡 Restart shell or run: source ~/.zshrc
----- stderr -----
- "#);
+ ");
});
// Verify the file was modified
@@ -70,19 +69,18 @@ fn test_configure_shell_specific_shell() {
.arg("--force")
.current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd, @r#"
+ assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
----- stdout -----
- ✅ Added zsh ~/.zshrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
+ ✅ Added shell extension for zsh @ ~/.zshrc
+ ⚪ Completions for zsh via lazy compdef (no file needed)
✅ Configured 1 shell
-
💡 Restart shell or run: source ~/.zshrc
----- stderr -----
- "#);
+ ");
});
// Verify the file was modified
@@ -121,7 +119,7 @@ fn test_configure_shell_already_exists() {
success: true
exit_code: 0
----- stdout -----
- ⚪ Already configured zsh ~/.zshrc
+ ⚪ Already configured shell extension for zsh @ ~/.zshrc
✅ All shells already configured
----- stderr -----
@@ -157,11 +155,10 @@ fn test_configure_shell_fish() {
success: true
exit_code: 0
----- stdout -----
- ✅ Created fish ~/.config/fish/conf.d/wt.fish
-   if type -q wt; command wt config shell init fish | source; end
-
- ✅ Configured 1 shell
+ ✅ Created shell extension for fish @ ~/.config/fish/conf.d/wt.fish
+ ✅ Created completions for fish @ ~/.config/fish/completions/wt.fish
+ ✅ Configured 2 shells
💡 Restart shell or run: source ~/.config/fish/conf.d/wt.fish
----- stderr -----
@@ -202,9 +199,9 @@ fn test_configure_shell_no_files() {
success: false
exit_code: 1
----- stdout -----
- 💡 bash ~/.bashrc (not found)
- 💡 zsh ~/.zshrc (not found)
- 💡 fish ~/.config/fish/conf.d (not found)
+ 💡 Skipped bash; ~/.bashrc not found
+ 💡 Skipped zsh; ~/.zshrc not found
+ 💡 Skipped fish; ~/.config/fish/conf.d not found
❌ No shell config files found
----- stderr -----
@@ -236,23 +233,21 @@ fn test_configure_shell_multiple_configs() {
.arg("--force")
.current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd, @r#"
+ assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
----- stdout -----
- ✅ Added bash ~/.bashrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init bash)"; fi
-
- ✅ Added zsh ~/.zshrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
-
- 💡 fish ~/.config/fish/conf.d (not found)
- ✅ Configured 2 shells
+ ✅ Added shell extension for bash @ ~/.bashrc
+ ✅ Created completions for bash @ ~/.local/share/bash-completion/completions/wt
+ ✅ Added shell extension for zsh @ ~/.zshrc
+ ⚪ Completions for zsh via lazy compdef (no file needed)
+ 💡 Skipped fish; ~/.config/fish/conf.d not found
+ ✅ Configured 3 shells
💡 Restart shell or run: source ~/.zshrc
----- stderr -----
- "#);
+ ");
});
// Verify both files were modified
@@ -299,23 +294,21 @@ fn test_configure_shell_mixed_states() {
.arg("--force")
.current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd, @r#"
+ assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
----- stdout -----
- ⚪ Already configured bash ~/.bashrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init bash)"; fi
-
- ✅ Added zsh ~/.zshrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
-
- 💡 fish ~/.config/fish/conf.d (not found)
- ✅ Configured 1 shell
+ ⚪ Already configured shell extension for bash @ ~/.bashrc
+ ✅ Created completions for bash @ ~/.local/share/bash-completion/completions/wt
+ ✅ Added shell extension for zsh @ ~/.zshrc
+ ⚪ Completions for zsh via lazy compdef (no file needed)
+ 💡 Skipped fish; ~/.config/fish/conf.d not found
+ ✅ Configured 2 shells
💡 Restart shell or run: source ~/.zshrc
----- stderr -----
- "#);
+ ");
});
// Verify bash was not modified (already configured)
@@ -360,21 +353,20 @@ fn test_uninstall_shell() {
.arg("--force")
.current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd, @r#"
+ assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
----- stdout -----
- ✅ Removed from zsh ~/.zshrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
+ ✅ Removed shell extension for zsh @ ~/.zshrc
+ ⚪ Completions for zsh were via lazy compdef (no file to remove)
💡 No bash integration in ~/.bashrc
💡 No fish integration in ~/.config/fish/conf.d/wt.fish
- ✅ Removed shell integration from 1 shell
-
+ ✅ Removed integration from 1 shell
💡 Restart shell to complete uninstall
----- stderr -----
- "#);
+ ");
});
// Verify the file no longer contains the integration
@@ -421,22 +413,20 @@ fn test_uninstall_shell_multiple() {
.arg("--force")
.current_dir(repo.root_path());
- assert_cmd_snapshot!(cmd, @r#"
+ assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
----- stdout -----
- ✅ Removed from bash ~/.bashrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init bash)"; fi
- ✅ Removed from zsh ~/.zshrc
-   if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
+ ✅ Removed shell extension for bash @ ~/.bashrc
+ ✅ Removed shell extension for zsh @ ~/.zshrc
+ ⚪ Completions for zsh were via lazy compdef (no file to remove)
💡 No fish integration in ~/.config/fish/conf.d/wt.fish
- ✅ Removed shell integration from 2 shells
-
+ ✅ Removed integration from 2 shells
💡 Restart shell to complete uninstall
----- stderr -----
- "#);
+ ");
});
// Verify both files no longer contain the integration
@@ -520,11 +510,9 @@ fn test_uninstall_shell_fish() {
success: true
exit_code: 0
----- stdout -----
- ✅ Removed from fish ~/.config/fish/conf.d/wt.fish
-   wt.fish
-
- ✅ Removed shell integration from 1 shell
+ ✅ Removed shell extension for fish @ ~/.config/fish/conf.d/wt.fish
+ ✅ Removed integration from 1 shell
💡 Restart shell to complete uninstall
----- stderr -----
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index a11baeb11..6e111de38 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -201,6 +201,12 @@ fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&s
script.push_str("set -x CLICOLOR_FORCE 1\n");
}
"zsh" => {
+ // For zsh, initialize the completion system first
+ // This allows static completions (which call compdef) to work in isolated mode
+ // We run with --no-rcs to prevent user rc files from touching /dev/tty,
+ // but compinit is safe since it only sets up completion functions
+ script.push_str("autoload -Uz compinit && compinit -i 2>/dev/null\n");
+
script.push_str(&format!("export WORKTRUNK_BIN='{}'\n", wt_bin.display()));
script.push_str(&format!(
"export WORKTRUNK_CONFIG_PATH='{}'\n",
@@ -1378,6 +1384,7 @@ approved-commands = ["echo 'fish background task'"]
script.push_str("set -x CLICOLOR_FORCE 1\n");
}
"zsh" => {
+ script.push_str("autoload -Uz compinit && compinit -i 2>/dev/null\n");
script.push_str(&format!("export WORKTRUNK_BIN='{}'\n", wt_bin.display()));
script.push_str(&format!(
"export WORKTRUNK_CONFIG_PATH='{}'\n",
@@ -1647,79 +1654,27 @@ approved-commands = ["echo 'bash background'"]
);
}
- /// Test that zsh completions are properly registered
- #[test]
- fn test_zsh_completions_registered() {
- let repo = TestRepo::new();
- repo.commit("Initial commit");
-
- let wt_bin = get_cargo_bin("wt");
- let wrapper_script = generate_wrapper(&repo, "zsh");
-
- // Script that sources wrapper and checks if completion function exists
- // Tests deferred registration: compinit runs AFTER wrapper (like real .zshrc)
- let script = format!(
- r#"
- export WORKTRUNK_BIN='{}'
- export WORKTRUNK_CONFIG_PATH='{}'
- {}
- # Run compinit after wrapper (simulates typical user .zshrc order)
- autoload -Uz compinit && compinit -i 2>/dev/null
- # Trigger precmd hook to complete deferred registration
- for func in $precmd_functions; do $func; done
- # Check if lazy completion stub is registered
- if (( $+functions[_wt_lazy_complete] )); then
- echo "__COMPLETION_REGISTERED__"
- else
- echo "__NO_COMPLETION__"
- fi
- "#,
- wt_bin.display(),
- repo.test_config_path().display(),
- wrapper_script
- );
-
- let final_script = format!("( {} ) 2>&1", script);
- let config_path = repo.test_config_path().to_string_lossy().to_string();
- let env_vars: Vec<(&str, &str)> = vec![
- ("WORKTRUNK_CONFIG_PATH", &config_path),
- ("TERM", "xterm"),
- ("ZDOTDIR", "/dev/null"),
- ];
-
- let (combined, exit_code) =
- exec_in_pty_interactive("zsh", &final_script, repo.root_path(), &env_vars, &[]);
-
- assert_eq!(exit_code, 0, "Script should succeed");
- assert!(
- combined.contains("__COMPLETION_REGISTERED__"),
- "Zsh completions should be registered after sourcing wrapper.\nOutput:\n{}",
- combined
- );
- }
-
- /// Test that zsh completions work with immediate registration (compinit before wrapper)
+ /// Test that zsh wrapper function is properly defined
+ /// Note: Completions come from fpath (~/.zfunc/_wt), not from the wrapper
#[test]
- fn test_zsh_completions_immediate_registration() {
+ fn test_zsh_wrapper_function_registered() {
let repo = TestRepo::new();
repo.commit("Initial commit");
let wt_bin = get_cargo_bin("wt");
let wrapper_script = generate_wrapper(&repo, "zsh");
- // Script that runs compinit BEFORE wrapper (immediate registration path)
+ // Script that sources wrapper and checks if wt function exists
let script = format!(
r#"
- # Run compinit first (some users do this)
- autoload -Uz compinit && compinit -i 2>/dev/null
export WORKTRUNK_BIN='{}'
export WORKTRUNK_CONFIG_PATH='{}'
{}
- # Check if lazy completion stub is registered (should be immediate, no precmd needed)
- if (( $+functions[_wt_lazy_complete] )); then
- echo "__COMPLETION_REGISTERED__"
+ # Check if wt wrapper function is defined
+ if (( $+functions[wt] )); then
+ echo "__WRAPPER_REGISTERED__"
else
- echo "__NO_COMPLETION__"
+ echo "__NO_WRAPPER__"
fi
"#,
wt_bin.display(),
@@ -1740,8 +1695,8 @@ approved-commands = ["echo 'bash background'"]
assert_eq!(exit_code, 0, "Script should succeed");
assert!(
- combined.contains("__COMPLETION_REGISTERED__"),
- "Zsh completions should register immediately when compinit runs first.\nOutput:\n{}",
+ combined.contains("__WRAPPER_REGISTERED__"),
+ "Zsh wrapper function should be registered after sourcing.\nOutput:\n{}",
combined
);
}
@@ -1814,6 +1769,7 @@ approved-commands = ["echo 'bash background'"]
let script = match shell {
"zsh" => format!(
r#"
+ autoload -Uz compinit && compinit -i 2>/dev/null
# Clear PATH to ensure wt is not found via PATH
export PATH="/usr/bin:/bin"
export WORKTRUNK_BIN='{}'
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap b/tests/snapshots/integration__integration_tests__help__help_config_shell.snap
index cf79514de..fcb8b41d0 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_shell.snap
@@ -19,9 +19,10 @@ wt config shell - Shell integration setup
Usage: wt config shell [OPTIONS] <COMMAND>
Commands:
- init Generate shell integration code
- install Write shell integration to config files
- uninstall Remove shell integration from config files
+ init Generate shell integration code
+ install Write shell integration to config files
+ uninstall Remove shell integration from config files
+ completions Generate shell completion script
Options:
-h, --help
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index b97f94877..f45deb2c2 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -165,32 +165,8 @@ wt_exec() {
return $result
}
- # Lazy completion loader - loads real completions on first tab-press
- # This avoids ~11ms binary invocation at shell startup
- _wt_lazy_complete() {
- # Only try to install completions once
- if [[ -z "${_WT_COMPLETION_LOADED:-}" ]]; then
- _WT_COMPLETION_LOADED=1
- if completion_script=$(COMPLETE=bash "${_WORKTRUNK_CMD:-wt}" 2>/dev/null); then
- eval "$completion_script"
- else
- # Failed to load - remove completion registration
- complete -r wt 2>/dev/null || true
- return 1
- fi
- fi
-
- # Delegate to real completion function if it was installed
- if declare -F _clap_complete_wt >/dev/null 2>&1; then
- _clap_complete_wt
- fi
- }
- # nosort requires Bash 4.4+ (macOS ships with 3.2)
- if [[ ${BASH_VERSINFO[0]} -gt 4 || (${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -ge 4) ]]; then
- complete -o nospace -o bashdefault -o nosort -F _wt_lazy_complete wt
- else
- complete -o nospace -o bashdefault -F _wt_lazy_complete wt
- fi
+ # Completions are loaded from ~/.local/share/bash-completion/completions/wt
+ # Install with: wt config shell install
fi
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index e106833ed..52f086f4d 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -152,11 +152,8 @@ if type -q wt; or set -q WORKTRUNK_BIN
return $result
end
- # Register Clap-based completions (auto-updates after wt upgrades)
- set -l _wt_completion_script (COMPLETE=fish $_WORKTRUNK_CMD 2>/dev/null | string collect)
- if test -n "$_wt_completion_script"
- eval $_wt_completion_script
- end
+ # Completions are loaded from ~/.config/fish/completions/wt.fish
+ # Install with: wt config shell install
end
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 7716cc2d8..cfcdbf5eb 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -165,44 +165,25 @@ wt_exec() {
return $result
}
- # Lazy completion loader - loads real completions on first tab-press
- # This avoids ~11ms binary invocation at shell startup
- _wt_lazy_complete() {
- # Only try to install completions once
- if [[ -z "${_WT_COMPLETION_LOADED:-}" ]]; then
- typeset -g _WT_COMPLETION_LOADED=1
- local completion_script
- if completion_script=$(COMPLETE=zsh "${_WORKTRUNK_CMD:-wt}" 2>/dev/null); then
- eval "$completion_script"
- else
- # Failed to load - unregister to prevent future silent failures
- compdef -d wt 2>/dev/null
- return 1
+ # Lazy completions via compdef - no fpath setup needed
+ # Regenerates on first TAB in each shell session
+ if (( $+functions[compdef] )); then
+ _wt_lazy_complete() {
+ # Load dynamic completion script once
+ unfunction _wt_lazy_complete 2>/dev/null || true
+
+ # Generate & eval the real completer from the binary
+ local _script
+ _script="$(COMPLETE=zsh "$_WORKTRUNK_CMD" 2>/dev/null)" || return
+ eval "$_script"
+
+ # Delegate to clap's generated function
+ if (( $+functions[_clap_dynamic_completer_wt] )); then
+ _clap_dynamic_completer_wt "$@"
fi
- fi
-
- # Delegate to real completion function if it was installed
- if (( $+functions[_clap_dynamic_completer_wt] )); then
- _clap_dynamic_completer_wt
- fi
- }
-
- # Register completion - either now or deferred until compinit runs
- _wt_register_completion() {
- if (( $+functions[compdef] )); then
- compdef _wt_lazy_complete wt
- # Remove hook once registered
- precmd_functions=(${precmd_functions:#_wt_register_completion})
- unfunction _wt_register_completion 2>/dev/null
- return 0
- fi
- return 1
- }
+ }
- # Try immediate registration, otherwise defer via precmd hook
- if ! _wt_register_completion; then
- # Add to hook only if not already present (handles re-sourcing .zshrc)
- (( ${precmd_functions[(I)_wt_register_completion]} )) || precmd_functions+=(_wt_register_completion)
+ compdef _wt_lazy_complete wt
fi
fi