Skip to content

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

Add Windows support via Git Bash with PowerShell fallback (#122)

Maximilian Roos6922780d5e51
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 065bcb5dd..c1c8c7102 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -57,7 +57,7 @@ jobs:
run: |
# Git Bash is pre-installed on GitHub Actions Windows runners
# Fish and zsh are not commonly available on native Windows (require WSL/MSYS2)
- # CI will test with bash only on Windows
+ # CI will test with bash only on Windows (tests skip unavailable shells)
echo "Using Git Bash for Windows tests"
shell: pwsh
@@ -65,14 +65,14 @@ jobs:
uses: clechasseur/rs-cargo@v4
with:
command: test
- args: --no-run --locked ${{ runner.os != 'Windows' && '--features shell-integration-tests' || '' }}
+ args: --no-run --locked --features shell-integration-tests
- name: πŸ“‹ Test
uses: clechasseur/rs-cargo@v4
timeout-minutes: 10
with:
command: insta
- args: test --test-runner=nextest ${{ runner.os != 'Windows' && '--features shell-integration-tests' || '' }}
+ args: test --test-runner=nextest --features shell-integration-tests
- name: πŸ“– Doctest
uses: clechasseur/rs-cargo@v4
diff --git a/Cargo.lock b/Cargo.lock
index 954c2d548..c4ad062de 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2949,6 +2949,7 @@ dependencies = [
"criterion",
"crossbeam-channel",
"crossterm",
+ "dirs",
"env_logger",
"etcetera",
"home",
@@ -2981,6 +2982,7 @@ dependencies = [
"unicode-width",
"vergen-gitcl",
"vt100",
+ "which",
"wrap-ansi",
]
diff --git a/Cargo.toml b/Cargo.toml
index 76e7e08c4..7c376880b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -81,7 +81,9 @@ unicode-width = "0.2"
wrap-ansi = "0.1"
osc8 = "0.1.0"
home = "0.5.12"
+dirs = "6.0"
normalize-path = "0.2.1"
+which = "7.0"
[target.'cfg(unix)'.dependencies]
skim = "0.20"
diff --git a/src/cli.rs b/src/cli.rs
index 97f13f2e1..001381414 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1,9 +1,19 @@
use clap::builder::styling::{AnsiColor, Color, Styles};
-use clap::{Command, CommandFactory, Parser, Subcommand};
+use clap::{Command, CommandFactory, Parser, Subcommand, ValueEnum};
use std::sync::OnceLock;
use crate::commands::Shell;
+/// Shell type for directive output in --internal mode
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
+pub enum DirectiveShell {
+ /// POSIX shells (bash, zsh, fish) - outputs `cd '/path'`
+ #[default]
+ Posix,
+ /// PowerShell - outputs `Set-Location '/path'`
+ Powershell,
+}
+
/// Custom styles for help output - matches worktrunk's color scheme
fn help_styles() -> Styles {
Styles::styled()
@@ -138,9 +148,10 @@ pub struct Cli {
)]
pub verbose: bool,
- /// Shell wrapper mode
- #[arg(long, global = true, hide = true)]
- pub internal: bool,
+ /// Shell wrapper mode (optionally specify shell type for directive output)
+ /// Usage: --internal (defaults to posix) or --internal=powershell
+ #[arg(long, global = true, hide = true, default_missing_value = "posix", num_args = 0..=1, require_equals = true)]
+ pub internal: Option<DirectiveShell>,
#[command(subcommand)]
pub command: Option<Commands>,
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 83df81d0d..66ab9a4e4 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -3,9 +3,10 @@ use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{self, Shell};
+use worktrunk::shell_exec::ShellConfig;
use worktrunk::styling::{
INFO_EMOJI, PROGRESS_EMOJI, PROMPT_EMOJI, SUCCESS_EMOJI, format_bash_with_gutter,
- format_with_gutter, warning_message,
+ format_with_gutter, hint_message, warning_message,
};
pub struct ConfigureResult {
@@ -186,6 +187,22 @@ pub fn handle_configure_shell(
}
}
+ // On Windows without Git Bash, show advisory about PowerShell limitations
+ let powershell_was_configured = result
+ .configured
+ .iter()
+ .any(|r| r.shell == Shell::PowerShell && !matches!(r.action, ConfigAction::AlreadyExists));
+
+ if powershell_was_configured && ShellConfig::get().is_windows_without_git_bash() {
+ let _ = crate::output::blank();
+ let _ = crate::output::print(warning_message(
+ "PowerShell mode: hooks using bash syntax won't work",
+ ));
+ let _ = crate::output::print(hint_message(
+ "Install Git for Windows for full hook support",
+ ));
+ }
+
Ok(ScanResult {
configured: result.configured,
completion_results,
@@ -201,7 +218,15 @@ pub fn scan_shell_configs(
vec![shell]
} else {
// Try all supported shells in consistent order
- vec![Shell::Bash, Shell::Zsh, Shell::Fish]
+ // On Windows, also include PowerShell for native Windows users
+ #[cfg(windows)]
+ {
+ vec![Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell]
+ }
+ #[cfg(not(windows))]
+ {
+ vec![Shell::Bash, Shell::Zsh, Shell::Fish]
+ }
};
let mut results = Vec::new();
diff --git a/src/commands/process.rs b/src/commands/process.rs
index f25b35afc..1623c0d72 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -1,10 +1,50 @@
use anyhow::Context;
use std::fs;
use std::path::Path;
-use std::process::{Command, Stdio};
+#[cfg(unix)]
+use std::process::Command;
+use std::process::Stdio;
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
+/// Sanitize a string for use as a filename on all platforms.
+/// Replaces characters that are illegal in Windows filenames or are path separators.
+/// Also handles Windows reserved device names (CON, PRN, AUX, NUL, COM1-9, LPT1-9).
+fn sanitize_for_filename(s: &str) -> String {
+ // Replace illegal characters
+ let sanitized: String = s
+ .chars()
+ .map(|c| match c {
+ '/' | '\\' | '<' | '>' | ':' | '"' | '|' | '?' | '*' => '-',
+ _ => c,
+ })
+ .collect();
+
+ // Check for Windows reserved device names (case-insensitive)
+ // These cannot be used as filenames on Windows, even with extensions
+ let upper = sanitized.to_uppercase();
+ let is_reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
+ || (upper.len() == 4
+ && (upper.starts_with("COM") || upper.starts_with("LPT"))
+ && upper.chars().nth(3).is_some_and(|c| matches!(c, '1'..='9')));
+
+ if is_reserved {
+ format!("_{}", sanitized)
+ } else {
+ sanitized
+ }
+}
+
+/// Get the separator needed before closing brace in POSIX shell command grouping.
+/// Returns empty string if command already ends with newline or semicolon.
+fn posix_command_separator(command: &str) -> &'static str {
+ if command.ends_with('\n') || command.ends_with(';') {
+ ""
+ } else {
+ ";"
+ }
+}
+
/// Spawn a detached background process with output redirected to a log file
///
/// The process will be fully detached from the parent:
@@ -45,9 +85,8 @@ pub fn spawn_detached(
// Generate log filename (no timestamp - overwrites on each run)
// Format: {branch}-{name}.log (e.g., "feature-post-start-npm.log", "bugfix-remove.log")
- // Sanitize branch and name: replace '/' with '-' to avoid creating subdirectories
- let safe_branch = branch.replace('/', "-");
- let safe_name = name.replace('/', "-");
+ let safe_branch = sanitize_for_filename(branch);
+ let safe_name = sanitize_for_filename(name);
let log_path = log_dir.join(format!("{}-{}.log", safe_branch, safe_name));
// Create log file
@@ -92,18 +131,11 @@ fn spawn_detached_unix(
// Use printf to pipe JSON to the command's stdin
// printf is more portable than echo for arbitrary content
// Wrap command in braces to ensure proper grouping with &&, ||, etc.
- // Only add semicolon if command doesn't already end with newline or semicolon
- // (shell syntax: `{ cmd\n }` is valid, but `{ cmd\n; }` is not)
- let separator = if command.ends_with('\n') || command.ends_with(';') {
- ""
- } else {
- ";"
- };
format!(
"printf '%s' {} | {{ {}{} }}",
shell_escape::escape(json.into()),
command,
- separator
+ posix_command_separator(command)
)
}
None => command.to_string(),
@@ -142,28 +174,48 @@ fn spawn_detached_windows(
context_json: Option<&str>,
) -> anyhow::Result<()> {
use std::os::windows::process::CommandExt;
+ use worktrunk::shell_exec::ShellConfig;
// CREATE_NEW_PROCESS_GROUP: Creates new process group (0x00000200)
// DETACHED_PROCESS: Creates process without console (0x00000008)
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
const DETACHED_PROCESS: u32 = 0x00000008;
- // Build the command, optionally piping JSON context to stdin
- let full_command = match context_json {
- Some(json) => {
- // PowerShell single-quote escaping:
- // - Single quotes prevent variable expansion ($)
- // - Backticks need escaping even in single quotes (`` ` `` β†’ ``` `` ```)
- // - Single quotes need doubling (`'` β†’ `''`)
- let escaped_json = json.replace('`', "``").replace('\'', "''");
- // Pipe JSON to the command via PowerShell script block
- format!("'{}' | & {{ {} }}", escaped_json, command)
- }
- None => command.to_string(),
- };
+ let shell = ShellConfig::get();
- let mut cmd = Command::new("powershell");
- cmd.args(["-NoProfile", "-Command", &full_command]);
+ // Build the command based on shell type
+ let mut cmd = if shell.is_posix() {
+ // Git Bash available - use same syntax as Unix
+ let full_command = match context_json {
+ Some(json) => {
+ // Use printf to pipe JSON to the command's stdin (same as Unix)
+ format!(
+ "printf '%s' {} | {{ {}{} }}",
+ shell_escape::escape(json.into()),
+ command,
+ posix_command_separator(command)
+ )
+ }
+ None => command.to_string(),
+ };
+ shell.command(&full_command)
+ } else {
+ // PowerShell fallback
+ let full_command = match context_json {
+ Some(json) => {
+ // PowerShell single-quote escaping:
+ // - Single quotes prevent variable expansion ($) and are literal
+ // - Backticks are literal in single quotes (NOT escape characters)
+ // - Only single quotes need doubling (`'` β†’ `''`)
+ // See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
+ let escaped_json = json.replace('\'', "''");
+ // Pipe JSON to the command via PowerShell script block
+ format!("'{}' | & {{ {} }}", escaped_json, command)
+ }
+ None => command.to_string(),
+ };
+ shell.command(&full_command)
+ };
cmd.current_dir(worktree_path)
.stdin(Stdio::null())
@@ -177,5 +229,60 @@ fn spawn_detached_windows(
.spawn()
.context("Failed to spawn detached process")?;
+ // Windows: Process is fully detached via DETACHED_PROCESS flag,
+ // no need to wait (unlike Unix which waits for the outer shell)
+
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_sanitize_for_filename() {
+ // Path separators
+ assert_eq!(sanitize_for_filename("feature/branch"), "feature-branch");
+ assert_eq!(sanitize_for_filename("feature\\branch"), "feature-branch");
+
+ // Windows-illegal characters
+ assert_eq!(sanitize_for_filename("bug:123"), "bug-123");
+ assert_eq!(sanitize_for_filename("fix<angle>"), "fix-angle-");
+ assert_eq!(sanitize_for_filename("fix|pipe"), "fix-pipe");
+ assert_eq!(sanitize_for_filename("fix?question"), "fix-question");
+ assert_eq!(sanitize_for_filename("fix*wildcard"), "fix-wildcard");
+ assert_eq!(sanitize_for_filename("fix\"quotes\""), "fix-quotes-");
+
+ // Multiple special characters
+ assert_eq!(
+ sanitize_for_filename("a/b\\c<d>e:f\"g|h?i*j"),
+ "a-b-c-d-e-f-g-h-i-j"
+ );
+
+ // Already safe
+ assert_eq!(sanitize_for_filename("normal-branch"), "normal-branch");
+ assert_eq!(
+ sanitize_for_filename("branch_with_underscore"),
+ "branch_with_underscore"
+ );
+
+ // Windows reserved device names (must be prefixed to avoid conflicts)
+ assert_eq!(sanitize_for_filename("CON"), "_CON");
+ assert_eq!(sanitize_for_filename("con"), "_con");
+ assert_eq!(sanitize_for_filename("PRN"), "_PRN");
+ assert_eq!(sanitize_for_filename("AUX"), "_AUX");
+ assert_eq!(sanitize_for_filename("NUL"), "_NUL");
+ assert_eq!(sanitize_for_filename("COM1"), "_COM1");
+ assert_eq!(sanitize_for_filename("com9"), "_com9");
+ assert_eq!(sanitize_for_filename("LPT1"), "_LPT1");
+ assert_eq!(sanitize_for_filename("lpt9"), "_lpt9");
+
+ // COM0/LPT0 are NOT reserved (only 1-9 are)
+ assert_eq!(sanitize_for_filename("COM0"), "COM0");
+ assert_eq!(sanitize_for_filename("LPT0"), "LPT0");
+
+ // Longer names are fine
+ assert_eq!(sanitize_for_filename("CONSOLE"), "CONSOLE");
+ assert_eq!(sanitize_for_filename("COM10"), "COM10");
+ }
+}
diff --git a/src/help_pager.rs b/src/help_pager.rs
index 943d28520..01c617e8c 100644
--- a/src/help_pager.rs
+++ b/src/help_pager.rs
@@ -14,9 +14,15 @@
//! prevent hangs from TTY access
//!
//! Both follow git's pager detection but spawn differently based on their usage context.
+//!
+//! # Cross-Platform Support
+//!
+//! On Windows, the pager uses Git Bash (if available) to support standard pager
+//! commands like `less`. If Git Bash is not available, falls back to direct output.
use std::io::{IsTerminal, Write};
use std::process::{Command, Stdio};
+use worktrunk::shell_exec::ShellConfig;
fn validate_pager(s: &str) -> Option<String> {
let trimmed = s.trim();
@@ -26,9 +32,14 @@ fn validate_pager(s: &str) -> Option<String> {
/// Detect pager for help output, following git's pager precedence.
///
/// Checks in order: GIT_PAGER β†’ git config core.pager β†’ PAGER β†’ "less"
+///
+/// On Windows without Git Bash, returns None if only `less` would be selected
+/// (since `less` isn't available without Git for Windows).
fn detect_help_pager() -> Option<String> {
+ let shell = ShellConfig::get();
+
// Check environment variables in git's precedence order
- std::env::var("GIT_PAGER")
+ let pager = std::env::var("GIT_PAGER")
.ok()
.and_then(|s| validate_pager(&s))
.or_else(|| {
@@ -48,8 +59,21 @@ fn detect_help_pager() -> Option<String> {
.and_then(|s| validate_pager(&s))
})
})
- .or_else(|| std::env::var("PAGER").ok().and_then(|s| validate_pager(&s)))
- .or_else(|| Some("less".to_string())) // Default fallback (may fail if less not installed)
+ .or_else(|| std::env::var("PAGER").ok().and_then(|s| validate_pager(&s)));
+
+ // If user explicitly configured a pager, use it
+ if pager.is_some() {
+ return pager;
+ }
+
+ // Default to "less" only if we have a POSIX shell (Unix or Git Bash on Windows)
+ // Without Git Bash, less isn't typically available on Windows
+ if shell.is_posix() {
+ Some("less".to_string())
+ } else {
+ log::debug!("No POSIX shell available, skipping pager (less not available)");
+ None
+ }
}
/// Show help text through a pager with TTY access for interactive scrolling.
@@ -93,33 +117,17 @@ pub fn show_help_in_pager(help_text: &str) -> std::io::Result<()> {
// Spawn pager with TTY access (interactive, unlike detached diff renderer)
// Falls back to direct output if pager unavailable (e.g., less not installed)
- #[cfg(unix)]
- let mut child = match Command::new("sh")
- .arg("-c")
- .arg(&final_cmd)
- .stdin(Stdio::piped())
- .env("LESS", &less_flags)
- .spawn()
- {
- Ok(child) => child,
- Err(e) => {
- log::debug!("Failed to spawn pager '{}': {}", pager_cmd, e);
- eprint!("{}", help_text);
- return Ok(());
- }
- };
-
- #[cfg(windows)]
- let mut child = match Command::new("cmd")
- .arg("/C")
- .arg(&final_cmd)
- .stdin(Stdio::piped())
- .env("LESS", &less_flags)
- .spawn()
- {
+ let shell = ShellConfig::get();
+ let mut cmd = shell.command(&final_cmd);
+ let mut child = match cmd.stdin(Stdio::piped()).env("LESS", &less_flags).spawn() {
Ok(child) => child,
Err(e) => {
- log::debug!("Failed to spawn pager '{}': {}", pager_cmd, e);
+ log::debug!(
+ "Failed to spawn pager '{}' with {}: {}",
+ pager_cmd,
+ shell.name,
+ e
+ );
eprint!("{}", help_text);
return Ok(());
}
diff --git a/src/lib.rs b/src/lib.rs
index c06c1162c..c0bdf3ff9 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,6 +2,7 @@ pub mod config;
pub mod git;
pub mod path;
pub mod shell;
+pub mod shell_exec;
pub mod styling;
// Re-export HookType for convenience
diff --git a/src/main.rs b/src/main.rs
index 805eb2961..fe37633d7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -522,10 +522,9 @@ fn main() {
}
// Initialize output context based on --internal flag
- let output_mode = if cli.internal {
- output::OutputMode::Directive
- } else {
- output::OutputMode::Interactive
+ let output_mode = match cli.internal {
+ Some(shell) => output::OutputMode::Directive(shell),
+ None => output::OutputMode::Interactive,
};
output::initialize(output_mode);
@@ -995,7 +994,7 @@ fn main() {
},
},
#[cfg(unix)]
- Commands::Select => handle_select(cli.internal),
+ Commands::Select => handle_select(cli.internal.is_some()),
Commands::List {
subcommand,
format,
@@ -1098,7 +1097,12 @@ fn main() {
// Show success message (temporal locality: immediately after worktree creation)
// Pass cli.internal to indicate whether shell integration is active
- handle_switch_output(&result, &resolved_branch, execute.is_some(), cli.internal)?;
+ handle_switch_output(
+ &result,
+ &resolved_branch,
+ execute.is_some(),
+ cli.internal.is_some(),
+ )?;
// Now spawn post-start hooks (background processes, after success message)
// Only run post-start commands when creating a NEW worktree, not when switching to existing
diff --git a/src/output/directive.rs b/src/output/directive.rs
index 83565ea30..4088f8417 100644
--- a/src/output/directive.rs
+++ b/src/output/directive.rs
@@ -59,14 +59,17 @@ pub struct DirectiveOutput {
target_dir: Option<PathBuf>,
/// Command to execute (set by execute, emitted in terminate_output)
exec_command: Option<String>,
+ /// Shell type for directive output formatting
+ shell: crate::cli::DirectiveShell,
}
impl DirectiveOutput {
- pub fn new() -> Self {
+ pub fn new(shell: crate::cli::DirectiveShell) -> Self {
Self {
stderr: io::stderr(),
target_dir: None,
exec_command: None,
+ shell,
}
}
}
@@ -105,24 +108,33 @@ impl OutputHandler for DirectiveOutput {
}
fn terminate_output(&mut self) -> io::Result<()> {
+ use crate::cli::DirectiveShell;
+
// Reset ANSI state before returning to shell.
// wt's colored messages set terminal state on stderr.
write!(self.stderr, "{}", anstyle::Reset)?;
self.stderr.flush()?;
// Emit shell script to stdout with buffered directives
- // The shell wrapper captures this via $(...) and evals it
+ // The shell wrapper captures this via $(...) and evals it (POSIX)
+ // or | Out-String | Invoke-Expression (PowerShell)
let mut stdout = io::stdout();
// cd command (if target directory was set)
if let Some(ref path) = self.target_dir {
- // Use single quotes for safety, escape any embedded single quotes
- // Single quotes preserve all characters literally (including newlines,
- // tabs, $, `, etc.) except for single quotes themselves, which we
- // escape as '\'' (end quote, literal quote, start quote)
let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- writeln!(stdout, "cd '{}'", escaped)?;
+ match self.shell {
+ DirectiveShell::Posix => {
+ // POSIX: Use single quotes, escape embedded single quotes as '\''
+ let escaped = path_str.replace('\'', "'\\''");
+ writeln!(stdout, "cd '{}'", escaped)?;
+ }
+ DirectiveShell::Powershell => {
+ // PowerShell: Use single quotes, escape embedded single quotes by doubling
+ let escaped = path_str.replace('\'', "''");
+ writeln!(stdout, "Set-Location '{}'", escaped)?;
+ }
+ }
}
// exec command (if one was set via --execute)
@@ -136,7 +148,7 @@ impl OutputHandler for DirectiveOutput {
impl Default for DirectiveOutput {
fn default() -> Self {
- Self::new()
+ Self::new(crate::cli::DirectiveShell::Posix)
}
}
@@ -189,6 +201,26 @@ mod tests {
assert_eq!(cd_cmd, "cd '/test/$HOME/`whoami`/path'");
}
+ #[test]
+ fn test_powershell_path_format() {
+ // PowerShell uses Set-Location and doubles single quotes for escaping
+ let path = PathBuf::from("C:\\Users\\test\\path");
+ let path_str = path.to_string_lossy();
+ let escaped = path_str.replace('\'', "''");
+ let ps_cmd = format!("Set-Location '{}'", escaped);
+ assert_eq!(ps_cmd, "Set-Location 'C:\\Users\\test\\path'");
+ }
+
+ #[test]
+ fn test_powershell_path_with_single_quotes() {
+ // PowerShell escapes single quotes by doubling them
+ let path = PathBuf::from("C:\\Users\\it's a test\\path");
+ let path_str = path.to_string_lossy();
+ let escaped = path_str.replace('\'', "''");
+ let ps_cmd = format!("Set-Location '{}'", escaped);
+ assert_eq!(ps_cmd, "Set-Location 'C:\\Users\\it''s a test\\path'");
+ }
+
/// Test that anstyle formatting is preserved in directive output
#[test]
fn test_success_preserves_anstyle() {
diff --git a/src/output/global.rs b/src/output/global.rs
index af2c07d7e..9765e96db 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -22,6 +22,7 @@
use super::directive::DirectiveOutput;
use super::interactive::InteractiveOutput;
use super::traits::OutputHandler;
+use crate::cli::DirectiveShell;
use std::cell::RefCell;
use std::io;
use std::path::Path;
@@ -30,7 +31,8 @@ use std::path::Path;
#[derive(Debug, Clone, Copy)]
pub enum OutputMode {
Interactive,
- Directive,
+ /// Directive mode with shell type for output formatting
+ Directive(DirectiveShell),
}
thread_local! {
@@ -53,7 +55,7 @@ fn with_output<R>(f: impl FnOnce(&mut dyn OutputHandler) -> R) -> R {
pub fn initialize(mode: OutputMode) {
let handler: Box<dyn OutputHandler> = match mode {
OutputMode::Interactive => Box::new(InteractiveOutput::new()),
- OutputMode::Directive => Box::new(DirectiveOutput::new()),
+ OutputMode::Directive(shell) => Box::new(DirectiveOutput::new(shell)),
};
OUTPUT_CONTEXT.with(|ctx| {
@@ -170,12 +172,18 @@ mod tests {
#[test]
fn test_mode_switching() {
+ use crate::cli::DirectiveShell;
+
// Default is interactive
initialize(OutputMode::Interactive);
// Just verify initialize doesn't panic
- // Switch to directive
- initialize(OutputMode::Directive);
+ // Switch to directive (POSIX)
+ initialize(OutputMode::Directive(DirectiveShell::Posix));
+ // Just verify initialize doesn't panic
+
+ // Switch to directive (PowerShell)
+ initialize(OutputMode::Directive(DirectiveShell::Powershell));
// Just verify initialize doesn't panic
}
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index ae34b43a8..e4332b4bc 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -659,6 +659,12 @@ fn handle_removed_worktree_output(
///
/// Returns error if command exits with non-zero status.
///
+/// ## Cross-Platform Shell Execution
+///
+/// Uses the platform's preferred shell via `shell_exec::ShellConfig`:
+/// - Unix: `/bin/sh -c`
+/// - Windows: Git Bash if available, PowerShell fallback
+///
/// ## Signal Handling (Unix)
///
/// SIGINT (Ctrl-C) is handled by checking the child's exit status:
@@ -673,15 +679,34 @@ pub(crate) fn execute_streaming(
stdin_content: Option<&str>,
) -> anyhow::Result<()> {
use std::io::Write;
- use std::process::Command;
use worktrunk::git::WorktrunkError;
-
- let command_to_run = if redirect_stdout_to_stderr {
- // Use newline instead of semicolon before closing brace to support
- // multi-line commands with control structures (if/fi, for/done, etc.)
- format!("{{ {}\n}} 1>&2", command)
+ use worktrunk::shell_exec::ShellConfig;
+
+ let shell = ShellConfig::get();
+
+ // Determine stdout handling based on shell and redirect flag
+ let (command_to_run, stdout_mode) = if redirect_stdout_to_stderr {
+ if shell.is_posix() {
+ // POSIX: wrap command to redirect stdout to stderr at shell level
+ // Use newline instead of semicolon before closing brace to support
+ // multi-line commands with control structures (if/fi, for/done, etc.)
+ (
+ format!("{{ {}\n}} 1>&2", command),
+ std::process::Stdio::inherit(),
+ )
+ } else {
+ // Non-POSIX (PowerShell): redirect stdout to stderr at OS level
+ // PowerShell doesn't support shell-level stdout-to-stderr redirection (*>&2 fails).
+ // Use Stdio::from(io::stderr()) to redirect child stdout to our stderr.
+ // This keeps stdout clean for directive scripts while hook output goes to stderr.
+ // See: https://github.com/PowerShell/PowerShell/issues/7620
+ (
+ command.to_string(),
+ std::process::Stdio::from(std::io::stderr()),
+ )
+ }
} else {
- command.to_string()
+ (command.to_string(), std::process::Stdio::inherit())
};
let stdin_mode = if stdin_content.is_some() {
@@ -690,12 +715,11 @@ pub(crate) fn execute_streaming(
std::process::Stdio::null()
};
- let mut child = Command::new("sh")
- .arg("-c")
- .arg(&command_to_run)
+ let mut cmd = shell.command(&command_to_run);
+ let mut child = cmd
.current_dir(working_dir)
.stdin(stdin_mode)
- .stdout(std::process::Stdio::inherit()) // Preserve TTY for output
+ .stdout(stdout_mode)
.stderr(std::process::Stdio::inherit()) // Preserve TTY for errors
// Prevent vergen "overridden" warning in nested cargo builds when run via `cargo run`.
// Add more VERGEN_* variables here if we expand build.rs and hit similar issues.
@@ -703,7 +727,7 @@ pub(crate) fn execute_streaming(
.spawn()
.map_err(|e| {
anyhow::Error::from(worktrunk::git::GitError::Other {
- message: format!("Failed to execute command: {}", e),
+ message: format!("Failed to execute command with {}: {}", shell.name, e),
})
})?;
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index 1ae389a52..fe352aa79 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -2,6 +2,10 @@
use std::io::{self, Write};
use std::path::Path;
+#[cfg(unix)]
+use std::process::Stdio;
+#[cfg(unix)]
+use worktrunk::shell_exec::ShellConfig;
use worktrunk::styling::{eprintln, stderr};
#[cfg(not(unix))]
@@ -59,16 +63,15 @@ impl OutputHandler for InteractiveOutput {
#[cfg(unix)]
fn execute(&mut self, command: String) -> anyhow::Result<()> {
use std::os::unix::process::CommandExt;
- use std::process::{Command, Stdio};
let exec_dir = self.target_dir.as_deref().unwrap_or_else(|| Path::new("."));
+ let shell = ShellConfig::get();
// Use exec() to replace wt process with the command.
// This gives the command full TTY access (stdin, stdout, stderr all inherited),
// enabling interactive programs like `claude` to work properly.
- let err = Command::new("sh")
- .arg("-c")
- .arg(&command)
+ let mut cmd = shell.command(&command);
+ let err = cmd
.current_dir(exec_dir)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
@@ -76,12 +79,18 @@ impl OutputHandler for InteractiveOutput {
.exec();
// exec() only returns on error
- Err(anyhow::anyhow!("Failed to exec '{}': {}", command, err))
+ Err(anyhow::anyhow!(
+ "Failed to exec '{}' with {}: {}",
+ command,
+ shell.name,
+ err
+ ))
}
#[cfg(not(unix))]
fn execute(&mut self, command: String) -> anyhow::Result<()> {
// On non-Unix platforms, fall back to spawn-and-wait
+ // This uses the shell abstraction (Git Bash if available)
let exec_dir = self.target_dir.as_deref().unwrap_or_else(|| Path::new("."));
execute_streaming(&command, exec_dir, false, None)?;
Ok(())
diff --git a/src/shell.rs b/src/shell.rs
index 1be37e91a..3778990fc 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -4,25 +4,58 @@ use std::path::PathBuf;
use crate::path::home_dir;
+/// 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.
+fn powershell_profile_paths(home: &std::path::Path) -> 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![
+ // 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![
+ home.join(".config")
+ .join("powershell")
+ .join("Microsoft.PowerShell_profile.ps1"),
+ ]
+ }
+}
+
/// Get the user's home directory or return an error
fn home_dir_required() -> Result<PathBuf, std::io::Error> {
home_dir().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
- "Cannot determine home directory. Set $HOME environment variable",
+ "Cannot determine home directory. Set $HOME (Unix) or $USERPROFILE (Windows)",
)
})
}
/// Supported shells
///
-/// Currently supported: bash, fish, zsh
+/// Currently supported: bash, fish, zsh, powershell
+///
+/// On Windows, Git Bash users should use `bash` for shell integration.
+/// PowerShell integration is available for native Windows users without Git Bash.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display, strum::EnumString)]
#[strum(serialize_all = "lowercase", ascii_case_insensitive)]
pub enum Shell {
Bash,
Fish,
Zsh,
+ #[strum(serialize = "powershell")]
+ #[clap(name = "powershell")]
+ PowerShell,
}
impl Shell {
@@ -52,6 +85,7 @@ impl Shell {
.join("wt.fish"),
]
}
+ Self::PowerShell => powershell_profile_paths(&home),
})
}
@@ -88,6 +122,12 @@ impl Shell {
.unwrap_or_else(|| home.join(".config"));
config_home.join("fish").join("completions").join("wt.fish")
}
+ Self::PowerShell => {
+ // PowerShell doesn't use a separate completion file - completions are
+ // registered inline in the profile using Register-ArgumentCompleter
+ // Return a dummy path that won't be used
+ home.join(".wt-powershell-completions")
+ }
})
}
@@ -108,6 +148,10 @@ impl Shell {
self
)
}
+ Self::PowerShell => {
+ // PowerShell: Check if wt is available, then invoke and execute the output
+ "if (Get-Command wt -ErrorAction SilentlyContinue) { Invoke-Expression (& wt config shell init powershell) }".to_string()
+ }
}
}
@@ -186,6 +230,19 @@ impl Shell {
}
}
+ // Check PowerShell profiles for integration (both Core and 5.1)
+ for profile_path in powershell_profile_paths(&home) {
+ if profile_path.exists()
+ && let Ok(content) = fs::read_to_string(&profile_path)
+ {
+ // Look for PowerShell integration pattern:
+ // Invoke-Expression (& wt config shell init powershell)
+ if content.contains("Invoke-Expression") && content.contains("shell init") {
+ return Ok(Some(profile_path));
+ }
+ }
+ }
+
Ok(None)
}
@@ -231,6 +288,10 @@ impl ShellInit {
let template = FishTemplate { cmd_prefix: "wt" };
template.render()
}
+ Shell::PowerShell => {
+ let template = PowerShellTemplate { cmd_prefix: "wt" };
+ template.render()
+ }
}
}
}
@@ -266,6 +327,13 @@ struct FishTemplate<'a> {
cmd_prefix: &'a str,
}
+/// PowerShell template
+#[derive(Template)]
+#[template(path = "powershell.ps1", escape = "none")]
+struct PowerShellTemplate<'a> {
+ cmd_prefix: &'a str,
+}
+
/// Detect if user's zsh has compinit enabled by probing for the compdef function.
///
/// Zsh's completion system (compinit) must be explicitly enabled - it's not on by default.
@@ -356,6 +424,14 @@ mod tests {
assert!(matches!("BASH".parse::<Shell>(), Ok(Shell::Bash)));
assert!(matches!("fish".parse::<Shell>(), Ok(Shell::Fish)));
assert!(matches!("zsh".parse::<Shell>(), Ok(Shell::Zsh)));
+ assert!(matches!(
+ "powershell".parse::<Shell>(),
+ Ok(Shell::PowerShell)
+ ));
+ assert!(matches!(
+ "POWERSHELL".parse::<Shell>(),
+ Ok(Shell::PowerShell)
+ ));
assert!("invalid".parse::<Shell>().is_err());
}
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
new file mode 100644
index 000000000..4ae743134
--- /dev/null
+++ b/src/shell_exec.rs
@@ -0,0 +1,293 @@
+//! Cross-platform shell execution
+//!
+//! Provides a unified interface for executing shell commands across platforms:
+//! - Unix: Uses `/bin/sh -c`
+//! - Windows: Prefers Git Bash if available, falls back to PowerShell
+//!
+//! This enables hooks and commands to use the same bash syntax on all platforms,
+//! as long as Git for Windows is installed (which is nearly universal among
+//! Windows developers).
+//!
+//! ## Windows Limitations
+//!
+//! When Git Bash is not available, PowerShell is used as a fallback with limitations:
+//! - Hooks using bash syntax won't work
+//! - No support for POSIX redirections like `{ cmd; } 1>&2`
+//! - Different string escaping rules for JSON piping
+
+use std::path::PathBuf;
+use std::process::Command;
+use std::sync::OnceLock;
+
+/// Cached shell configuration for the current platform
+static SHELL_CONFIG: OnceLock<ShellConfig> = OnceLock::new();
+
+/// Shell configuration for command execution
+#[derive(Debug, Clone)]
+pub struct ShellConfig {
+ /// Path to the shell executable
+ pub executable: PathBuf,
+ /// Arguments to pass before the command (e.g., ["-c"] for sh, ["/C"] for cmd)
+ pub args: Vec<String>,
+ /// Whether this is a POSIX-compatible shell (bash/sh)
+ pub is_posix: bool,
+ /// Human-readable name for error messages
+ pub name: String,
+}
+
+impl ShellConfig {
+ /// Get the shell configuration for the current platform
+ ///
+ /// On Unix, this always returns sh.
+ /// On Windows, this prefers Git Bash if available, then falls back to PowerShell.
+ pub fn get() -> &'static ShellConfig {
+ SHELL_CONFIG.get_or_init(detect_shell)
+ }
+
+ /// Create a Command configured for shell execution
+ ///
+ /// The command string will be passed to the shell for interpretation.
+ pub fn command(&self, shell_command: &str) -> Command {
+ let mut cmd = Command::new(&self.executable);
+ for arg in &self.args {
+ cmd.arg(arg);
+ }
+ cmd.arg(shell_command);
+ cmd
+ }
+
+ /// Check if this shell supports POSIX syntax (bash, sh, zsh, etc.)
+ ///
+ /// When true, commands can use POSIX features like:
+ /// - `{ cmd; } 1>&2` for stdout redirection
+ /// - `printf '%s' ... | cmd` for stdin piping
+ /// - `nohup ... &` for background execution
+ pub fn is_posix(&self) -> bool {
+ self.is_posix
+ }
+
+ /// Check if running on Windows without Git Bash (using PowerShell fallback)
+ ///
+ /// Returns true when hooks using bash syntax won't work properly.
+ /// Used to show warnings to users about limited functionality.
+ #[cfg(windows)]
+ pub fn is_windows_without_git_bash(&self) -> bool {
+ !self.is_posix
+ }
+
+ #[cfg(not(windows))]
+ pub fn is_windows_without_git_bash(&self) -> bool {
+ false
+ }
+}
+
+/// Detect the best available shell for the current platform
+fn detect_shell() -> ShellConfig {
+ #[cfg(unix)]
+ {
+ ShellConfig {
+ executable: PathBuf::from("sh"),
+ args: vec!["-c".to_string()],
+ is_posix: true,
+ name: "sh".to_string(),
+ }
+ }
+
+ #[cfg(windows)]
+ {
+ detect_windows_shell()
+ }
+}
+
+/// Detect the best available shell on Windows
+///
+/// Priority order:
+/// 1. Git Bash (if Git for Windows is installed)
+/// 2. PowerShell (fallback, with warnings about syntax differences)
+#[cfg(windows)]
+fn detect_windows_shell() -> ShellConfig {
+ if let Some(bash_path) = find_git_bash() {
+ return ShellConfig {
+ executable: bash_path,
+ args: vec!["-c".to_string()],
+ is_posix: true,
+ name: "Git Bash".to_string(),
+ };
+ }
+
+ // Fall back to PowerShell
+ ShellConfig {
+ executable: PathBuf::from("powershell.exe"),
+ args: vec!["-NoProfile".to_string(), "-Command".to_string()],
+ is_posix: false,
+ name: "PowerShell".to_string(),
+ }
+}
+
+/// Find Git Bash executable on Windows
+///
+/// Checks:
+/// 1. MSYSTEM environment variable (indicates running in Git Bash/MSYS2)
+/// 2. Standard Git for Windows installation paths
+/// 3. `git.exe` in PATH to find Git installation directory
+#[cfg(windows)]
+fn find_git_bash() -> Option<PathBuf> {
+ // If we're already in Git Bash (MSYSTEM is set), bash should be in PATH
+ if std::env::var("MSYSTEM").is_ok() && which::which("bash").is_ok() {
+ return Some(PathBuf::from("bash"));
+ }
+
+ // Check standard Git for Windows installation paths
+ let standard_paths = [
+ r"C:\Program Files\Git\bin\bash.exe",
+ r"C:\Program Files (x86)\Git\bin\bash.exe",
+ r"C:\Git\bin\bash.exe",
+ ];
+
+ for path in &standard_paths {
+ let path = PathBuf::from(path);
+ if path.exists() {
+ return Some(path);
+ }
+ }
+
+ // Try to find Git installation via `git.exe` in PATH
+ if let Ok(git_path) = which::which("git") {
+ // git.exe is typically at Git/cmd/git.exe or Git/bin/git.exe
+ // bash.exe is at Git/bin/bash.exe
+ if let Some(git_dir) = git_path.parent().and_then(|p| p.parent()) {
+ let bash_path = git_dir.join("bin").join("bash.exe");
+ if bash_path.exists() {
+ return Some(bash_path);
+ }
+ }
+ }
+
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_shell_config_is_available() {
+ let config = ShellConfig::get();
+ assert!(!config.name.is_empty());
+ assert!(!config.args.is_empty());
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn test_unix_shell_is_posix() {
+ let config = ShellConfig::get();
+ assert!(config.is_posix);
+ assert_eq!(config.name, "sh");
+ }
+
+ #[test]
+ fn test_command_creation() {
+ let config = ShellConfig::get();
+ let cmd = config.command("echo hello");
+ // Just verify it doesn't panic
+ let _ = format!("{:?}", cmd);
+ }
+
+ #[test]
+ fn test_shell_command_execution() {
+ let config = ShellConfig::get();
+ let output = config
+ .command("echo hello")
+ .output()
+ .expect("Failed to execute shell command");
+ assert!(output.status.success(), "echo should succeed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("hello"),
+ "stdout should contain 'hello', got: '{}'",
+ stdout.trim()
+ );
+ }
+
+ #[test]
+ #[cfg(windows)]
+ fn test_windows_shell_detection() {
+ let config = ShellConfig::get();
+ // On Windows CI, Git is installed, so we should have Git Bash
+ // If this fails on a system without Git, PowerShell fallback should work
+ assert!(
+ config.name == "Git Bash" || config.name == "PowerShell",
+ "Expected 'Git Bash' or 'PowerShell', got '{}'",
+ config.name
+ );
+ }
+
+ #[test]
+ #[cfg(windows)]
+ fn test_windows_git_bash_has_posix_syntax() {
+ let config = ShellConfig::get();
+ if config.name == "Git Bash" {
+ assert!(config.is_posix, "Git Bash should support POSIX syntax");
+ assert!(
+ config.args.contains(&"-c".to_string()),
+ "Git Bash should use -c flag"
+ );
+ }
+ }
+
+ #[test]
+ #[cfg(windows)]
+ fn test_windows_powershell_fallback_not_posix() {
+ let config = ShellConfig::get();
+ if config.name == "PowerShell" {
+ assert!(!config.is_posix, "PowerShell should not be marked as POSIX");
+ assert!(
+ config.args.contains(&"-Command".to_string()),
+ "PowerShell should use -Command flag"
+ );
+ }
+ }
+
+ #[test]
+ #[cfg(windows)]
+ fn test_windows_echo_command() {
+ // Test that echo works regardless of which shell we detected
+ let config = ShellConfig::get();
+ let output = config
+ .command("echo test_output")
+ .output()
+ .expect("Failed to execute echo");
+
+ assert!(output.status.success(), "echo should succeed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("test_output"),
+ "stdout should contain 'test_output', got: '{}'",
+ stdout.trim()
+ );
+ }
+
+ #[test]
+ #[cfg(windows)]
+ fn test_windows_posix_redirection_with_git_bash() {
+ let config = ShellConfig::get();
+ if config.is_posix() {
+ // Test POSIX-style redirection: stdout redirected to stderr
+ let output = config
+ .command("echo redirected 1>&2")
+ .output()
+ .expect("Failed to execute redirection test");
+
+ assert!(
+ output.status.success(),
+ "redirection command should succeed"
+ );
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("redirected"),
+ "stderr should contain 'redirected' (stdout redirected to stderr), got: '{}'",
+ stderr.trim()
+ );
+ }
+ }
+}
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
new file mode 100644
index 000000000..31978ab04
--- /dev/null
+++ b/templates/powershell.ps1
@@ -0,0 +1,50 @@
+# worktrunk shell integration for PowerShell
+#
+# Limitations compared to bash/zsh/fish:
+# - Hooks using bash syntax won't work without Git Bash
+#
+# For full hook compatibility on Windows, install Git for Windows and use bash integration.
+
+# Only initialize if wt is available
+if (Get-Command {{ cmd_prefix }} -ErrorAction SilentlyContinue) {
+
+ # wt wrapper function - captures stdout and executes as PowerShell
+ function {{ cmd_prefix }} {
+ param(
+ [Parameter(ValueFromRemainingArguments = $true)]
+ [string[]]$Arguments
+ )
+
+ $wtBin = (Get-Command {{ cmd_prefix }} -CommandType Application).Source
+
+ # Run wt with --internal=powershell
+ # stdout is captured for Invoke-Expression (contains Set-Location directives)
+ # stderr passes through to console in real-time (user messages, progress, errors)
+ # Note: We do NOT use 2>&1 as that would merge stderr into the script variable
+ $script = & $wtBin --internal=powershell @Arguments | Out-String
+ $exitCode = $LASTEXITCODE
+
+ # Execute the directive script (e.g., Set-Location) if command succeeded
+ if ($exitCode -eq 0 -and $script.Trim()) {
+ Invoke-Expression $script
+ }
+
+ # Propagate exit code so $? and $LASTEXITCODE are consistent for scripts/CI
+ $global:LASTEXITCODE = $exitCode
+ if ($exitCode -ne 0) {
+ # Write error to set $? = $false without throwing
+ Write-Error "wt exited with code $exitCode" -ErrorAction SilentlyContinue
+ }
+ return $exitCode
+ }
+
+ # Tab completion - generate clap's completer script and eval it
+ # This registers Register-ArgumentCompleter with proper handling
+ $env:COMPLETE = "powershell"
+ try {
+ & (Get-Command {{ cmd_prefix }} -CommandType Application) | Out-String | Invoke-Expression
+ }
+ finally {
+ Remove-Item Env:\COMPLETE -ErrorAction SilentlyContinue
+ }
+}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index f6eec7aa1..eb80d3f96 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -1,3 +1,7 @@
+// Test utilities are Unix-only as they're used by integration tests
+// which rely on Unix-specific behavior (PTY, shell integration, etc.)
+#![cfg(unix)]
+
//! # Test Utilities for worktrunk
//!
//! This module provides test harnesses for testing the worktrunk CLI tool.
@@ -22,12 +26,12 @@
//! Paths are canonicalized to handle platform differences (especially macOS symlinks
//! like /var -> /private/var). This ensures snapshot filters work correctly.
-// Test utilities are Unix-only since integration tests are Unix-only
-#![cfg(unix)]
-
pub mod list_snapshots;
+// Progressive output tests use PTY and are Unix-only for now
+#[cfg(unix)]
pub mod progressive_output;
-#[cfg(feature = "shell-integration-tests")]
+// Shell integration tests are Unix-only for now (Windows support planned)
+#[cfg(all(unix, feature = "shell-integration-tests"))]
pub mod shell;
use insta_cmd::get_cargo_bin;
diff --git a/tests/common/shell.rs b/tests/common/shell.rs
index 1707e5a2a..deb2f86d5 100644
--- a/tests/common/shell.rs
+++ b/tests/common/shell.rs
@@ -1,6 +1,59 @@
use super::{TestRepo, wt_command};
use insta_cmd::get_cargo_bin;
-use std::process::Command;
+use std::{collections::HashSet, process::Command, sync::LazyLock};
+
+/// Set of shells available on this system (cached at first access)
+static AVAILABLE_SHELLS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
+ let mut shells = HashSet::new();
+
+ // Check bash availability
+ if Command::new("bash")
+ .arg("--version")
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+ {
+ shells.insert("bash");
+ }
+
+ // Check zsh availability (typically not on Windows)
+ if Command::new("zsh")
+ .arg("--version")
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+ {
+ shells.insert("zsh");
+ }
+
+ // Check fish availability (typically not on Windows)
+ if Command::new("fish")
+ .arg("--version")
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+ {
+ shells.insert("fish");
+ }
+
+ // Check PowerShell Core availability (pwsh, cross-platform)
+ if Command::new("pwsh")
+ .arg("-Version")
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+ {
+ shells.insert("pwsh");
+ shells.insert("powershell"); // Alias
+ }
+
+ shells
+});
+
+/// Check if a shell is available on the current system.
+pub fn shell_available(shell: &str) -> bool {
+ AVAILABLE_SHELLS.contains(shell)
+}
/// Path to dev-detach binary (built automatically as part of the crate).
/// The binary is gated behind the `shell-integration-tests` feature.
diff --git a/tests/integration_tests/e2e_shell.rs b/tests/integration_tests/e2e_shell.rs
index 0789b63e7..8c763a73e 100644
--- a/tests/integration_tests/e2e_shell.rs
+++ b/tests/integration_tests/e2e_shell.rs
@@ -1,18 +1,31 @@
//! End-to-end shell integration tests.
-#![cfg(feature = "shell-integration-tests")]
+#![cfg(all(unix, feature = "shell-integration-tests"))]
use crate::common::{
TestRepo,
- shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},
+ shell::{
+ execute_shell_script, generate_init_code, path_export_syntax, shell_available, wt_bin_dir,
+ },
};
use rstest::rstest;
+/// Skip test if the shell is not available on this system.
+macro_rules! skip_if_shell_unavailable {
+ ($shell:expr) => {
+ if !shell_available($shell) {
+ eprintln!("Skipping test: {} not available on this system", $shell);
+ return;
+ }
+ };
+}
+
#[rstest]
// Test with bash (baseline) and fish (alternate syntax)
#[case("bash")]
#[case("fish")]
#[case("zsh")]
fn test_shell_integration_switch_and_remove(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
repo.setup_remote("main");
@@ -69,6 +82,7 @@ fn test_shell_integration_switch_and_remove(#[case] shell: &str) {
#[test]
fn test_bash_shell_integration_error_handling() {
+ skip_if_shell_unavailable!("bash");
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -110,6 +124,7 @@ fn test_bash_shell_integration_error_handling() {
#[test]
fn test_bash_shell_integration_switch_existing_worktree() {
+ skip_if_shell_unavailable!("bash");
let repo = TestRepo::new();
repo.commit("Initial commit");
diff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rs
index 565f3b7e4..f2fbc8202 100644
--- a/tests/integration_tests/e2e_shell_post_start.rs
+++ b/tests/integration_tests/e2e_shell_post_start.rs
@@ -1,21 +1,34 @@
//! Post-start command shell integration tests.
-#![cfg(feature = "shell-integration-tests")]
+#![cfg(all(unix, feature = "shell-integration-tests"))]
use crate::common::{
TestRepo, resolve_git_common_dir,
- shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},
+ shell::{
+ execute_shell_script, generate_init_code, path_export_syntax, shell_available, wt_bin_dir,
+ },
wait_for_file, wait_for_file_content,
};
use rstest::rstest;
use std::fs;
use std::time::Duration;
+/// Skip test if the shell is not available on this system.
+macro_rules! skip_if_shell_unavailable {
+ ($shell:expr) => {
+ if !shell_available($shell) {
+ eprintln!("Skipping test: {} not available on this system", $shell);
+ return;
+ }
+ };
+}
+
/// Test that post-start background commands work with shell integration
#[rstest]
// Test with bash and fish
#[case("bash")]
#[case("fish")]
fn test_shell_integration_post_start_background(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let repo = TestRepo::new();
repo.commit("Initial commit");
diff --git a/tests/integration_tests/init.rs b/tests/integration_tests/init.rs
index 5c3a51d15..bd582a382 100644
--- a/tests/integration_tests/init.rs
+++ b/tests/integration_tests/init.rs
@@ -66,7 +66,7 @@ fn test_init_invalid_shell() {
----- stderr -----
error: invalid value 'invalid-shell' for '<SHELL>'
- [possible values: bash, fish, zsh]
+ [possible values: bash, fish, zsh, powershell]
For more information, try '--help'.
");
diff --git a/tests/integration_tests/list_progressive.rs b/tests/integration_tests/list_progressive.rs
index a0cb318a1..f69fb5299 100644
--- a/tests/integration_tests/list_progressive.rs
+++ b/tests/integration_tests/list_progressive.rs
@@ -2,6 +2,7 @@
//!
//! These tests capture multiple snapshots of the output as it renders,
//! verifying that the table structure appears first and data fills in progressively.
+#![cfg(unix)]
use crate::common::TestRepo;
use crate::common::progressive_output::{ProgressiveCaptureOptions, capture_progressive_output};
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 63ed53262..f3cba34d4 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -32,9 +32,11 @@
//! is necessary, and file snapshots are the right storage format for escape-code-heavy output.
// All shell integration tests and infrastructure gated by feature flag
-#![cfg(feature = "shell-integration-tests")]
+// Unix-only for now - Windows shell integration is planned
+#![cfg(all(unix, feature = "shell-integration-tests"))]
use crate::common::TestRepo;
+use crate::common::shell::shell_available;
use insta::assert_snapshot;
use insta_cmd::get_cargo_bin;
use std::fs;
@@ -42,6 +44,17 @@ use std::path::PathBuf;
use std::process::Command;
use std::sync::LazyLock;
+/// Skip test if the shell is not available.
+/// Returns early from the test with a message.
+macro_rules! skip_if_shell_unavailable {
+ ($shell:expr) => {
+ if !shell_available($shell) {
+ eprintln!("Skipping test: {} not available on this system", $shell);
+ return;
+ }
+ };
+}
+
/// Regex for normalizing temporary directory paths in test snapshots
static TMPDIR_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {
regex::Regex::new(
@@ -686,6 +699,7 @@ mod tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_handles_command_failure(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
@@ -720,6 +734,7 @@ mod tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_switch_create(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -747,6 +762,7 @@ mod tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_remove(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
@@ -770,6 +786,7 @@ mod tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_merge(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
@@ -793,6 +810,7 @@ mod tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_switch_with_execute(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -834,6 +852,7 @@ mod tests {
#[case("zsh")]
#[case("fish")]
fn test_wrapper_execute_exit_code_propagation(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -879,6 +898,7 @@ mod tests {
#[case("zsh")]
// #[case("fish")] // TODO: Fish shell has non-deterministic PTY output ordering
fn test_wrapper_switch_with_hooks(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -935,6 +955,7 @@ approved-commands = [
#[case("zsh")]
// #[case("fish")] // TODO: Fish shell has non-deterministic PTY output ordering
fn test_wrapper_merge_with_pre_merge_success(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
repo.setup_remote("main");
@@ -1017,6 +1038,7 @@ approved-commands = [
#[case("zsh")]
// #[case("fish")] // TODO: Fish shell has non-deterministic PTY output ordering
fn test_wrapper_merge_with_pre_merge_failure(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
repo.setup_remote("main");
@@ -1097,6 +1119,7 @@ approved-commands = [
#[case("zsh")]
// #[case("fish")] // TODO: Fish shell has non-deterministic PTY output ordering
fn test_wrapper_merge_with_mixed_stdout_stderr(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
let mut repo = TestRepo::new();
repo.commit("Initial commit");
repo.setup_remote("main");
@@ -3088,6 +3111,7 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done
#[case("zsh")]
#[case("fish")]
fn test_wrapper_help_redirect_captures_all_output(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use std::io::Read;
@@ -3285,6 +3309,7 @@ echo "SCRIPT_COMPLETED"
#[case("zsh")]
#[case("fish")]
fn test_wrapper_help_interactive_uses_pager(#[case] shell: &str) {
+ skip_if_shell_unavailable!(shell);
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use std::io::Read;