Skip to content

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

fix(shell): discover the Unix PowerShell profile from the installed pwsh (#4422)

Worktrunk Bot6b0f8e2bdb0d
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index b593e1dba..b4629689a 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -27,7 +27,9 @@ use worktrunk::styling::{
};
use crate::cli::{SwitchFormat, version_str};
-use crate::commands::configure_shell::{ConfigAction, ConfigureResult, scan_shell_configs};
+use crate::commands::configure_shell::{
+ ConfigAction, ConfigureResult, ShellConfigError, scan_shell_configs,
+};
use crate::commands::list::ci_status::CiToolsStatus;
use crate::help_pager::show_help_in_pager;
use crate::llm::test_commit_generation;
@@ -1364,7 +1366,8 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
let cmd = crate::binary_name();
let scan_result = match scan_shell_configs(None, true, &cmd) {
Ok(r) => r,
- Err(e) => {
+ Err(e @ ShellConfigError::Interrupted(_)) => return Err(e.into()),
+ Err(ShellConfigError::Failed(e)) => {
writeln!(
out,
"{}",
@@ -1374,7 +1377,9 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
}
};
- // Get detection details to show matched lines inline
+ // Get detection details to show matched lines inline. The PowerShell
+ // profile query is answered once per process, so a cancelled one already
+ // ended the scan above and can't surface here.
let detection_results = scan_for_detection_details(&cmd).unwrap_or_default();
// Check for legacy fish conf.d path (deprecated location from before #566)
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index a6ef295ca..43660c3be 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -355,7 +355,7 @@ pub fn handle_configure_shell(
skip_confirmation: bool,
dry_run: bool,
cmd: String,
-) -> Result<ScanResult, String> {
+) -> Result<ScanResult, ShellConfigError> {
shell::validate_shell_command_name(&cmd)?;
// First, do a dry-run to see what would be changed
@@ -408,7 +408,7 @@ pub fn handle_configure_shell(
prompt,
)?
{
- return Err("Cancelled by user".to_string());
+ return Err("Cancelled by user".to_string().into());
}
apply_confirmed_shell_config(preview, shell_filter, &cmd)
@@ -429,7 +429,7 @@ pub(crate) fn apply_confirmed_shell_config(
mut preview: ScanResult,
shell_filter: Option<Shell>,
cmd: &str,
-) -> Result<ScanResult, String> {
+) -> Result<ScanResult, ShellConfigError> {
if !install_changes_needed(&preview) {
preview.legacy_cleanups = collect_legacy_cleanups(&preview.configured, cmd, false);
return Ok(preview);
@@ -513,13 +513,57 @@ fn should_auto_configure_powershell() -> bool {
}
}
+/// Why a shell config scan or edit failed. A cancelled PowerShell profile
+/// query stays typed, so a consumer that treats ordinary failures as "not
+/// configured" still stops the command instead of moving on to its next step.
+#[derive(Debug)]
+pub enum ShellConfigError {
+ /// The profile query was cancelled by this signal.
+ Interrupted(i32),
+ Failed(String),
+}
+
+impl ShellConfigError {
+ fn config_paths(shell: Shell, error: std::io::Error) -> Self {
+ match shell::profile_query_interruption(&error) {
+ Some(signal) => Self::Interrupted(signal),
+ None => Self::Failed(format!("Failed to get config paths for {shell}: {error}")),
+ }
+ }
+
+ /// Prefix an ordinary failure with `context`; a cancellation stays typed.
+ pub(crate) fn context(self, context: &str) -> anyhow::Error {
+ match self {
+ Self::Failed(message) => anyhow::anyhow!("{context}: {message}"),
+ interrupted => interrupted.into(),
+ }
+ }
+}
+
+impl From<String> for ShellConfigError {
+ fn from(message: String) -> Self {
+ Self::Failed(message)
+ }
+}
+
+impl From<ShellConfigError> for anyhow::Error {
+ fn from(error: ShellConfigError) -> Self {
+ match error {
+ ShellConfigError::Interrupted(signal) => {
+ worktrunk::git::WorktrunkError::Interrupted { signal, hint: None }.into()
+ }
+ ShellConfigError::Failed(message) => anyhow::anyhow!(message),
+ }
+ }
+}
+
/// Read or apply shell integration files. Completion planning belongs to the
/// installation flow so a completion error cannot hide integration status.
pub fn scan_shell_configs(
shell_filter: Option<Shell>,
dry_run: bool,
cmd: &str,
-) -> Result<ScanResult, String> {
+) -> Result<ScanResult, ShellConfigError> {
shell::validate_shell_command_name(cmd)?;
// Iterate every supported shell. Shells the user doesn't have are filtered
@@ -545,7 +589,7 @@ pub fn scan_shell_configs(
for shell in shells {
let paths = shell
.config_paths(cmd)
- .map_err(|e| format!("Failed to get config paths for {shell}: {e}"))?;
+ .map_err(|e| ShellConfigError::config_paths(shell, e))?;
// Find the first existing config file
let target_path = paths.iter().find(|p| p.exists());
@@ -603,7 +647,7 @@ pub fn scan_shell_configs(
Err(e) => {
// For non-critical errors, we could continue with other shells
// but for now we'll fail fast
- return Err(format!("Failed to configure {shell}: {e}"));
+ return Err(format!("Failed to configure {shell}: {e}").into());
}
}
}
@@ -1268,7 +1312,7 @@ pub fn handle_unconfigure_shell(
shell_filter: Option<Shell>,
skip_confirmation: bool,
dry_run: bool,
-) -> Result<UninstallScanResult, String> {
+) -> Result<UninstallScanResult, ShellConfigError> {
let preview = scan_for_uninstall(shell_filter)?;
// If nothing to do, return early
@@ -1294,12 +1338,12 @@ pub fn handle_unconfigure_shell(
if !skip_confirmation
&& !prompt_for_uninstall_confirmation(&preview.results, &preview.completion_results)?
{
- return Err("Cancelled by user".to_string());
+ return Err("Cancelled by user".to_string().into());
}
// User confirmed (or --yes flag was used), so apply exactly the paths and
// rc-line multiplicities represented by the preview above.
- preview.apply()
+ Ok(preview.apply()?)
}
/// Uninstall scans the shell-owned directories and removes every worktrunk-managed
@@ -1311,7 +1355,9 @@ pub fn handle_unconfigure_shell(
/// completion header for `completions/`). For Bash/Zsh/PowerShell (line-based),
/// it scans the rc/profile files and uses `is_shell_integration_line_for_uninstall_any_cmd`.
/// No `--cmd` is needed because the marker is the content, not the file name.
-fn scan_for_uninstall(shell_filter: Option<Shell>) -> Result<UninstallScanResult, String> {
+fn scan_for_uninstall(
+ shell_filter: Option<Shell>,
+) -> Result<UninstallScanResult, ShellConfigError> {
// For uninstall, scan every shell (Shell::all includes PowerShell) to clean
// up any existing profiles.
let default_shells = Shell::all();
@@ -1392,7 +1438,8 @@ fn scan_for_uninstall(shell_filter: Option<Shell>) -> Result<UninstallScanResult
}
Shell::Bash | Shell::Zsh | Shell::PowerShell => {
- let paths = shell::line_based_config_paths(shell, &home);
+ let paths = shell::line_based_config_paths(shell, &home)
+ .map_err(|e| ShellConfigError::config_paths(shell, e))?;
let mut found = false;
for path in &paths {
@@ -1714,6 +1761,16 @@ pub fn handle_show_theme() {
mod tests {
use super::*;
+ #[test]
+ fn test_shell_config_error_config_paths_ordinary_failure() {
+ let error = ShellConfigError::config_paths(Shell::Bash, std::io::Error::other("no home"));
+ assert!(
+ matches!(&error, ShellConfigError::Failed(message)
+ if message == "Failed to get config paths for bash: no home"),
+ "{error:?}"
+ );
+ }
+
#[test]
fn test_config_action_description() {
assert_eq!(ConfigAction::Added.description(), "Added");
@@ -1932,8 +1989,16 @@ mod tests {
// Fish and Nushell are configured via wrapper files, not line-based rc
// edits, so the line-based path list is empty for them.
let home = Path::new("/home/user");
- assert!(shell::line_based_config_paths(Shell::Fish, home).is_empty());
- assert!(shell::line_based_config_paths(Shell::Nushell, home).is_empty());
+ assert!(
+ shell::line_based_config_paths(Shell::Fish, home)
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ shell::line_based_config_paths(Shell::Nushell, home)
+ .unwrap()
+ .is_empty()
+ );
}
#[test]
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 679fc9f24..1f6931c40 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1959,13 +1959,18 @@ impl SwitchPipeline<'_> {
// --execute, show hints only — don't interrupt with a prompt. Skip when
// change_dir is false (the user opted out of cd, so shell integration
// is irrelevant) and on the picker path (no `binary_name`).
- // Best-effort: don't fail the switch if the offer fails.
+ // Best-effort: don't fail the switch if the offer fails, but stop on
+ // cancellation.
if let Some(binary_name) = shell_integration_binary
&& change_dir
&& !is_shell_integration_active()
{
let skip_prompt = execute.is_some();
- let _ = prompt_shell_integration(repo, config, binary_name, skip_prompt);
+ if let Err(err) = prompt_shell_integration(repo, config, binary_name, skip_prompt)
+ && err.interrupt_signal().is_some()
+ {
+ return Err(err);
+ }
}
// Build template vars for base/target context (used by both hooks and
diff --git a/src/git/reap.rs b/src/git/reap.rs
index 6839d7ec9..a0f576323 100644
--- a/src/git/reap.rs
+++ b/src/git/reap.rs
@@ -66,13 +66,14 @@ pub struct CwdProcess {
}
/// Timeout for the `lsof` / `ps` probes. Discovery is opt-in and off the hot
-/// path, but a hung probe should still not stall removal indefinitely.
+/// path, but a hung probe should still not stall removal indefinitely. The
+/// PowerShell profile query (`shell::paths`) shares this bound.
///
/// Tests override via `WORKTRUNK_TEST_PROBE_TIMEOUT_MS` (set generously in
/// `STATIC_TEST_ENV_VARS`): under suite load a probe's spawn alone can stall
/// past the production bound, and the timeout's fail-safe empty result then
/// reads as "no processes to reap" — a load-dependent test outcome.
-fn probe_timeout() -> Duration {
+pub(crate) fn probe_timeout() -> Duration {
let ms = std::env::var("WORKTRUNK_TEST_PROBE_TIMEOUT_MS")
.ok()
.and_then(|s| s.parse().ok())
diff --git a/src/main.rs b/src/main.rs
index 270fddf44..78a5e3ddc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -598,7 +598,7 @@ fn handle_config_shell_command(action: ConfigShellCommand, yes: bool) -> anyhow:
// Auto-write to shell config files and completions
let cmd = cmd.unwrap_or_else(binary_name);
handle_configure_shell(shell, yes, dry_run, cmd)
- .map_err(|e| anyhow::anyhow!("{}", e))
+ .map_err(anyhow::Error::from)
.and_then(|scan_result| {
// Exit with error if no shells configured
// Show skipped shells first so user knows what was tried
@@ -620,7 +620,7 @@ fn handle_config_shell_command(action: ConfigShellCommand, yes: bool) -> anyhow:
ConfigShellCommand::Uninstall { shell, dry_run } => {
let explicit_shell = shell.is_some();
handle_unconfigure_shell(shell, yes, dry_run)
- .map_err(|e| anyhow::anyhow!("{}", e))
+ .map_err(anyhow::Error::from)
.map(|result| {
if !dry_run {
crate::output::print_shell_uninstall_result(&result, explicit_shell);
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 3d2f0eafd..20d914439 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -605,7 +605,7 @@ fn build_switch_output_context(
result: &SwitchResult,
branch_info: &SwitchBranchInfo,
change_dir: bool,
-) -> SwitchOutputContext {
+) -> anyhow::Result<SwitchOutputContext> {
let path = super::to_logical_path(result.path());
let path_display = format_path_for_display(&path);
let branch = branch_info
@@ -620,28 +620,29 @@ fn build_switch_output_context(
} else if is_git_subcommand {
Some("ran git wt; running through git prevents cd".to_string())
} else {
- Some(compute_shell_warning_reason())
+ Some(compute_shell_warning_reason()?)
};
let user_wont_be_in_worktree = !change_dir || shell_warning_reason.is_some();
- SwitchOutputContext {
+ Ok(SwitchOutputContext {
path,
path_display,
branch,
shell_warning_reason,
user_wont_be_in_worktree,
is_git_subcommand,
- }
+ })
}
-fn print_switch_directory_hint(branch: &str, is_git_subcommand: bool) {
+fn print_switch_directory_hint(branch: &str, is_git_subcommand: bool) -> anyhow::Result<()> {
if is_git_subcommand {
eprintln!("{}", hint_message(git_subcommand_warning()));
} else if super::retired_shell_wrapper_active() {
super::print_outdated_shell_wrapper_hint_once();
- } else if should_show_explicit_path_hint() {
+ } else if should_show_explicit_path_hint()? {
eprintln!("{}", hint_message(explicit_path_hint(branch)));
}
+ Ok(())
}
fn handle_switch_already_at_output(ctx: &SwitchOutputContext) -> Option<PathBuf> {
@@ -656,7 +657,7 @@ fn handle_switch_already_at_output(ctx: &SwitchOutputContext) -> Option<PathBuf>
None
}
-fn handle_switch_existing_output(ctx: &SwitchOutputContext) -> Option<PathBuf> {
+fn handle_switch_existing_output(ctx: &SwitchOutputContext) -> anyhow::Result<Option<PathBuf>> {
if let Some(reason) = &ctx.shell_warning_reason {
eprintln!(
"{}",
@@ -666,7 +667,7 @@ fn handle_switch_existing_output(ctx: &SwitchOutputContext) -> Option<PathBuf> {
ctx.path_display
))
);
- print_switch_directory_hint(&ctx.branch, ctx.is_git_subcommand);
+ print_switch_directory_hint(&ctx.branch, ctx.is_git_subcommand)?;
} else if ctx.user_wont_be_in_worktree {
eprintln!(
"{}",
@@ -690,7 +691,7 @@ fn handle_switch_existing_output(ctx: &SwitchOutputContext) -> Option<PathBuf> {
);
}
- ctx.user_wont_be_in_worktree.then(|| ctx.path.clone())
+ Ok(ctx.user_wont_be_in_worktree.then(|| ctx.path.clone()))
}
fn maybe_print_worktree_path_hint(created_branch: bool) {
@@ -723,7 +724,7 @@ fn handle_switch_created_output(
created_branch: bool,
base_branch: Option<&str>,
from_remote: Option<&str>,
-) -> Option<PathBuf> {
+) -> anyhow::Result<Option<PathBuf>> {
eprintln!(
"{}",
success_message(format_switch_message(
@@ -743,10 +744,10 @@ fn handle_switch_created_output(
"{}",
warning_message(cformat!("Cannot change directory — {reason}"))
);
- print_switch_directory_hint(&ctx.branch, ctx.is_git_subcommand);
+ print_switch_directory_hint(&ctx.branch, ctx.is_git_subcommand)?;
}
- ctx.user_wont_be_in_worktree.then(|| ctx.path.clone())
+ Ok(ctx.user_wont_be_in_worktree.then(|| ctx.path.clone()))
}
struct BranchDeletionDisplay {
@@ -1014,7 +1015,7 @@ fn print_switch_message_if_changed(
eprintln!("{}", hint_message(git_subcommand_warning()));
} else {
// Shell integration not active - compute specific reason
- let reason = compute_shell_warning_reason();
+ let reason = compute_shell_warning_reason()?;
eprintln!(
"{}",
warning_message(cformat!(
@@ -1024,10 +1025,10 @@ fn print_switch_message_if_changed(
// Show appropriate hint based on invocation mode
if super::retired_shell_wrapper_active() {
super::print_outdated_shell_wrapper_hint_once();
- } else if should_show_explicit_path_hint() {
+ } else if should_show_explicit_path_hint()? {
eprintln!("{}", hint_message(explicit_path_hint(&dest_branch)));
} else {
- print_shell_activation_hint(&repo);
+ print_shell_activation_hint(&repo)?;
}
}
Ok(())
@@ -1139,11 +1140,11 @@ pub fn handle_switch_output(
// Translate to the user's logical (symlink-preserved) path for display messages.
// The cd directive (above) handles its own translation internally.
- let ctx = build_switch_output_context(result, branch_info, change_dir);
+ let ctx = build_switch_output_context(result, branch_info, change_dir)?;
let display_path_for_hooks = match result {
SwitchResult::AlreadyAt(_) => handle_switch_already_at_output(&ctx),
- SwitchResult::Existing { .. } => handle_switch_existing_output(&ctx),
+ SwitchResult::Existing { .. } => handle_switch_existing_output(&ctx)?,
SwitchResult::Created {
created_branch,
base_branch,
@@ -1154,7 +1155,7 @@ pub fn handle_switch_output(
*created_branch,
base_branch.as_deref(),
from_remote.as_deref(),
- ),
+ )?,
};
// The program runs in `destination`, which is the worktree root only when
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index a7d1664c1..7fa351a85 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -83,8 +83,9 @@ use worktrunk::styling::{
};
use crate::commands::configure_shell::{
- ConfigAction, UninstallScanResult, apply_confirmed_shell_config, collect_legacy_cleanups,
- format_matched_lines, preview_shell_completions, prompt_for_install, scan_shell_configs,
+ ConfigAction, ShellConfigError, UninstallScanResult, apply_confirmed_shell_config,
+ collect_legacy_cleanups, format_matched_lines, preview_shell_completions, prompt_for_install,
+ scan_shell_configs,
};
/// Git config key tracking how many times the shell-integration install hint
@@ -162,31 +163,37 @@ pub(crate) fn explicit_path_hint(branch: &str) -> String {
/// Check if we should show the explicit path hint.
/// True when: explicit path invocation AND current shell has integration configured.
-pub(crate) fn should_show_explicit_path_hint() -> bool {
- crate::was_invoked_with_explicit_path() && current_shell_is_configured()
+pub(crate) fn should_show_explicit_path_hint() -> anyhow::Result<bool> {
+ Ok(crate::was_invoked_with_explicit_path() && current_shell_is_configured()?)
}
/// Whether integration is installed for the shell running this invocation,
/// using the installer’s read-only comparison for both rc lines and wrapper files.
/// Legacy or outdated wrappers need installation rather than a restart.
-fn current_shell_is_configured() -> bool {
- current_shell()
- .and_then(|shell| scan_shell_configs(Some(shell), true, &crate::binary_name()).ok())
- .is_some_and(|scan| {
- scan.configured
- .iter()
- .any(|result| matches!(result.action, ConfigAction::AlreadyExists))
- })
+/// A failed scan reads as "not configured"; a cancelled one is an error.
+fn current_shell_is_configured() -> anyhow::Result<bool> {
+ let Some(shell) = current_shell() else {
+ return Ok(false);
+ };
+ match scan_shell_configs(Some(shell), true, &crate::binary_name()) {
+ Ok(scan) => Ok(scan
+ .configured
+ .iter()
+ .any(|result| matches!(result.action, ConfigAction::AlreadyExists))),
+ Err(ShellConfigError::Failed(_)) => Ok(false),
+ Err(e) => Err(e.into()),
+ }
}
/// Merge and remove report after changing worktrees, without prompting to
/// install. Match their advice to the current shell's installation state.
-pub(crate) fn print_shell_activation_hint(repo: &Repository) {
- if current_shell_is_configured() {
+pub(crate) fn print_shell_activation_hint(repo: &Repository) -> anyhow::Result<()> {
+ if current_shell_is_configured()? {
eprintln!("{}", hint_message(shell_inactive_hint()));
} else {
print_shell_integration_hint(repo);
}
+ Ok(())
}
/// Compute the shell warning reason for display in messages.
@@ -198,18 +205,23 @@ pub(crate) fn print_shell_activation_hint(repo: &Repository) {
/// falling back to $SHELL / PSModulePath) has integration configured, not just
/// any shell. This prevents misleading "restart" advice when e.g. bash has
/// integration but the user is running fish.
-pub(crate) fn compute_shell_warning_reason() -> String {
+pub(crate) fn compute_shell_warning_reason() -> anyhow::Result<String> {
if super::retired_shell_wrapper_active() {
- return "shell wrapper is out of date".to_string();
+ return Ok("shell wrapper is out of date".to_string());
}
// Check if the CURRENT shell has integration configured, not just ANY shell
- let is_configured = current_shell_is_configured();
+ let is_configured = current_shell_is_configured()?;
let explicit_path = crate::was_invoked_with_explicit_path();
let invoked = crate::invocation_path();
let wraps = crate::binary_name();
- compute_shell_warning_reason_inner(is_configured, explicit_path, &invoked, &wraps)
+ Ok(compute_shell_warning_reason_inner(
+ is_configured,
+ explicit_path,
+ &invoked,
+ &wraps,
+ ))
}
/// Inner logic for computing shell warning reason.
@@ -479,7 +491,7 @@ pub fn prompt_shell_integration(
return Ok(false);
};
- if current_shell_is_configured() {
+ if current_shell_is_configured()? {
// Shell integration is configured but not active for this invocation
if !crate::was_invoked_with_explicit_path() {
// Invoked via PATH but wrapper isn't active — a restart usually fixes it
@@ -492,7 +504,7 @@ pub fn prompt_shell_integration(
// Scan ALL shells (same as `wt config shell install`)
// Only includes shells where config files already exist
let mut scan = scan_shell_configs(None, true, binary_name)
- .map_err(|e| anyhow::anyhow!("Failed to scan shell configs: {e}"))?;
+ .map_err(|e| e.context("Failed to scan shell configs"))?;
// No config files exist - show install hint
if scan.configured.is_empty() {
@@ -540,7 +552,7 @@ pub fn prompt_shell_integration(
// Apply the exact plan confirmed above; deriving another preview here would
// authorize filesystem changes made while the prompt was waiting.
let install_result = apply_confirmed_shell_config(scan, None, binary_name)
- .map_err(|e| anyhow::anyhow!("Failed to configure shell integration: {e}"))?;
+ .map_err(|e| e.context("Failed to configure shell integration"))?;
print_shell_install_result(&install_result);
diff --git a/src/shell/detection.rs b/src/shell/detection.rs
index 7fe10ad64..710abfd87 100644
--- a/src/shell/detection.rs
+++ b/src/shell/detection.rs
@@ -586,7 +586,7 @@ pub fn scan_for_detection_details(cmd: &str) -> Result<Vec<FileDetectionResult>,
config_files.extend(super::Shell::Nushell.config_paths(cmd).unwrap_or_default());
// Add PowerShell profiles
- config_files.extend(powershell_profile_paths(&home));
+ config_files.extend(powershell_profile_paths(&home)?);
// Deduplicate and scan
let mut seen = HashSet::new();
diff --git a/src/shell/mod.rs b/src/shell/mod.rs
index efc2aa039..2b433c7f3 100644
--- a/src/shell/mod.rs
+++ b/src/shell/mod.rs
@@ -18,6 +18,7 @@ pub use detection::{
};
pub use paths::{
fish_config_dir, home_dir_required, line_based_config_paths, nushell_autoload_candidates,
+ profile_query_interruption,
};
pub use utils::{
AncestorShell, ZshStartupScope, ancestor_shell, current_shell, current_shell_name,
diff --git a/src/shell/paths.rs b/src/shell/paths.rs
index 21f1ca7f5..985e84036 100644
--- a/src/shell/paths.rs
+++ b/src/shell/paths.rs
@@ -191,30 +191,158 @@ pub fn nushell_autoload_candidates(home: &std::path::Path) -> Vec<PathBuf> {
candidates
}
+/// Parse the profile path `pwsh` prints: one absolute path, else `None`.
+#[cfg(unix)]
+fn parse_powershell_profile(stdout: &str) -> Option<PathBuf> {
+ let line = stdout.trim();
+ let path = PathBuf::from(line);
+ (!line.contains('\n') && path.is_absolute()).then_some(path)
+}
+
+/// Classify a profile query's outcome.
+///
+/// `Ok(None)` — use the conventional path — when the runtime is missing,
+/// fails, times out, or prints anything but one absolute path. `Err(signal)`
+/// when the query was cancelled: the child died of SIGINT/SIGTERM, or the
+/// command operation was cancelled while wt waited.
+#[cfg(unix)]
+fn powershell_profile_from(
+ output: &std::io::Result<std::process::Output>,
+ operation_signal: Option<i32>,
+) -> Result<Option<PathBuf>, i32> {
+ use signal_hook::consts::{SIGINT, SIGTERM};
+ use std::os::unix::process::ExitStatusExt;
+ let output = output.as_ref().ok();
+ if let Some(signal) = output
+ .and_then(|output| output.status.signal())
+ .filter(|signal| matches!(*signal, SIGINT | SIGTERM))
+ .or(operation_signal)
+ {
+ return Err(signal);
+ }
+ Ok(output
+ .filter(|output| output.status.success())
+ .and_then(|output| parse_powershell_profile(&String::from_utf8_lossy(&output.stdout))))
+}
+
+/// The profile query's answer, or the signal that cancelled it.
+#[cfg(unix)]
+static POWERSHELL_PROFILE: OnceLock<Result<Option<PathBuf>, i32>> = OnceLock::new();
+
+/// The current-user, current-host profile (`$PROFILE.CurrentUserCurrentHost`)
+/// the installed `pwsh` loads, queried at most once per process so install,
+/// uninstall and detection all act on the same answer.
+///
+/// `-NoProfile` keeps the query from running the profiles it names, and the
+/// telemetry and update-check opt-outs keep it off the network. Bounded by the
+/// shared local-probe timeout. A timed child runs in its own process group, so
+/// a terminal Ctrl-C reaches only wt, whose default disposition ends it;
+/// SIGTERM to wt is latched by the command operation and read back here.
+#[cfg(unix)]
+fn queried_powershell_profile() -> std::io::Result<Option<PathBuf>> {
+ POWERSHELL_PROFILE
+ .get_or_init(|| {
+ let output = crate::shell_exec::Cmd::new("pwsh")
+ .args([
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "$PROFILE.CurrentUserCurrentHost",
+ ])
+ .env("POWERSHELL_TELEMETRY_OPTOUT", "1")
+ .env("POWERSHELL_UPDATECHECK", "Off")
+ .timeout(crate::git::reap::probe_timeout())
+ .run();
+ let result = powershell_profile_from(
+ &output,
+ crate::signal_forwarder::operation_interrupt_signal(),
+ );
+ if let Err(signal) = result {
+ crate::signal_forwarder::cancel_foreground(signal);
+ }
+ result
+ })
+ .clone()
+ .map_err(|signal| {
+ std::io::Error::new(
+ std::io::ErrorKind::Interrupted,
+ ProfileQueryInterrupted(signal),
+ )
+ })
+}
+
+/// The payload of the `io::Error` the profile path helpers return when the
+/// PowerShell profile query was cancelled, naming the signal.
+#[cfg(unix)]
+#[derive(Debug)]
+struct ProfileQueryInterrupted(i32);
+
+#[cfg(unix)]
+impl std::fmt::Display for ProfileQueryInterrupted {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "PowerShell profile query interrupted by signal {}",
+ self.0
+ )
+ }
+}
+
+#[cfg(unix)]
+impl std::error::Error for ProfileQueryInterrupted {}
+
+/// The signal that cancelled the PowerShell profile query, when `error` is
+/// that cancellation rather than an ordinary path failure.
+pub fn profile_query_interruption(error: &std::io::Error) -> Option<i32> {
+ #[cfg(unix)]
+ {
+ error
+ .get_ref()?
+ .downcast_ref::<ProfileQueryInterrupted>()
+ .map(|interrupted| interrupted.0)
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = error;
+ None
+ }
+}
+
/// Get PowerShell profile paths in order of preference.
+///
/// On Windows, returns both PowerShell Core (7+) and Windows PowerShell (5.1) paths.
-/// On Unix, uses the conventional ~/.config/powershell location.
-pub fn powershell_profile_paths(home: &std::path::Path) -> Vec<PathBuf> {
+/// On Unix, returns the current-user, current-host profile the installed `pwsh`
+/// reports — PowerShell honors `$XDG_CONFIG_HOME` — falling back to the
+/// conventional `~/.config/powershell` location when `pwsh` can't be queried.
+/// Errors only when the query was cancelled, so no caller writes a fallback
+/// profile after Ctrl-C.
+pub fn powershell_profile_paths(home: &std::path::Path) -> std::io::Result<Vec<PathBuf>> {
#[cfg(windows)]
{
// Use platform-specific Documents path (handles non-English Windows)
let docs = dirs::document_dir().unwrap_or_else(|| home.join("Documents"));
- vec![
+ Ok(vec![
// PowerShell Core 6+ (pwsh.exe) - preferred
docs.join("PowerShell")
.join("Microsoft.PowerShell_profile.ps1"),
// Windows PowerShell 5.1 (powershell.exe) - legacy but still common
docs.join("WindowsPowerShell")
.join("Microsoft.PowerShell_profile.ps1"),
- ]
+ ])
}
#[cfg(not(windows))]
{
- vec![
+ #[cfg(unix)]
+ let queried = queried_powershell_profile()?;
+ #[cfg(not(unix))]
+ let queried = None;
+ let profile = queried.unwrap_or_else(|| {
home.join(".config")
.join("powershell")
- .join("Microsoft.PowerShell_profile.ps1"),
- ]
+ .join("Microsoft.PowerShell_profile.ps1")
+ });
+ Ok(vec![profile])
}
}
@@ -274,16 +402,19 @@ pub(super) fn zsh_config_dir(home: &std::path::Path) -> PathBuf {
/// are independent of the binary name; Fish and Nushell use per-name wrapper
/// files instead and have no line-based config. `config_paths` builds on this
/// for the line-based shells, so install and uninstall cannot drift apart.
-pub fn line_based_config_paths(shell: super::Shell, home: &std::path::Path) -> Vec<PathBuf> {
- match shell {
+pub fn line_based_config_paths(
+ shell: super::Shell,
+ home: &std::path::Path,
+) -> std::io::Result<Vec<PathBuf>> {
+ Ok(match shell {
super::Shell::Bash => {
// Use .bashrc - sourced by interactive shells (login shells should source .bashrc)
vec![home.join(".bashrc")]
}
super::Shell::Zsh => vec![zsh_config_dir(home).join(".zshrc")],
- super::Shell::PowerShell => powershell_profile_paths(home),
+ super::Shell::PowerShell => powershell_profile_paths(home)?,
super::Shell::Fish | super::Shell::Nushell => Vec::new(),
- }
+ })
}
/// Returns the config file paths for a shell.
@@ -295,7 +426,7 @@ pub(super) fn config_paths(shell: super::Shell, cmd: &str) -> Result<Vec<PathBuf
Ok(match shell {
super::Shell::Bash | super::Shell::Zsh | super::Shell::PowerShell => {
- line_based_config_paths(shell, &home)
+ line_based_config_paths(shell, &home)?
}
super::Shell::Fish => {
// For fish, we write to functions/ which is autoloaded on first use.
@@ -411,6 +542,74 @@ mod tests {
assert_eq!(parse_nu_path(" \n"), None);
}
+ #[cfg(unix)]
+ #[test]
+ fn test_parse_powershell_profile() {
+ assert_eq!(
+ parse_powershell_profile("/x/powershell/Microsoft.PowerShell_profile.ps1\n"),
+ Some(PathBuf::from(
+ "/x/powershell/Microsoft.PowerShell_profile.ps1"
+ ))
+ );
+ assert_eq!(parse_powershell_profile(""), None);
+ assert_eq!(parse_powershell_profile("relative/profile.ps1"), None);
+ assert_eq!(parse_powershell_profile("/a.ps1\n/b.ps1\n"), None);
+ }
+
+ /// Stand-in runtimes via `/bin/sh -c`: the reported path is trusted, a
+ /// runtime that can't answer falls back, and SIGINT/SIGTERM — on the child
+ /// or latched by the operation — cancels instead of falling back.
+ #[cfg(unix)]
+ #[test]
+ fn test_powershell_profile_from() {
+ let sh = |script: &str| {
+ crate::shell_exec::Cmd::new("/bin/sh")
+ .args(["-c", script])
+ .run()
+ };
+ assert_eq!(
+ powershell_profile_from(&sh("echo /custom/powershell/profile.ps1"), None),
+ Ok(Some(PathBuf::from("/custom/powershell/profile.ps1")))
+ );
+ assert_eq!(
+ powershell_profile_from(&sh("echo /custom/profile.ps1; exit 1"), None),
+ Ok(None)
+ );
+ let missing = crate::shell_exec::Cmd::new("/nonexistent/pwsh-xxxxxxxx").run();
+ assert_eq!(powershell_profile_from(&missing, None), Ok(None));
+ assert_eq!(powershell_profile_from(&sh("kill -INT $$"), None), Err(2));
+ assert_eq!(powershell_profile_from(&sh("kill -TERM $$"), None), Err(15));
+ // A crash is a failed query, not a cancellation.
+ assert_eq!(
+ powershell_profile_from(&sh("kill -KILL $$"), None),
+ Ok(None)
+ );
+ assert_eq!(
+ powershell_profile_from(&sh("echo /custom/profile.ps1"), Some(15)),
+ Err(15)
+ );
+ }
+
+ /// Only the cancelled query's own error reads as an interruption; an
+ /// ordinary `Interrupted` io error stays an ordinary failure.
+ #[cfg(unix)]
+ #[test]
+ fn test_profile_query_interruption() {
+ for signal in [2, 15] {
+ let cancelled = std::io::Error::new(
+ std::io::ErrorKind::Interrupted,
+ ProfileQueryInterrupted(signal),
+ );
+ assert_eq!(profile_query_interruption(&cancelled), Some(signal));
+ assert_eq!(
+ cancelled.to_string(),
+ format!("PowerShell profile query interrupted by signal {signal}")
+ );
+ }
+ let ordinary = std::io::Error::from(std::io::ErrorKind::Interrupted);
+ assert_eq!(profile_query_interruption(&ordinary), None);
+ }
+
#[test]
fn test_nushell_vendor_autoload_dir_prefers_queried() {
let home = PathBuf::from("/home/user");
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index f42b55128..21c691c3e 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -1060,10 +1060,23 @@ fn run_with_timeout_impl(
let output = match collect() {
Ok(output) => output,
Err(error) => {
+ // A child already ended by a native INT/TERM stays cancelled even
+ // when a descendant holding its pipes ran the readers to the
+ // deadline; reporting `TimedOut` would let callers fall back as
+ // if the command were merely slow. The probe leaves the leader
+ // unreaped for the teardown, and signalling its zombie cannot
+ // change the status the final `wait` then reports.
+ let interrupted = exited_by_native_interrupt(child.id());
kill_timed_out_tree(child.id());
let _ = child.kill();
- let _ = child.wait();
- return Err(error);
+ return match child.wait() {
+ Ok(status) if interrupted => Ok(std::process::Output {
+ status,
+ stdout: Vec::new(),
+ stderr: Vec::new(),
+ }),
+ _ => Err(error),
+ };
}
};
let status = match wait_shared_child(&child, Some(deadline)) {
@@ -1085,6 +1098,51 @@ fn run_with_timeout_impl(
})
}
+/// Whether SIGINT/SIGTERM already ended `pid`, read with `WNOWAIT` so the
+/// child stays unreaped and keeps pinning its pgid for the teardown.
+#[cfg(target_os = "linux")]
+fn exited_by_native_interrupt(pid: u32) -> bool {
+ use nix::sys::signal::Signal;
+ use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid};
+ matches!(
+ waitid(
+ Id::Pid(nix::unistd::Pid::from_raw(pid as i32)),
+ WaitPidFlag::WEXITED | WaitPidFlag::WNOWAIT | WaitPidFlag::WNOHANG,
+ ),
+ Ok(WaitStatus::Signaled(_, Signal::SIGINT | Signal::SIGTERM, _))
+ )
+}
+
+/// Darwin's `waitid` with the same flags; nix doesn't wrap it there. Darwin
+/// leaves `siginfo` untouched for a running child, hence the zeroed buffer,
+/// and can report a stop through `WEXITED`, hence matching `CLD_KILLED` only.
+#[cfg(target_vendor = "apple")]
+#[allow(unsafe_code)]
+fn exited_by_native_interrupt(pid: u32) -> bool {
+ use nix::libc;
+ // SAFETY: `siginfo_t` is plain data; all-zero is a valid value.
+ let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
+ // SAFETY: `info` is a valid, exclusively borrowed `siginfo_t`.
+ let ret = unsafe {
+ libc::waitid(
+ libc::P_PID,
+ pid as libc::id_t,
+ &mut info,
+ libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
+ )
+ };
+ ret == 0
+ && info.si_signo == libc::SIGCHLD
+ && info.si_code == libc::CLD_KILLED
+ && matches!(info.si_status, libc::SIGINT | libc::SIGTERM)
+}
+
+/// No unreaped status probe here: a deadline-bound cancellation stays `TimedOut`.
+#[cfg(all(unix, not(target_os = "linux"), not(target_vendor = "apple")))]
+fn exited_by_native_interrupt(_pid: u32) -> bool {
+ false
+}
+
/// Tear down the process tree of a child that outlived its timeout.
///
/// `run_with_timeout_impl` made the child its own process-group leader, so its
@@ -3163,6 +3221,26 @@ print(*counts)
);
}
+ /// A child that INT/TERM already ended keeps that status when a descendant
+ /// holds its pipes past the deadline, instead of reading as `TimedOut`.
+ #[test]
+ #[cfg(unix)]
+ fn test_cmd_timeout_keeps_native_interrupt_with_pipe_holding_descendant() {
+ use signal_hook::consts::{SIGINT, SIGTERM};
+ use std::os::unix::process::ExitStatusExt;
+ for (name, signal) in [("INT", SIGINT), ("TERM", SIGTERM)] {
+ let start = std::time::Instant::now();
+ let output = Cmd::new("sh")
+ .args(["-c", &format!("sleep 30 & kill -{name} $$")])
+ // Long enough that `kill` lands first even under suite load.
+ .timeout(Duration::from_secs(2))
+ .run()
+ .unwrap();
+ assert_eq!(output.status.signal(), Some(signal));
+ assert!(start.elapsed() < Duration::from_secs(20));
+ }
+ }
+
#[test]
fn test_cmd_without_timeout_completes() {
let result = Cmd::new("echo").arg("no timeout").run();
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index bbc1b1525..2ce326618 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -4875,6 +4875,125 @@ fn test_plugins_codex_install_plugin_add_fails(mut repo: TestRepo, temp_home: Te
});
}
+/// A PowerShell profile query that INT/TERM cancels stops `config show --full`
+/// at the shell section, before the forge diagnostics probe `gh`.
+#[cfg(unix)]
+#[rstest]
+#[case::sigint("INT", 130)]
+#[case::sigterm("TERM", 143)]
+fn test_config_show_full_stops_after_cancelled_powershell_query(
+ mut repo: TestRepo,
+ temp_home: TempDir,
+ #[case] signal: &str,
+ #[case] exit_code: i32,
+) {
+ use crate::common::mock_commands::mock_calls;
+ use std::os::unix::fs::PermissionsExt;
+
+ repo.setup_mock_ci_tools_unauthenticated();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/example/repo.git",
+ ]);
+ let pwsh = repo.mock_bin_path().unwrap().join("pwsh");
+ fs::write(&pwsh, format!("#!/bin/sh\nkill -{signal} $$\n")).unwrap();
+ fs::set_permissions(&pwsh, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let call_log = TempDir::new().unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_LATEST_VERSION", env!("CARGO_PKG_VERSION"))
+ .env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path())
+ .args(["config", "show", "--full"])
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let output = cmd.output().unwrap();
+
+ assert_eq!(
+ crate::common::shell_exit_code(&output.status),
+ Some(exit_code),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(mock_calls(call_log.path(), "gh"), Vec::<String>::new());
+}
+
+/// A `pwsh` that fails without being cancelled leaves `config show --full` on
+/// its ordinary path, through to the forge diagnostics.
+#[cfg(unix)]
+#[rstest]
+fn test_config_show_full_continues_after_failed_powershell_query(
+ mut repo: TestRepo,
+ temp_home: TempDir,
+) {
+ use crate::common::mock_commands::mock_calls;
+ use std::os::unix::fs::PermissionsExt;
+
+ repo.setup_mock_ci_tools_unauthenticated();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/example/repo.git",
+ ]);
+ let pwsh = repo.mock_bin_path().unwrap().join("pwsh");
+ fs::write(&pwsh, "#!/bin/sh\nexit 130\n").unwrap();
+ fs::set_permissions(&pwsh, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let call_log = TempDir::new().unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_LATEST_VERSION", env!("CARGO_PKG_VERSION"))
+ .env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path())
+ .args(["config", "show", "--full"])
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let output = cmd.output().unwrap();
+
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(!mock_calls(call_log.path(), "gh").is_empty());
+}
+
+/// An ordinary shell scan failure — an rc path that can't be read as a file —
+/// reports the shell status as undetermined and carries on to the forge
+/// diagnostics.
+#[cfg(unix)]
+#[rstest]
+fn test_config_show_full_continues_after_failed_shell_scan(mut repo: TestRepo, temp_home: TempDir) {
+ use crate::common::mock_commands::mock_calls;
+
+ repo.setup_mock_ci_tools_unauthenticated();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/example/repo.git",
+ ]);
+ fs::create_dir(temp_home.path().join(".bashrc")).unwrap();
+
+ let call_log = TempDir::new().unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_LATEST_VERSION", env!("CARGO_PKG_VERSION"))
+ .env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path())
+ .args(["config", "show", "--full"])
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let output = cmd.output().unwrap();
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(output.status.success(), "{stderr}");
+ assert!(
+ format!("{stdout}{stderr}").contains("Could not determine shell status"),
+ "{stdout}{stderr}"
+ );
+ assert!(!mock_calls(call_log.path(), "gh").is_empty());
+}
+
/// Run `wt config plugins <tool> <action>` and accept the prompt, returning the
/// argv of every `<tool>` the run spawned — argv\[0\] excluded, as `mock_calls`
/// records it.
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
index 3f0ca59d0..2dd2d5be2 100644
--- a/tests/integration_tests/configure_shell.rs
+++ b/tests/integration_tests/configure_shell.rs
@@ -154,6 +154,29 @@ fn test_configure_shell_rejects_unsafe_cmd_without_modifying_rc(
assert_eq!(fs::read_to_string(&zshrc_path).unwrap(), original);
}
+/// An rc path that can't be read as a file fails installation with the read
+/// error and leaves the path untouched.
+#[rstest]
+fn test_configure_shell_bashrc_directory_fails(repo: TestRepo, temp_home: TempDir) {
+ let bashrc = temp_home.path().join(".bashrc");
+ fs::create_dir(&bashrc).unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["config", "shell", "install", "bash", "--yes"])
+ .current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(!output.status.success(), "{stderr}");
+ assert!(
+ stderr.contains("Failed to configure bash: Failed to read"),
+ "{stderr}"
+ );
+ assert!(bashrc.is_dir());
+}
+
#[rstest]
fn test_configure_shell_already_exists(repo: TestRepo, temp_home: TempDir) {
// Create a fake .zshrc file with the line already present
@@ -1784,6 +1807,215 @@ fn test_uninstall_shell_powershell_removes_integration_line(repo: TestRepo, temp
assert!(content.contains("Set-Alias ll Get-ChildItem"));
}
+/// Put a mock `pwsh` answering every query with `response` first on PATH.
+#[cfg(unix)]
+fn mock_pwsh(
+ cmd: &mut std::process::Command,
+ temp_home: &TempDir,
+ response: crate::common::mock_commands::MockResponse,
+) -> std::path::PathBuf {
+ let mock_bin = temp_home.path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+ crate::common::mock_commands::MockConfig::new("pwsh")
+ .command("_default", response)
+ .write(&mock_bin);
+ cmd.env("WORKTRUNK_TEST_MOCK_CONFIG_DIR", &mock_bin);
+ let path = std::env::var_os("PATH").unwrap_or_default();
+ let mut paths = vec![mock_bin.clone()];
+ paths.extend(std::env::split_paths(&path));
+ cmd.env("PATH", std::env::join_paths(paths).unwrap());
+ mock_bin
+}
+
+/// The profile `pwsh` reports wins over `~/.config/powershell`: PowerShell
+/// honors `$XDG_CONFIG_HOME`, so install and uninstall both follow it.
+#[cfg(unix)]
+#[rstest]
+fn test_powershell_profile_follows_runtime(repo: TestRepo, temp_home: TempDir) {
+ let home = canonical_temp_home(&temp_home);
+ let profile = home.join("custom-config/powershell/Microsoft.PowerShell_profile.ps1");
+ let conventional = home.join(".config/powershell/Microsoft.PowerShell_profile.ps1");
+ let reported = format!("{}\n", profile.display());
+
+ let mut install = wt_command();
+ repo.configure_wt_cmd(&mut install);
+ set_temp_home_env(&mut install, temp_home.path());
+ mock_pwsh(
+ &mut install,
+ &temp_home,
+ crate::common::mock_commands::MockResponse::output(&reported),
+ );
+ install.env("WORKTRUNK_TEST_POWERSHELL_ENV", "1");
+ install
+ .args(["config", "shell", "install", "powershell", "--yes"])
+ .current_dir(repo.root_path());
+ let output = install.output().unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let content = fs::read_to_string(&profile).unwrap();
+ assert!(
+ content.contains("wt config shell init powershell"),
+ "{content}"
+ );
+ assert!(!conventional.exists());
+
+ let mut uninstall = wt_command();
+ repo.configure_wt_cmd(&mut uninstall);
+ set_temp_home_env(&mut uninstall, temp_home.path());
+ mock_pwsh(
+ &mut uninstall,
+ &temp_home,
+ crate::common::mock_commands::MockResponse::output(&reported),
+ );
+ uninstall
+ .args(["config", "shell", "uninstall", "powershell", "--yes"])
+ .current_dir(repo.root_path());
+ let output = uninstall.output().unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let content = fs::read_to_string(&profile).unwrap_or_default();
+ assert!(!content.contains("config shell init"), "{content}");
+}
+
+/// A `pwsh` that can't answer leaves install on the conventional profile.
+#[cfg(unix)]
+#[rstest]
+fn test_powershell_profile_falls_back_when_runtime_fails(repo: TestRepo, temp_home: TempDir) {
+ let home = canonical_temp_home(&temp_home);
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ mock_pwsh(
+ &mut cmd,
+ &temp_home,
+ crate::common::mock_commands::MockResponse::exit(1),
+ );
+ cmd.env("WORKTRUNK_TEST_POWERSHELL_ENV", "1");
+ cmd.args(["config", "shell", "install", "powershell", "--yes"])
+ .current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ home.join(".config/powershell/Microsoft.PowerShell_profile.ps1")
+ .exists()
+ );
+}
+
+/// SIGINT or SIGTERM while the profile query runs cancels install: wt
+/// neither writes the reported profile nor falls back to the conventional one.
+#[cfg(unix)]
+#[rstest]
+#[case::sigint(nix::sys::signal::Signal::SIGINT)]
+#[case::sigterm(nix::sys::signal::Signal::SIGTERM)]
+fn test_powershell_profile_query_cancellation_stops_install(
+ repo: TestRepo,
+ temp_home: TempDir,
+ #[case] signal: nix::sys::signal::Signal,
+) {
+ use crate::common::mock_commands::{MockResponse, mock_calls};
+ let home = canonical_temp_home(&temp_home);
+ let profile = home.join("custom-config/powershell/Microsoft.PowerShell_profile.ps1");
+ let log_dir = temp_home.path().join("calls");
+ fs::create_dir_all(&log_dir).unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let mock_bin = mock_pwsh(
+ &mut cmd,
+ &temp_home,
+ MockResponse::output(&format!("{}\n", profile.display())).wait_for_file("release"),
+ );
+ cmd.env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", &log_dir);
+ cmd.env("WORKTRUNK_TEST_POWERSHELL_ENV", "1");
+ cmd.args(["config", "shell", "install", "powershell", "--yes"])
+ .current_dir(repo.root_path())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::piped());
+ let child = cmd.spawn().unwrap();
+
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
+ while mock_calls(&log_dir, "pwsh").is_empty() {
+ assert!(std::time::Instant::now() < deadline, "pwsh never queried");
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ nix::sys::signal::kill(nix::unistd::Pid::from_raw(child.id() as i32), signal).unwrap();
+ fs::write(mock_bin.join("release"), "").unwrap();
+
+ let output = child.wait_with_output().unwrap();
+ assert_eq!(
+ crate::common::shell_exit_code(&output.status),
+ Some(128 + signal as i32),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(!profile.exists());
+ assert!(
+ !home
+ .join(".config/powershell/Microsoft.PowerShell_profile.ps1")
+ .exists()
+ );
+}
+
+/// A `pwsh` killed by INT/TERM while a descendant still holds its output
+/// pipes cancels install too, rather than reading as a timeout past the probe
+/// deadline and falling back to the conventional profile.
+#[cfg(unix)]
+#[rstest]
+#[case::sigint("INT", 130)]
+#[case::sigterm("TERM", 143)]
+fn test_powershell_profile_query_signal_with_pipe_holding_descendant(
+ repo: TestRepo,
+ temp_home: TempDir,
+ #[case] signal: &str,
+ #[case] exit_code: i32,
+) {
+ use std::os::unix::fs::PermissionsExt;
+ let home = canonical_temp_home(&temp_home);
+ let mock_bin = temp_home.path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+ let pwsh = mock_bin.join("pwsh");
+ fs::write(&pwsh, format!("#!/bin/sh\nsleep 60 &\nkill -{signal} $$\n")).unwrap();
+ fs::set_permissions(&pwsh, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ let path = std::env::var_os("PATH").unwrap_or_default();
+ let mut paths = vec![mock_bin];
+ paths.extend(std::env::split_paths(&path));
+ cmd.env("PATH", std::env::join_paths(paths).unwrap());
+ // Expire the probe before the descendant releases the pipes, yet late
+ // enough that the mock's `kill` lands first even under suite load.
+ cmd.env("WORKTRUNK_TEST_PROBE_TIMEOUT_MS", "5000");
+ cmd.env("WORKTRUNK_TEST_POWERSHELL_ENV", "1");
+ cmd.args(["config", "shell", "install", "powershell", "--yes"])
+ .current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+
+ assert_eq!(
+ crate::common::shell_exit_code(&output.status),
+ Some(exit_code),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ !home
+ .join(".config/powershell/Microsoft.PowerShell_profile.ps1")
+ .exists()
+ );
+}
+
#[rstest]
fn test_uninstall_scan_removes_custom_cmd_nushell_file(repo: TestRepo, temp_home: TempDir) {
let home = canonical_temp_home(&temp_home);
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 5ca76b349..55ea1acea 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -59,6 +59,43 @@ fn test_removal_shell_activation_advice(
});
}
+/// A PowerShell profile query that INT/TERM cancels while removal computes its
+/// change-directory warning stops the command before that warning or any
+/// activation hint.
+#[cfg(unix)]
+#[rstest]
+#[case::sigint("INT", 130)]
+#[case::sigterm("TERM", 143)]
+fn test_remove_stops_after_cancelled_powershell_query(
+ mut repo: TestRepo,
+ #[case] signal: &str,
+ #[case] exit_code: i32,
+) {
+ use std::os::unix::fs::PermissionsExt;
+ use std::os::unix::process::CommandExt;
+
+ repo.setup_mock_ci_tools_unauthenticated();
+ let pwsh = repo.mock_bin_path().unwrap().join("pwsh");
+ fs::write(&pwsh, format!("#!/bin/sh\nkill -{signal} $$\n")).unwrap();
+ fs::set_permissions(&pwsh, fs::Permissions::from_mode(0o755)).unwrap();
+ let worktree_path = repo.add_worktree("feature");
+
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_PARENT_SHELL", "pwsh")
+ .arg0("wt")
+ .args(["remove", "--foreground", "--yes"])
+ .current_dir(&worktree_path);
+ let output = cmd.output().unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_eq!(
+ crate::common::shell_exit_code(&output.status),
+ Some(exit_code),
+ "{stderr}"
+ );
+ assert!(!stderr.contains("cannot change directory"), "{stderr}");
+}
+
/// Installation advice must use the installer's wrapper-aware state: a
/// legacy fish wrapper needs migration, while current fish/Nushell wrappers
/// need activation. Exercise the real installer and removal output together.
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index 5d10acef3..985994469 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -296,6 +296,125 @@ fn test_process_tree_unsupported_shell_overrides_shell_env(repo: TestRepo) {
);
}
+/// A PowerShell profile query that INT/TERM cancels while `wt switch` computes
+/// its shell warning stops the command there: no further shell probes (the
+/// all-shell scan asks `nu` for its autoload dirs) and no later hints.
+#[cfg(unix)]
+#[rstest]
+#[case::sigint("INT", 130)]
+#[case::sigterm("TERM", 143)]
+fn test_switch_stops_after_cancelled_powershell_query(
+ mut repo: TestRepo,
+ #[case] signal: &str,
+ #[case] exit_code: i32,
+) {
+ use crate::common::mock_commands::{MockConfig, MockResponse, mock_calls};
+ use std::os::unix::fs::PermissionsExt;
+ use std::os::unix::process::CommandExt;
+
+ repo.setup_mock_ci_tools_unauthenticated();
+ let mock_bin = repo.mock_bin_path().unwrap();
+ let pwsh = mock_bin.join("pwsh");
+ fs::write(&pwsh, format!("#!/bin/sh\nkill -{signal} $$\n")).unwrap();
+ fs::set_permissions(&pwsh, fs::Permissions::from_mode(0o755)).unwrap();
+ MockConfig::new("nu")
+ .command("_default", MockResponse::output("[]\n"))
+ .write(mock_bin);
+
+ let call_log = tempfile::TempDir::new().unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_PARENT_SHELL", "pwsh")
+ .env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path())
+ .arg0("wt")
+ .args(["switch", "--create", "feature"])
+ .stdin(std::process::Stdio::null());
+ let output = cmd.output().unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_eq!(
+ crate::common::shell_exit_code(&output.status),
+ Some(exit_code),
+ "{stderr}"
+ );
+ assert_eq!(mock_calls(call_log.path(), "nu"), Vec::<String>::new());
+ assert!(
+ !stderr.contains("To customize worktree locations"),
+ "{stderr}"
+ );
+ assert!(!stderr.contains("Cannot change directory"), "{stderr}");
+}
+
+/// With a current shell other than PowerShell, the first profile query is the
+/// install offer's all-shell scan. Cancelling it stops the switch before the
+/// `--execute` program runs; a query that merely fails (a plain exit 130)
+/// falls back and the program runs.
+#[cfg(unix)]
+#[rstest]
+#[case::sigint("kill -INT $$", 130, false)]
+#[case::sigterm("kill -TERM $$", 143, false)]
+#[case::ordinary_failure("exit 130", 0, true)]
+fn test_switch_offer_after_powershell_query(
+ mut repo: TestRepo,
+ #[case] pwsh_body: &str,
+ #[case] exit_code: i32,
+ #[case] executed: bool,
+) {
+ use std::os::unix::fs::PermissionsExt;
+ use std::os::unix::process::CommandExt;
+
+ repo.setup_mock_ci_tools_unauthenticated();
+ let pwsh = repo.mock_bin_path().unwrap().join("pwsh");
+ fs::write(&pwsh, format!("#!/bin/sh\n{pwsh_body}\n")).unwrap();
+ fs::set_permissions(&pwsh, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let marker = repo.root_path().join("executed");
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_PARENT_SHELL", "zsh")
+ .arg0("wt")
+ .args(["switch", "--create", "feature", "--execute", "touch", "--"])
+ .arg(&marker)
+ .stdin(std::process::Stdio::null());
+ let output = cmd.output().unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_eq!(
+ crate::common::shell_exit_code(&output.status),
+ Some(exit_code),
+ "{stderr}"
+ );
+ assert_eq!(marker.exists(), executed, "{stderr}");
+}
+
+/// An ordinary shell scan failure — an rc path that can't be read as a file —
+/// reads as "not configured": the switch completes and runs `--execute`.
+#[cfg(unix)]
+#[rstest]
+fn test_switch_continues_after_failed_shell_scan(repo: TestRepo) {
+ use crate::common::set_temp_home_env;
+ use std::os::unix::process::CommandExt;
+
+ let temp_home = tempfile::TempDir::new().unwrap();
+ fs::create_dir(temp_home.path().join(".bashrc")).unwrap();
+
+ let marker = repo.root_path().join("executed");
+ let mut cmd = repo.wt_command();
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.env("WORKTRUNK_TEST_PARENT_SHELL", "bash")
+ .arg0("wt")
+ .args(["switch", "--create", "feature", "--execute", "touch", "--"])
+ .arg(&marker)
+ .stdin(std::process::Stdio::null());
+ let output = cmd.output().unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(output.status.success(), "{stderr}");
+ assert!(
+ stderr.contains("Cannot change directory — shell integration not installed"),
+ "{stderr}"
+ );
+ assert!(marker.exists(), "{stderr}");
+}
+
// PTY-based tests for interactive scenarios
#[cfg(all(unix, feature = "shell-integration-tests"))]
mod pty_tests {
diff --git a/tests/integration_tests/shell_powershell.rs b/tests/integration_tests/shell_powershell.rs
index 939dfca2c..35f1d1338 100644
--- a/tests/integration_tests/shell_powershell.rs
+++ b/tests/integration_tests/shell_powershell.rs
@@ -180,3 +180,41 @@ wt list
stdout: {stdout}\nstderr: {stderr}",
);
}
+
+/// The installed `pwsh` decides where install writes on Unix: with
+/// `XDG_CONFIG_HOME` pointing away from `~/.config`, the profile lands where
+/// PowerShell loads it.
+#[cfg(unix)]
+#[test]
+fn test_install_uses_profile_reported_by_pwsh() {
+ let repo = crate::common::TestRepo::standard();
+ let temp_home = crate::common::temp_home();
+ let home = crate::common::canonical_temp_home(&temp_home);
+ let custom_config = home.join("custom-config");
+
+ let mut cmd = crate::common::wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ crate::common::set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.env("XDG_CONFIG_HOME", &custom_config);
+ cmd.env("WORKTRUNK_TEST_POWERSHELL_ENV", "1");
+ cmd.args(["config", "shell", "install", "powershell", "--yes"])
+ .current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let profile = custom_config.join("powershell/Microsoft.PowerShell_profile.ps1");
+ let content = std::fs::read_to_string(&profile).unwrap();
+ assert!(
+ content.contains("wt config shell init powershell"),
+ "{content}"
+ );
+ assert!(
+ !home
+ .join(".config/powershell/Microsoft.PowerShell_profile.ps1")
+ .exists()
+ );
+}