Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add git-wt binary for Windows (#177)
Maximilian Roosd3c9bf650b18
diff --git a/Cargo.toml b/Cargo.tomlindex f4e9c0ac2..423542049 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -32,6 +32,8 @@ syntax-highlighting = ["dep:tree-sitter", "dep:tree-sitter-bash", "dep:tree-sitt# When enabled, run with NEXTEST_NO_INPUT_HANDLER=1 to avoid suspension.# See CLAUDE.md "Nextest Terminal Suspension" section for details.shell-integration-tests = []+# Install git-wt binary so `git wt` works as a git subcommand+git-wt = [][lib]name = "worktrunk"@@ -41,6 +43,15 @@ path = "src/lib.rs"name = "wt"path = "src/main.rs"+# Also install as git-wt so `git wt <command>` works as a git subcommand.+# Primarily useful on Windows where `wt` conflicts with Windows Terminal.+# See: https://github.com/max-sixty/worktrunk/issues/133+# Install with: cargo install worktrunk --features git-wt+[[bin]]+name = "git-wt"+path = "src/main.rs"+required-features = ["git-wt"]+[dependencies]anyhow = "1.0"diff --git a/docs/content/faq.md b/docs/content/faq.mdindex 0b602c70d..59c73c135 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -105,6 +105,23 @@ Arguments resolve by checking the filesystem before git branches:3. Otherwise, look up as branch name4. If the path and branch resolve to different worktrees (e.g., `repo.foo/` tracks branch `bar`), the path takes precedence+## On Windows, `wt` conflicts with Windows Terminal++Windows Terminal uses `wt` as its command-line launcher, so running `wt` invokes Terminal instead of Worktrunk.++As an immediate workaround, install as `git-wt`:++```bash+cargo install worktrunk --features git-wt+git-wt config shell install+```++This creates a `git-wt` shell function with directory changing and completions.++`git wt` (as a git subcommand) also works but cannot change directories since git runs subcommands as subprocesses.++We're considering better solutions — a better name, anyone?+## Does Worktrunk work on Windows?**Experimental.** Core functionality works, but some features are unavailable.diff --git a/src/cli.rs b/src/cli.rsindex 53b7c6004..de428b93d 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -220,6 +220,14 @@ Use `wt config shell install` to add to the shell config automatically."#)]/// Shell to generate code for#[arg(value_enum)]shell: Shell,++ /// Command name for shell integration (defaults to binary name)+ ///+ /// Use this to create shell integration for an alternate command name.+ /// For example, `--cmd=git-wt` creates a `git-wt` shell function+ /// instead of `wt`, useful on Windows where `wt` conflicts with Windows Terminal.+ #[arg(long)]+ cmd: Option<String>,},/// Write shell integration to config files@@ -245,6 +253,14 @@ Use --force to skip confirmation."#)]/// Skip confirmation prompt#[arg(short, long)]force: bool,++ /// Command name for shell integration (defaults to binary name)+ ///+ /// Use this to create shell integration for an alternate command name.+ /// For example, `--cmd=git-wt` creates a `git-wt` shell function+ /// instead of `wt`, useful on Windows where `wt` conflicts with Windows Terminal.+ #[arg(long)]+ cmd: Option<String>,},/// Remove shell integration from config filesdiff --git a/src/commands/config.rs b/src/commands/config.rsindex 44e9151a9..e5f8c9c52 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -312,7 +312,7 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {writeln!(out, "{}", cformat!("<cyan>SHELL INTEGRATION</>"))?;// Use the same detection logic as `wt config shell install`- let scan_result = match scan_shell_configs(None, true) {+ let scan_result = match scan_shell_configs(None, true, "wt") {Ok(r) => r,Err(e) => {writeln!(diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex ee3e6d937..b9feed05d 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -104,13 +104,14 @@ impl ConfigAction {pub fn handle_configure_shell(shell_filter: Option<Shell>,skip_confirmation: bool,+ cmd: String,) -> Result<ScanResult, String> {// First, do a dry-run to see what would be changed- let preview = scan_shell_configs(shell_filter, true)?;+ let preview = scan_shell_configs(shell_filter, true, &cmd)?;// Preview completions that would be writtenlet shells: Vec<_> = preview.configured.iter().map(|r| r.shell).collect();- let completion_preview = process_shell_completions(&shells, true)?;+ let completion_preview = process_shell_completions(&shells, true, &cmd)?;// If nothing to do, return earlyif preview.configured.is_empty() {@@ -140,13 +141,15 @@ pub fn handle_configure_shell(}// Show what will be done and ask for confirmation (unless --force flag is used)- if !skip_confirmation && !prompt_for_confirmation(&preview.configured, &completion_preview)? {+ if !skip_confirmation+ && !prompt_for_confirmation(&preview.configured, &completion_preview, &cmd)?+ {return Err("Cancelled by user".to_string());}// User confirmed (or --force flag was used), now actually apply the changes- let result = scan_shell_configs(shell_filter, false)?;- let completion_results = process_shell_completions(&shells, false)?;+ let result = scan_shell_configs(shell_filter, false, &cmd)?;+ let completion_results = process_shell_completions(&shells, false, &cmd)?;// Zsh completions require compinit to be enabled. Unlike bash/fish, zsh doesn't// enable its completion system by default - users must explicitly call compinit.@@ -213,6 +216,7 @@ pub fn handle_configure_shell(pub fn scan_shell_configs(shell_filter: Option<Shell>,dry_run: bool,+ cmd: &str,) -> Result<ScanResult, String> {#[cfg(windows)]let default_shells = vec![Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];@@ -226,7 +230,7 @@ pub fn scan_shell_configs(for shell in shells {let paths = shell- .config_paths()+ .config_paths_with_prefix(cmd).map_err(|e| format!("Failed to get config paths for {}: {}", shell, e))?;// Find the first existing config file@@ -251,7 +255,7 @@ pub 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()) {+ match configure_shell_file(shell, path, dry_run, shell_filter.is_some(), cmd) {Ok(Some(result)) => results.push(result),Ok(None) => {} // No action neededErr(e) => {@@ -295,12 +299,13 @@ fn configure_shell_file(path: &Path,dry_run: bool,explicit_shell: bool,+ cmd: &str,) -> Result<Option<ConfigureResult>, String> {// Get a summary of the shell integration for display- let integration_summary = shell.integration_summary();+ let integration_summary = shell.integration_summary_with_prefix(cmd);// The actual line we write to the config file- let config_content = shell.config_line();+ let config_content = shell.config_line_with_prefix(cmd);// For Fish, we write to a separate conf.d/ fileif matches!(shell, Shell::Fish) {@@ -427,7 +432,7 @@ fn configure_fish_file(explicit_shell: bool,integration_summary: &str,) -> Result<Option<ConfigureResult>, String> {- // For Fish, we write to conf.d/{cmd_prefix}.fish (separate file)+ // For Fish, we write to conf.d/{cmd}.fish (separate file)// Check if it already exists and has our integrationif path.exists() {@@ -495,6 +500,7 @@ fn configure_fish_file(fn prompt_for_confirmation(results: &[ConfigureResult],completion_results: &[CompletionResult],+ cmd: &str,) -> Result<bool, String> {use anstyle::Style;use worktrunk::styling::{eprint, eprintln};@@ -549,7 +555,8 @@ fn prompt_for_confirmation();// Show the completion content that will be written- eprint!("{}", format_bash_with_gutter(FISH_COMPLETION.trim(), ""));+ let fish_completion = fish_completion_content(cmd);+ eprint!("{}", format_bash_with_gutter(fish_completion.trim(), ""));eprintln!(); // Blank line after}@@ -577,21 +584,27 @@ fn prompt_yes_no() -> Result<bool, String> {Ok(response == "y" || response == "yes")}-/// Fish completion content - finds wt in PATH, with WORKTRUNK_BIN as optional override-const FISH_COMPLETION: &str = r#"# worktrunk completions for fish-complete --keep-order --exclusive --command wt --arguments "(test -n \"\$WORKTRUNK_BIN\"; or set -l WORKTRUNK_BIN (type -P wt); COMPLETE=fish \$WORKTRUNK_BIN -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"-"#;+/// Fish completion content - finds command in PATH, with WORKTRUNK_BIN as optional override+fn fish_completion_content(cmd: &str) -> String {+ format!(+ r#"# worktrunk completions for fish+complete --keep-order --exclusive --command {cmd} --arguments "(test -n \"\$WORKTRUNK_BIN\"; or set -l WORKTRUNK_BIN (type -P {cmd}); 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 use inline lazy completions in the init script.-/// Fish uses a separate completion file at ~/.config/fish/completions/wt.fish-/// that finds wt in PATH (with WORKTRUNK_BIN as optional override) to bypass the shell wrapper.+/// Fish uses a separate completion file at ~/.config/fish/completions/{cmd}.fish+/// that finds the command in PATH (with WORKTRUNK_BIN as optional override) to bypass the shell wrapper.pub fn process_shell_completions(shells: &[Shell],dry_run: bool,+ cmd: &str,) -> Result<Vec<CompletionResult>, String> {let mut results = Vec::new();+ let fish_completion = fish_completion_content(cmd);for &shell in shells {// Only fish has a separate completion file@@ -600,14 +613,14 @@ pub fn process_shell_completions(}let completion_path = shell- .completion_path()+ .completion_path_with_prefix(cmd).map_err(|e| format!("Failed to get completion path for {}: {}", shell, e))?;// Check if completions already exist with correct contentif completion_path.exists() {let existing = fs::read_to_string(&completion_path).map_err(|e| format!("Failed to read {}: {}", completion_path.display(), e))?;- if existing == FISH_COMPLETION {+ if existing == fish_completion {results.push(CompletionResult {shell,path: completion_path,@@ -638,7 +651,7 @@ pub fn process_shell_completions(}// Write the completion file- fs::write(&completion_path, FISH_COMPLETION)+ fs::write(&completion_path, &fish_completion).map_err(|e| format!("Failed to write {}: {}", completion_path.display(), e))?;results.push(CompletionResult {diff --git a/src/commands/init.rs b/src/commands/init.rsindex ff041e5c9..b2cee3632 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) -> Result<(), String> {- let init = shell::ShellInit::new(shell);+pub fn handle_init(shell: shell::Shell, cmd: String) -> Result<(), String> {+ let init = shell::ShellInit::with_prefix(shell, cmd);// Generate shell integration code (includes dynamic completion registration)let integration_output = initdiff --git a/src/main.rs b/src/main.rsindex 5a0847c21..e2e756fd5 100644--- a/src/main.rs+++ b/src/main.rs@@ -42,6 +42,22 @@ use cli::{};use worktrunk::HookType;+/// Get the binary name from `argv[0]`, falling back to "wt".+///+/// Used as the default for `--cmd` in shell integration commands.+/// When invoked as `git-wt`, returns "git-wt"; when invoked as `wt`, returns "wt".+fn binary_name() -> String {+ std::env::args()+ .next()+ .and_then(|arg0| {+ std::path::Path::new(&arg0)+ .file_stem() // Use file_stem to strip .exe on Windows+ .and_then(|name| name.to_str())+ .map(String::from)+ })+ .unwrap_or_else(|| "wt".to_string())+}+/// Custom help handling for pager support and markdown rendering.////// We intercept help requests to provide:@@ -598,13 +614,15 @@ fn main() {Commands::Config { action } => match action {ConfigCommand::Shell { action } => {match action {- ConfigShellCommand::Init { shell } => {+ ConfigShellCommand::Init { shell, cmd } => {// Generate shell code to stdout- handle_init(shell).map_err(|e| anyhow::anyhow!("{}", e))+ let cmd = cmd.unwrap_or_else(binary_name);+ handle_init(shell, cmd).map_err(|e| anyhow::anyhow!("{}", e))}- ConfigShellCommand::Install { shell, force } => {+ ConfigShellCommand::Install { shell, force, cmd } => {// Auto-write to shell config files and completions- handle_configure_shell(shell, force)+ let cmd = cmd.unwrap_or_else(binary_name);+ handle_configure_shell(shell, force, cmd).map_err(|e| anyhow::anyhow!("{}", e)).and_then(|scan_result| {diff --git a/src/shell.rs b/src/shell.rsindex ad069fe01..24aafbf66 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -63,6 +63,11 @@ impl Shell {////// Returns paths in order of preference. The first existing file should be used.pub fn config_paths(&self) -> Result<Vec<PathBuf>, std::io::Error> {+ self.config_paths_with_prefix("wt")+ }++ /// Returns config paths with custom prefix (affects fish conf.d filename)+ pub fn config_paths_with_prefix(&self, cmd: &str) -> Result<Vec<PathBuf>, std::io::Error> {let home = home_dir_required()?;Ok(match self {@@ -78,11 +83,12 @@ impl Shell {}Self::Fish => {// For fish, we write to conf.d/ which is auto-sourced+ // Filename includes prefix to avoid conflicts (e.g., wt.fish, git-wt.fish)vec![home.join(".config").join("fish").join("conf.d")- .join("wt.fish"),+ .join(format!("{}.fish", cmd)),]}Self::PowerShell => powershell_profile_paths(&home),@@ -96,6 +102,11 @@ impl Shell {/// (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> {+ self.completion_path_with_prefix("wt")+ }++ /// Returns completion path with custom prefix (affects fish completion filename)+ pub fn completion_path_with_prefix(&self, cmd: &str) -> Result<PathBuf, std::io::Error> {let home = home_dir_required()?;// Use etcetera for XDG-compliant paths when available@@ -111,22 +122,25 @@ impl Shell {data_home.join("bash-completion").join("completions")- .join("wt")+ .join(cmd)}- Self::Zsh => home.join(".zfunc").join("_wt"),+ Self::Zsh => home.join(".zfunc").join(format!("_{}", cmd)),Self::Fish => {// XDG_CONFIG_HOME defaults to ~/.configlet 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")+ config_home+ .join("fish")+ .join("completions")+ .join(format!("{}.fish", cmd))}Self::PowerShell => {// PowerShell doesn't use a separate completion file - completions are// registered inline in the profile using Register-ArgumentCompleter// Return a dummy path that won't be used- home.join(".wt-powershell-completions")+ home.join(format!(".{}-powershell-completions", cmd))}})}@@ -135,22 +149,35 @@ impl Shell {////// All shells use a conditional wrapper to avoid errors when the command doesn't exist.pub fn config_line(&self) -> String {+ self.config_line_with_prefix("wt")+ }++ /// Returns the line to add to the config file for shell integration with custom prefix+ pub fn config_line_with_prefix(&self, cmd: &str) -> String {+ // For non-default prefixes, include --cmd in the init command+ let prefix_arg = if cmd == "wt" {+ String::new()+ } else {+ format!(" --cmd={}", cmd)+ };+match self {Self::Bash | Self::Zsh => {format!(- "if command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init {})\"; fi",+ "if command -v {cmd} >/dev/null 2>&1; then eval \"$(command {cmd} config shell init {}{prefix_arg})\"; fi",self)}Self::Fish => {format!(- "if type -q wt; command wt config shell init {} | source; end",+ "if type -q {cmd}; command {cmd} config shell init {}{prefix_arg} | source; end",self)}Self::PowerShell => {- // PowerShell: Check if wt is available, then invoke and execute the output- "if (Get-Command wt -ErrorAction SilentlyContinue) { Invoke-Expression (& wt config shell init powershell) }".to_string()+ format!(+ "if (Get-Command {cmd} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {cmd} config shell init powershell{prefix_arg}) }}",+ )}}}@@ -161,7 +188,7 @@ impl Shell {/// This helps detect the "configured but not restarted shell" state.////// This function is prefix-agnostic - it detects integration patterns regardless- /// of what cmd_prefix was used during configuration (wt, worktree, etc).+ /// of what cmd was used during configuration (wt, worktree, etc).pub fn is_integration_configured() -> Result<Option<PathBuf>, std::io::Error> {use std::fs;use std::io::{BufRead, BufReader};@@ -252,44 +279,54 @@ impl Shell {pub fn integration_summary(&self) -> String {self.config_line()}++ /// Returns a summary with custom prefix for display in confirmation+ pub fn integration_summary_with_prefix(&self, cmd: &str) -> String {+ self.config_line_with_prefix(cmd)+ }}/// Shell integration configurationpub struct ShellInit {pub shell: Shell,+ pub cmd: String,}impl ShellInit {pub fn new(shell: Shell) -> Self {- Self { shell }+ Self::with_prefix(shell, "wt".to_string())+ }++ pub fn with_prefix(shell: Shell, cmd: String) -> Self {+ Self { shell, cmd }}/// Generate shell integration codepub fn generate(&self) -> Result<String, askama::Error> {match self.shell {Shell::Bash => {- let posix_shim = PosixDirectivesTemplate { cmd_prefix: "wt" }.render()?;+ let posix_shim = PosixDirectivesTemplate { cmd: &self.cmd }.render()?;let template = BashTemplate {shell_name: self.shell.to_string(),- cmd_prefix: "wt",+ cmd: &self.cmd,posix_shim: &posix_shim,};template.render()}Shell::Zsh => {- let posix_shim = PosixDirectivesTemplate { cmd_prefix: "wt" }.render()?;+ let posix_shim = PosixDirectivesTemplate { cmd: &self.cmd }.render()?;let template = ZshTemplate {- cmd_prefix: "wt",+ cmd: &self.cmd,posix_shim: &posix_shim,};template.render()}Shell::Fish => {- let template = FishTemplate { cmd_prefix: "wt" };+ let template = FishTemplate { cmd: &self.cmd };template.render()}Shell::PowerShell => {- let template = PowerShellTemplate { cmd_prefix: "wt" };+ let template = PowerShellTemplate { cmd: &self.cmd };template.render()}}@@ -300,7 +337,7 @@ impl ShellInit {#[derive(Template)]#[template(path = "posix_directives.sh", escape = "none")]struct PosixDirectivesTemplate<'a> {- cmd_prefix: &'a str,+ cmd: &'a str,}/// Bash shell template@@ -308,7 +345,7 @@ struct PosixDirectivesTemplate<'a> {#[template(path = "bash.sh", escape = "none")]struct BashTemplate<'a> {shell_name: String,- cmd_prefix: &'a str,+ cmd: &'a str,posix_shim: &'a str,}@@ -316,7 +353,7 @@ struct BashTemplate<'a> {#[derive(Template)]#[template(path = "zsh.zsh", escape = "none")]struct ZshTemplate<'a> {- cmd_prefix: &'a str,+ cmd: &'a str,posix_shim: &'a str,}@@ -324,14 +361,14 @@ struct ZshTemplate<'a> {#[derive(Template)]#[template(path = "fish.fish", escape = "none")]struct FishTemplate<'a> {- cmd_prefix: &'a str,+ cmd: &'a str,}/// PowerShell template#[derive(Template)]#[template(path = "powershell.ps1", escape = "none")]struct PowerShellTemplate<'a> {- cmd_prefix: &'a str,+ cmd: &'a str,}/// Detect if user's zsh has compinit enabled by probing for the compdef function.@@ -473,6 +510,47 @@ mod tests {assert!(line.contains("wt config shell init powershell"));}+ #[test]+ fn test_config_line_uses_custom_prefix() {+ // When using a custom prefix, the generated shell config line must use that prefix+ // throughout - both in the command check AND the command invocation.+ // This prevents the bug where we check for `git-wt` but then call `wt`.+ let prefix = "git-wt";++ // Bash/Zsh+ let bash_line = Shell::Bash.config_line_with_prefix(prefix);+ assert!(+ bash_line.contains("command -v git-wt"),+ "bash should check for git-wt"+ );+ assert!(+ bash_line.contains("command git-wt config shell init"),+ "bash should call git-wt, not wt"+ );++ // Fish+ let fish_line = Shell::Fish.config_line_with_prefix(prefix);+ assert!(+ fish_line.contains("type -q git-wt"),+ "fish should check for git-wt"+ );+ assert!(+ fish_line.contains("command git-wt config shell init"),+ "fish should call git-wt, not wt"+ );++ // PowerShell+ let ps_line = Shell::PowerShell.config_line_with_prefix(prefix);+ assert!(+ ps_line.contains("Get-Command git-wt"),+ "powershell should check for git-wt"+ );+ assert!(+ ps_line.contains("& git-wt config shell init"),+ "powershell should call git-wt, not wt"+ );+ }+#[test]fn test_shell_init_generate() {// Test that shell init generates valid output for each shelldiff --git a/templates/bash.sh b/templates/bash.shindex 7a4900966..01718e68d 100644--- a/templates/bash.sh+++ b/templates/bash.sh@@ -1,12 +1,12 @@# worktrunk shell integration for {{ shell_name }}-# 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+# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)+if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then{{ posix_shim }}- # Override {{ cmd_prefix }} command to add --internal flag- {{ cmd_prefix }}() {+ # Override {{ cmd }} command to add --internal flag+ {{ cmd }}() {local use_source=falselocal args=()@@ -19,14 +19,14 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];# handler runs before argument parsing - we can't detect --internal there.# The binary outputs completion candidates, not shell script to eval.if [[ -n "${COMPLETE:-}" ]]; then- command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" "${args[@]}"+ command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}"returnfi# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; thenlocal script exit_code=0- script="$(cargo run --quiet -- --internal "${args[@]}")" || exit_code=$?+ script="$(cargo run --bin {{ cmd }} --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; theneval "$script"if [[ $exit_code -eq 0 ]]; then@@ -40,16 +40,16 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];}# Lazy completions - generate on first TAB, then delegate to clap's completer- _{{ cmd_prefix }}_lazy_complete() {+ _{{ cmd }}_lazy_complete() {# Generate completions function once (check if clap's function exists)- if ! declare -F _clap_complete_{{ cmd_prefix }} >/dev/null; then+ if ! declare -F _clap_complete_{{ cmd }} >/dev/null; then# Use `command` to bypass the shell function and call the binary directly.- # Without this, `{{ cmd_prefix }}` would call the shell function which evals+ # Without this, `{{ cmd }}` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=bash command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" 2>/dev/null)" || return+ eval "$(COMPLETE=bash command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || returnfi- _clap_complete_{{ cmd_prefix }} "$@"+ _clap_complete_{{ cmd }} "$@"}- complete -o nospace -o bashdefault -F _{{ cmd_prefix }}_lazy_complete {{ cmd_prefix }}+ complete -o nospace -o bashdefault -F _{{ cmd }}_lazy_complete {{ cmd }}fidiff --git a/templates/fish.fish b/templates/fish.fishindex 0ea127f35..c35acdd86 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -1,7 +1,7 @@# worktrunk shell integration for fish-# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)-if type -q {{ cmd_prefix }}; or test -n "$WORKTRUNK_BIN"+# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)+if type -q {{ cmd }}; or test -n "$WORKTRUNK_BIN"# Capture stdout (shell script), eval in parent shell. stderr streams to terminal.# WORKTRUNK_BIN can override the binary path (for testing dev builds).#@@ -10,7 +10,7 @@ if type -q {{ cmd_prefix }}; or test -n "$WORKTRUNK_BIN"# doesn't inherit caller redirects. With pipeline capture, stderr flows through# normally and respects redirects like `wt --help &>file`.function wt_exec- test -n "$WORKTRUNK_BIN"; or set -l WORKTRUNK_BIN (type -P {{ cmd_prefix }})+ test -n "$WORKTRUNK_BIN"; or set -l WORKTRUNK_BIN (type -P {{ cmd }})# Pipeline capture: stderr streams through, stdout captured via read# -z (null delimiter) ensures we capture all lines, not just the first@@ -27,8 +27,8 @@ if type -q {{ cmd_prefix }}; or test -n "$WORKTRUNK_BIN"return $exit_codeend- # Override {{ cmd_prefix }} command to add --internal flag- function {{ cmd_prefix }}+ # Override {{ cmd }} command to add --internal flag+ function {{ cmd }}set -l use_source falseset -l args@@ -38,7 +38,7 @@ if type -q {{ cmd_prefix }}; or test -n "$WORKTRUNK_BIN"# --source: use cargo run (builds from source)if test $use_source = true- cargo run --quiet -- --internal $args | string collect --allow-empty | read --local -z script+ cargo run --bin {{ cmd }} --quiet -- --internal $args | string collect --allow-empty | read --local -z scriptset -l exit_code $pipestatus[1]if test -n "$script"eval $scriptdiff --git a/templates/posix_directives.sh b/templates/posix_directives.shindex d15077054..0e9579087 100644--- a/templates/posix_directives.sh+++ b/templates/posix_directives.sh@@ -2,7 +2,7 @@# WORKTRUNK_BIN can override the binary path (for testing dev builds).wt_exec() {local script exit_code=0- script="$(command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" "$@")" || exit_code=$?+ script="$(command "${WORKTRUNK_BIN:-{{ cmd }}}" "$@")" || exit_code=$?if [[ -n "$script" ]]; theneval "$script"diff --git a/templates/powershell.ps1 b/templates/powershell.ps1index 31978ab04..17044ac36 100644--- a/templates/powershell.ps1+++ b/templates/powershell.ps1@@ -6,16 +6,16 @@# For full hook compatibility on Windows, install Git for Windows and use bash integration.# Only initialize if wt is available-if (Get-Command {{ cmd_prefix }} -ErrorAction SilentlyContinue) {+if (Get-Command {{ cmd }} -ErrorAction SilentlyContinue) {# wt wrapper function - captures stdout and executes as PowerShell- function {{ cmd_prefix }} {+ function {{ cmd }} {param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)- $wtBin = (Get-Command {{ cmd_prefix }} -CommandType Application).Source+ $wtBin = (Get-Command {{ cmd }} -CommandType Application).Source# Run wt with --internal=powershell# stdout is captured for Invoke-Expression (contains Set-Location directives)@@ -42,7 +42,7 @@ if (Get-Command {{ cmd_prefix }} -ErrorAction SilentlyContinue) {# This registers Register-ArgumentCompleter with proper handling$env:COMPLETE = "powershell"try {- & (Get-Command {{ cmd_prefix }} -CommandType Application) | Out-String | Invoke-Expression+ & (Get-Command {{ cmd }} -CommandType Application) | Out-String | Invoke-Expression}finally {Remove-Item Env:\COMPLETE -ErrorAction SilentlyContinuediff --git a/templates/zsh.zsh b/templates/zsh.zshindex bced5d881..53f44e51f 100644--- a/templates/zsh.zsh+++ b/templates/zsh.zsh@@ -3,13 +3,13 @@# Completions require zsh's completion system (compinit). If completions don't work:# autoload -Uz compinit && compinit # add before this line in your .zshrc-# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)-if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then+# Only initialize if {{ cmd }} is available (in PATH or via WORKTRUNK_BIN)+if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then{{ posix_shim }}- # Override {{ cmd_prefix }} command to add --internal flag- {{ cmd_prefix }}() {+ # Override {{ cmd }} command to add --internal flag+ {{ cmd }}() {local use_source=falselocal -a args@@ -22,14 +22,14 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];# handler runs before argument parsing - we can't detect --internal there.# The binary outputs completion candidates, not shell script to eval.if [[ -n "${COMPLETE:-}" ]]; then- command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" "${args[@]}"+ command "${WORKTRUNK_BIN:-{{ cmd }}}" "${args[@]}"returnfi# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; thenlocal script exit_code=0- script="$(cargo run --quiet -- --internal "${args[@]}")" || exit_code=$?+ script="$(cargo run --bin {{ cmd }} --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; theneval "$script"if [[ $exit_code -eq 0 ]]; then@@ -43,11 +43,11 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];}# Lazy completions - generate on first TAB, then delegate to clap's completer- _{{ cmd_prefix }}_lazy_complete() {+ _{{ cmd }}_lazy_complete() {# Generate completions function once (check if clap's function exists)- if ! (( $+functions[_clap_dynamic_completer_{{ cmd_prefix }}] )); then+ if ! (( $+functions[_clap_dynamic_completer_{{ cmd }}] )); then# Use `command` to bypass the shell function and call the binary directly.- # Without this, `{{ cmd_prefix }}` would call the shell function which evals+ # Without this, `{{ cmd }}` would call the shell function which evals# the completion script internally but doesn't re-emit it.## The -V flag creates an unsorted group, preserving our recency-based@@ -56,9 +56,9 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];# The _describe function internally passes -o nosort to compadd.# TODO(clap): Ideally clap_complete would preserve ordering natively.# See: https://github.com/clap-rs/clap/issues/5752- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" 2>/dev/null | sed "s/_describe 'values'/_describe -V 'values'/")" || return+ eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null | sed "s/_describe 'values'/_describe -V 'values'/")" || returnfi- _clap_dynamic_completer_{{ cmd_prefix }} "$@"+ _clap_dynamic_completer_{{ cmd }} "$@"}# Register completion (silently skip if compinit hasn't run yet).@@ -66,12 +66,12 @@ if command -v {{ cmd_prefix }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]];# shouldn't see warnings every time they open a terminal. Instead, `wt config# shell install` detects missing compinit and shows a one-time advisory.if (( $+functions[compdef] )); then- compdef _{{ cmd_prefix }}_lazy_complete {{ cmd_prefix }}+ compdef _{{ cmd }}_lazy_complete {{ cmd }}# Single-column display keeps descriptions visually associated with each branch.- # Users can override: zstyle ':completion:*:{{ cmd_prefix }}:*' list-max ''- zstyle ':completion:*:{{ cmd_prefix }}:*' list-max 1+ # Users can override: zstyle ':completion:*:{{ cmd }}:*' list-max ''+ zstyle ':completion:*:{{ cmd }}:*' list-max 1# Prevent grouping branches with identical descriptions (same timestamp) on one line.# Without this, "release main -- + 12m" instead of separate lines per branch.- zstyle ':completion:*:*:{{ cmd_prefix }}:*' list-grouped false+ zstyle ':completion:*:*:{{ cmd }}:*' list-grouped falsefifidiff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 9126af037..c1b66ab59 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1543,6 +1543,22 @@ exit /b 1}}+/// Add standard env var redactions to insta settings+///+/// These redact volatile metadata captured by insta-cmd in the `info` block.+/// Called by all snapshot settings helpers for consistency.+pub fn add_standard_env_redactions(settings: &mut insta::Settings) {+ settings.add_redaction(".env.GIT_CONFIG_GLOBAL", "[TEST_GIT_CONFIG]");+ settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");+ settings.add_redaction(".env.HOME", "[TEST_HOME]");+ // Windows: the `home` crate uses USERPROFILE for home_dir()+ settings.add_redaction(".env.USERPROFILE", "[TEST_HOME]");+ settings.add_redaction(".env.XDG_CONFIG_HOME", "[TEST_CONFIG_HOME]");+ // Windows: etcetera uses APPDATA for config_dir()+ settings.add_redaction(".env.APPDATA", "[TEST_CONFIG_HOME]");+ settings.add_redaction(".env.PATH", "[PATH]");+}+/// Create configured insta Settings for snapshot tests////// This extracts the common settings configuration while allowing the@@ -1648,16 +1664,7 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {// Windows: HOME: C:\Users\...\Temp\.tmpXXX (after backslash normalization)settings.add_filter(r"HOME: .*/\.tmp[^/\s]+", "HOME: [TEST_HOME]");- // Redact volatile metadata captured by insta-cmd (applies to the `info` block)- settings.add_redaction(".env.GIT_CONFIG_GLOBAL", "[TEST_GIT_CONFIG]");- settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");- settings.add_redaction(".env.HOME", "[TEST_HOME]");- // Windows: the `home` crate uses USERPROFILE for home_dir()- settings.add_redaction(".env.USERPROFILE", "[TEST_HOME]");- settings.add_redaction(".env.XDG_CONFIG_HOME", "[TEST_CONFIG_HOME]");- // Windows: etcetera uses APPDATA for config_dir()- settings.add_redaction(".env.APPDATA", "[TEST_CONFIG_HOME]");- settings.add_redaction(".env.PATH", "[PATH]");+ add_standard_env_redactions(&mut settings);// Normalize timestamps in log filenames (format: YYYYMMDD-HHMMSS)// Match: post-start-NAME-SHA-HHMMSS.log@@ -1733,6 +1740,9 @@ pub fn setup_home_snapshot_settings(temp_home: &TempDir) -> insta::Settings {settings.add_filter(r"(?m)^.*[Pp]owershell.*\n", "");// Normalize Windows executable extension in help outputsettings.add_filter(r"wt\.exe", "wt");++ add_standard_env_redactions(&mut settings);+settings}@@ -1750,9 +1760,7 @@ pub fn setup_temp_snapshot_settings(temp_path: &std::path::Path) -> insta::Setti// Normalize Windows executable extension in help outputsettings.add_filter(r"wt\.exe", "wt");- // Redact volatile metadata captured by insta-cmd- settings.add_redaction(".env.GIT_CONFIG_GLOBAL", "[TEST_GIT_CONFIG]");- settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");+ add_standard_env_redactions(&mut settings);settings}diff --git a/tests/integration_tests/hook_show.rs b/tests/integration_tests/hook_show.rsindex 7d3a7a409..6cd5e255c 100644--- a/tests/integration_tests/hook_show.rs+++ b/tests/integration_tests/hook_show.rs@@ -1,7 +1,8 @@//! Integration tests for `wt hook show` commanduse crate::common::{- TestRepo, repo, set_temp_home_env, setup_snapshot_settings_with_home, temp_home, wt_command,+ TestRepo, repo, set_temp_home_env, setup_home_snapshot_settings,+ setup_snapshot_settings_with_home, temp_home, wt_command,};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;@@ -170,8 +171,8 @@ lint = "pre-commit run").unwrap();- let mut settings = insta::Settings::clone_current();- // Replace temp home path with ~ for stable snapshots+ let mut settings = setup_home_snapshot_settings(&temp_home);+ // Replace temp home path with ~ for stable snapshots (override the [TEMP_HOME] filter)settings.add_filter(®ex::escape(&temp_home.path().to_string_lossy()), "~");settings.bind(|| {let mut cmd = wt_command();diff --git a/tests/integration_tests/init.rs b/tests/integration_tests/init.rsindex 37eb5e267..b041d177f 100644--- a/tests/integration_tests/init.rs+++ b/tests/integration_tests/init.rs@@ -5,7 +5,7 @@//! are not the primary shell integration path on Windows (PowerShell is).#![cfg(not(windows))]-use crate::common::{TestRepo, repo, wt_command};+use crate::common::{TestRepo, add_standard_env_redactions, repo, wt_command};use insta::Settings;use insta_cmd::assert_cmd_snapshot;use rstest::rstest;@@ -17,9 +17,7 @@ fn snapshot_init(test_name: &str, repo: &TestRepo, shell: &str, extra_args: &[&s// backslash normalization filter that would corrupt the outputlet mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");- // Redact volatile env vars in metadata- settings.add_redaction(".env.GIT_CONFIG_GLOBAL", "[TEST_GIT_CONFIG]");- settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");+ add_standard_env_redactions(&mut settings);settings.bind(|| {let mut cmd = wt_command();@@ -50,8 +48,7 @@ fn test_init_invalid_shell(repo: TestRepo) {// Same custom settings as snapshot_initlet mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");- settings.add_redaction(".env.GIT_CONFIG_GLOBAL", "[TEST_GIT_CONFIG]");- settings.add_redaction(".env.WORKTRUNK_CONFIG_PATH", "[TEST_CONFIG]");+ add_standard_env_redactions(&mut settings);settings.bind(|| {let mut cmd = wt_command();diff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snapnew file mode 100644index 000000000..2a17a87dc--- /dev/null+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/hook_show.rs+info:+ program: wt+ args:+ - hook+ - show+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_EDITOR: ""+ HOME: "[TEST_HOME]"+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+❌ [31mfatal: not a git repository (or any of the parent directories): .git[39mdiff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 6f2346d02..41d7495e9 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -8,6 +8,7 @@ info:- init- bashenv:+ APPDATA: "[TEST_CONFIG_HOME]"CLICOLOR_FORCE: "1"COLUMNS: "150"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"@@ -15,10 +16,14 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ HOME: "[TEST_HOME]"LANG: CLC_ALL: C+ PATH: "[PATH]"SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: trueexit_code: 0@@ -65,7 +70,7 @@ wt_exec() {# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; thenlocal script exit_code=0- script="$(cargo run --quiet -- --internal "${args[@]}")" || exit_code=$?+ script="$(cargo run --bin wt --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; theneval "$script"if [[ $exit_code -eq 0 ]]; thendiff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex bc6c2e80a..0791ebe65 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -8,6 +8,7 @@ info:- init- fishenv:+ APPDATA: "[TEST_CONFIG_HOME]"CLICOLOR_FORCE: "1"COLUMNS: "150"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"@@ -15,10 +16,14 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ HOME: "[TEST_HOME]"LANG: CLC_ALL: C+ PATH: "[PATH]"SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: trueexit_code: 0@@ -63,7 +68,7 @@ if type -q wt; or test -n "$WORKTRUNK_BIN"# --source: use cargo run (builds from source)if test $use_source = true- cargo run --quiet -- --internal $args | string collect --allow-empty | read --local -z script+ cargo run --bin wt --quiet -- --internal $args | string collect --allow-empty | read --local -z scriptset -l exit_code $pipestatus[1]if test -n "$script"eval $scriptdiff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 61dd1a3e3..8f63fb851 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -8,6 +8,7 @@ info:- init- zshenv:+ APPDATA: "[TEST_CONFIG_HOME]"CLICOLOR_FORCE: "1"COLUMNS: "150"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"@@ -15,10 +16,14 @@ info:GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ HOME: "[TEST_HOME]"LANG: CLC_ALL: C+ PATH: "[PATH]"SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"---success: trueexit_code: 0@@ -68,7 +73,7 @@ wt_exec() {# --source: use cargo run (builds from source)if [[ "$use_source" == true ]]; thenlocal script exit_code=0- script="$(cargo run --quiet -- --internal "${args[@]}")" || exit_code=$?+ script="$(cargo run --bin wt --quiet -- --internal "${args[@]}")" || exit_code=$?if [[ -n "$script" ]]; theneval "$script"if [[ $exit_code -eq 0 ]]; then