Skip to content

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

Feat: Add confirmation prompt to `configure-shell` command

Maximilian Roos71aecd5974d6
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 471c57152..659db80b5 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -1,5 +1,5 @@
use std::fs::{self, OpenOptions};
-use std::io::{BufRead, BufReader, Write};
+use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use worktrunk::shell::Shell;
@@ -25,13 +25,48 @@ impl ConfigAction {
ConfigAction::Added => "Added",
ConfigAction::AlreadyExists => "Already configured",
ConfigAction::Created => "Created",
- ConfigAction::WouldAdd => "Would add to",
- ConfigAction::WouldCreate => "Would create",
+ ConfigAction::WouldAdd => "Will add to",
+ ConfigAction::WouldCreate => "Will create",
}
}
}
pub fn handle_configure_shell(
+ shell_filter: Option<Shell>,
+ cmd_prefix: &str,
+ skip_confirmation: bool,
+) -> Result<Vec<ConfigureResult>, String> {
+ // Validate cmd_prefix to prevent command injection
+ validate_cmd_prefix(cmd_prefix)?;
+
+ // First, do a dry-run to see what would be changed
+ let preview_results = scan_shell_configs(shell_filter, cmd_prefix, true)?;
+
+ // If nothing to do, return early
+ if preview_results.is_empty() {
+ return Ok(vec![]);
+ }
+
+ // Check if any changes are needed (not all are AlreadyExists)
+ let needs_changes = preview_results
+ .iter()
+ .any(|r| !matches!(r.action, ConfigAction::AlreadyExists));
+
+ // If nothing needs to be changed, just return the preview results
+ if !needs_changes {
+ return Ok(preview_results);
+ }
+
+ // Show what will be done and ask for confirmation (unless --yes flag is used)
+ if !skip_confirmation && !prompt_for_confirmation(&preview_results)? {
+ return Err("Cancelled by user".to_string());
+ }
+
+ // User confirmed (or --yes flag was used), now actually apply the changes
+ scan_shell_configs(shell_filter, cmd_prefix, false)
+}
+
+fn scan_shell_configs(
shell_filter: Option<Shell>,
cmd_prefix: &str,
dry_run: bool,
@@ -121,6 +156,10 @@ fn configure_shell_file(
dry_run: bool,
explicit_shell: bool,
) -> Result<Option<ConfigureResult>, String> {
+ // Get a summary of the shell integration for display
+ let integration_summary = shell.integration_summary(cmd_prefix);
+
+ // The actual line we write to the config file
let config_content = shell.config_line(cmd_prefix);
// For Fish, we write to a separate conf.d/ file
@@ -143,22 +182,17 @@ fn configure_shell_file(
let reader = BufReader::new(file);
- // More precise pattern matching for the eval statement
- let eval_pattern = format!("eval \"$({} init", cmd_prefix);
- let eval_pattern_single_quote = format!("eval '$({} init", cmd_prefix);
-
+ // Check for the exact conditional wrapper we would write
for line in reader.lines() {
let line = line.map_err(|e| format!("Failed to read line: {}", e))?;
- let trimmed = line.trim();
- // Check for the actual eval statement, not just any mention of "wt init"
- if trimmed.starts_with(&eval_pattern) || trimmed.starts_with(&eval_pattern_single_quote)
- {
+ // Canonical detection: check if the line matches exactly what we write
+ if line.trim() == config_content {
return Ok(Some(ConfigureResult {
shell,
path: path.to_path_buf(),
action: ConfigAction::AlreadyExists,
- config_line: config_content.to_string(),
+ config_line: integration_summary.clone(),
}));
}
}
@@ -169,7 +203,7 @@ fn configure_shell_file(
shell,
path: path.to_path_buf(),
action: ConfigAction::WouldAdd,
- config_line: config_content.to_string(),
+ config_line: integration_summary.clone(),
}));
}
@@ -187,7 +221,7 @@ fn configure_shell_file(
shell,
path: path.to_path_buf(),
action: ConfigAction::Added,
- config_line: config_content.to_string(),
+ config_line: integration_summary.clone(),
}))
} else {
// File doesn't exist
@@ -198,7 +232,7 @@ fn configure_shell_file(
shell,
path: path.to_path_buf(),
action: ConfigAction::WouldCreate,
- config_line: config_content.to_string(),
+ config_line: integration_summary.clone(),
}));
}
@@ -217,7 +251,7 @@ fn configure_shell_file(
shell,
path: path.to_path_buf(),
action: ConfigAction::Created,
- config_line: config_content.to_string(),
+ config_line: integration_summary.clone(),
}))
} else {
// Don't create config files for shells the user might not use
@@ -234,6 +268,9 @@ fn configure_fish_file(
dry_run: bool,
explicit_shell: bool,
) -> Result<Option<ConfigureResult>, String> {
+ // Get a summary of the shell integration for display
+ let integration_summary = shell.integration_summary(cmd_prefix);
+
// For Fish, we write to conf.d/{cmd_prefix}.fish (separate file)
// Check if it already exists and has our integration
@@ -241,16 +278,13 @@ fn configure_fish_file(
let existing_content = fs::read_to_string(path)
.map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
- // Check for the init pattern (either old function-based or new eval-based)
- let init_pattern = format!("{} init", cmd_prefix);
- let has_integration = existing_content.contains(&init_pattern);
-
- if has_integration {
+ // Canonical detection: check if the file matches exactly what we write
+ if existing_content.trim() == content {
return Ok(Some(ConfigureResult {
shell,
path: path.to_path_buf(),
action: ConfigAction::AlreadyExists,
- config_line: content.to_string(),
+ config_line: integration_summary.clone(),
}));
}
}
@@ -276,7 +310,7 @@ fn configure_fish_file(
} else {
ConfigAction::WouldCreate
},
- config_line: content.to_string(),
+ config_line: integration_summary.clone(),
}));
}
@@ -286,7 +320,7 @@ fn configure_fish_file(
.map_err(|e| format!("Failed to create directory {}: {}", parent.display(), e))?;
}
- // Write the config content with newline
+ // Write the conditional wrapper (short one-liner that calls wt init fish | source)
fs::write(path, format!("{}\n", content))
.map_err(|e| format!("Failed to write to {}: {}", path.display(), e))?;
@@ -294,6 +328,84 @@ fn configure_fish_file(
shell,
path: path.to_path_buf(),
action: ConfigAction::Created,
- config_line: content.to_string(),
+ config_line: integration_summary.clone(),
}))
}
+
+fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String> {
+ use anstyle::Style;
+
+ eprintln!();
+ eprintln!("The following changes will be made:");
+ eprintln!();
+
+ for result in results {
+ // Skip items that are already configured
+ if matches!(result.action, ConfigAction::AlreadyExists) {
+ continue;
+ }
+
+ // Format with bold shell and path
+ let bold = Style::new().bold();
+ let shell = result.shell;
+ let path = result.path.display();
+ eprintln!(
+ " {} {bold}{shell}{bold:#} {bold}{path}{bold:#}",
+ result.action.description(),
+ );
+
+ // Show the config line that will be added with dim styling
+ for line in result.config_line.lines() {
+ let dim = Style::new().dimmed();
+ eprintln!(" {dim}{line}{dim:#}");
+ }
+ }
+
+ eprintln!();
+ eprint!("Proceed? [y/N] ");
+ io::stderr().flush().map_err(|e| e.to_string())?;
+
+ let mut input = String::new();
+ io::stdin()
+ .read_line(&mut input)
+ .map_err(|e| e.to_string())?;
+
+ let response = input.trim().to_lowercase();
+ Ok(response == "y" || response == "yes")
+}
+
+fn validate_cmd_prefix(cmd_prefix: &str) -> Result<(), String> {
+ // Ensure it's not empty
+ if cmd_prefix.is_empty() {
+ return Err("Command prefix cannot be empty".to_string());
+ }
+
+ // Can't start with dash (would be interpreted as a flag)
+ if cmd_prefix.starts_with('-') {
+ return Err(format!(
+ "Invalid command prefix '{}': cannot start with '-'",
+ cmd_prefix
+ ));
+ }
+
+ // Only allow alphanumeric, dash, and underscore
+ if !cmd_prefix
+ .chars()
+ .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
+ {
+ return Err(format!(
+ "Invalid command prefix '{}': only alphanumeric characters, dash, and underscore allowed",
+ cmd_prefix
+ ));
+ }
+
+ // Ensure it's not too long (reasonable limit)
+ if cmd_prefix.len() > 64 {
+ return Err(format!(
+ "Command prefix '{}' is too long (max 64 characters)",
+ cmd_prefix
+ ));
+ }
+
+ Ok(())
+}
diff --git a/src/main.rs b/src/main.rs
index e6931405a..a8e60f96d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -54,9 +54,9 @@ enum Commands {
#[arg(long, default_value = "wt")]
cmd: String,
- /// Show what would be done without making changes
- #[arg(long)]
- dry_run: bool,
+ /// Skip confirmation prompt
+ #[arg(long, short)]
+ yes: bool,
},
/// List all worktrees
@@ -152,27 +152,26 @@ fn main() {
let mut cli_cmd = Cli::command();
handle_init(&shell, &cmd, &mut cli_cmd).map_err(GitError::CommandFailed)
}
- Commands::ConfigureShell {
- shell,
- cmd,
- dry_run,
- } => handle_configure_shell(shell, &cmd, dry_run)
- .map(|results| {
- for result in results {
- println!(
- "{:12} {} {}",
- result.action.description(),
- result.shell,
- result.path.display()
- );
- // Indent each line of the config content with dim/gray color
- for line in result.config_line.lines() {
- let dim = Style::new().dimmed();
- println!(" {dim}{line}{dim:#}");
+ Commands::ConfigureShell { shell, cmd, yes } => {
+ handle_configure_shell(shell, &cmd, yes)
+ .map(|results| {
+ for result in results {
+ let bold = Style::new().bold();
+ let shell = result.shell;
+ let path = result.path.display();
+ println!(
+ "{} {bold}{shell}{bold:#} {path}",
+ result.action.description(),
+ );
+ // Indent each line of the config content with dim/gray color
+ for line in result.config_line.lines() {
+ let dim = Style::new().dimmed();
+ println!(" {dim}{line}{dim:#}");
+ }
}
- }
- })
- .map_err(GitError::CommandFailed),
+ })
+ .map_err(GitError::CommandFailed)
+ }
Commands::List { format, branches } => handle_list(format, branches),
Commands::Switch {
branch,
@@ -233,3 +232,4 @@ fn main() {
process::exit(1);
}
}
+// test change
diff --git a/src/shell.rs b/src/shell.rs
index c379d0735..80c0f8811 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -122,16 +122,45 @@ impl Shell {
/// Returns the line to add to the config file for shell integration
///
- /// All shells use an eval-like pattern now.
+ /// All shells use a conditional wrapper to avoid errors when the command doesn't exist.
pub fn config_line(&self, cmd_prefix: &str) -> String {
match self {
+ Self::Bash | Self::Zsh | Self::Oil => {
+ format!(
+ "if command -v {} >/dev/null 2>&1; then eval \"$({} init {})\"; fi",
+ cmd_prefix, cmd_prefix, self
+ )
+ }
Self::Fish => {
- // Fish uses 'source' instead of 'eval'
- format!("{} init {} | source", cmd_prefix, self)
+ format!(
+ "if type -q {}; {} init {} | source; end",
+ cmd_prefix, cmd_prefix, self
+ )
+ }
+ Self::Nushell => {
+ // Use user's home directory cache instead of shared /tmp for security
+ format!(
+ "if (which {} | is-not-empty) {{ let tmpfile = ($env.HOME | path join \".cache\" \"nushell-{}-init.nu\"); {} init {} | save --force $tmpfile; source $tmpfile }}",
+ cmd_prefix, cmd_prefix, cmd_prefix, self
+ )
}
- _ => {
- // All other shells use eval pattern
- format!("eval \"$({} init {})\"", cmd_prefix, self)
+ Self::Powershell => {
+ format!(
+ "if (Get-Command {} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {} init {}) }}",
+ cmd_prefix, cmd_prefix, self
+ )
+ }
+ Self::Elvish => {
+ format!(
+ "if (has-external {}) {{ eval ({} init {}) }}",
+ cmd_prefix, cmd_prefix, self
+ )
+ }
+ Self::Xonsh => {
+ format!(
+ "import shutil; exec(shutil.which('{}') and $({} init {}).strip() or '')",
+ cmd_prefix, cmd_prefix, self
+ )
}
}
}
@@ -215,6 +244,13 @@ impl Shell {
None
}
+
+ /// Returns a summary of what the shell integration does for display in confirmation
+ ///
+ /// This just returns the same as config_line since we want to show the exact wrapper
+ pub fn integration_summary(&self, cmd_prefix: &str) -> String {
+ self.config_line(cmd_prefix)
+ }
}
/// Shell integration configuration
diff --git a/templates/bash.sh b/templates/bash.sh
index 9ad299f12..3cf10540e 100644
--- a/templates/bash.sh
+++ b/templates/bash.sh
@@ -1,50 +1,53 @@
# worktrunk shell integration for {{ shell_name }}
-# Helper function to parse wt output and handle directives
-_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
-
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
- else
- # Regular output - print it
- echo "$line"
- fi
- done <<< "$output"
-
- return $exit_code
-}
-
-# Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
-{{ cmd_prefix }}() {
- local subcommand="$1"
-
- case "$subcommand" in
- switch|remove|merge)
- # Commands that need --internal for directory change support
- shift
- _wt_exec "$subcommand" --internal "$@"
- ;;
- *)
- # All other commands pass through directly
- command wt "$@"
- ;;
- esac
-}
-
-# 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 }}
+# Only initialize if wt is available
+if command -v wt >/dev/null 2>&1; then
+ # Helper function to parse wt output and handle directives
+ _wt_exec() {
+ local output line exit_code
+ output="$(command wt "$@" 2>&1)"
+ exit_code=$?
+
+ # Parse output line by line
+ while IFS= read -r line; do
+ if [[ "$line" == __WORKTRUNK_CD__* ]]; then
+ # Extract path and change directory
+ \cd "${line#__WORKTRUNK_CD__}"
+ else
+ # Regular output - print it
+ echo "$line"
+ fi
+ done <<< "$output"
+
+ return $exit_code
+ }
+
+ # Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
+ {{ cmd_prefix }}() {
+ local subcommand="$1"
+
+ case "$subcommand" in
+ switch|remove|merge)
+ # Commands that need --internal for directory change support
+ shift
+ _wt_exec "$subcommand" --internal "$@"
+ ;;
+ *)
+ # All other commands pass through directly
+ command wt "$@"
+ ;;
+ esac
+ }
+
+ # 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 }}
+fi
diff --git a/templates/elvish.elv b/templates/elvish.elv
index 4b60dd286..fa26b0e08 100644
--- a/templates/elvish.elv
+++ b/templates/elvish.elv
@@ -1,52 +1,55 @@
# worktrunk shell integration for elvish
-# Helper function to parse wt output and handle directives
-fn _wt_exec {|@args|
- var exit-code = 0
- var output = ""
+# Only initialize if wt is available
+if (has-external wt) {
+ # Helper function to parse wt output and handle directives
+ fn _wt_exec {|@args|
+ var exit-code = 0
+ var output = ""
- # Capture output and handle potential non-zero exit
- try {
- set output = (e:wt $@args 2>&1 | slurp)
- } catch e {
- set exit-code = 1
- set output = $e[reason][content]
- }
+ # Capture output and handle potential non-zero exit
+ try {
+ set output = (e:wt $@args 2>&1 | slurp)
+ } catch e {
+ set exit-code = 1
+ set output = $e[reason][content]
+ }
- # Parse output line by line
- var lines = [(str:split "\n" $output)]
- for line $lines {
- if (str:has-prefix $line "__WORKTRUNK_CD__") {
- # Extract path and change directory
- var path = (str:trim-prefix $line "__WORKTRUNK_CD__")
- cd $path
- } else {
- # Regular output - print it
- echo $line
+ # Parse output line by line
+ var lines = [(str:split "\n" $output)]
+ for line $lines {
+ if (str:has-prefix $line "__WORKTRUNK_CD__") {
+ # Extract path and change directory
+ var path = (str:trim-prefix $line "__WORKTRUNK_CD__")
+ cd $path
+ } else {
+ # Regular output - print it
+ echo $line
+ }
}
- }
- # Return exit code (will throw exception if non-zero)
- if (!=s $exit-code 0) {
- fail "command failed with exit code "$exit-code
+ # Return exit code (will throw exception if non-zero)
+ if (!=s $exit-code 0) {
+ fail "command failed with exit code "$exit-code
+ }
}
-}
-# Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
-fn {{ cmd_prefix }} {|@args|
- if (== (count $args) 0) {
- e:wt
- return
- }
+ # Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
+ fn {{ cmd_prefix }} {|@args|
+ if (== (count $args) 0) {
+ e:wt
+ return
+ }
- var subcommand = $args[0]
+ var subcommand = $args[0]
- if (or (eq $subcommand "switch") (eq $subcommand "remove") (eq $subcommand "merge")) {
- # Commands that need --internal for directory change support
- var rest-args = $args[1..]
- _wt_exec $subcommand --internal $@rest-args
- } else {
- # All other commands pass through directly
- e:wt $@args
+ if (or (eq $subcommand "switch") (eq $subcommand "remove") (eq $subcommand "merge")) {
+ # Commands that need --internal for directory change support
+ var rest-args = $args[1..]
+ _wt_exec $subcommand --internal $@rest-args
+ } else {
+ # All other commands pass through directly
+ e:wt $@args
+ }
}
}
diff --git a/templates/fish.fish b/templates/fish.fish
index a3b27e2c4..3eb1f77e5 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -1,46 +1,49 @@
# worktrunk shell integration for fish
-# Helper function to parse wt output and handle directives
-function _wt_exec
- set -l output (command wt $argv 2>&1)
- set -l exit_code $status
+# Only initialize if {{ cmd_prefix }} is available
+if type -q {{ cmd_prefix }}
+ # Helper function to parse wt output and handle directives
+ function _wt_exec
+ set -l output (command {{ cmd_prefix }} $argv 2>&1)
+ set -l exit_code $status
- # Parse output line by line
- for line in (string split \n -- $output)
- if string match -q '__WORKTRUNK_CD__*' -- $line
- # Extract path and change directory
- cd (string replace '__WORKTRUNK_CD__' '' -- $line)
- else
- # Regular output - print it
- echo $line
+ # Parse output line by line
+ for line in (string split \n -- $output)
+ if string match -q '__WORKTRUNK_CD__*' -- $line
+ # Extract path and change directory
+ cd (string replace '__WORKTRUNK_CD__' '' -- $line)
+ else
+ # Regular output - print it
+ echo $line
+ end
end
+
+ return $exit_code
end
- return $exit_code
-end
+ # Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
+ function {{ cmd_prefix }}
+ set -l subcommand $argv[1]
-# Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
-function {{ cmd_prefix }}
- set -l subcommand $argv[1]
+ switch $subcommand
+ case switch remove merge
+ # Commands that need --internal for directory change support
+ _wt_exec $subcommand --internal $argv[2..-1]
+ case '*'
+ # All other commands pass through directly
+ command {{ cmd_prefix }} $argv
+ end
+ end
- switch $subcommand
- case switch remove merge
- # Commands that need --internal for directory change support
- _wt_exec $subcommand --internal $argv[2..-1]
- case '*'
- # All other commands pass through directly
- command wt $argv
+ # Dynamic completion function
+ function __{{ cmd_prefix }}_complete
+ # Call {{ cmd_prefix }} complete with current command line
+ set -l cmd (commandline -opc)
+ command {{ cmd_prefix }} complete $cmd 2>/dev/null
end
-end
-# 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
+ # 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'
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'
diff --git a/templates/nushell.nu b/templates/nushell.nu
index b0f0d2f54..7abdd935f 100644
--- a/templates/nushell.nu
+++ b/templates/nushell.nu
@@ -1,42 +1,45 @@
# worktrunk shell integration for nushell
-# Helper function to parse wt output and handle directives
-export def --env _wt_exec [...args] {
- let result = (do { ^wt ...$args } | complete)
+# Only initialize if wt is available
+if (which wt | is-not-empty) {
+ # Helper function to parse wt output and handle directives
+ export def --env _wt_exec [...args] {
+ let result = (do { ^wt ...$args } | complete)
- # Parse output line by line
- let lines = ($result.stdout | lines)
- for line in $lines {
- if ($line | str starts-with "__WORKTRUNK_CD__") {
- # Extract path and change directory
- let path = ($line | str substring 16..)
- cd $path
- } else {
- # Regular output - print it
- print $line
+ # Parse output line by line
+ let lines = ($result.stdout | lines)
+ for line in $lines {
+ if ($line | str starts-with "__WORKTRUNK_CD__") {
+ # Extract path and change directory
+ let path = ($line | str substring 16..)
+ cd $path
+ } else {
+ # Regular output - print it
+ print $line
+ }
}
- }
- # Return the exit code
- return $result.exit_code
-}
+ # Return the exit code
+ return $result.exit_code
+ }
-# Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
-# Use --wrapped to pass through all flags without parsing them
-export def --env --wrapped {{ cmd_prefix }} [...rest] {
- let subcommand = ($rest | get 0? | default "")
+ # Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
+ # Use --wrapped to pass through all flags without parsing them
+ export def --env --wrapped {{ cmd_prefix }} [...rest] {
+ let subcommand = ($rest | get 0? | default "")
- match $subcommand {
- "switch" | "remove" | "merge" => {
- # Commands that need --internal for directory change support
- let rest_args = ($rest | skip 1)
- let internal_args = ([$subcommand, "--internal"] | append $rest_args)
- let exit_code = (_wt_exec ...$internal_args)
- return $exit_code
- }
- _ => {
- # All other commands pass through directly
- ^wt ...$rest
+ match $subcommand {
+ "switch" | "remove" | "merge" => {
+ # Commands that need --internal for directory change support
+ let rest_args = ($rest | skip 1)
+ let internal_args = ([$subcommand, "--internal"] | append $rest_args)
+ let exit_code = (_wt_exec ...$internal_args)
+ return $exit_code
+ }
+ _ => {
+ # All other commands pass through directly
+ ^wt ...$rest
+ }
}
}
}
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index ed76ff3e5..f2ab20584 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -1,56 +1,59 @@
# worktrunk shell integration for PowerShell
-# Helper function to parse wt output and handle directives
-function _wt_exec {
- param(
- [Parameter(ValueFromRemainingArguments=$true)]
- [string[]]$Arguments
- )
-
- # Capture output and exit code
- $output = & wt @Arguments 2>&1
- $exitCode = $LASTEXITCODE
-
- # Parse output line by line
- foreach ($line in $output) {
- if ($line -match '^__WORKTRUNK_CD__(.+)$') {
- # Extract path and change directory
- Set-Location $matches[1]
- } else {
- # Regular output - write it
- Write-Output $line
+# Only initialize if wt is available
+if (Get-Command wt -ErrorAction SilentlyContinue) {
+ # Helper function to parse wt output and handle directives
+ function _wt_exec {
+ param(
+ [Parameter(ValueFromRemainingArguments=$true)]
+ [string[]]$Arguments
+ )
+
+ # Capture output and exit code
+ $output = & wt @Arguments 2>&1
+ $exitCode = $LASTEXITCODE
+
+ # Parse output line by line
+ foreach ($line in $output) {
+ if ($line -match '^__WORKTRUNK_CD__(.+)$') {
+ # Extract path and change directory
+ Set-Location $matches[1]
+ } else {
+ # Regular output - write it
+ Write-Output $line
+ }
}
- }
-
- # Return the exit code
- return $exitCode
-}
-
-# Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
-function {{ cmd_prefix }} {
- param(
- [Parameter(ValueFromRemainingArguments=$true)]
- [string[]]$Arguments
- )
- if ($Arguments.Count -eq 0) {
- & wt
- return $LASTEXITCODE
+ # Return the exit code
+ return $exitCode
}
- $subcommand = $Arguments[0]
+ # Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge
+ function {{ cmd_prefix }} {
+ param(
+ [Parameter(ValueFromRemainingArguments=$true)]
+ [string[]]$Arguments
+ )
- switch ($subcommand) {
- { $_ -in @("switch", "remove", "merge") } {
- # Commands that need --internal for directory change support
- $restArgs = $Arguments[1..($Arguments.Count-1)]
- $exitCode = _wt_exec $subcommand --internal @restArgs
- return $exitCode
- }
- default {
- # All other commands pass through directly
- & wt @Arguments
+ if ($Arguments.Count -eq 0) {
+ & wt
return $LASTEXITCODE
}
+
+ $subcommand = $Arguments[0]
+
+ switch ($subcommand) {
+ { $_ -in @("switch", "remove", "merge") } {
+ # Commands that need --internal for directory change support
+ $restArgs = $Arguments[1..($Arguments.Count-1)]
+ $exitCode = _wt_exec $subcommand --internal @restArgs
+ return $exitCode
+ }
+ default {
+ # All other commands pass through directly
+ & wt @Arguments
+ return $LASTEXITCODE
+ }
+ }
}
}
diff --git a/templates/xonsh.xsh b/templates/xonsh.xsh
index 8301387d9..c60361360 100644
--- a/templates/xonsh.xsh
+++ b/templates/xonsh.xsh
@@ -1,41 +1,44 @@
# worktrunk shell integration for xonsh
-def _wt_exec(args):
- """Helper function to parse wt output and handle directives"""
- # Capture full output including return code
- result = !(wt @(args))
+# Only initialize if wt is available
+import shutil
+if shutil.which("wt") is not None:
+ def _wt_exec(args):
+ """Helper function to parse wt output and handle directives"""
+ # Capture full output including return code
+ result = !(wt @(args))
- # Parse output line by line
- if result.out:
- for line in result.out.splitlines():
- if line.startswith("__WORKTRUNK_CD__"):
- # Extract path and change directory
- path = line[17:] # Remove prefix
- cd @(path)
- else:
- # Regular output - print it
- print(line)
+ # Parse output line by line
+ if result.out:
+ for line in result.out.splitlines():
+ if line.startswith("__WORKTRUNK_CD__"):
+ # Extract path and change directory
+ path = line[17:] # Remove prefix
+ cd @(path)
+ else:
+ # Regular output - print it
+ print(line)
- # Return the exit code
- return result.returncode
+ # Return the exit code
+ return result.returncode
-def _{{ cmd_prefix }}_wrapper(args):
- """Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge"""
- if not args:
- # No arguments, just run wt
- wt
- return
+ def _{{ cmd_prefix }}_wrapper(args):
+ """Override {{ cmd_prefix }} command to add --internal flag for switch, remove, and merge"""
+ if not args:
+ # No arguments, just run wt
+ wt
+ return
- subcommand = args[0]
+ subcommand = args[0]
- if subcommand in ["switch", "remove", "merge"]:
- # Commands that need --internal for directory change support
- rest_args = args[1:]
- return _wt_exec([subcommand, "--internal"] + rest_args)
- else:
- # All other commands pass through directly
- result = !(wt @(args))
- return result.returncode
+ if subcommand in ["switch", "remove", "merge"]:
+ # Commands that need --internal for directory change support
+ rest_args = args[1:]
+ return _wt_exec([subcommand, "--internal"] + rest_args)
+ else:
+ # All other commands pass through directly
+ result = !(wt @(args))
+ return result.returncode
-# Register the alias
-aliases['{{ cmd_prefix }}'] = _{{ cmd_prefix }}_wrapper
+ # Register the alias
+ aliases['{{ cmd_prefix }}'] = _{{ cmd_prefix }}_wrapper
diff --git a/test3.txt b/test3.txt
new file mode 100644
index 000000000..df6b0d2bc
--- /dev/null
+++ b/test3.txt
@@ -0,0 +1 @@
+test3
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
index 19e28871a..eed16cf50 100644
--- a/tests/integration_tests/configure_shell.rs
+++ b/tests/integration_tests/configure_shell.rs
@@ -5,9 +5,9 @@ use std::fs;
use std::process::Command;
use tempfile::TempDir;
-/// Test configure-shell with dry-run flag
+/// Test configure-shell with --yes flag (skips confirmation)
#[test]
-fn test_configure_shell_dry_run() {
+fn test_configure_shell_with_yes() {
let repo = TestRepo::new();
let temp_home = TempDir::new().unwrap();
@@ -23,12 +23,16 @@ fn test_configure_shell_dry_run() {
let mut cmd = Command::new(get_cargo_bin("wt"));
repo.clean_cli_env(&mut cmd);
cmd.arg("configure-shell")
- .arg("--dry-run")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
- assert_cmd_snapshot!("configure_shell_dry_run", cmd);
+ assert_cmd_snapshot!("configure_shell_with_yes", cmd);
});
+
+ // Verify the file was modified
+ let content = fs::read_to_string(&zshrc_path).unwrap();
+ assert!(content.contains("eval \"$(wt init zsh)\""));
}
/// Test configure-shell with specific shell
@@ -51,6 +55,7 @@ fn test_configure_shell_specific_shell() {
cmd.arg("configure-shell")
.arg("--shell")
.arg("zsh")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -70,7 +75,11 @@ fn test_configure_shell_already_exists() {
// Create a fake .zshrc file with the line already present
let zshrc_path = temp_home.path().join(".zshrc");
- fs::write(&zshrc_path, "# Existing config\neval \"$(wt init zsh)\"\n").unwrap();
+ fs::write(
+ &zshrc_path,
+ "# Existing config\nif command -v wt >/dev/null 2>&1; then eval \"$(wt init zsh)\"; fi\n",
+ )
+ .unwrap();
let mut settings = Settings::clone_current();
settings.set_snapshot_path("../snapshots");
@@ -82,6 +91,7 @@ fn test_configure_shell_already_exists() {
cmd.arg("configure-shell")
.arg("--shell")
.arg("zsh")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -120,6 +130,7 @@ fn test_configure_shell_custom_prefix() {
.arg("bash")
.arg("--cmd")
.arg("worktree")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -147,6 +158,7 @@ fn test_configure_shell_fish() {
cmd.arg("configure-shell")
.arg("--shell")
.arg("fish")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -159,8 +171,9 @@ fn test_configure_shell_fish() {
let content = fs::read_to_string(&fish_config).unwrap();
assert!(
- content.contains("wt init fish | source"),
- "Should contain wt init command"
+ content.trim() == "if type -q wt; wt init fish | source; end",
+ "Should contain conditional wrapper: {}",
+ content
);
}
@@ -178,6 +191,7 @@ fn test_configure_shell_no_files() {
let mut cmd = Command::new(get_cargo_bin("wt"));
repo.clean_cli_env(&mut cmd);
cmd.arg("configure-shell")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -203,6 +217,7 @@ fn test_configure_shell_fish_custom_prefix() {
.arg("fish")
.arg("--cmd")
.arg("worktree")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -218,8 +233,9 @@ fn test_configure_shell_fish_custom_prefix() {
let content = fs::read_to_string(&fish_config).unwrap();
assert!(
- content.contains("worktree init fish | source"),
- "Should contain worktree init command with custom prefix"
+ content.trim() == "if type -q worktree; worktree init fish | source; end",
+ "Should contain conditional wrapper with custom prefix: {}",
+ content
);
}
@@ -247,6 +263,7 @@ fn test_configure_shell_multiple_configs() {
let mut cmd = Command::new(get_cargo_bin("wt"));
repo.clean_cli_env(&mut cmd);
cmd.arg("configure-shell")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -281,7 +298,7 @@ fn test_configure_shell_mixed_states() {
};
fs::write(
&bash_config_path,
- "# Existing config\neval \"$(wt init bash)\"\n",
+ "# Existing config\nif command -v wt >/dev/null 2>&1; then eval \"$(wt init bash)\"; fi\n",
)
.unwrap();
@@ -297,6 +314,7 @@ fn test_configure_shell_mixed_states() {
let mut cmd = Command::new(get_cargo_bin("wt"));
repo.clean_cli_env(&mut cmd);
cmd.arg("configure-shell")
+ .arg("--yes")
.env("HOME", temp_home.path())
.current_dir(repo.root_path());
@@ -318,88 +336,3 @@ fn test_configure_shell_mixed_states() {
"Zsh config should be updated"
);
}
-
-/// Test configure-shell --dry-run shows both shells needing updates and already configured shells
-#[test]
-fn test_configure_shell_mixed_states_dry_run() {
- let repo = TestRepo::new();
- let temp_home = TempDir::new().unwrap();
-
- // Create bash config with wt already configured
- let bash_config_path = if cfg!(target_os = "macos") {
- temp_home.path().join(".bash_profile")
- } else {
- temp_home.path().join(".bashrc")
- };
- fs::write(
- &bash_config_path,
- "# Existing config\neval \"$(wt init bash)\"\n",
- )
- .unwrap();
-
- // Create zsh config without wt
- let zshrc_path = temp_home.path().join(".zshrc");
- fs::write(&zshrc_path, "# Existing zsh config\n").unwrap();
-
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
- settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
-
- settings.bind(|| {
- let mut cmd = Command::new(get_cargo_bin("wt"));
- repo.clean_cli_env(&mut cmd);
- cmd.arg("configure-shell")
- .arg("--dry-run")
- .env("HOME", temp_home.path())
- .current_dir(repo.root_path());
-
- assert_cmd_snapshot!("configure_shell_mixed_states_dry_run", cmd);
- });
-
- // Verify files were not modified in dry-run
- let bash_content = fs::read_to_string(&bash_config_path).unwrap();
- let bash_wt_count = bash_content.matches("wt init").count();
- assert_eq!(
- bash_wt_count, 1,
- "Bash should still have exactly one wt init line"
- );
-
- let zsh_content = fs::read_to_string(&zshrc_path).unwrap();
- assert!(
- !zsh_content.contains("eval \"$(wt init zsh)\""),
- "Zsh config should not be modified in dry-run"
- );
-}
-
-/// Test configure-shell detects Fish when conf.d directory exists
-#[test]
-fn test_configure_shell_fish_conf_d_exists() {
- let repo = TestRepo::new();
- let temp_home = TempDir::new().unwrap();
-
- // Create Fish conf.d directory (but not the wt.fish file)
- let fish_conf_d = temp_home.path().join(".config/fish/conf.d");
- fs::create_dir_all(&fish_conf_d).unwrap();
-
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
- settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
-
- settings.bind(|| {
- let mut cmd = Command::new(get_cargo_bin("wt"));
- repo.clean_cli_env(&mut cmd);
- cmd.arg("configure-shell")
- .arg("--dry-run")
- .env("HOME", temp_home.path())
- .current_dir(repo.root_path());
-
- assert_cmd_snapshot!("configure_shell_fish_conf_d_exists", cmd);
- });
-
- // Verify the fish file was not created in dry-run
- let fish_config = temp_home.path().join(".config/fish/conf.d/wt.fish");
- assert!(
- !fish_config.exists(),
- "Fish config file should not be created in dry-run"
- );
-}
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap
index d7151e69d..6bf91360d 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap
@@ -6,6 +6,7 @@ info:
- configure-shell
- "--shell"
- zsh
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -13,7 +14,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpCE8Zcm
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpERU3Zo
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -21,7 +22,7 @@ info:
success: true
exit_code: 0
----- stdout -----
-Already configured zsh [TEMP_HOME]/.zshrc
- eval "$(wt init zsh)"
+Already configured zsh [TEMP_HOME]/.zshrc
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init zsh)"; fi
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap
index de1e99dd2..a6904cd1b 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap
@@ -8,6 +8,7 @@ info:
- bash
- "--cmd"
- worktree
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -15,7 +16,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpus29kR
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2TPYeW
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -23,7 +24,7 @@ info:
success: true
exit_code: 0
----- stdout -----
-Added bash [TEMP_HOME]/.bash_profile
- eval "$(worktree init bash)"
+Added bash [TEMP_HOME]/.bash_profile
+ if command -v worktree >/dev/null 2>&1; then eval "$(worktree init bash)"; fi
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap
index 6c4128a17..6e9659624 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap
@@ -6,6 +6,7 @@ info:
- configure-shell
- "--shell"
- fish
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -13,7 +14,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpusgPLX
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRrLvi6
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -21,7 +22,7 @@ info:
success: true
exit_code: 0
----- stdout -----
-Created fish [TEMP_HOME]/.config/fish/conf.d/wt.fish
- wt init fish | source
+Created fish [TEMP_HOME]/.config/fish/conf.d/wt.fish
+ if type -q wt; wt init fish | source; end
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap
index 8a3af9ca3..272e89085 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap
@@ -8,6 +8,7 @@ info:
- fish
- "--cmd"
- worktree
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -15,7 +16,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp7RffoA
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpHWEVR4
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -23,7 +24,7 @@ info:
success: true
exit_code: 0
----- stdout -----
-Created fish [TEMP_HOME]/.config/fish/conf.d/worktree.fish
- worktree init fish | source
+Created fish [TEMP_HOME]/.config/fish/conf.d/worktree.fish
+ if type -q worktree; worktree init fish | source; end
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_mixed_states.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_mixed_states.snap
index 88fd0fbfb..da1fa1147 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_mixed_states.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_mixed_states.snap
@@ -4,6 +4,7 @@ info:
program: wt
args:
- configure-shell
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -11,7 +12,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpah5k5T
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpCqxPsc
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -19,9 +20,9 @@ info:
success: true
exit_code: 0
----- stdout -----
-Already configured bash [TEMP_HOME]/.bash_profile
- eval "$(wt init bash)"
-Added zsh [TEMP_HOME]/.zshrc
- eval "$(wt init zsh)"
+Already configured bash [TEMP_HOME]/.bash_profile
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init bash)"; fi
+Added zsh [TEMP_HOME]/.zshrc
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init zsh)"; fi
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap
index 76b789859..f6f546e84 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap
@@ -4,6 +4,7 @@ info:
program: wt
args:
- configure-shell
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -11,7 +12,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpV1fR3f
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp5RiHJU
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -19,9 +20,9 @@ info:
success: true
exit_code: 0
----- stdout -----
-Added bash [TEMP_HOME]/.bash_profile
- eval "$(wt init bash)"
-Added zsh [TEMP_HOME]/.zshrc
- eval "$(wt init zsh)"
+Added bash [TEMP_HOME]/.bash_profile
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init bash)"; fi
+Added zsh [TEMP_HOME]/.zshrc
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init zsh)"; fi
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_with_yes.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_with_yes.snap
new file mode 100644
index 000000000..752baa9c9
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_with_yes.snap
@@ -0,0 +1,26 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--yes"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpsM7nu9
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Added zsh [TEMP_HOME]/.zshrc
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init zsh)"; fi
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap
index 1ab5ff25d..460f1109b 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap
@@ -6,6 +6,7 @@ info:
- configure-shell
- "--shell"
- zsh
+ - "--yes"
env:
CLICOLOR_FORCE: "1"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
@@ -13,7 +14,7 @@ info:
GIT_CONFIG_GLOBAL: /dev/null
GIT_CONFIG_SYSTEM: /dev/null
GIT_EDITOR: ""
- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpQbOOEv
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpyxX7Uq
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1704067200"
@@ -21,7 +22,7 @@ info:
success: true
exit_code: 0
----- stdout -----
-Added zsh [TEMP_HOME]/.zshrc
- eval "$(wt init zsh)"
+Added zsh [TEMP_HOME]/.zshrc
+ if command -v wt >/dev/null 2>&1; then eval "$(wt init zsh)"; fi
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 3ca027463..5627e2864 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -21,54 +21,57 @@ exit_code: 0
----- stdout -----
# worktrunk shell integration for bash
-# Helper function to parse wt output and handle directives
-_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
+# Only initialize if wt is available
+if command -v wt >/dev/null 2>&1; then
+ # Helper function to parse wt output and handle directives
+ _wt_exec() {
+ local output line exit_code
+ output="$(command wt "$@" 2>&1)"
+ exit_code=$?
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
- else
- # Regular output - print it
- echo "$line"
- fi
- done <<< "$output"
+ # Parse output line by line
+ while IFS= read -r line; do
+ if [[ "$line" == __WORKTRUNK_CD__* ]]; then
+ # Extract path and change directory
+ \cd "${line#__WORKTRUNK_CD__}"
+ else
+ # Regular output - print it
+ echo "$line"
+ fi
+ done <<< "$output"
- return $exit_code
-}
+ return $exit_code
+ }
-# Override wt command to add --internal flag for switch, remove, and merge
-wt() {
- local subcommand="$1"
+ # Override wt command to add --internal flag for switch, remove, and merge
+ wt() {
+ local subcommand="$1"
- case "$subcommand" in
- switch|remove|merge)
- # Commands that need --internal for directory change support
- shift
- _wt_exec "$subcommand" --internal "$@"
- ;;
- *)
- # All other commands pass through directly
- command wt "$@"
- ;;
- esac
-}
+ case "$subcommand" in
+ switch|remove|merge)
+ # Commands that need --internal for directory change support
+ shift
+ _wt_exec "$subcommand" --internal "$@"
+ ;;
+ *)
+ # All other commands pass through directly
+ command wt "$@"
+ ;;
+ esac
+ }
-# Dynamic completion function
-_wt_complete() {
- local cur="${COMP_WORDS[COMP_CWORD]}"
+ # 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"))
-}
+ # 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
+ # Register dynamic completion
+ complete -F _wt_complete wt
+fi
# Static completions (commands and flags)
_wt() {
@@ -165,7 +168,7 @@ _wt() {
return 0
;;
wt__configure__shell)
- opts="-h --shell --cmd --dry-run --help"
+ opts="-y -h --shell --cmd --yes --help"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
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 30f47f167..5065187ad 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
@@ -23,54 +23,57 @@ exit_code: 0
----- stdout -----
# worktrunk shell integration for bash
-# Helper function to parse wt output and handle directives
-_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
+# Only initialize if wt is available
+if command -v wt >/dev/null 2>&1; then
+ # Helper function to parse wt output and handle directives
+ _wt_exec() {
+ local output line exit_code
+ output="$(command wt "$@" 2>&1)"
+ exit_code=$?
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
- else
- # Regular output - print it
- echo "$line"
- fi
- done <<< "$output"
+ # Parse output line by line
+ while IFS= read -r line; do
+ if [[ "$line" == __WORKTRUNK_CD__* ]]; then
+ # Extract path and change directory
+ \cd "${line#__WORKTRUNK_CD__}"
+ else
+ # Regular output - print it
+ echo "$line"
+ fi
+ done <<< "$output"
- return $exit_code
-}
+ return $exit_code
+ }
-# Override wt command to add --internal flag for switch, remove, and merge
-wt() {
- local subcommand="$1"
+ # Override wt command to add --internal flag for switch, remove, and merge
+ wt() {
+ local subcommand="$1"
- case "$subcommand" in
- switch|remove|merge)
- # Commands that need --internal for directory change support
- shift
- _wt_exec "$subcommand" --internal "$@"
- ;;
- *)
- # All other commands pass through directly
- command wt "$@"
- ;;
- esac
-}
+ case "$subcommand" in
+ switch|remove|merge)
+ # Commands that need --internal for directory change support
+ shift
+ _wt_exec "$subcommand" --internal "$@"
+ ;;
+ *)
+ # All other commands pass through directly
+ command wt "$@"
+ ;;
+ esac
+ }
-# Dynamic completion function
-_wt_complete() {
- local cur="${COMP_WORDS[COMP_CWORD]}"
+ # 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"))
-}
+ # 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
+ # Register dynamic completion
+ complete -F _wt_complete wt
+fi
# Static completions (commands and flags)
_wt() {
@@ -167,7 +170,7 @@ _wt() {
return 0
;;
wt__configure__shell)
- opts="-h --shell --cmd --dry-run --help"
+ opts="-y -h --shell --cmd --yes --help"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 88c1bce25..e2d47b7f1 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -21,51 +21,54 @@ exit_code: 0
----- stdout -----
# worktrunk shell integration for fish
-# Helper function to parse wt output and handle directives
-function _wt_exec
- set -l output (command wt $argv 2>&1)
- set -l exit_code $status
+# Only initialize if wt is available
+if type -q wt
+ # Helper function to parse wt output and handle directives
+ function _wt_exec
+ set -l output (command wt $argv 2>&1)
+ set -l exit_code $status
- # Parse output line by line
- for line in (string split \n -- $output)
- if string match -q '__WORKTRUNK_CD__*' -- $line
- # Extract path and change directory
- cd (string replace '__WORKTRUNK_CD__' '' -- $line)
- else
- # Regular output - print it
- echo $line
+ # Parse output line by line
+ for line in (string split \n -- $output)
+ if string match -q '__WORKTRUNK_CD__*' -- $line
+ # Extract path and change directory
+ cd (string replace '__WORKTRUNK_CD__' '' -- $line)
+ else
+ # Regular output - print it
+ echo $line
+ end
end
+
+ return $exit_code
end
- return $exit_code
-end
+ # Override wt command to add --internal flag for switch, remove, and merge
+ function wt
+ set -l subcommand $argv[1]
-# Override wt command to add --internal flag for switch, remove, and merge
-function wt
- set -l subcommand $argv[1]
+ switch $subcommand
+ case switch remove merge
+ # Commands that need --internal for directory change support
+ _wt_exec $subcommand --internal $argv[2..-1]
+ case '*'
+ # All other commands pass through directly
+ command wt $argv
+ end
+ end
- switch $subcommand
- case switch remove merge
- # Commands that need --internal for directory change support
- _wt_exec $subcommand --internal $argv[2..-1]
- case '*'
- # All other commands pass through directly
- command wt $argv
+ # 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
-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
+ # 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'
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'
-
# Static completions (commands and flags)
# Print an optspec for argparse to handle cmd's options that are independent of any subcommand.
function __fish_wt_global_optspecs
@@ -113,7 +116,7 @@ powershell\t''
xonsh\t''
zsh\t''"
complete -c wt -n "__fish_wt_using_subcommand configure-shell" -l cmd -d 'Command prefix (default: wt)' -r
-complete -c wt -n "__fish_wt_using_subcommand configure-shell" -l dry-run -d 'Show what would be done without making changes'
+complete -c wt -n "__fish_wt_using_subcommand configure-shell" -s y -l yes -d 'Skip confirmation prompt'
complete -c wt -n "__fish_wt_using_subcommand configure-shell" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand list" -l format -d 'Output format' -r -f -a "table\t'Human-readable table format'
json\t'JSON format'"
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 21ae261bd..36b69d726 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -21,54 +21,57 @@ exit_code: 0
----- stdout -----
# worktrunk shell integration for zsh
-# Helper function to parse wt output and handle directives
-_wt_exec() {
- local output line exit_code
- output="$(command wt "$@" 2>&1)"
- exit_code=$?
-
- # Parse output line by line
- while IFS= read -r line; do
- if [[ "$line" == __WORKTRUNK_CD__* ]]; then
- # Extract path and change directory
- \cd "${line#__WORKTRUNK_CD__}"
- else
- # Regular output - print it
- echo "$line"
- fi
- done <<< "$output"
-
- return $exit_code
-}
+# Only initialize if wt is available
+if command -v wt >/dev/null 2>&1; then
+ # Helper function to parse wt output and handle directives
+ _wt_exec() {
+ local output line exit_code
+ output="$(command wt "$@" 2>&1)"
+ exit_code=$?
-# Override wt command to add --internal flag for switch, remove, and merge
-wt() {
- local subcommand="$1"
-
- case "$subcommand" in
- switch|remove|merge)
- # Commands that need --internal for directory change support
- shift
- _wt_exec "$subcommand" --internal "$@"
- ;;
- *)
- # All other commands pass through directly
- command wt "$@"
- ;;
- esac
-}
+ # Parse output line by line
+ while IFS= read -r line; do
+ if [[ "$line" == __WORKTRUNK_CD__* ]]; then
+ # Extract path and change directory
+ \cd "${line#__WORKTRUNK_CD__}"
+ else
+ # Regular output - print it
+ echo "$line"
+ fi
+ done <<< "$output"
-# Dynamic completion function
-_wt_complete() {
- local cur="${COMP_WORDS[COMP_CWORD]}"
+ return $exit_code
+ }
- # Call wt complete with current command line
- local completions=$(command wt complete "${COMP_WORDS[@]}" 2>/dev/null)
- COMPREPLY=($(compgen -W "$completions" -- "$cur"))
-}
+ # Override wt command to add --internal flag for switch, remove, and merge
+ wt() {
+ local subcommand="$1"
+
+ case "$subcommand" in
+ switch|remove|merge)
+ # Commands that need --internal for directory change support
+ shift
+ _wt_exec "$subcommand" --internal "$@"
+ ;;
+ *)
+ # All other commands pass through directly
+ command wt "$@"
+ ;;
+ esac
+ }
+
+ # Dynamic completion function
+ _wt_complete() {
+ local cur="${COMP_WORDS[COMP_CWORD]}"
-# Register dynamic completion
-complete -F _wt_complete wt
+ # 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
+fi
# Static completions (commands and flags)
#compdef wt
@@ -113,7 +116,8 @@ _arguments "${_arguments_options[@]}" : \
_arguments "${_arguments_options[@]}" : \
'--shell=[Specific shell to configure (default\: all shells with existing config files)]:SHELL:(bash elvish fish nushell oil powershell xonsh zsh)' \
'--cmd=[Command prefix (default\: wt)]:CMD:_default' \
-'--dry-run[Show what would be done without making changes]' \
+'-y[Skip confirmation prompt]' \
+'--yes[Skip confirmation prompt]' \
'-h[Print help]' \
'--help[Print help]' \
&& ret=0