Skip to content

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

Remove `config shell completions` subcommand

Maximilian Roos72a00e462923
diff --git a/src/cli.rs b/src/cli.rs
index 51063388d..bc7b78e4c 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -225,24 +225,6 @@ 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 manual shell setup:
-
-```console
-wt config shell completions fish > ~/.config/fish/completions/wt.fish
-```
-
-Note: Bash and Zsh completions are automatically included via
-`wt config shell install` using inline lazy loading. This command
-is primarily for Fish or manual configuration."#)]
- Completions {
- /// Shell to generate completions for
- #[arg(value_enum)]
- shell: Shell,
- },
}
#[derive(Subcommand)]
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 651ddbaeb..94545b5a3 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -6,7 +6,7 @@ use worktrunk::path::format_path_for_display;
use worktrunk::shell::Shell;
use worktrunk::styling::{AnstyleStyle, CYAN, GREEN, GREEN_BOLD, format_toml};
-use super::configure_shell::{ConfigAction, process_shell_completions, scan_shell_configs};
+use super::configure_shell::{ConfigAction, scan_shell_configs};
use crate::output;
/// Example configuration file content (displayed in help with values uncommented)
@@ -185,22 +185,20 @@ fn display_shell_status() -> anyhow::Result<()> {
}
};
- // Get completion status for fish (bash/zsh completions are inline in init script)
- let shells: Vec<_> = scan_result.configured.iter().map(|r| r.shell).collect();
- let completion_results = process_shell_completions(&shells, true).unwrap_or_default();
-
let mut any_configured = false;
let mut any_not_configured = false;
// Show configured and not-configured shells (matching `config shell install` format exactly)
+ // Bash/Zsh: inline completions, show "shell extension & completions"
+ // Fish: separate completion file, show "shell extension" for conf.d and "completions" for completions/
for result in &scan_result.configured {
let shell = result.shell;
let path = format_path_for_display(&result.path);
- // Match the format from `wt config shell install`
- let what = if matches!(shell, Shell::Bash | Shell::Zsh) {
- "shell extension & completions"
- } else {
+ // Fish has separate completion file; bash/zsh have inline completions
+ let what = if matches!(shell, Shell::Fish) {
"shell extension"
+ } else {
+ "shell extension & completions"
};
match result.action {
@@ -221,6 +219,23 @@ fn display_shell_status() -> anyhow::Result<()> {
None,
))?;
}
+
+ // For fish, check completions file separately
+ if matches!(shell, Shell::Fish)
+ && let Ok(completion_path) = shell.completion_path()
+ {
+ let completion_display = format_path_for_display(&completion_path);
+ if completion_path.exists() {
+ output::info(format!(
+ "Already configured completions for {bold}{shell}{bold:#} @ {completion_display}"
+ ))?;
+ } else {
+ any_not_configured = true;
+ output::hint(format!(
+ "Not configured completions for {bold}{shell}{bold:#} @ {completion_display}"
+ ))?;
+ }
+ }
}
ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
any_not_configured = true;
@@ -232,28 +247,6 @@ fn display_shell_status() -> anyhow::Result<()> {
}
}
- // Show fish completions separately (fish has separate completion files)
- for result in &completion_results {
- let shell = result.shell;
- let path = format_path_for_display(&result.path);
-
- match result.action {
- ConfigAction::AlreadyExists => {
- any_configured = true;
- output::info(format!(
- "Already configured completions for {bold}{shell}{bold:#} @ {path}"
- ))?;
- }
- ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
- any_not_configured = true;
- output::hint(format!(
- "Not configured completions for {bold}{shell}{bold:#} @ {path}"
- ))?;
- }
- _ => {}
- }
- }
-
// Show skipped (not installed) shells
for (shell, path) in &scan_result.skipped {
let path = format_path_for_display(path);
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 5744f0516..ef56e01fa 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -5,8 +5,6 @@ use worktrunk::path::format_path_for_display;
use worktrunk::shell::{self, 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,
@@ -489,11 +487,11 @@ fn prompt_for_confirmation(
let shell = result.shell;
let path = format_path_for_display(&result.path);
- // For bash/zsh, completions are inline in the init script
- let what = if matches!(shell, Shell::Bash | Shell::Zsh) {
- "shell extension & completions"
- } else {
+ // Bash/Zsh: inline completions; Fish: separate completion file
+ let what = if matches!(shell, Shell::Fish) {
"shell extension"
+ } else {
+ "shell extension & completions"
};
eprintln!(
@@ -522,14 +520,8 @@ fn prompt_for_confirmation(
result.action.description(),
);
- // Show what will be created (dynamic completions generated by clap)
- eprint!(
- "{}",
- format_bash_with_gutter(
- &format!("# Dynamic completions generated by: wt config shell completions {shell}"),
- ""
- )
- );
+ // Show the completion content that will be written
+ eprint!("{}", format_bash_with_gutter(FISH_COMPLETION.trim(), ""));
eprintln!(); // Blank line after
}
@@ -557,11 +549,16 @@ fn prompt_yes_no() -> Result<bool, String> {
Ok(response == "y" || response == "yes")
}
+/// Fish completion content - uses $WORKTRUNK_BIN to bypass shell wrapper
+const FISH_COMPLETION: &str = r#"# worktrunk completions for fish - uses $WORKTRUNK_BIN to bypass shell wrapper
+complete --keep-order --exclusive --command wt --arguments "(COMPLETE=fish \$WORKTRUNK_BIN -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"
+"#;
+
/// Process shell completions - either preview or write based on dry_run flag
///
-/// Note: Bash and Zsh completions are handled via lazy loading in the init script,
-/// so we only write static completion files for Fish (which uses native lazy loading
-/// from ~/.config/fish/completions/).
+/// Note: Bash and Zsh use inline lazy completions in the init script.
+/// Fish uses a separate completion file at ~/.config/fish/completions/wt.fish
+/// that calls $WORKTRUNK_BIN directly to bypass the shell wrapper.
pub fn process_shell_completions(
shells: &[Shell],
dry_run: bool,
@@ -569,20 +566,18 @@ pub fn process_shell_completions(
let mut results = Vec::new();
for &shell in shells {
- // Skip bash/zsh - completions are handled via lazy loading in the init script
- if matches!(shell, Shell::Bash | Shell::Zsh) {
+ // Only fish has a separate completion file
+ if shell != Shell::Fish {
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)?;
+ let completion_path = shell.completion_path().map_err(|e| e.to_string())?;
+ // Check if completions already exist with correct content
if completion_path.exists() {
- let existing = fs::read_to_string(&completion_path).unwrap_or_default();
- if existing == completion_content {
+ let existing = fs::read_to_string(&completion_path)
+ .map_err(|e| format!("Failed to read {}: {}", completion_path.display(), e))?;
+ if existing == FISH_COMPLETION {
results.push(CompletionResult {
shell,
path: completion_path,
@@ -592,59 +587,40 @@ pub fn process_shell_completions(
}
}
- // Determine action based on dry_run and whether file exists
- let action = if dry_run {
- if completion_path.exists() {
+ if dry_run {
+ let action = 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
- )
- })?;
- }
+ };
+ results.push(CompletionResult {
+ shell,
+ path: completion_path,
+ action,
+ });
+ continue;
+ }
- // Write completion file
- fs::write(&completion_path, &completion_content).map_err(|e| {
- format!(
- "Failed to write {}: {}",
- format_path_for_display(&completion_path),
- e
- )
- })?;
+ // Create parent directory if needed
+ if let Some(parent) = completion_path.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?;
}
+ // Write the completion file
+ fs::write(&completion_path, FISH_COMPLETION)
+ .map_err(|e| format!("Failed to write {}: {}", completion_path.display(), e))?;
+
results.push(CompletionResult {
shell,
path: completion_path,
- action,
+ action: ConfigAction::Created,
});
}
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();
@@ -693,7 +669,6 @@ fn scan_for_uninstall(
let mut results = Vec::new();
let mut not_found = Vec::new();
- let mut completion_not_found = Vec::new();
for &shell in &shells {
let paths = shell
@@ -755,18 +730,17 @@ fn scan_for_uninstall(
}
}
- // Also remove completion files
+ // Fish has a separate completion file that needs to be removed
let mut completion_results = Vec::new();
+ let mut completion_not_found = Vec::new();
for &shell in &shells {
- // Skip bash/zsh - completions are handled via lazy loading in the init script
- if matches!(shell, Shell::Bash | Shell::Zsh) {
+ if shell != Shell::Fish {
continue;
}
- let completion_path = shell
- .completion_path()
- .map_err(|e| format!("Failed to get completion path: {}", e))?;
+ let completion_path = shell.completion_path().map_err(|e| e.to_string())?;
+
if completion_path.exists() {
if dry_run {
completion_results.push(CompletionUninstallResult {
@@ -776,11 +750,7 @@ fn scan_for_uninstall(
});
} else {
fs::remove_file(&completion_path).map_err(|e| {
- format!(
- "Failed to remove {}: {}",
- format_path_for_display(&completion_path),
- e
- )
+ format!("Failed to remove {}: {}", completion_path.display(), e)
})?;
completion_results.push(CompletionUninstallResult {
shell,
@@ -870,11 +840,11 @@ fn prompt_for_uninstall_confirmation(
let bold = Style::new().bold();
let shell = result.shell;
let path = format_path_for_display(&result.path);
- // For bash/zsh, completions are inline in the init script
- let what = if matches!(shell, Shell::Bash | Shell::Zsh) {
- "shell extension & completions"
- } else {
+ // Bash/Zsh: inline completions; Fish: separate completion file
+ let what = if matches!(shell, Shell::Fish) {
"shell extension"
+ } else {
+ "shell extension & completions"
};
eprintln!(
diff --git a/src/completion.rs b/src/completion.rs
index 52922a991..635c6c5a4 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -1,15 +1,13 @@
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, EnvCompleter};
+use clap_complete::env::CompleteEnv;
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 {
@@ -29,33 +27,6 @@ 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<()> {
- // Use "wt" instead of absolute path - the shell will find it via PATH.
- // This makes completions portable (work regardless of where wt is installed).
- let completer = "wt";
- 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 b23a27f44..82964d96e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -464,11 +464,6 @@ fn main() {
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(),
diff --git a/src/shell.rs b/src/shell.rs
index 885c61bdb..17a081da4 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -55,11 +55,10 @@ impl Shell {
/// Returns the path to the native completion directory for this shell
///
- /// Note: Only Fish uses static completion files. Bash and Zsh use inline
- /// lazy loading in the init script, so these paths are for reference only:
- /// - Bash: `~/.local/share/bash-completion/completions/` (not used by install)
- /// - Zsh: `~/.zfunc/` (not used by install)
- /// - Fish: `~/.config/fish/completions/` (used by install)
+ /// Note: Bash and Zsh use inline lazy completions in the init script.
+ /// Only Fish uses a separate completion file at ~/.config/fish/completions/wt.fish
+ /// (installed by `wt config shell install`) that uses $WORKTRUNK_BIN to bypass
+ /// the shell function wrapper.
pub fn completion_path(&self) -> Result<PathBuf, std::io::Error> {
let home = home_dir()?;
@@ -210,7 +209,7 @@ impl ShellInit {
pub fn generate(&self) -> Result<String, askama::Error> {
match self.shell {
Shell::Bash => {
- let posix_shim = PosixDirectivesTemplate { cmd_prefix: "wt" }.render()?;
+ let posix_shim = PosixDirectivesTemplate {}.render()?;
let template = BashTemplate {
shell_name: self.shell.to_string(),
cmd_prefix: "wt",
@@ -219,7 +218,7 @@ impl ShellInit {
template.render()
}
Shell::Zsh => {
- let posix_shim = PosixDirectivesTemplate { cmd_prefix: "wt" }.render()?;
+ let posix_shim = PosixDirectivesTemplate {}.render()?;
let template = ZshTemplate {
cmd_prefix: "wt",
posix_shim: &posix_shim,
@@ -237,9 +236,7 @@ impl ShellInit {
/// POSIX directive shim template (shared by bash, zsh, oil)
#[derive(Template)]
#[template(path = "posix_directives.sh", escape = "none")]
-struct PosixDirectivesTemplate<'a> {
- cmd_prefix: &'a str,
-}
+struct PosixDirectivesTemplate {}
/// Bash shell template
#[derive(Template)]
diff --git a/templates/bash.sh b/templates/bash.sh
index 67cbaa3f0..7b553d930 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -2,23 +2,21 @@
# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)
if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Use WORKTRUNK_BIN if set, otherwise resolve binary path
- # Must resolve BEFORE defining shell function, so lazy completion can call binary directly
- # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/{{ cmd_prefix }}
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v {{ cmd_prefix }})}"
+ # Resolve binary path once at init. WORKTRUNK_BIN can override (for testing dev builds).
+ export WORKTRUNK_BIN="${WORKTRUNK_BIN:-$(command -v {{ cmd_prefix }})}"
{{ posix_shim }}
# Override {{ cmd_prefix }} command to add --internal flag
{{ cmd_prefix }}() {
- # Initialize _WORKTRUNK_CMD if not set (e.g., after shell snapshot restore)
- if [[ -z "$_WORKTRUNK_CMD" ]]; then
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v {{ cmd_prefix }})}"
+ # Re-resolve if unset (e.g., after shell snapshot restore)
+ if [[ -z "$WORKTRUNK_BIN" ]]; then
+ export WORKTRUNK_BIN="$(command -v {{ cmd_prefix }})"
fi
local use_source=false
local args=()
- local saved_cmd="$_WORKTRUNK_CMD"
+ local saved_bin="$WORKTRUNK_BIN"
# Check for --source flag and strip it
for arg in "$@"; do
@@ -32,10 +30,9 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
# If --source was specified, build and use local debug binary
if [[ "$use_source" == true ]]; then
if ! cargo build --quiet; then
- _WORKTRUNK_CMD="$saved_cmd"
return 1
fi
- _WORKTRUNK_CMD="./target/debug/{{ cmd_prefix }}"
+ export WORKTRUNK_BIN="./target/debug/{{ cmd_prefix }}"
fi
# Force colors if stderr is a TTY (directive mode outputs to stderr)
@@ -49,7 +46,7 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
# Restore original command
local result=$?
- _WORKTRUNK_CMD="$saved_cmd"
+ export WORKTRUNK_BIN="$saved_bin"
return $result
}
@@ -57,7 +54,7 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
_{{ cmd_prefix }}_lazy_complete() {
# Generate completions function once (check if clap's function exists)
if ! declare -F _clap_complete_{{ cmd_prefix }} >/dev/null; then
- eval "$(COMPLETE=bash "$_WORKTRUNK_CMD" 2>/dev/null)" || return
+ eval "$(COMPLETE=bash "$WORKTRUNK_BIN" 2>/dev/null)" || return
fi
_clap_complete_{{ cmd_prefix }} "$@"
}
diff --git a/templates/fish.fish b/templates/fish.fish
index c1fd07024..5e087831b 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -2,16 +2,17 @@
# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)
if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN
+ # Resolve binary path once at init. WORKTRUNK_BIN can override (for testing dev builds).
+ if not set -q WORKTRUNK_BIN
+ set -gx WORKTRUNK_BIN (type -p {{ cmd_prefix }})
+ end
+
# Helper function to run wt and eval the output script
# stderr streams to terminal for real-time feedback, stdout is captured as shell script
- #
- # Set WORKTRUNK_BIN to test development builds: set -x WORKTRUNK_BIN ./target/debug/wt
function wt_exec
- set -l cmd (if set -q WORKTRUNK_BIN; echo $WORKTRUNK_BIN; else; echo {{ cmd_prefix }}; end)
-
# Capture stdout (shell script), let stderr flow to terminal
# Use string collect to join lines into a single string (fish splits on newlines by default)
- set -l script (command $cmd $argv 2>&2 | string collect)
+ set -l script (command $WORKTRUNK_BIN $argv 2>&2 | string collect)
set -l exit_code $pipestatus[1]
# Eval the script (cd, exec command, etc.) even on failure
@@ -31,6 +32,7 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN
function {{ cmd_prefix }}
set -l use_source false
set -l args
+ set -l saved_bin $WORKTRUNK_BIN
# Check for --source flag and strip it
for arg in $argv
@@ -46,7 +48,7 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN
if not cargo build --quiet
return 1
end
- set -lx WORKTRUNK_BIN ./target/debug/{{ cmd_prefix }}
+ set -gx WORKTRUNK_BIN ./target/debug/{{ cmd_prefix }}
end
# Force colors if stderr is a TTY (directive mode outputs to stderr)
@@ -59,8 +61,12 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN
# Always use --internal mode for directive support
wt_exec --internal $args
+
+ # Restore original command
+ set -l result $status
+ set -gx WORKTRUNK_BIN $saved_bin
+ return $result
end
- # Completions are loaded from ~/.config/fish/completions/wt.fish
- # Install with: wt config shell install
+ # Completions are in ~/.config/fish/completions/wt.fish (installed by `wt config shell install`)
end
diff --git a/templates/posix_directives.sh b/templates/posix_directives.sh
index c770a0da4..7ddcfaf57 100644
--- a/templates/posix_directives.sh
+++ b/templates/posix_directives.sh
@@ -5,14 +5,12 @@
#
# This pattern (stderr for logs, stdout for script) is proven by direnv.
# No FIFOs, no background processes, no job control suppression needed.
-#
-# Set WORKTRUNK_BIN to test development builds: WORKTRUNK_BIN=./target/debug/wt
wt_exec() {
local script exit_code=0
# Run wt with stderr attached to terminal (2>&2)
# Capture stdout (the shell script) into $script
- script="$(command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" "$@" 2>&2)" || exit_code=$?
+ script="$(command "$WORKTRUNK_BIN" "$@" 2>&2)" || exit_code=$?
# Eval the script (cd, exec command, etc.) even on failure
# This ensures cd happens before returning the error code
diff --git a/templates/zsh.zsh b/templates/zsh.zsh
index 991e6f48a..8d9c16c47 100644
--- a/templates/zsh.zsh
+++ b/templates/zsh.zsh
@@ -5,23 +5,21 @@
# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)
if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Use WORKTRUNK_BIN if set, otherwise resolve binary path
- # Must resolve BEFORE defining shell function, so lazy completion can call binary directly
- # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/{{ cmd_prefix }}
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v {{ cmd_prefix }})}"
+ # Resolve binary path once at init. WORKTRUNK_BIN can override (for testing dev builds).
+ export WORKTRUNK_BIN="${WORKTRUNK_BIN:-$(command -v {{ cmd_prefix }})}"
{{ posix_shim }}
# Override {{ cmd_prefix }} command to add --internal flag
{{ cmd_prefix }}() {
- # Initialize _WORKTRUNK_CMD if not set (e.g., after shell snapshot restore)
- if [[ -z "$_WORKTRUNK_CMD" ]]; then
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v {{ cmd_prefix }})}"
+ # Re-resolve if unset (e.g., after shell snapshot restore)
+ if [[ -z "$WORKTRUNK_BIN" ]]; then
+ export WORKTRUNK_BIN="$(command -v {{ cmd_prefix }})"
fi
local use_source=false
local -a args
- local saved_cmd="$_WORKTRUNK_CMD"
+ local saved_bin="$WORKTRUNK_BIN"
# Check for --source flag and strip it
for arg in "$@"; do
@@ -35,10 +33,9 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
# If --source was specified, build and use local debug binary
if [[ "$use_source" == true ]]; then
if ! cargo build --quiet; then
- _WORKTRUNK_CMD="$saved_cmd"
return 1
fi
- _WORKTRUNK_CMD="./target/debug/{{ cmd_prefix }}"
+ export WORKTRUNK_BIN="./target/debug/{{ cmd_prefix }}"
fi
# Force colors if stderr is a TTY (directive mode outputs to stderr)
@@ -52,7 +49,7 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
# Restore original command
local result=$?
- _WORKTRUNK_CMD="$saved_cmd"
+ export WORKTRUNK_BIN="$saved_bin"
return $result
}
@@ -60,7 +57,7 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];
_{{ cmd_prefix }}_lazy_complete() {
# Generate completions function once (check if clap's function exists)
if ! (( $+functions[_clap_dynamic_completer_{{ cmd_prefix }}] )); then
- eval "$(COMPLETE=zsh "$_WORKTRUNK_CMD" 2>/dev/null)" || return
+ eval "$(COMPLETE=zsh "$WORKTRUNK_BIN" 2>/dev/null)" || return
fi
_clap_dynamic_completer_{{ cmd_prefix }} "$@"
}
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 7ad5655ca..9c5354e97 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_references_completion_location() {
- // Test that fish init references the completion file location
+fn test_init_fish_no_inline_completions() {
+ // Test that fish init does NOT have inline completions (they're in a separate file)
let mut cmd = wt_command();
let output = cmd
.arg("config")
@@ -308,14 +308,15 @@ fn test_init_fish_references_completion_location() {
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
- // Verify completions are loaded from native fish completions directory
+ // Verify completions are NOT inline - they go to ~/.config/fish/completions/wt.fish
assert!(
- stdout.contains("~/.config/fish/completions/wt.fish"),
- "Fish template should reference native completion location"
+ !stdout.contains("complete --keep-order --exclusive --command wt --arguments"),
+ "Fish init should NOT have inline completions (they go to separate file)"
);
+ // But should reference where completions are
assert!(
- stdout.contains("wt config shell install"),
- "Fish template should mention install command"
+ stdout.contains("Completions are in"),
+ "Fish init should mention where completions are"
);
}
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
index e839e816d..adadffd06 100644
--- a/tests/integration_tests/configure_shell.rs
+++ b/tests/integration_tests/configure_shell.rs
@@ -181,10 +181,10 @@ fn test_configure_shell_fish() {
);
}
-/// Test `wt config shell install` when extension exists but completions don't (Fish-specific)
-/// Regression test: previously showed "All shells already configured" even when completions were added
+/// Test `wt config shell install` when fish extension already exists
+/// Fish completions are now inline in the init script, so no separate file is needed
#[test]
-fn test_configure_shell_fish_completions_only() {
+fn test_configure_shell_fish_extension_exists() {
let repo = TestRepo::new();
let temp_home = TempDir::new().unwrap();
@@ -198,8 +198,6 @@ fn test_configure_shell_fish_completions_only() {
)
.unwrap();
- // But NO completions file exists
-
let settings = setup_home_snapshot_settings(&temp_home);
settings.bind(|| {
let mut cmd = wt_command();
@@ -213,8 +211,8 @@ fn test_configure_shell_fish_completions_only() {
.arg("--force")
.current_dir(repo.root_path());
- // Should say "Configured 1 shell" because completions were added,
- // NOT "All shells already configured"
+ // Fish completions are inline in the init script, so when extension exists,
+ // it should say "All shells already configured"
assert_cmd_snapshot!(cmd, @r"
success: true
exit_code: 0
@@ -228,12 +226,17 @@ fn test_configure_shell_fish_completions_only() {
");
});
- // Verify the completions file was created
+ // Fish completions should be in a separate file using $WORKTRUNK_BIN
let completions_file = temp_home.path().join(".config/fish/completions/wt.fish");
assert!(
completions_file.exists(),
"Fish completions file should be created"
);
+ let contents = std::fs::read_to_string(&completions_file).unwrap();
+ assert!(
+ contents.contains("$WORKTRUNK_BIN"),
+ "Fish completions should use $WORKTRUNK_BIN to bypass shell wrapper"
+ );
}
/// Test `wt config shell install` when no config files exist
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 0c4251c04..d89417558 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -176,34 +176,22 @@ fn generate_wrapper(repo: &TestRepo, shell: &str) -> String {
}
/// Generate shell completions script for the given shell
-fn generate_completions(repo: &TestRepo, shell: &str) -> String {
- let wt_bin = get_cargo_bin("wt");
-
- let mut cmd = Command::new(&wt_bin);
- cmd.arg("config").arg("shell").arg("completions").arg(shell);
-
- // Configure environment
- repo.clean_cli_env(&mut cmd);
-
- let output = cmd
- .output()
- .unwrap_or_else(|_| panic!("Failed to run wt config shell completions {}", shell));
-
- if !output.status.success() {
- panic!(
- "wt config shell completions {} failed with exit code: {:?}\nOutput:\n{}",
- shell,
- output.status.code(),
- String::from_utf8_lossy(&output.stderr)
- );
+///
+/// Note: Fish completions are custom (use $WORKTRUNK_BIN to bypass shell wrapper).
+/// Bash and Zsh use inline lazy loading in the init script.
+fn generate_completions(_repo: &TestRepo, shell: &str) -> String {
+ match shell {
+ "fish" => {
+ // Fish uses a custom completion that bypasses the shell wrapper
+ r#"# worktrunk completions for fish - uses $WORKTRUNK_BIN to bypass shell wrapper
+complete --keep-order --exclusive --command wt --arguments "(COMPLETE=fish \$WORKTRUNK_BIN -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"
+"#.to_string()
+ }
+ _ => {
+ // Bash and Zsh use inline lazy loading in the init script
+ String::new()
+ }
}
-
- String::from_utf8(output.stdout).unwrap_or_else(|_| {
- panic!(
- "wt config shell completions {} produced invalid UTF-8",
- shell
- )
- })
}
/// Quote a shell argument if it contains special characters
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__select__select_multiple_worktrees.snap b/tests/integration_tests/snapshots/integration__integration_tests__select__select_multiple_worktrees.snap
index 2e143f668..b91675804 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__select__select_multiple_worktrees.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__select__select_multiple_worktrees.snap
@@ -1,5 +1,6 @@
---
source: tests/integration_tests/select.rs
+assertion_line: 268
expression: normalized
---
> [QUERY] │[PREVIEW_HEADER]
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 fcb8b41d0..cf79514de 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_shell.snap
@@ -19,10 +19,9 @@ 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
- completions Generate shell completion script
+ init Generate shell integration code
+ install Write shell integration to config files
+ uninstall Remove shell integration from config files
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 624c80a1a..b8f8cbfe8 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -27,10 +27,8 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Use WORKTRUNK_BIN if set, otherwise resolve binary path
- # Must resolve BEFORE defining shell function, so lazy completion can call binary directly
- # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v wt)}"
+ # Resolve binary path once at init. WORKTRUNK_BIN can override (for testing dev builds).
+ export WORKTRUNK_BIN="${WORKTRUNK_BIN:-$(command -v wt)}"
# Simple shell integration for POSIX shells (bash, zsh).
#
@@ -39,14 +37,12 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
#
# This pattern (stderr for logs, stdout for script) is proven by direnv.
# No FIFOs, no background processes, no job control suppression needed.
-#
-# Set WORKTRUNK_BIN to test development builds: WORKTRUNK_BIN=./target/debug/wt
wt_exec() {
local script exit_code=0
# Run wt with stderr attached to terminal (2>&2)
# Capture stdout (the shell script) into $script
- script="$(command "${WORKTRUNK_BIN:-wt}" "$@" 2>&2)" || exit_code=$?
+ script="$(command "$WORKTRUNK_BIN" "$@" 2>&2)" || exit_code=$?
# Eval the script (cd, exec command, etc.) even on failure
# This ensures cd happens before returning the error code
@@ -63,14 +59,14 @@ wt_exec() {
# Override wt command to add --internal flag
wt() {
- # Initialize _WORKTRUNK_CMD if not set (e.g., after shell snapshot restore)
- if [[ -z "$_WORKTRUNK_CMD" ]]; then
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v wt)}"
+ # Re-resolve if unset (e.g., after shell snapshot restore)
+ if [[ -z "$WORKTRUNK_BIN" ]]; then
+ export WORKTRUNK_BIN="$(command -v wt)"
fi
local use_source=false
local args=()
- local saved_cmd="$_WORKTRUNK_CMD"
+ local saved_bin="$WORKTRUNK_BIN"
# Check for --source flag and strip it
for arg in "$@"; do
@@ -84,10 +80,9 @@ wt_exec() {
# If --source was specified, build and use local debug binary
if [[ "$use_source" == true ]]; then
if ! cargo build --quiet; then
- _WORKTRUNK_CMD="$saved_cmd"
return 1
fi
- _WORKTRUNK_CMD="./target/debug/wt"
+ export WORKTRUNK_BIN="./target/debug/wt"
fi
# Force colors if stderr is a TTY (directive mode outputs to stderr)
@@ -101,7 +96,7 @@ wt_exec() {
# Restore original command
local result=$?
- _WORKTRUNK_CMD="$saved_cmd"
+ export WORKTRUNK_BIN="$saved_bin"
return $result
}
@@ -109,7 +104,7 @@ wt_exec() {
_wt_lazy_complete() {
# Generate completions function once (check if clap's function exists)
if ! declare -F _clap_complete_wt >/dev/null; then
- eval "$(COMPLETE=bash "$_WORKTRUNK_CMD" 2>/dev/null)" || return
+ eval "$(COMPLETE=bash "$WORKTRUNK_BIN" 2>/dev/null)" || return
fi
_clap_complete_wt "$@"
}
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 2fad35714..735e8a9a4 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -27,16 +27,17 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if type -q wt; or set -q WORKTRUNK_BIN
+ # Resolve binary path once at init. WORKTRUNK_BIN can override (for testing dev builds).
+ if not set -q WORKTRUNK_BIN
+ set -gx WORKTRUNK_BIN (type -p wt)
+ end
+
# Helper function to run wt and eval the output script
# stderr streams to terminal for real-time feedback, stdout is captured as shell script
- #
- # Set WORKTRUNK_BIN to test development builds: set -x WORKTRUNK_BIN ./target/debug/wt
function wt_exec
- set -l cmd (if set -q WORKTRUNK_BIN; echo $WORKTRUNK_BIN; else; echo wt; end)
-
# Capture stdout (shell script), let stderr flow to terminal
# Use string collect to join lines into a single string (fish splits on newlines by default)
- set -l script (command $cmd $argv 2>&2 | string collect)
+ set -l script (command $WORKTRUNK_BIN $argv 2>&2 | string collect)
set -l exit_code $pipestatus[1]
# Eval the script (cd, exec command, etc.) even on failure
@@ -56,6 +57,7 @@ if type -q wt; or set -q WORKTRUNK_BIN
function wt
set -l use_source false
set -l args
+ set -l saved_bin $WORKTRUNK_BIN
# Check for --source flag and strip it
for arg in $argv
@@ -71,7 +73,7 @@ if type -q wt; or set -q WORKTRUNK_BIN
if not cargo build --quiet
return 1
end
- set -lx WORKTRUNK_BIN ./target/debug/wt
+ set -gx WORKTRUNK_BIN ./target/debug/wt
end
# Force colors if stderr is a TTY (directive mode outputs to stderr)
@@ -84,10 +86,14 @@ if type -q wt; or set -q WORKTRUNK_BIN
# Always use --internal mode for directive support
wt_exec --internal $args
+
+ # Restore original command
+ set -l result $status
+ set -gx WORKTRUNK_BIN $saved_bin
+ return $result
end
- # Completions are loaded from ~/.config/fish/completions/wt.fish
- # Install with: wt config shell install
+ # Completions are in ~/.config/fish/completions/wt.fish (installed by `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 acaf50281..801c35a7f 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -30,10 +30,8 @@ exit_code: 0
# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)
if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
- # Use WORKTRUNK_BIN if set, otherwise resolve binary path
- # Must resolve BEFORE defining shell function, so lazy completion can call binary directly
- # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v wt)}"
+ # Resolve binary path once at init. WORKTRUNK_BIN can override (for testing dev builds).
+ export WORKTRUNK_BIN="${WORKTRUNK_BIN:-$(command -v wt)}"
# Simple shell integration for POSIX shells (bash, zsh).
#
@@ -42,14 +40,12 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then
#
# This pattern (stderr for logs, stdout for script) is proven by direnv.
# No FIFOs, no background processes, no job control suppression needed.
-#
-# Set WORKTRUNK_BIN to test development builds: WORKTRUNK_BIN=./target/debug/wt
wt_exec() {
local script exit_code=0
# Run wt with stderr attached to terminal (2>&2)
# Capture stdout (the shell script) into $script
- script="$(command "${WORKTRUNK_BIN:-wt}" "$@" 2>&2)" || exit_code=$?
+ script="$(command "$WORKTRUNK_BIN" "$@" 2>&2)" || exit_code=$?
# Eval the script (cd, exec command, etc.) even on failure
# This ensures cd happens before returning the error code
@@ -66,14 +62,14 @@ wt_exec() {
# Override wt command to add --internal flag
wt() {
- # Initialize _WORKTRUNK_CMD if not set (e.g., after shell snapshot restore)
- if [[ -z "$_WORKTRUNK_CMD" ]]; then
- _WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v wt)}"
+ # Re-resolve if unset (e.g., after shell snapshot restore)
+ if [[ -z "$WORKTRUNK_BIN" ]]; then
+ export WORKTRUNK_BIN="$(command -v wt)"
fi
local use_source=false
local -a args
- local saved_cmd="$_WORKTRUNK_CMD"
+ local saved_bin="$WORKTRUNK_BIN"
# Check for --source flag and strip it
for arg in "$@"; do
@@ -87,10 +83,9 @@ wt_exec() {
# If --source was specified, build and use local debug binary
if [[ "$use_source" == true ]]; then
if ! cargo build --quiet; then
- _WORKTRUNK_CMD="$saved_cmd"
return 1
fi
- _WORKTRUNK_CMD="./target/debug/wt"
+ export WORKTRUNK_BIN="./target/debug/wt"
fi
# Force colors if stderr is a TTY (directive mode outputs to stderr)
@@ -104,7 +99,7 @@ wt_exec() {
# Restore original command
local result=$?
- _WORKTRUNK_CMD="$saved_cmd"
+ export WORKTRUNK_BIN="$saved_bin"
return $result
}
@@ -112,7 +107,7 @@ wt_exec() {
_wt_lazy_complete() {
# Generate completions function once (check if clap's function exists)
if ! (( $+functions[_clap_dynamic_completer_wt] )); then
- eval "$(COMPLETE=zsh "$_WORKTRUNK_CMD" 2>/dev/null)" || return
+ eval "$(COMPLETE=zsh "$WORKTRUNK_BIN" 2>/dev/null)" || return
fi
_clap_dynamic_completer_wt "$@"
}