Skip to content

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

Add shell completion for commands, flags, and branches

Maximilian Roos962eb382c970
diff --git a/Cargo.lock b/Cargo.lock
index 548477478..78a2dc476 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -200,6 +200,15 @@ dependencies = [
"strsim",
]
+[[package]]
+name = "clap_complete"
+version = "4.5.59"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2348487adcd4631696ced64ccdb40d38ac4d31cae7f2eec8817fcea1b9d1c43c"
+dependencies = [
+ "clap",
+]
+
[[package]]
name = "clap_derive"
version = "4.5.49"
@@ -1648,6 +1657,7 @@ dependencies = [
"askama",
"assert_cmd",
"clap",
+ "clap_complete",
"config",
"directories",
"insta",
diff --git a/Cargo.toml b/Cargo.toml
index 5508dbdca..2d9daa0e2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,6 +17,7 @@ anstream = "0.6"
anstyle = "1.0"
askama = { version = "0.14", default-features = false, features = ["derive", "std"] }
clap = { version = "4.5", features = ["derive"] }
+clap_complete = "4.5"
config = "0.15"
directories = "6.0"
serde = { version = "1.0", features = ["derive"] }
diff --git a/README.md b/README.md
index 7667a1aa6..f09b4f6e9 100644
--- a/README.md
+++ b/README.md
@@ -17,31 +17,70 @@ cargo build --release
# Copy target/release/wt to a directory in your PATH
```
-## Shell Integration Setup
+## Setup
-Worktrunk uses shell integration to automatically change directories when switching worktrees. Add one of the following to your shell config:
+Worktrunk requires a two-step setup for full functionality:
-### Bash
+### 1. Shell Integration (for automatic `cd`)
-Add to `~/.bashrc`:
+This enables `wt switch` and `wt finish` to automatically change directories.
+
+**Bash** - Add to `~/.bashrc`:
```bash
eval "$(wt init bash)"
```
-### Fish
-
-Add to `~/.config/fish/config.fish`:
+**Fish** - Add to `~/.config/fish/config.fish`:
```fish
wt init fish | source
```
-### Zsh
-
-Add to `~/.zshrc`:
+**Zsh** - Add to `~/.zshrc`:
```bash
eval "$(wt init zsh)"
```
+### 2. Shell Completion (for TAB completion)
+
+This enables completion for commands, flags, and branch names.
+
+**Fish:**
+```fish
+wt completion fish > ~/.config/fish/completions/wt.fish
+```
+
+**Bash** - Add to `~/.bashrc` (after the init line):
+```bash
+eval "$(wt completion bash)"
+```
+
+**Zsh** - Add to `~/.zshrc` (after the init line):
+```bash
+eval "$(wt completion zsh)"
+```
+
+### Complete Setup Example (Fish)
+
+```fish
+# In ~/.config/fish/config.fish
+wt init fish | source
+
+# Run once to install completions
+wt completion fish > ~/.config/fish/completions/wt.fish
+```
+
+### What Gets Completed
+
+- **Subcommands**: `wt <TAB>` → shows `list`, `switch`, `finish`, `push`, `merge`
+- **Flags**: `wt switch --<TAB>` → shows `--create`, `--base`, `--internal`
+- **Branch names**: `wt switch <TAB>` → shows branches without worktrees
+- **Target branches**: `wt push <TAB>` → shows all branches
+
+**Notes:**
+- Zsh currently uses Bash-compatible completion syntax. Dynamic branch completion may require `bashcompinit`. For best results, use Fish or Bash.
+- Regenerate completion scripts after updating `wt`
+- Debug completion: Set `WT_DEBUG_COMPLETION=1` to see errors
+
## Usage
### Basic Commands
diff --git a/TODO.md b/TODO.md
index d9be53b66..2ac47cf96 100644
--- a/TODO.md
+++ b/TODO.md
@@ -230,6 +230,195 @@ Another output line
- **direnv**: `eval "$(direnv hook bash)"` → generates `_direnv_hook` function
- **pyenv**: `eval "$(pyenv init -)"` → sets up shims + shell functions
+## Shell Completion (Autocomplete)
+
+**Decision: Two-tier completion system**
+1. **Tier 1 (Static)**: Command and flag completion via `clap_complete`
+2. **Tier 2 (Dynamic)**: Branch and worktree completion via callback protocol
+
+### Architecture
+
+```
+User presses [TAB]
+ ↓
+Shell-specific completion script (generated by: wt completion <shell>)
+ ↓
+Static path: subcommands/flags (from clap metadata)
+ ↓
+Dynamic path: wt __complete <args...>
+ ↓
+Rust queries git and returns: branch names, worktree paths, etc.
+```
+
+### Implementation Phases
+
+**Phase 1: Static Completion** (Quick Win - 2-4 hours)
+- [ ] Add `clap_complete` dependency to Cargo.toml
+- [ ] Create `Shell` enum compatible with `clap_complete::Shell`
+- [ ] Add `Completion` subcommand: `wt completion <shell>`
+- [ ] Implement `handle_completion()` using `clap_complete::generate()`
+- [ ] Test completion generation for Fish, Bash, Zsh
+- [ ] Update README with installation instructions
+
+**Phase 2: Git Primitives for Dynamic Completion** (Foundation - 2-3 hours)
+- [ ] Add `get_all_branches()` to `src/git.rs`
+ - Uses: `git branch --format='%(refname:short)'`
+ - Returns: `Vec<String>` of branch names
+- [ ] Add `get_available_branches()` helper
+ - Filters out branches that already have worktrees
+ - Used for `wt switch` completion
+- [ ] Add unit tests for branch listing functions
+- [ ] Performance test: ensure <100ms for repos with 100+ branches
+
+**Phase 3: Dynamic Completion Backend** (Core - 4-6 hours)
+- [ ] Add hidden `__complete` command to `Commands` enum
+ - Mark with `#[command(hide = true)]`
+ - Takes trailing args: `args: Vec<String>`
+- [ ] Implement `CompletionContext` enum:
+ - `SwitchBranch` - complete available branches
+ - `PushTarget` - complete all branches
+ - `MergeTarget` - complete all branches
+ - `BaseFlag` - complete all branches for `--base`
+ - `Unknown` - no completions
+- [ ] Implement `parse_completion_context()`:
+ - Parse command line: `["wt", "switch", "feat"]`
+ - Determine what position we're completing
+ - Return appropriate `CompletionContext`
+- [ ] Implement context-specific completion functions:
+ - `complete_available_branches()` - for `switch`
+ - `complete_all_branches()` - for `push`, `merge`, `--base`
+- [ ] Implement `handle_complete()` main dispatcher
+- [ ] Add unit tests for context parsing
+- [ ] Add integration tests for completion output
+
+**Phase 4: Shell Template Enhancement** (Polish - 3-4 hours)
+- [ ] Enhance `templates/fish.fish`:
+ - Add `__wt_complete` function that calls `wt __complete`
+ - Add `complete -c wt` rules for dynamic completion
+ - Test with real Fish shell
+- [ ] Enhance `templates/bash.sh`:
+ - Add `_wt_complete()` bash completion function
+ - Register with `complete -F _wt_complete wt`
+ - Test with real Bash shell
+- [ ] Create `templates/zsh.zsh`:
+ - Add `_wt_complete()` zsh completion function
+ - Add zsh-specific completion registration
+ - Test with real Zsh shell
+- [ ] Update `shell.rs` to include completion code in templates
+- [ ] Test all three shells with various completion scenarios
+
+**Phase 5: Integration & Testing** (Validation - 2-3 hours)
+- [ ] Manual testing checklist:
+ - [ ] Fish: `wt sw<TAB>` shows `switch`
+ - [ ] Fish: `wt switch <TAB>` shows available branches
+ - [ ] Fish: `wt push <TAB>` shows all branches
+ - [ ] Bash: same as Fish tests
+ - [ ] Zsh: same as Fish tests
+- [ ] Performance testing:
+ - [ ] Measure `wt __complete` response time
+ - [ ] Target: <100ms for typical repos
+ - [ ] Test with repo containing 100+ branches
+- [ ] Edge case testing:
+ - [ ] Completion in non-git directory (should fail gracefully)
+ - [ ] Completion with no branches
+ - [ ] Completion with partial branch names
+- [ ] Documentation:
+ - [ ] Update README with completion installation
+ - [ ] Add performance notes
+ - [ ] Document `wt completion` usage
+
+### Completion Context Logic
+
+```rust
+// Example completion contexts based on command line:
+
+["wt", "switch", "feat"]
+→ CompletionContext::SwitchBranch
+→ Output: branches without worktrees matching "feat*"
+
+["wt", "push", "ma"]
+→ CompletionContext::PushTarget
+→ Output: all branches matching "ma*"
+
+["wt", "switch", "--create", "new", "--base", "dev"]
+→ CompletionContext::BaseFlag
+→ Output: all branches matching "dev*"
+```
+
+### Performance Requirements
+
+- **Target:** <100ms for completion response
+- **Acceptable:** <200ms
+- **Optimization strategies (if needed):**
+ - Cache branch list with 5-10 second TTL
+ - Read `.git/refs/heads/*` directly instead of `git branch`
+ - Stream results instead of collecting to vector
+
+### Shell-Specific Output Formats
+
+**Fish:** Supports descriptions
+```
+main Default branch
+develop Development branch
+```
+
+**Bash/Zsh:** Plain list
+```
+main
+develop
+```
+
+### Installation Instructions (for README)
+
+```bash
+# Fish
+wt completion fish > ~/.config/fish/completions/wt.fish
+
+# Bash (add to ~/.bashrc)
+eval "$(wt completion bash)"
+
+# Zsh (add to ~/.zshrc)
+eval "$(wt completion zsh)"
+```
+
+**Note:** Users must regenerate completion scripts after updating `wt`.
+
+### Testing Strategy
+
+**Unit tests:**
+```rust
+#[test]
+fn test_parse_completion_context_switch() {
+ let args = vec!["wt".to_string(), "switch".to_string(), "feat".to_string()];
+ assert_eq!(
+ parse_completion_context(&args),
+ CompletionContext::SwitchBranch
+ );
+}
+
+#[test]
+fn test_complete_available_branches() {
+ // Create test repo with branches and worktrees
+ // Verify only available branches returned
+}
+```
+
+**Integration tests:**
+```bash
+# Test actual shell completion behavior
+# (requires manual testing in real shells)
+```
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Static library | `clap_complete` | Official, well-integrated with clap |
+| Dynamic protocol | Callback via `__complete` | Proven by gh, kubectl, git |
+| Performance target | <100ms | Perceived as instant by users |
+| Command name | `wt completion <shell>` | Industry standard convention |
+| Hidden command | `wt __complete` | Prevents accidental user invocation |
+
## Open Questions
1. ~~**Shell integration approach**: How to handle `cd` in a compiled binary?~~
diff --git a/src/git.rs b/src/git.rs
index dffa375d4..c61f84128 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -516,6 +516,44 @@ fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {
Ok((total_added, total_deleted))
}
+/// Get all branch names (local and remote)
+pub fn get_all_branches() -> Result<Vec<String>, GitError> {
+ get_all_branches_in(std::path::Path::new("."))
+}
+
+/// Get all branch names in a specific directory
+pub fn get_all_branches_in(path: &std::path::Path) -> Result<Vec<String>, GitError> {
+ let stdout = run_git_command(
+ &["branch", "--all", "--format=%(refname:short)"],
+ Some(path),
+ )?;
+ Ok(stdout
+ .lines()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect())
+}
+
+/// Get branches that don't have worktrees (available for switch)
+/// Note: This function operates on the current directory (assumes you're in a git repo)
+pub fn get_available_branches() -> Result<Vec<String>, GitError> {
+ // Get all branches from current directory
+ let all_branches = get_all_branches()?;
+
+ // Get worktrees (always operates on current git repository)
+ let worktrees = list_worktrees()?;
+
+ // Collect branches that have worktrees
+ let branches_with_worktrees: std::collections::HashSet<String> =
+ worktrees.into_iter().filter_map(|wt| wt.branch).collect();
+
+ // Filter out branches with worktrees
+ Ok(all_branches
+ .into_iter()
+ .filter(|branch| !branches_with_worktrees.contains(branch))
+ .collect())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/main.rs b/src/main.rs
index e5d343125..25a8d8b26 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,12 +1,14 @@
use anstyle::{AnsiColor, Color, Style};
-use clap::{Parser, Subcommand};
+use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
+use clap_complete::{Shell as CompletionShell, generate};
+use std::io;
use std::process;
use worktrunk::git::{
- GitError, branch_exists, count_commits, get_ahead_behind_in, get_branch_diff_stats_in,
- get_changed_files, get_commit_timestamp_in, get_current_branch, get_current_branch_in,
- get_default_branch, get_git_common_dir, get_working_tree_diff_stats_in, get_worktree_root,
- has_merge_commits, is_ancestor, is_dirty, is_dirty_in, is_in_worktree, list_worktrees,
- worktree_for_branch,
+ GitError, branch_exists, count_commits, get_ahead_behind_in, get_all_branches,
+ get_available_branches, get_branch_diff_stats_in, get_changed_files, get_commit_timestamp_in,
+ get_current_branch, get_current_branch_in, get_default_branch, get_git_common_dir,
+ get_working_tree_diff_stats_in, get_worktree_root, has_merge_commits, is_ancestor, is_dirty,
+ is_dirty_in, is_in_worktree, list_worktrees, worktree_for_branch,
};
use worktrunk::shell;
@@ -88,6 +90,28 @@ enum Commands {
/// Hook type
hook_type: String,
},
+
+ /// Generate shell completion script
+ Completion {
+ /// Shell to generate completions for
+ #[arg(value_enum)]
+ shell: Shell,
+ },
+
+ /// Internal completion helper (hidden)
+ #[command(hide = true)]
+ Complete {
+ /// Arguments to complete
+ #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
+ args: Vec<String>,
+ },
+}
+
+#[derive(ValueEnum, Clone, Copy)]
+enum Shell {
+ Bash,
+ Fish,
+ Zsh,
}
fn main() {
@@ -111,6 +135,11 @@ fn main() {
} => handle_push(target.as_deref(), allow_merge_commits),
Commands::Merge { target, keep } => handle_merge(target.as_deref(), keep),
Commands::Hook { hook_type } => handle_hook(&hook_type).map_err(GitError::CommandFailed),
+ Commands::Completion { shell } => {
+ handle_completion(shell);
+ Ok(())
+ }
+ Commands::Complete { args } => handle_complete(args),
};
if let Err(e) = result {
@@ -776,3 +805,140 @@ fn handle_hook(hook_type: &str) -> Result<(), String> {
_ => Err(format!("Unknown hook type: {}", hook_type)),
}
}
+
+fn handle_completion(shell: Shell) {
+ let mut cmd = Cli::command();
+ let completion_shell = match shell {
+ Shell::Bash => CompletionShell::Bash,
+ Shell::Fish => CompletionShell::Fish,
+ Shell::Zsh => CompletionShell::Zsh,
+ };
+ generate(completion_shell, &mut cmd, "wt", &mut io::stdout());
+}
+
+#[derive(Debug, PartialEq)]
+enum CompletionContext {
+ SwitchBranch,
+ PushTarget,
+ MergeTarget,
+ BaseFlag,
+ Unknown,
+}
+
+fn parse_completion_context(args: &[String]) -> CompletionContext {
+ // args format: ["wt", "switch", "partial"]
+ // or: ["wt", "switch", "--create", "new", "--base", "partial"]
+
+ if args.len() < 2 {
+ return CompletionContext::Unknown;
+ }
+
+ let subcommand = &args[1];
+
+ match subcommand.as_str() {
+ "switch" => {
+ // Check if we're completing --base flag value
+ if args.len() >= 3 {
+ for i in 2..args.len() - 1 {
+ if args[i] == "--base" || args[i] == "-b" {
+ // We're completing the value after --base
+ return CompletionContext::BaseFlag;
+ }
+ }
+ }
+ CompletionContext::SwitchBranch
+ }
+ "push" => CompletionContext::PushTarget,
+ "merge" => CompletionContext::MergeTarget,
+ _ => CompletionContext::Unknown,
+ }
+}
+
+fn handle_complete(args: Vec<String>) -> Result<(), GitError> {
+ let context = parse_completion_context(&args);
+
+ match context {
+ CompletionContext::SwitchBranch => {
+ // Complete with available branches (excluding those with worktrees)
+ let branches = get_available_branches().unwrap_or_else(|e| {
+ if std::env::var("WT_DEBUG_COMPLETION").is_ok() {
+ eprintln!("completion error: {}", e);
+ }
+ Vec::new()
+ });
+ for branch in branches {
+ println!("{}", branch);
+ }
+ }
+ CompletionContext::PushTarget
+ | CompletionContext::MergeTarget
+ | CompletionContext::BaseFlag => {
+ // Complete with all branches
+ let branches = get_all_branches().unwrap_or_else(|e| {
+ if std::env::var("WT_DEBUG_COMPLETION").is_ok() {
+ eprintln!("completion error: {}", e);
+ }
+ Vec::new()
+ });
+ for branch in branches {
+ println!("{}", branch);
+ }
+ }
+ CompletionContext::Unknown => {
+ // No completions
+ }
+ }
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_parse_completion_context_switch() {
+ let args = vec!["wt".to_string(), "switch".to_string(), "feat".to_string()];
+ assert_eq!(
+ parse_completion_context(&args),
+ CompletionContext::SwitchBranch
+ );
+ }
+
+ #[test]
+ fn test_parse_completion_context_push() {
+ let args = vec!["wt".to_string(), "push".to_string(), "ma".to_string()];
+ assert_eq!(
+ parse_completion_context(&args),
+ CompletionContext::PushTarget
+ );
+ }
+
+ #[test]
+ fn test_parse_completion_context_merge() {
+ let args = vec!["wt".to_string(), "merge".to_string(), "de".to_string()];
+ assert_eq!(
+ parse_completion_context(&args),
+ CompletionContext::MergeTarget
+ );
+ }
+
+ #[test]
+ fn test_parse_completion_context_base_flag() {
+ let args = vec![
+ "wt".to_string(),
+ "switch".to_string(),
+ "--create".to_string(),
+ "new".to_string(),
+ "--base".to_string(),
+ "dev".to_string(),
+ ];
+ assert_eq!(parse_completion_context(&args), CompletionContext::BaseFlag);
+ }
+
+ #[test]
+ fn test_parse_completion_context_unknown() {
+ let args = vec!["wt".to_string()];
+ assert_eq!(parse_completion_context(&args), CompletionContext::Unknown);
+ }
+}
diff --git a/templates/bash.sh b/templates/bash.sh
index 6e55223e4..a0b0d94db 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -51,3 +51,15 @@ else
PROMPT_COMMAND="${PROMPT_COMMAND}; _wt_prompt_hook"
fi
{% endif %}
+
+# Dynamic completion function
+_{{ cmd_prefix }}_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+
+ # Call wt complete with current command line
+ local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+}
+
+# Register dynamic completion
+complete -F _{{ cmd_prefix }}_complete {{ cmd_prefix }}
diff --git a/templates/fish.fish b/templates/fish.fish
index 4355b76e5..1fc7322ad 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -40,3 +40,16 @@ function _wt_prompt_hook --on-event fish_prompt
command wt hook prompt 2>/dev/null; or true
end
{% endif %}
+
+# Dynamic completion function
+function __{{ cmd_prefix }}_complete
+ # Call wt complete with current command line
+ set -l cmd (commandline -opc)
+ command wt complete $cmd 2>/dev/null
+end
+
+# Register dynamic completions
+complete -c {{ cmd_prefix }} -n '__fish_seen_subcommand_from switch' -f -a '(__{{ cmd_prefix }}_complete)' -d 'Branch'
+complete -c {{ cmd_prefix }} -n '__fish_seen_subcommand_from push' -f -a '(__{{ cmd_prefix }}_complete)' -d 'Target branch'
+complete -c {{ cmd_prefix }} -n '__fish_seen_subcommand_from merge' -f -a '(__{{ cmd_prefix }}_complete)' -d 'Target branch'
+complete -c {{ cmd_prefix }} -l base -f -a '(__{{ cmd_prefix }}_complete)' -d 'Base branch'
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
new file mode 100644
index 000000000..d3d0efbae
--- /dev/null
+++ b/tests/integration_tests/completion.rs
@@ -0,0 +1,209 @@
+use crate::common::TestRepo;
+use assert_cmd::Command;
+use std::process::Command as StdCommand;
+
+#[test]
+fn test_completion_command_static() {
+ // Test that static completion generates valid Fish script
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd.arg("completion").arg("fish").output().unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Check for expected Fish completion functions
+ assert!(stdout.contains("__fish_wt_needs_command"));
+ assert!(stdout.contains("complete -c wt"));
+ assert!(stdout.contains("switch"));
+ assert!(stdout.contains("finish"));
+ assert!(stdout.contains("push"));
+ assert!(stdout.contains("merge"));
+}
+
+#[test]
+fn test_completion_command_bash() {
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd.arg("completion").arg("bash").output().unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Check for Bash completion structure
+ assert!(stdout.contains("_wt()"));
+ assert!(stdout.contains("COMPREPLY"));
+ assert!(stdout.contains("complete"));
+}
+
+#[test]
+fn test_complete_switch_shows_branches() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ // Create some branches using git
+ StdCommand::new("git")
+ .args(&["branch", "feature/new"])
+ .current_dir(temp.root_path())
+ .output()
+ .unwrap();
+
+ StdCommand::new("git")
+ .args(&["branch", "hotfix/bug"])
+ .current_dir(temp.root_path())
+ .output()
+ .unwrap();
+
+ // Test completion for switch command
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd
+ .current_dir(temp.root_path())
+ .args(&["complete", "wt", "switch", ""])
+ .output()
+ .unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let branches: Vec<&str> = stdout.lines().collect();
+
+ // Should include both branches (no worktrees created yet)
+ assert!(branches.iter().any(|b| b.contains("feature/new")));
+ assert!(branches.iter().any(|b| b.contains("hotfix/bug")));
+}
+
+#[test]
+fn test_complete_switch_excludes_branches_with_worktrees() {
+ let mut temp = TestRepo::new();
+ temp.commit("initial");
+
+ // Create worktree (this creates a new branch "feature/new")
+ temp.add_worktree("feature-worktree", "feature/new");
+
+ // Create another branch without worktree
+ StdCommand::new("git")
+ .args(&["branch", "hotfix/bug"])
+ .current_dir(temp.root_path())
+ .output()
+ .unwrap();
+
+ // Test completion
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd
+ .current_dir(temp.root_path())
+ .args(&["complete", "wt", "switch", ""])
+ .output()
+ .unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let branches: Vec<&str> = stdout.lines().collect();
+
+ // Should NOT include feature/new (has worktree)
+ assert!(!branches.iter().any(|b| b.contains("feature/new")));
+ // Should include hotfix/bug (no worktree)
+ assert!(branches.iter().any(|b| b.contains("hotfix/bug")));
+}
+
+#[test]
+fn test_complete_push_shows_all_branches() {
+ let mut temp = TestRepo::new();
+ temp.commit("initial");
+
+ // Create worktree (creates "feature/new" branch)
+ temp.add_worktree("feature-worktree", "feature/new");
+
+ // Create another branch without worktree
+ StdCommand::new("git")
+ .args(&["branch", "hotfix/bug"])
+ .current_dir(temp.root_path())
+ .output()
+ .unwrap();
+
+ // Test completion for push (should show ALL branches, including those with worktrees)
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd
+ .current_dir(temp.root_path())
+ .args(&["complete", "wt", "push", ""])
+ .output()
+ .unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let branches: Vec<&str> = stdout.lines().collect();
+
+ // Should include both branches (push shows all)
+ assert!(branches.iter().any(|b| b.contains("feature/new")));
+ assert!(branches.iter().any(|b| b.contains("hotfix/bug")));
+}
+
+#[test]
+fn test_complete_base_flag_shows_all_branches() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ // Create branches
+ StdCommand::new("git")
+ .args(&["branch", "develop"])
+ .current_dir(temp.root_path())
+ .output()
+ .unwrap();
+
+ StdCommand::new("git")
+ .args(&["branch", "feature/existing"])
+ .current_dir(temp.root_path())
+ .output()
+ .unwrap();
+
+ // Test completion for --base flag
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd
+ .current_dir(temp.root_path())
+ .args(&[
+ "complete",
+ "wt",
+ "switch",
+ "--create",
+ "new-branch",
+ "--base",
+ "",
+ ])
+ .output()
+ .unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let branches: Vec<&str> = stdout.lines().collect();
+
+ // Should show all branches as potential base
+ assert!(branches.iter().any(|b| b.contains("develop")));
+ assert!(branches.iter().any(|b| b.contains("feature/existing")));
+}
+
+#[test]
+fn test_complete_outside_git_repo_returns_empty() {
+ let temp = tempfile::tempdir().unwrap();
+
+ // Test completion outside a git repo
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd
+ .current_dir(temp.path())
+ .args(&["complete", "wt", "switch", ""])
+ .output()
+ .unwrap();
+
+ // Should succeed but return no branches
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert_eq!(stdout.trim(), "");
+}
+
+#[test]
+fn test_init_fish_includes_no_file_flag() {
+ // Test that fish init includes -f flag to disable file completion
+ let mut cmd = Command::cargo_bin("wt").unwrap();
+ let output = cmd.arg("init").arg("fish").output().unwrap();
+
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ // Check that completions include -f flag
+ assert!(stdout.contains("-f -a '(__wt_complete)'"));
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 09824466d..71fdecab6 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -1,3 +1,4 @@
+pub mod completion;
pub mod default_branch;
pub mod directives;
pub mod e2e_shell;
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 22e118632..84a39d7b8 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -59,4 +59,16 @@ wt() {
+# Dynamic completion function
+_wt_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+
+ # Call wt complete with current command line
+ local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+}
+
+# Register dynamic completion
+complete -F _wt_complete wt
+
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap b/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap
index a7fa4d0c5..37fbe2f7f 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap
@@ -76,4 +76,16 @@ else
fi
+# Dynamic completion function
+_wt_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+
+ # Call wt complete with current command line
+ local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+}
+
+# Register dynamic completion
+complete -F _wt_complete wt
+
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
index 060601fd7..4603bc2ff 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
@@ -61,4 +61,16 @@ wt() {
+# Dynamic completion function
+_wt_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+
+ # Call wt complete with current command line
+ local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+}
+
+# Register dynamic completion
+complete -F _wt_complete wt
+
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap b/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap
index 1ca7f4e1c..7ee57dd24 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap
@@ -74,4 +74,16 @@ else
fi
+# Dynamic completion function
+_wt_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+
+ # Call wt complete with current command line
+ local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+}
+
+# Register dynamic completion
+complete -F _wt_complete wt
+
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 764e189e8..6a7d00bab 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -55,4 +55,17 @@ end
+# Dynamic completion function
+function __wt_complete
+ # Call wt complete with current command line
+ set -l cmd (commandline -opc)
+ command wt complete $cmd 2>/dev/null
+end
+
+# Register dynamic completions
+complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch'
+complete -c wt -n '__fish_seen_subcommand_from push' -f -a '(__wt_complete)' -d 'Target branch'
+complete -c wt -n '__fish_seen_subcommand_from merge' -f -a '(__wt_complete)' -d 'Target branch'
+complete -c wt -l base -f -a '(__wt_complete)' -d 'Base branch'
+
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap b/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap
index 43f00a8b8..46825b106 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap
@@ -63,4 +63,17 @@ function _wt_prompt_hook --on-event fish_prompt
end
+# Dynamic completion function
+function __wt_complete
+ # Call wt complete with current command line
+ set -l cmd (commandline -opc)
+ command wt complete $cmd 2>/dev/null
+end
+
+# Register dynamic completions
+complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch'
+complete -c wt -n '__fish_seen_subcommand_from push' -f -a '(__wt_complete)' -d 'Target branch'
+complete -c wt -n '__fish_seen_subcommand_from merge' -f -a '(__wt_complete)' -d 'Target branch'
+complete -c wt -l base -f -a '(__wt_complete)' -d 'Base branch'
+
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 197794686..9cbb4f7a9 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -59,4 +59,16 @@ wt() {
+# Dynamic completion function
+_wt_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
+
+ # Call wt complete with current command line
+ local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))
+}
+
+# Register dynamic completion
+complete -F _wt_complete wt
+
----- stderr -----