Skip to content

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

Refactor shell completion to improve filtering and flag visibility

Maximilian Roosaacae4a20805
diff --git a/ISSUE.md b/ISSUE.md
deleted file mode 100644
index af91ebecb..000000000
--- a/ISSUE.md
+++ /dev/null
@@ -1,182 +0,0 @@
-# Issue: Zsh Completion Grouping of Branches with Identical Descriptions
-
-## Goal
-
-We have a CLI tool (`wt`) that provides zsh completions for git branch names. Each completion includes a description showing the branch category and relative timestamp:
-
-```
-main -- + 15m (worktree, 15 minutes ago)
-feature -- / 2h (local branch, 2 hours ago)
-upstream -- ⇣ 1d origin (remote branch, 1 day ago)
-```
-
-**The problem:** When multiple branches have identical descriptions (same timestamp), zsh groups them on a single line:
-
-```
-release main -- + 12m
-```
-
-**Desired behavior:** Each branch should appear on its own line:
-
-```
-release -- + 12m
-main -- + 12m
-```
-
-## Technical Setup
-
-### How Completions Are Generated
-
-We use `clap_complete` for dynamic completions. The binary generates completion candidates when invoked with `COMPLETE=zsh`:
-
-```bash
-$ _CLAP_IFS=$'\n' _CLAP_COMPLETE_INDEX=2 COMPLETE=zsh wt -- wt switch ''
-main:+ 15m
-release:+ 15m
-feature:+ 1h
-```
-
-The format is `value:description` pairs, one per line.
-
-### The Generated Zsh Completion Script
-
-`clap_complete` generates this zsh function:
-
-```zsh
-#compdef wt
-function _clap_dynamic_completer_wt() {
- local _CLAP_COMPLETE_INDEX=$(expr $CURRENT - 1)
- local _CLAP_IFS=$'\n'
-
- local completions=("${(@f)$( \
- _CLAP_IFS="$_CLAP_IFS" \
- _CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \
- COMPLETE="zsh" \
- /path/to/wt -- "${words[@]}" 2>/dev/null \
- )}")
-
- if [[ -n $completions ]]; then
- _describe 'values' completions
- fi
-}
-
-compdef _clap_dynamic_completer_wt wt
-```
-
-### Our Custom Shell Init Script
-
-We post-process the clap output with sed to add the `-V` flag for preserving sort order:
-
-```zsh
-eval "$(COMPLETE=zsh command wt 2>/dev/null | sed "s/_describe 'values'/_describe -V 'values'/")"
-```
-
-This transforms the call to:
-```zsh
-_describe -V 'values' completions
-```
-
-## What We've Tried
-
-### Attempt 1: Add `-1` flag to `_describe`
-
-Based on research suggesting `-1` forces one completion per line, we tried:
-
-```zsh
-_describe -1 -V 'values' completions
-```
-
-**Result: COMPLETELY BROKEN**
-
-The output became:
-```
--- + 31m
--- + 2d
--- + 6d
--- + 1h
-main readme zellij zsh-auto t
-```
-
-The descriptions were separated from the values entirely - descriptions on top, values on bottom. This is clearly wrong behavior.
-
-### Attempt 2: Make descriptions unique (add branch name)
-
-We tried including the branch name in the description:
-
-```rust
-let help = match branch.category {
- BranchCategory::Worktree => format!("+ {} {}", time_str, branch.name),
- // ...
-};
-```
-
-Output: `main:+ 15m main`
-
-**Result:** Works (each branch gets its own line) but looks redundant:
-```
-main -- + 15m main
-release -- + 15m release
-```
-
-User feedback: "meh, that's not so great"
-
-### Attempt 3: Invisible spacer characters
-
-We tried appending varying numbers of Unicode EN SPACE (U+2002) to make descriptions technically unique but visually identical:
-
-```rust
-let spacer = "\u{2002}".repeat(i); // i is the index
-let help = format!("+ {}{}", time_str, spacer);
-```
-
-**Result:** Not tested in practice because the `-1` approach was tried first. This feels hacky and may have issues with terminal rendering or text normalization.
-
-## Root Cause Analysis
-
-The grouping happens inside zsh's `_describe` function. When multiple completions have identical descriptions, `_describe` groups them together on a single line to save space. This is intentional behavior in zsh, not a bug.
-
-The `-1` flag was supposed to prevent this, but based on our testing, it does something completely different - it seems to separate the display of values and descriptions into different regions of the output.
-
-## Open Questions
-
-1. **What does `_describe -1` actually do?**
- - The zsh documentation mentions `-1` "only has an effect if used together with the -d option" and affects whether "display strings are listed one per line, not arrayed in columns"
- - But our testing shows it completely breaks the value/description association
- - Is there a specific context or additional flags needed?
-
-2. **Is there another flag or combination that prevents grouping?**
- - Are there other `_describe` options we haven't tried?
- - Would different `compadd` options work better?
-
-3. **Can we use `compadd` directly instead of `_describe`?**
- - `_describe` is a convenience wrapper around `compadd`
- - Would calling `compadd` directly give us more control?
-
-4. **Are there zstyle options that affect grouping?**
- - zsh's completion system has many zstyle settings
- - Is there a style that controls whether identical descriptions are grouped?
-
-5. **How do other tools handle this?**
- - How do tools like `git`, `docker`, `kubectl` handle completions with potentially identical descriptions?
- - Do they use `_describe` or something else?
-
-## Constraints
-
-- We're using `clap_complete` which generates the base zsh script
-- We can post-process with sed but ideally want minimal changes
-- The solution should work without requiring users to configure zstyles
-- Should degrade gracefully if the approach doesn't work
-
-## Relevant Documentation Links
-
-- zsh Completion System: https://zsh.sourceforge.io/Doc/Release/Completion-System.html
-- zsh Completion Widgets: https://zsh.sourceforge.io/Doc/Release/Completion-Widgets.html
-- zsh-completions howto: https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org
-
-## Specific Research Needed
-
-1. Find the exact documentation for `_describe` function and ALL its flags
-2. Find examples of completion scripts that prevent description grouping
-3. Understand what `-1` actually does in different contexts
-4. Find if there's a `compadd` approach that avoids grouping
-5. Check if there are zstyle settings that affect this behavior
diff --git a/src/completion.rs b/src/completion.rs
index c20236a90..56be3032c 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -1,5 +1,6 @@
use std::cell::RefCell;
use std::ffi::{OsStr, OsString};
+use std::io::Write;
use clap::Command;
use clap_complete::engine::{ArgValueCompleter, CompletionCandidate, ValueCompleter};
@@ -10,22 +11,139 @@ use crate::display::format_relative_time_short;
use worktrunk::config::ProjectConfig;
use worktrunk::git::{BranchCategory, Repository};
+/// Args that should never appear in completions, even when all options are shown.
+const COMPLETION_DENYLIST: &[&str] = &["--internal"];
+
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
pub fn maybe_handle_env_completion() -> bool {
- if std::env::var_os("COMPLETE").is_none() {
+ let Some(shell_name) = std::env::var_os("COMPLETE") else {
+ return false;
+ };
+
+ if shell_name.is_empty() || shell_name == "0" {
return false;
}
- let args: Vec<OsString> = std::env::args_os().collect();
+ let mut args: Vec<OsString> = std::env::args_os().collect();
CONTEXT.with(|ctx| *ctx.borrow_mut() = Some(CompletionContext { args: args.clone() }));
+ // Remove the binary name and find the `--` separator
+ args.remove(0);
+ let escape_index = args
+ .iter()
+ .position(|a| *a == "--")
+ .map(|i| i + 1)
+ .unwrap_or(args.len());
+ args.drain(0..escape_index);
+
let current_dir = std::env::current_dir().ok();
- let handled = CompleteEnv::with_factory(completion_command)
- .try_complete(args, current_dir.as_deref())
- .unwrap_or_else(|err| err.exit());
+
+ // If no args after `--`, output the shell registration script
+ if args.is_empty() {
+ // Use CompleteEnv for registration script generation
+ let all_args: Vec<OsString> = std::env::args_os().collect();
+ let _ = CompleteEnv::with_factory(completion_command)
+ .try_complete(all_args, current_dir.as_deref());
+ CONTEXT.with(|ctx| ctx.borrow_mut().take());
+ return true;
+ }
+
+ // Generate completions with filtering
+ let mut cmd = completion_command();
+ cmd.build();
+
+ let index: usize = std::env::var("_CLAP_COMPLETE_INDEX")
+ .ok()
+ .and_then(|i| i.parse().ok())
+ .unwrap_or_default();
+
+ // Check if the current word is exactly "-" (single dash)
+ // If so, we want to show both short flags (-h) AND long flags (--help)
+ // clap only returns matches for the prefix, so we call complete twice
+ let current_word = args.get(index).map(|s| s.to_string_lossy());
+ let include_long_flags = current_word.as_deref() == Some("-");
+
+ let completions = match clap_complete::engine::complete(
+ &mut cmd,
+ args.clone(),
+ index,
+ current_dir.as_deref(),
+ ) {
+ Ok(c) => c,
+ Err(_) => {
+ CONTEXT.with(|ctx| ctx.borrow_mut().take());
+ return true;
+ }
+ };
+
+ // If single dash, also get completions for "--" and merge
+ let completions = if include_long_flags {
+ let mut merged = completions;
+ let mut args_with_double_dash = args;
+ if let Some(word) = args_with_double_dash.get_mut(index) {
+ *word = OsString::from("--");
+ }
+ let mut cmd2 = completion_command();
+ cmd2.build();
+ if let Ok(long_completions) = clap_complete::engine::complete(
+ &mut cmd2,
+ args_with_double_dash,
+ index,
+ current_dir.as_deref(),
+ ) {
+ // Add long flags that aren't already present (avoid duplicates)
+ for candidate in long_completions {
+ let value = candidate.get_value();
+ if !merged.iter().any(|c| c.get_value() == value) {
+ merged.push(candidate);
+ }
+ }
+ }
+ merged
+ } else {
+ completions
+ };
+
+ // Filter out denylisted completions
+ let filtered: Vec<_> = completions
+ .into_iter()
+ .filter(|c| {
+ let value = c.get_value().to_string_lossy();
+ !COMPLETION_DENYLIST.contains(&value.as_ref())
+ })
+ .collect();
+
+ // Write completions in the appropriate format for the shell
+ let shell_name = shell_name.to_string_lossy();
+ let ifs = std::env::var("_CLAP_IFS").ok();
+ let separator = ifs.as_deref().unwrap_or("\n");
+
+ // Shell-specific separator between value and description
+ // zsh uses ":", fish uses "\t", bash doesn't support descriptions
+ let help_sep = match shell_name.as_ref() {
+ "zsh" => Some(":"),
+ "fish" => Some("\t"),
+ _ => None,
+ };
+
+ let mut stdout = std::io::stdout();
+ for (i, candidate) in filtered.iter().enumerate() {
+ if i != 0 {
+ let _ = write!(stdout, "{}", separator);
+ }
+ let value = candidate.get_value().to_string_lossy();
+ match (help_sep, candidate.get_help()) {
+ (Some(sep), Some(help)) => {
+ let _ = write!(stdout, "{}{}{}", value, sep, help);
+ }
+ _ => {
+ let _ = write!(stdout, "{}", value);
+ }
+ }
+ }
CONTEXT.with(|ctx| ctx.borrow_mut().take());
- handled
+ true
}
/// Branch completion without additional context filtering (e.g., --base, merge target).
@@ -242,27 +360,44 @@ fn completion_command() -> Command {
/// This exploits clap_complete's behavior: if any non-hidden candidates exist,
/// hidden ones are dropped. When all candidates are hidden, they're kept.
fn hide_non_positional_options_for_completion(cmd: Command) -> Command {
- // Disable built-in help/version flags for completion only
- let cmd = cmd
- .disable_help_flag(true)
- .disable_help_subcommand(true)
- .disable_version_flag(true);
-
- fn recurse(cmd: Command) -> Command {
- // Hide every non-positional arg on this Command
+ fn process_command(cmd: Command, is_root: bool) -> Command {
+ // Disable built-in help flag (not visible to mut_args) and add custom replacement
+ let cmd = cmd.disable_help_flag(true).arg(
+ clap::Arg::new("help")
+ .short('h')
+ .long("help")
+ .action(clap::ArgAction::Help)
+ .help("Print help (see more with '--help')"),
+ );
+
+ // Only root command has --version
+ let cmd = if is_root {
+ cmd.disable_version_flag(true).arg(
+ clap::Arg::new("version")
+ .short('V')
+ .long("version")
+ .action(clap::ArgAction::Version)
+ .help("Print version"),
+ )
+ } else {
+ cmd
+ };
+
+ // Hide non-positional args that aren't already hidden.
+ // Args originally marked hide=true (like --internal) stay hidden always.
+ // Args we hide here will appear when completing `--` (all-hidden = all shown).
let cmd = cmd.mut_args(|arg| {
- if arg.is_positional() {
+ if arg.is_positional() || arg.is_hide_set() {
arg
} else {
arg.hide(true)
}
});
- // Recurse into subcommands
- cmd.mut_subcommands(recurse)
+ cmd.mut_subcommands(|sub| process_command(sub, false))
}
- recurse(cmd)
+ process_command(cmd, true)
}
// Mark positional args as `.last(true)` to allow them after all flags.
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 143c70614..33bd45f88 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -71,10 +71,15 @@ pub fn wt_completion_command(words: &[&str]) -> Command {
/// Configure an existing command to mimic shell completion environment.
pub fn configure_completion_invocation(cmd: &mut Command, words: &[&str]) {
+ configure_completion_invocation_for_shell(cmd, words, "bash");
+}
+
+/// Configure an existing command to mimic shell completion environment for a specific shell.
+pub fn configure_completion_invocation_for_shell(cmd: &mut Command, words: &[&str], shell: &str) {
let index = words.len().saturating_sub(1);
cmd.arg("--");
cmd.args(words);
- cmd.env("COMPLETE", "bash");
+ cmd.env("COMPLETE", shell);
cmd.env("_CLAP_COMPLETE_INDEX", index.to_string());
cmd.env("_CLAP_COMPLETE_COMP_TYPE", "9"); // normal completion
cmd.env("_CLAP_COMPLETE_SPACE", "true");
@@ -272,7 +277,13 @@ impl TestRepo {
/// Prepare a `wt` command configured for shell completions within this repo.
pub fn completion_cmd(&self, words: &[&str]) -> Command {
- let mut cmd = wt_completion_command(words);
+ self.completion_cmd_for_shell(words, "bash")
+ }
+
+ /// Prepare a `wt` command configured for shell completions for a specific shell.
+ pub fn completion_cmd_for_shell(&self, words: &[&str], shell: &str) -> Command {
+ let mut cmd = wt_command();
+ configure_completion_invocation_for_shell(&mut cmd, words, shell);
self.clean_cli_env(&mut cmd);
cmd.current_dir(self.root_path());
cmd
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index e83008a75..92ce8961c 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -1206,3 +1206,163 @@ fn test_complete_switch_single_dash_shows_options_not_branches() {
"Should only show options when input starts with -, got:\n{stdout}"
);
}
+
+/// Verify --help appears in completions across all supported shells.
+///
+/// This is a regression test for a bug where --help was missing from zsh completions
+/// because clap's built-in help flag was disabled (to participate in completion filtering)
+/// but not replaced with a visible alternative.
+#[test]
+fn test_complete_help_flag_all_shells() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ for shell in ["bash", "zsh", "fish"] {
+ // Test: wt --help<cursor> - should complete --help
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "--help"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--help"),
+ "{shell}: --help should appear in completions for 'wt --help', got:\n{stdout}"
+ );
+
+ // Test: wt config --help<cursor> - should complete --help on subcommands too
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "config", "--help"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--help"),
+ "{shell}: --help should appear in completions for 'wt config --help', got:\n{stdout}"
+ );
+ }
+}
+
+/// Verify --version appears in completions across all supported shells (root command only).
+#[test]
+fn test_complete_version_flag_all_shells() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ for shell in ["bash", "zsh", "fish"] {
+ // Test: wt --version<cursor> - should complete --version
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "--version"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("--version"),
+ "{shell}: --version should appear in completions for 'wt --version', got:\n{stdout}"
+ );
+ }
+}
+
+/// Verify --internal never appears in completions across all supported shells.
+///
+/// The --internal flag is used by shell wrappers and should never be exposed to users.
+/// This is a regression test for a bug where global hidden args would appear in completions
+/// due to clap's "all hidden = all shown" behavior when completing `--`.
+#[test]
+fn test_complete_internal_flag_never_shown() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ for shell in ["bash", "zsh", "fish"] {
+ // Test: wt --<cursor> - should NOT show --internal
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "--"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("--internal"),
+ "{shell}: --internal should NEVER appear in completions, got:\n{stdout}"
+ );
+
+ // Test: wt config --<cursor> - should NOT show --internal on subcommands either
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "config", "--"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("--internal"),
+ "{shell}: --internal should NEVER appear in subcommand completions, got:\n{stdout}"
+ );
+
+ // Test: wt -<cursor> - should NOT show --internal even with single dash
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "-"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ !stdout.contains("--internal"),
+ "{shell}: --internal should NEVER appear in single-dash completions, got:\n{stdout}"
+ );
+ }
+}
+
+/// Verify single dash '-' shows both short AND long flags.
+///
+/// When completing `wt -`, users should see both short flags like `-h` and long flags
+/// like `--help`. This is more discoverable than requiring users to type `--` first.
+#[test]
+fn test_complete_single_dash_shows_both_short_and_long_flags() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ for shell in ["bash", "zsh", "fish"] {
+ // Test: wt -<cursor> - should show both -h and --help
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "-"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Should have short flags
+ assert!(
+ stdout.contains("-h"),
+ "{shell}: single dash should show -h, got:\n{stdout}"
+ );
+ assert!(
+ stdout.contains("-v") || stdout.contains("-V"),
+ "{shell}: single dash should show -v or -V, got:\n{stdout}"
+ );
+
+ // Should also have long flags
+ assert!(
+ stdout.contains("--help"),
+ "{shell}: single dash should show --help, got:\n{stdout}"
+ );
+ assert!(
+ stdout.contains("--verbose") || stdout.contains("--version"),
+ "{shell}: single dash should show --verbose or --version, got:\n{stdout}"
+ );
+
+ // Test: wt config -<cursor> - same behavior on subcommands
+ let output = temp
+ .completion_cmd_for_shell(&["wt", "config", "-"], shell)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{shell}: completion failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ assert!(
+ stdout.contains("-h") && stdout.contains("--help"),
+ "{shell}: subcommand single dash should show both -h and --help, got:\n{stdout}"
+ );
+ }
+}