Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(shell): auto-configure PowerShell on Windows when SHELL is not set (#898)
Maximilian Roosdc753d0f85bc
diff --git a/.claude-plugin/skills/worktrunk/reference/faq.md b/.claude-plugin/skills/worktrunk/reference/faq.mdindex e724f0700..400baaede 100644--- a/.claude-plugin/skills/worktrunk/reference/faq.md+++ b/.claude-plugin/skills/worktrunk/reference/faq.md@@ -90,6 +90,11 @@ Created by `wt config shell install`:- **Bash**: adds line to `~/.bashrc`- **Zsh**: adds line to `~/.zshrc` (or `$ZDOTDIR/.zshrc`)- **Fish**: creates `~/.config/fish/functions/wt.fish` and `~/.config/fish/completions/wt.fish`+- **PowerShell** (Windows): creates both profile files if they don't exist:+ - `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+)+ - `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)++**PowerShell detection on Windows:** When running from cmd.exe or PowerShell, both PowerShell profile files are created automatically. When running from Git Bash or MSYS2, PowerShell is skipped (use `wt config shell install powershell` to create the profiles explicitly).**To remove:** `wt config shell uninstall`.diff --git a/.claude-plugin/skills/worktrunk/reference/troubleshooting.md b/.claude-plugin/skills/worktrunk/reference/troubleshooting.mdindex 30f9fe838..a791f26ba 100644--- a/.claude-plugin/skills/worktrunk/reference/troubleshooting.md+++ b/.claude-plugin/skills/worktrunk/reference/troubleshooting.md@@ -73,3 +73,27 @@ post-create = "npm run build"post-create = "npm install"post-start = "npm run build"```++## PowerShell on Windows++### PowerShell profiles not created++On Windows, `wt config shell install` creates PowerShell profiles automatically when running from cmd.exe or PowerShell. It creates both:+- `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+/pwsh)+- `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)++**If running from Git Bash or MSYS2**, PowerShell is skipped because the `SHELL` environment variable is set. To create PowerShell profiles explicitly:++```bash+wt config shell install powershell+```++### Wrong PowerShell variant configured++Both profile files are created when installing from a Windows-native shell. This ensures shell integration works regardless of which PowerShell variant the user opens later. The profile files are small and harmless if unused.++### Detection logic++Worktrunk detects Windows-native shells (cmd/PowerShell) by checking if the `SHELL` environment variable is **not** set:+- `SHELL` not set → Windows-native shell → create both PowerShell profiles+- `SHELL` set (e.g., `/usr/bin/bash`) → Git Bash/MSYS2 → skip PowerShelldiff --git a/docs/content/faq.md b/docs/content/faq.mdindex c45304fc2..323c737f4 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -96,6 +96,11 @@ Created by `wt config shell install`:- **Bash**: adds line to `~/.bashrc`- **Zsh**: adds line to `~/.zshrc` (or `$ZDOTDIR/.zshrc`)- **Fish**: creates `~/.config/fish/functions/wt.fish` and `~/.config/fish/completions/wt.fish`+- **PowerShell** (Windows): creates both profile files if they don't exist:+ - `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+)+ - `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)++**PowerShell detection on Windows:** When running from cmd.exe or PowerShell, both PowerShell profile files are created automatically. When running from Git Bash or MSYS2, PowerShell is skipped (use `wt config shell install powershell` to create the profiles explicitly).**To remove:** `wt config shell uninstall`.diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex bf36897fc..45ab4c423 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -292,15 +292,53 @@ pub fn handle_configure_shell(})}+/// Check if we should auto-configure PowerShell profiles.+///+/// **Non-Windows:** PowerShell Core sets PSModulePath, which we use to detect+/// PowerShell sessions. This is reliable because PowerShell must be explicitly+/// installed on these platforms.+///+/// **Windows:** We check that `SHELL` is NOT set. The `SHELL` env var is set by+/// Git Bash, MSYS2, and Cygwin, but NOT by cmd.exe or PowerShell. When `SHELL`+/// is absent on Windows, the user is likely in a Windows-native shell (cmd or+/// PowerShell), so we auto-configure both PowerShell profiles. This avoids the+/// PSModulePath false-positive issue (issue #885) while still supporting+/// PowerShell users who haven't created a profile yet.+fn should_auto_configure_powershell() -> bool {+ // Allow tests to override detection (set via Command::env() in integration tests)+ if let Ok(val) = std::env::var("WORKTRUNK_TEST_POWERSHELL_ENV") {+ return val == "1";+ }++ #[cfg(windows)]+ {+ // On Windows, SHELL is set by Git Bash/MSYS2/Cygwin but not by cmd/PowerShell.+ // If SHELL is absent, we're likely in a Windows-native shell.+ std::env::var_os("SHELL").is_none()+ }++ #[cfg(not(windows))]+ {+ // On non-Windows, PSModulePath reliably indicates PowerShell Core+ std::env::var_os("PSModulePath").is_some()+ }+}+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];- #[cfg(not(windows))]- let default_shells = vec![Shell::Bash, Shell::Zsh, Shell::Fish];+ // Base shells to check+ let mut default_shells = vec![Shell::Bash, Shell::Zsh, Shell::Fish];++ // Add PowerShell if we detect we're in a PowerShell-compatible environment.+ // - Non-Windows: PSModulePath reliably indicates PowerShell Core+ // - Windows: SHELL not set indicates Windows-native shell (cmd or PowerShell)+ let in_powershell_env = should_auto_configure_powershell();+ if in_powershell_env {+ default_shells.push(Shell::PowerShell);+ }let shells = shell_filter.map_or(default_shells, |shell| vec![shell]);@@ -328,13 +366,26 @@ pub fn scan_shell_configs(target_path.is_some()};+ // Auto-configure PowerShell when user is in a PowerShell-compatible environment,+ // even if the profile doesn't exist yet (issue #885). PowerShell doesn't create+ // a profile by default, so most users won't have one until they create it.+ // Detection:+ // - Non-Windows: PSModulePath indicates PowerShell Core+ // - Windows: SHELL not set indicates Windows-native shell (not Git Bash/MSYS2)+ let in_detected_shell = matches!(shell, Shell::PowerShell) && in_powershell_env;+// Only configure if explicitly targeting this shell OR if config file/location exists- let should_configure = shell_filter.is_some() || has_config_location;+ // OR if we detected we're running in this shell's environment+ let should_configure = shell_filter.is_some() || has_config_location || in_detected_shell;++ // Allow creating the config file if explicitly targeting this shell,+ // or if we detected we're in this shell's environment+ let allow_create = shell_filter.is_some() || in_detected_shell;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(), cmd) {+ match configure_shell_file(shell, path, dry_run, allow_create, cmd) {Ok(Some(result)) => results.push(result),Ok(None) => {} // No action neededErr(e) => {@@ -379,7 +430,7 @@ fn configure_shell_file(shell: Shell,path: &Path,dry_run: bool,- explicit_shell: bool,+ allow_create: bool,cmd: &str,) -> Result<Option<ConfigureResult>, String> {// The line we write to the config file (also used for display)@@ -398,7 +449,7 @@ fn configure_shell_file(path,&fish_wrapper,dry_run,- explicit_shell,+ allow_create,&config_line,);}@@ -468,8 +519,8 @@ fn configure_shell_file(}))} else {// File doesn't exist- // Only create if explicitly targeting this shell- if explicit_shell {+ // Only create if allowed (explicitly targeting this shell or detected environment)+ if allow_create {if dry_run {return Ok(Some(ConfigureResult {shell,@@ -517,7 +568,7 @@ fn configure_fish_file(path: &Path,content: &str,dry_run: bool,- explicit_shell: bool,+ allow_create: bool,config_line: &str,) -> Result<Option<ConfigureResult>, String> {// For Fish, we write a minimal wrapper to functions/{cmd}.fish that sources@@ -544,10 +595,10 @@ fn configure_fish_file(}// File doesn't exist or doesn't have our integration- // For Fish, create if parent directory exists or if explicitly targeting this shell+ // For Fish, create if parent directory exists or if explicitly allowed// This is different from other shells because Fish uses functions/ which may exist// even if the specific wt.fish file doesn't- if !explicit_shell && !path.exists() {+ if !allow_create && !path.exists() {// Check if parent directory existsif !path.parent().is_some_and(|p| p.exists()) {return Ok(None);@@ -614,11 +665,11 @@ pub fn show_install_preview(let shell = result.shell;let path = format_path_for_display(&result.path);- // Bash/Zsh: inline completions; Fish: separate completion file- let what = if matches!(shell, Shell::Fish) {- "shell extension"- } else {+ // Bash/Zsh: inline completions; Fish/PowerShell: separate or no completions+ let what = if matches!(shell, Shell::Bash | Shell::Zsh) {"shell extension & completions"+ } else {+ "shell extension"};eprintln!(@@ -882,10 +933,8 @@ fn scan_for_uninstall(dry_run: bool,cmd: &str,) -> Result<UninstallScanResult, String> {- #[cfg(windows)]+ // For uninstall, always include PowerShell to clean up any existing profileslet default_shells = vec![Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];- #[cfg(not(windows))]- let default_shells = vec![Shell::Bash, Shell::Zsh, Shell::Fish];let shells = shell_filter.map_or(default_shells, |shell| vec![shell]);@@ -1122,11 +1171,11 @@ fn prompt_for_uninstall_confirmation(let bold = Style::new().bold();let shell = result.shell;let path = format_path_for_display(&result.path);- // Bash/Zsh: inline completions; Fish: separate completion file- let what = if matches!(shell, Shell::Fish) {- "shell extension"- } else {+ // Bash/Zsh: inline completions; Fish/PowerShell: separate or no completions+ let what = if matches!(shell, Shell::Bash | Shell::Zsh) {"shell extension & completions"+ } else {+ "shell extension"};eprintln!(@@ -1316,4 +1365,7 @@ mod tests {fn test_fish_completion_content_custom_cmd() {insta::assert_snapshot!(fish_completion_content("myapp"));}++ // Note: should_auto_configure_powershell() is tested via WORKTRUNK_TEST_POWERSHELL_ENV+ // override in tests/integration_tests/configure_shell.rs.}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex ba570769c..0daafa244 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -690,6 +690,11 @@ pub fn configure_cli_command(cmd: &mut Command) {// Remove $SHELL to avoid platform-dependent diagnostic output (macOS has /bin/zsh,// Linux has /bin/bash). Tests that need SHELL should set it explicitly.cmd.env_remove("SHELL");+ // Remove PSModulePath to prevent false PowerShell detection on CI environments+ // where PowerShell Core is installed but not being used.+ cmd.env_remove("PSModulePath");+ // Disable auto PowerShell detection (tests that need it should set to "1")+ cmd.env("WORKTRUNK_TEST_POWERSHELL_ENV", "0");cmd.env("WT_TEST_EPOCH", TEST_EPOCH.to_string());// Enable warn-level logging so diagnostics show up in test failurescmd.env("RUST_LOG", "warn");diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rsindex 12fdbe207..512a61012 100644--- a/tests/integration_tests/configure_shell.rs+++ b/tests/integration_tests/configure_shell.rs@@ -1626,3 +1626,57 @@ mod pty_tests {);}}++/// Test that WORKTRUNK_TEST_POWERSHELL_ENV=1 triggers PowerShell auto-detection.+/// This simulates the Windows behavior where we detect PowerShell when SHELL is not set.+#[rstest]+#[cfg_attr(+ windows,+ ignore = "Windows uses Documents folder which can't be easily overridden"+)]+fn test_powershell_env_detection(repo: TestRepo, temp_home: TempDir) {+ // Create the PowerShell config directory (Unix: ~/.config/powershell)+ // Note: On Windows, PowerShell uses Documents/ which dirs::document_dir() returns.+ // This test only runs on Unix where we can control the path via HOME.+ let powershell_dir = temp_home.path().join(".config/powershell");+ fs::create_dir_all(&powershell_dir).unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ // Force PowerShell detection via test env var+ cmd.env("WORKTRUNK_TEST_POWERSHELL_ENV", "1");+ // Set SHELL to something non-PowerShell to ensure we're testing the override+ cmd.env("SHELL", "/bin/bash");+ cmd.arg("config")+ .arg("shell")+ .arg("install")+ .arg("--yes")+ .current_dir(repo.root_path());++ let output = cmd.output().expect("Failed to execute command");+ assert!(output.status.success(), "Command should succeed");++ let stderr = String::from_utf8_lossy(&output.stderr);+ // Check that PowerShell was configured (not skipped)+ assert!(+ stderr.contains("Created shell extension for") && stderr.contains("powershell"),+ "Output should show PowerShell was created:\n{}",+ stderr+ );++ // Verify the PowerShell profile was created+ let profile_path = powershell_dir.join("Microsoft.PowerShell_profile.ps1");+ assert!(+ profile_path.exists(),+ "PowerShell profile should be created at {:?}",+ profile_path+ );++ let content = fs::read_to_string(&profile_path).unwrap();+ assert!(+ content.contains("wt config shell init powershell"),+ "Profile should contain shell init: {}",+ content+ );+}