Skip to content

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

fix(shell): add `| Out-String` to PowerShell config_line (#888)

Maximilian Roos722e70373d3e
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index f63f32b2f..bf36897fc 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -1063,7 +1063,7 @@ fn uninstall_from_file(
let integration_lines: Vec<(usize, &str)> = lines
.iter()
.enumerate()
- .filter(|(_, line)| shell::is_shell_integration_line(line, cmd))
+ .filter(|(_, line)| shell::is_shell_integration_line_for_uninstall(line, cmd))
.map(|(i, line)| (i, *line))
.collect();
diff --git a/src/shell/detection.rs b/src/shell/detection.rs
index 21be7a14d..50f11d8e1 100644
--- a/src/shell/detection.rs
+++ b/src/shell/detection.rs
@@ -85,6 +85,18 @@ use super::paths::{home_dir_required, powershell_profile_paths};
/// This means false negatives only cause incorrect messaging in `wt config show`
/// and when users run the binary directly before restarting their shell.
pub fn is_shell_integration_line(line: &str, cmd: &str) -> bool {
+ is_shell_integration_line_impl(line, cmd, true)
+}
+
+/// Permissive version for uninstall - matches old PowerShell configs without `| Out-String`.
+///
+/// Used by `wt config shell uninstall` to find and remove outdated config lines
+/// that would otherwise be left behind.
+pub fn is_shell_integration_line_for_uninstall(line: &str, cmd: &str) -> bool {
+ is_shell_integration_line_impl(line, cmd, false)
+}
+
+fn is_shell_integration_line_impl(line: &str, cmd: &str, strict: bool) -> bool {
let trimmed = line.trim();
// Skip comments (# for POSIX shells, <# #> for PowerShell block comments)
@@ -93,24 +105,27 @@ pub fn is_shell_integration_line(line: &str, cmd: &str) -> bool {
}
// Check for eval/source line pattern
- has_init_invocation(trimmed, cmd)
+ has_init_invocation(trimmed, cmd, strict)
}
/// Check if line contains `{cmd} config shell init` as a command invocation.
///
/// For `wt`: matches `wt config shell init` but NOT `git wt` or `git-wt`.
/// For `git-wt`: matches `git-wt config shell init` OR `git wt config shell init`.
-fn has_init_invocation(line: &str, cmd: &str) -> bool {
+///
+/// When `strict` is true, PowerShell lines must include `| Out-String` to match.
+/// When `strict` is false (for uninstall), old PowerShell lines without it also match.
+fn has_init_invocation(line: &str, cmd: &str, strict: bool) -> bool {
// For git-wt, we need to match both "git-wt config shell init" AND "git wt config shell init"
// because users invoke it both ways (and git dispatches "git wt" to "git-wt")
if cmd == "git-wt" {
// Match either form, with boundary check for "git" in "git wt" form
- return has_init_pattern_with_prefix_check(line, "git-wt")
- || has_init_pattern_with_prefix_check(line, "git wt");
+ return has_init_pattern_with_prefix_check(line, "git-wt", strict)
+ || has_init_pattern_with_prefix_check(line, "git wt", strict);
}
// For other commands, use normal matching with prefix exclusion
- has_init_pattern_with_prefix_check(line, cmd)
+ has_init_pattern_with_prefix_check(line, cmd, strict)
}
/// Check if line has the init pattern, with prefix exclusion for non-git-wt commands.
@@ -120,7 +135,10 @@ fn has_init_invocation(line: &str, cmd: &str) -> bool {
/// ```text
/// eval "$(git-wt.exe config shell init bash)"
/// ```
-fn has_init_pattern_with_prefix_check(line: &str, cmd: &str) -> bool {
+///
+/// When `strict` is true, PowerShell lines must include `| Out-String`.
+/// When `strict` is false (for uninstall), old PowerShell lines also match.
+fn has_init_pattern_with_prefix_check(line: &str, cmd: &str, strict: bool) -> bool {
// Search for both plain command and .exe variant (Windows Git Bash)
let patterns = [
format!("{cmd} config shell init"),
@@ -143,14 +161,34 @@ fn has_init_pattern_with_prefix_check(line: &str, cmd: &str) -> bool {
// Check what precedes the match
if is_valid_command_position(line, absolute_pos, &cmd_in_line) {
// Must be in an execution context (eval, source, dot command, PowerShell, etc.)
- if line.contains("eval")
+ //
+ // PowerShell detection is checked FIRST and uses case-insensitive matching.
+ // PowerShell requires | Out-String to work correctly (issue #885).
+ // Without it, Invoke-Expression fails with "Cannot convert 'System.Object[]'".
+ // In strict mode, we don't detect old configs without Out-String so that
+ // `wt config shell install` will update them.
+ // In permissive mode (uninstall), we match old configs so they can be removed.
+ let line_lower = line.to_lowercase();
+ let has_invoke =
+ line_lower.contains("invoke-expression") || line_lower.contains("iex");
+ if has_invoke {
+ // PowerShell line
+ if !strict || line_lower.contains("out-string") {
+ return true;
+ }
+ // Strict mode: old PowerShell config without Out-String, don't detect
+ // Skip to next pattern search position
+ search_start = absolute_pos + 1;
+ continue;
+ }
+
+ // POSIX shells (bash, zsh, fish)
+ let is_posix_shell = line.contains("eval")
|| line.contains("source")
- || line.contains(". <(") // POSIX dot command with process substitution
- || line.contains(". =(") // zsh dot command with =() substitution
- || line.contains("Invoke-Expression")
- || line.contains("iex")
- || line.contains("if ")
- {
+ || line.contains(". <(") // POSIX dot command with process substitution
+ || line.contains(". =("); // zsh dot command with =() substitution
+
+ if is_posix_shell {
return true;
}
}
@@ -668,11 +706,12 @@ mod tests {
// ------------------------------------------------------------------------
/// iex is PowerShell's alias for Invoke-Expression - now detected
+ /// Must include | Out-String to be detected (issue #885)
#[test]
fn test_powershell_iex_alias() {
- // Common in PowerShell profiles
+ // Common in PowerShell profiles - must have | Out-String
assert_detects(
- "iex (wt config shell init powershell)",
+ "iex (wt config shell init powershell | Out-String)",
"wt",
"PowerShell iex alias",
);
@@ -681,12 +720,67 @@ mod tests {
#[test]
fn test_powershell_iex_with_ampersand() {
assert_detects(
- "iex (& wt config shell init powershell)",
+ "iex (& wt config shell init powershell | Out-String)",
"wt",
"PowerShell iex with &",
);
}
+ /// PowerShell lines without | Out-String should NOT be detected (strict mode)
+ /// This ensures old configs are treated as "not installed" so users get the fix
+ #[test]
+ fn test_powershell_without_out_string_not_detected() {
+ assert_not_detects(
+ "iex (wt config shell init powershell)",
+ "wt",
+ "PowerShell without Out-String (outdated config)",
+ );
+ assert_not_detects(
+ "Invoke-Expression (& wt config shell init powershell)",
+ "wt",
+ "Invoke-Expression without Out-String (outdated config)",
+ );
+ // This is the exact old canonical PowerShell line that users have
+ assert_not_detects(
+ "if (Get-Command wt -ErrorAction SilentlyContinue) { Invoke-Expression (& wt config shell init powershell) }",
+ "wt",
+ "exact old canonical PowerShell line (must not detect)",
+ );
+ }
+
+ /// Permissive mode (for uninstall) SHOULD detect old PowerShell lines without | Out-String
+ #[test]
+ fn test_powershell_permissive_mode_for_uninstall() {
+ // Old configs should be detected by the permissive function (for uninstall)
+ assert!(
+ is_shell_integration_line_for_uninstall("iex (wt config shell init powershell)", "wt"),
+ "Permissive mode should detect old PowerShell config"
+ );
+ assert!(
+ is_shell_integration_line_for_uninstall(
+ "Invoke-Expression (& wt config shell init powershell)",
+ "wt"
+ ),
+ "Permissive mode should detect old Invoke-Expression config"
+ );
+ // The exact old canonical line
+ assert!(
+ is_shell_integration_line_for_uninstall(
+ "if (Get-Command wt -ErrorAction SilentlyContinue) { Invoke-Expression (& wt config shell init powershell) }",
+ "wt"
+ ),
+ "Permissive mode should detect exact old canonical PowerShell line"
+ );
+ // New configs should also be detected
+ assert!(
+ is_shell_integration_line_for_uninstall(
+ "iex (wt config shell init powershell | Out-String)",
+ "wt"
+ ),
+ "Permissive mode should also detect new PowerShell config"
+ );
+ }
+
// ------------------------------------------------------------------------
// FALSE NEGATIVE: PowerShell block comments
// Note: This is actually a FALSE POSITIVE risk (comments matching)
diff --git a/src/shell/mod.rs b/src/shell/mod.rs
index 0a18a49cf..491b924ba 100644
--- a/src/shell/mod.rs
+++ b/src/shell/mod.rs
@@ -16,7 +16,7 @@ use askama::Template;
// Re-export public types and functions
pub use detection::{
BypassAlias, DetectedLine, FileDetectionResult, is_shell_integration_line,
- scan_for_detection_details,
+ is_shell_integration_line_for_uninstall, scan_for_detection_details,
};
pub use paths::{completion_path, config_paths, legacy_fish_conf_d_path};
pub use utils::{current_shell, detect_zsh_compinit, extract_filename_from_path};
@@ -91,8 +91,11 @@ impl Shell {
)
}
Self::PowerShell => {
+ // Note: `| Out-String` is required because PowerShell command output is an array
+ // of strings by default, but Invoke-Expression expects a single string.
+ // Without it, Invoke-Expression fails with "Cannot convert 'System.Object[]'"
format!(
- "if (Get-Command {cmd} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {cmd} config shell init powershell) }}",
+ "if (Get-Command {cmd} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {cmd} config shell init powershell | Out-String) }}",
)
}
}
@@ -445,4 +448,7 @@ mod tests {
// Note: is_shell_configured() is not unit-tested because it requires
// mutating HOME env var (unsafe). It's tested indirectly via integration
// tests that exercise the shell integration warning paths.
+
+ // PowerShell config_line evaluation test is in tests/integration_tests/shell_powershell.rs
+ // because it needs CARGO_BIN_EXE_wt which is only available in integration tests.
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell.snap
index df308116c..de2c3f271 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell.snap
@@ -2,4 +2,4 @@
source: src/shell/mod.rs
expression: "Shell::PowerShell.config_line(\"wt\")"
---
-if (Get-Command wt -ErrorAction SilentlyContinue) { Invoke-Expression (& wt config shell init powershell) }
+if (Get-Command wt -ErrorAction SilentlyContinue) { Invoke-Expression (& wt config shell init powershell | Out-String) }
diff --git a/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snap
index 1cd4de9d2..61b678ea1 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snap
@@ -2,4 +2,4 @@
source: src/shell/mod.rs
expression: "Shell::PowerShell.config_line(\"git-wt\")"
---
-if (Get-Command git-wt -ErrorAction SilentlyContinue) { Invoke-Expression (& git-wt config shell init powershell) }
+if (Get-Command git-wt -ErrorAction SilentlyContinue) { Invoke-Expression (& git-wt config shell init powershell | Out-String) }
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index b6c44bb1d..cd20f1f19 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -49,6 +49,7 @@ pub mod select;
pub mod select_config;
pub mod shell_integration_prompt;
pub mod shell_integration_windows;
+pub mod shell_powershell;
pub mod shell_wrapper;
pub mod spacing_edge_cases;
pub mod statusline;
diff --git a/tests/integration_tests/shell_powershell.rs b/tests/integration_tests/shell_powershell.rs
new file mode 100644
index 000000000..db19db4ef
--- /dev/null
+++ b/tests/integration_tests/shell_powershell.rs
@@ -0,0 +1,72 @@
+//! PowerShell shell integration tests.
+//!
+//! These tests verify that PowerShell shell integration works correctly.
+//! Requires pwsh (PowerShell Core), which is pre-installed on GitHub Actions runners.
+
+#![cfg(feature = "shell-integration-tests")]
+
+use std::path::Path;
+use std::process::Command;
+
+use worktrunk::shell::Shell;
+
+/// Test that the PowerShell config_line() actually works when evaluated.
+///
+/// This is a regression test for issue #885 where `Invoke-Expression` failed
+/// because command output is an array of strings, not a single string.
+/// The fix was adding `| Out-String` to the config_line.
+#[test]
+fn test_powershell_config_line_evaluates_correctly() {
+ // Use CARGO_BIN_EXE_wt which Cargo sets to the wt binary path during tests
+ let wt_bin = Path::new(env!("CARGO_BIN_EXE_wt"));
+ let bin_dir = wt_bin.parent().expect("Failed to get binary directory");
+
+ // Build a script that:
+ // 1. Adds the binary directory to PATH so Get-Command wt works
+ // 2. Sets WORKTRUNK_BIN so the init script can find the binary
+ // 3. Runs the config_line (which uses Invoke-Expression)
+ // 4. Checks if the function is defined
+ let config_line = Shell::PowerShell.config_line("wt");
+ let script = format!(
+ r#"
+$env:PATH = '{}' + [IO.Path]::PathSeparator + $env:PATH
+$env:WORKTRUNK_BIN = '{}'
+{}
+$cmd = Get-Command wt -ErrorAction SilentlyContinue
+if ($cmd -and $cmd.CommandType -eq 'Function') {{
+ Write-Output 'FUNCTION_DEFINED'
+}} else {{
+ Write-Output "FUNCTION_NOT_DEFINED: CommandType=$($cmd.CommandType)"
+}}
+"#,
+ bin_dir.display().to_string().replace('\'', "''"),
+ wt_bin.display().to_string().replace('\'', "''"),
+ config_line
+ );
+
+ let output = Command::new("pwsh")
+ .args(["-NoProfile", "-NonInteractive", "-Command", &script])
+ .output()
+ .expect("Failed to run pwsh");
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ output.status.success(),
+ "pwsh command failed.\nstdout: {}\nstderr: {}",
+ stdout,
+ stderr
+ );
+
+ assert!(
+ stdout.contains("FUNCTION_DEFINED"),
+ "PowerShell config_line failed to define function.\n\
+ Config line: {}\n\
+ stdout: {}\n\
+ stderr: {}",
+ config_line,
+ stdout,
+ stderr
+ );
+}