Skip to content

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

Refactor output system: remove trait abstraction (#193)

Maximilian Roos7d0e1eacf50e
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 09d0fc042..0213c33f6 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -70,7 +70,7 @@ repos:
types: ["rust"]
entry: '\\x1b\['
# format.rs strips ANSI codes injected by wrap_ansi crate
- exclude: '^(tests/|.*_test\.rs$|src/styling/(line|mod|format)\.rs$|src/output/directive\.rs$|src/cli\.rs$)'
+ exclude: '^(tests/|.*_test\.rs$|src/styling/(line|mod|format)\.rs$|src/output/global\.rs$|src/cli\.rs$)'
ci:
# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.
diff --git a/src/output/directive.rs b/src/output/directive.rs
deleted file mode 100644
index 548333f14..000000000
--- a/src/output/directive.rs
+++ /dev/null
@@ -1,305 +0,0 @@
-//! Directive output mode for shell integration
-//!
-//! # How Shell Integration Works
-//!
-//! Worktrunk uses a simple shell script protocol for shell integration. When running
-//! with `--internal` flag (invoked by shell wrapper), all user-facing messages stream
-//! to stderr in real-time, and a shell script is emitted to stdout at the very end.
-//!
-//! ## Protocol
-//!
-//! Running `wt switch --internal my-branch` outputs:
-//!
-//! **stderr** (streams directly to terminal in real-time):
-//! ```text
-//! ✅ Created new worktree for my-branch @ ~/worktrees/my-branch
-//! ```
-//!
-//! **stdout** (shell script emitted at the end):
-//! ```text
-//! cd '/path/to/worktree'
-//! ```
-//!
-//! The shell wrapper captures stdout via command substitution and evals it:
-//! ```bash
-//! wt() {
-//! local script exit_code=0
-//! script="$(command "$WORKTRUNK_BIN" --internal "$@" 2>&2)" || exit_code=$?
-//! if [[ -n "$script" ]]; then
-//! eval "$script"
-//! fi
-//! return "$exit_code"
-//! }
-//! ```
-//!
-//! ## Why This Design
-//!
-//! This pattern (stderr for logs, stdout for script) is proven by direnv. Benefits:
-//! - No FIFOs, no background processes, no job control suppression
-//! - Full streaming: stderr goes directly to terminal while wt runs
-//! - Simple shell wrapper: just command substitution + eval
-//! - Works identically across bash, zsh, and fish
-//!
-//! The `--internal` flag is hidden from help output—end users never interact with it.
-
-use std::io::{self, Write};
-use std::path::{Path, PathBuf};
-
-use super::traits::OutputHandler;
-
-/// Directive output mode for shell integration
-///
-/// Buffers cd/exec directives and emits them as a shell script at the end.
-///
-/// See module-level documentation for protocol details.
-pub struct DirectiveOutput {
- /// Cached stderr handle
- stderr: io::Stderr,
- /// Target directory for cd (set by change_directory, emitted in terminate_output)
- 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(shell: crate::cli::DirectiveShell) -> Self {
- Self {
- stderr: io::stderr(),
- target_dir: None,
- exec_command: None,
- shell,
- }
- }
-}
-
-impl OutputHandler for DirectiveOutput {
- fn write_message_line(&mut self, line: &str) -> io::Result<()> {
- writeln!(self.stderr, "{line}")?;
- self.stderr.flush()
- }
-
- fn gutter(&mut self, content: String) -> io::Result<()> {
- // Gutter content is pre-formatted with its own newlines
- write!(self.stderr, "{content}")?;
- self.stderr.flush()
- }
-
- fn shell_integration_hint(&mut self, _message: String) -> io::Result<()> {
- // Shell integration hints are suppressed in directive mode
- // When users run through shell wrapper, they already have integration
- Ok(())
- }
-
- // Note: data() uses the default which calls write_message_line() -> stderr
- // This is correct for directive mode where stdout is reserved for the final shell script
-
- fn change_directory(&mut self, path: &Path) -> io::Result<()> {
- // Buffer the path - will be emitted as shell script in terminate_output()
- self.target_dir = Some(path.to_path_buf());
- Ok(())
- }
-
- fn execute(&mut self, command: String) -> anyhow::Result<()> {
- // Buffer the command - will be emitted as shell script in terminate_output()
- self.exec_command = Some(command);
- Ok(())
- }
-
- 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 (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 {
- let path_str = path.to_string_lossy();
- 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)
- if let Some(ref cmd) = self.exec_command {
- writeln!(stdout, "{}", cmd)?;
- }
-
- stdout.flush()
- }
-}
-
-impl Default for DirectiveOutput {
- fn default() -> Self {
- Self::new(crate::cli::DirectiveShell::Posix)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::path::PathBuf;
-
- /// Test that shell script output is correctly formatted
- #[test]
- fn test_shell_script_format() {
- // Test cd command escaping
- let path = PathBuf::from("/test/path");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
- assert_eq!(cd_cmd, "cd '/test/path'");
- }
-
- #[test]
- fn test_path_with_single_quotes() {
- // Paths with single quotes need escaping
- let path = PathBuf::from("/test/it's/path");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
-
- // Single quote is escaped as: end quote, escaped quote, start quote
- assert_eq!(cd_cmd, "cd '/test/it'\\''s/path'");
- }
-
- #[test]
- fn test_path_with_spaces() {
- // Paths with spaces are handled by single quoting
- let path = PathBuf::from("/test/my path/here");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
- assert_eq!(cd_cmd, "cd '/test/my path/here'");
- }
-
- #[test]
- fn test_path_with_special_shell_chars() {
- // Shell special chars like $, `, etc. are safe inside single quotes
- let path = PathBuf::from("/test/$HOME/`whoami`/path");
- let path_str = path.to_string_lossy();
- let escaped = path_str.replace('\'', "'\\''");
- let cd_cmd = format!("cd '{}'", escaped);
-
- // $ and ` are literal inside single quotes, no escaping needed
- 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() {
- use anstyle::{AnsiColor, Color, Style};
-
- let bold = Style::new().bold();
- let cyan = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));
-
- // Create a styled message
- let styled = format!("{cyan}Styled{cyan:#} {bold}message{bold:#}");
-
- // The styled message should contain ANSI escape codes
- assert!(
- styled.contains('\x1b'),
- "Styled message should contain ANSI escape codes"
- );
-
- // Directive mode preserves styling for users viewing through shell wrapper
- // Messages go to stderr which streams directly to terminal
- }
-
- #[test]
- fn test_color_reset_on_empty_style() {
- // BUG HYPOTHESIS from CLAUDE.md (lines 154-177):
- // Using {:#} on Style::new() produces empty string, not reset code
- use anstyle::Style;
-
- let empty_style = Style::new();
- let output = format!("{:#}", empty_style);
-
- // This is the bug: {:#} on empty style produces empty string!
- assert_eq!(
- output, "",
- "BUG: Empty style reset produces empty string, not \\x1b[0m"
- );
-
- // This means colors can leak: "text in color{:#}" where # is on empty Style
- // doesn't actually reset, it just removes the style prefix!
- }
-
- #[test]
- fn test_proper_reset_with_anstyle_reset() {
- // The correct way to reset ALL styles is anstyle::Reset
- use anstyle::Reset;
-
- let output = format!("{}", Reset);
-
- // This should produce the actual reset escape code
- assert!(
- output.contains("\x1b[0m") || output == "\x1b[0m",
- "Reset should produce actual ANSI reset code"
- );
- }
-
- #[test]
- fn test_nested_style_resets_leak_color() {
- // BUG HYPOTHESIS from CLAUDE.md:
- // Nested style resets can leak colors
- use anstyle::{AnsiColor, Color, Style};
-
- let warning = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
- let bold = Style::new().bold();
-
- // BAD pattern: nested reset
- let bad_output = format!("{warning}Text with {bold}nested{bold:#} styles{warning:#}");
-
- // When {bold:#} resets, it might also reset the warning color!
- // We can't easily test the actual ANSI codes here, but document the issue
- println!(
- "Nested reset output: {}",
- bad_output.replace('\x1b', "\\x1b")
- );
-
- // GOOD pattern: compose styles
- let warning_bold = warning.bold();
- let good_output =
- format!("{warning}Text with {warning_bold}composed{warning_bold:#} styles{warning:#}");
- println!("Composed output: {}", good_output.replace('\x1b', "\\x1b"));
-
- // The good pattern maintains color through the bold section
- }
-}
diff --git a/src/output/global.rs b/src/output/global.rs
index 9765e96db..b365bf03c 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -1,31 +1,39 @@
-//! Global output context using thread-local storage
+//! Global output context with thread-safe mode propagation
//!
//! This provides a logging-like API where you configure output mode once
//! at program start, then use it anywhere without passing parameters.
//!
//! # Implementation
//!
-//! Uses `thread_local!` to store per-thread output state:
-//! - Each thread gets its own `OUTPUT_CONTEXT`
-//! - `RefCell<T>` enables interior mutability (runtime borrow checking)
-//! - Trait object (`Box<dyn OutputHandler>`) for runtime polymorphism
+//! Uses a simple global approach:
+//! - `OnceLock<OutputMode>` stores the mode globally (set once at startup)
+//! - `OnceLock<Mutex<OutputState>>` stores stateful data (target_dir, exec_command)
+//! - All output functions check the mode and behave accordingly
+//!
+//! # Output Modes
+//!
+//! - **Interactive**: User messages to stderr, data (JSON) to stdout for piping
+//! - **Directive**: All output to stderr, stdout reserved for shell script at end
//!
//! # Trade-offs
//!
-//! - ✅ Zero parameter threading - call from anywhere
-//! - ✅ Single initialization point - set once in main()
-//! - ✅ Fast access - thread-local is just a pointer lookup
-//! - ✅ Simple mental model - one trait, no enum wrapper
-//! - ⚠️ Per-thread state - not an issue for single-threaded CLI
-//! - ⚠️ Runtime borrow checks - acceptable for this access pattern
-
-use super::directive::DirectiveOutput;
-use super::interactive::InteractiveOutput;
-use super::traits::OutputHandler;
+//! - Zero parameter threading - call from anywhere
+//! - Single initialization point - set once in main()
+//! - Spawned threads automatically use correct mode
+//! - Simple implementation - no traits, no handler structs
+
+#[cfg(not(unix))]
+use super::handlers::execute_streaming;
use crate::cli::DirectiveShell;
-use std::cell::RefCell;
-use std::io;
+use std::io::{self, Write};
use std::path::Path;
+use std::path::PathBuf;
+#[cfg(unix)]
+use std::process::Stdio;
+use std::sync::{Mutex, OnceLock};
+#[cfg(unix)]
+use worktrunk::shell_exec::ShellConfig;
+use worktrunk::styling::{eprintln, hint_message, println, stderr};
/// Output mode selection
#[derive(Debug, Clone, Copy)]
@@ -35,45 +43,58 @@ pub enum OutputMode {
Directive(DirectiveShell),
}
-thread_local! {
- static OUTPUT_CONTEXT: RefCell<Box<dyn OutputHandler>> = RefCell::new(
- Box::new(InteractiveOutput::new())
- );
+/// Global output mode, set once at initialization.
+static GLOBAL_MODE: OnceLock<OutputMode> = OnceLock::new();
+
+/// Accumulated state for change_directory/execute/terminate_output.
+/// Only used by main thread - these operations are never called from spawned threads.
+///
+/// Uses `OnceLock<Mutex<T>>` pattern:
+/// - `OnceLock` provides one-time initialization (set in `initialize()`)
+/// - `Mutex` allows mutation after initialization
+/// - No unsafe code required
+///
+/// Lock poisoning (from `.expect()`) is theoretically possible but practically
+/// unreachable - the lock is only held for trivial Option assignments that cannot panic.
+static OUTPUT_STATE: OnceLock<Mutex<OutputState>> = OnceLock::new();
+
+#[derive(Default)]
+struct OutputState {
+ target_dir: Option<PathBuf>,
+ exec_command: Option<String>,
}
-/// Helper to access the output handler
-fn with_output<R>(f: impl FnOnce(&mut dyn OutputHandler) -> R) -> R {
- OUTPUT_CONTEXT.with(|ctx| {
- let mut handler = ctx.borrow_mut();
- f(handler.as_mut())
- })
+/// Get the current output mode, defaulting to Interactive if not initialized.
+fn get_mode() -> OutputMode {
+ GLOBAL_MODE
+ .get()
+ .copied()
+ .unwrap_or(OutputMode::Interactive)
}
/// Initialize the global output context
///
/// Call this once at program startup to set the output mode.
+/// All threads will automatically use the same mode.
pub fn initialize(mode: OutputMode) {
- let handler: Box<dyn OutputHandler> = match mode {
- OutputMode::Interactive => Box::new(InteractiveOutput::new()),
- OutputMode::Directive(shell) => Box::new(DirectiveOutput::new(shell)),
- };
-
- OUTPUT_CONTEXT.with(|ctx| {
- *ctx.borrow_mut() = handler;
- });
+ let _ = GLOBAL_MODE.set(mode);
+ let _ = OUTPUT_STATE.set(Mutex::new(OutputState::default()));
}
-/// Display a shell integration hint (suppressed in directive mode)
+/// Display a shell integration hint
///
/// Shell integration hints like "Run `wt config shell install` to enable automatic cd" are only
-/// shown in interactive mode since directive mode users already have shell integration.
-///
-/// This is kept as a separate method because it has mode-specific behavior.
+/// shown in interactive mode. In directive mode, users already have shell integration.
+/// This is the canonical check - call sites don't need to guard.
pub fn shell_integration_hint(message: impl Into<String>) -> io::Result<()> {
- with_output(|h| h.shell_integration_hint(message.into()))
+ if matches!(get_mode(), OutputMode::Directive(_)) {
+ return Ok(());
+ }
+ eprintln!("{}", hint_message(message.into()));
+ stderr().flush()
}
-/// Print a message (written as-is)
+/// Print a message to stderr (written as-is)
///
/// Use with message formatting functions for semantic output:
/// ```ignore
@@ -83,35 +104,51 @@ pub fn shell_integration_hint(message: impl Into<String>) -> io::Result<()> {
/// output::print(hint_message("Use --force to override"))?;
/// ```
pub fn print(message: impl Into<String>) -> io::Result<()> {
- with_output(|h| h.print(message.into()))
+ eprintln!("{}", message.into());
+ stderr().flush()
}
-/// Emit gutter-formatted content
+/// Emit gutter-formatted content to stderr
///
/// Gutter content has its own visual structure (column 0 gutter + content),
/// so no additional emoji is added. Use with `format_with_gutter()` or `format_bash_with_gutter()`.
+///
+/// Note: Gutter content is pre-formatted with its own newlines, so we use write! not writeln!.
pub fn gutter(content: impl Into<String>) -> io::Result<()> {
- with_output(|h| h.gutter(content.into()))
+ write!(stderr(), "{}", content.into())?;
+ stderr().flush()
}
/// Emit a blank line for visual separation
-///
-/// Used to separate logical sections of output.
pub fn blank() -> io::Result<()> {
- with_output(|h| h.blank())
+ eprintln!();
+ stderr().flush()
}
/// Emit structured data output without emoji decoration
///
-/// Used for JSON and other pipeable data. In interactive mode, writes to stdout
-/// for piping. In directive mode, writes to stderr (where user messages go).
+/// Used for JSON and other pipeable data.
+/// - **Interactive**: writes to stdout (for piping to `jq`, etc.)
+/// - **Directive**: writes to stderr (stdout reserved for shell script)
///
/// Example:
/// ```rust,ignore
/// output::data(json_string)?;
/// ```
pub fn data(content: impl Into<String>) -> io::Result<()> {
- with_output(|h| h.data(content.into()))
+ let content = content.into();
+ match get_mode() {
+ OutputMode::Interactive => {
+ // Structured data goes to stdout for piping
+ println!("{content}");
+ io::stdout().flush()
+ }
+ OutputMode::Directive(_) => {
+ // stdout reserved for shell script, data goes to stderr
+ eprintln!("{content}");
+ stderr().flush()
+ }
+ }
}
/// Emit table/UI output to stderr
@@ -127,35 +164,116 @@ pub fn data(content: impl Into<String>) -> io::Result<()> {
/// }
/// ```
pub fn table(content: impl Into<String>) -> io::Result<()> {
- with_output(|h| h.table(content.into()))
+ eprintln!("{}", content.into());
+ stderr().flush()
}
/// Request directory change (for shell integration)
+///
+/// In directive mode, buffers the path for the final shell script.
+/// In interactive mode, stores path for execute() to use as working directory.
+///
+/// No-op if called before initialize() - this is safe since main thread
+/// operations only happen after initialization.
pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
- with_output(|h| h.change_directory(path.as_ref()))
+ if let Some(state) = OUTPUT_STATE.get() {
+ state.lock().expect("OUTPUT_STATE lock poisoned").target_dir =
+ Some(path.as_ref().to_path_buf());
+ }
+ Ok(())
}
/// Request command execution
+///
+/// In interactive mode, executes the command directly (replacing process on Unix).
+/// In directive mode, buffers the command for the final shell script.
pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
- with_output(|h| h.execute(command.into()))
+ let command = command.into();
+ match get_mode() {
+ OutputMode::Interactive => {
+ // Get target directory (lock released before execute to avoid holding across I/O)
+ let target_dir = OUTPUT_STATE.get().and_then(|s| {
+ let guard = s.lock().expect("OUTPUT_STATE lock poisoned");
+ guard.target_dir.clone()
+ });
+
+ execute_command(command, target_dir.as_deref())
+ }
+ OutputMode::Directive(_) => {
+ if let Some(state) = OUTPUT_STATE.get() {
+ state
+ .lock()
+ .expect("OUTPUT_STATE lock poisoned")
+ .exec_command = Some(command);
+ }
+ Ok(())
+ }
+ }
+}
+
+/// Execute a command in the given directory (Unix: exec, non-Unix: spawn)
+#[cfg(unix)]
+fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
+ use std::os::unix::process::CommandExt;
+
+ let exec_dir = target_dir.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 mut cmd = shell.command(&command);
+ let err = cmd
+ .current_dir(exec_dir)
+ .stdin(Stdio::inherit())
+ .stdout(Stdio::inherit())
+ .stderr(Stdio::inherit())
+ .exec();
+
+ // exec() only returns on error
+ Err(anyhow::anyhow!(
+ "Failed to exec '{}' with {}: {}",
+ command,
+ shell.name,
+ err
+ ))
+}
+
+/// Execute a command in the given directory (non-Unix: spawn and wait)
+#[cfg(not(unix))]
+fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
+ use worktrunk::git::WorktrunkError;
+
+ // On non-Unix platforms, fall back to spawn-and-wait.
+ // This uses the shell abstraction (Git Bash if available).
+ let exec_dir = target_dir.unwrap_or_else(|| Path::new("."));
+ if let Err(err) = execute_streaming(&command, exec_dir, false, None, true) {
+ // If the command failed with an exit code, just exit with that code.
+ // This matches Unix behavior where exec() replaces the process and
+ // the shell's exit code becomes the process exit code (no error message).
+ if let Some(WorktrunkError::ChildProcessExited { code, .. }) =
+ err.downcast_ref::<WorktrunkError>()
+ {
+ std::process::exit(*code);
+ }
+ return Err(err);
+ }
+ Ok(())
}
/// Flush any buffered output
pub fn flush() -> io::Result<()> {
- with_output(|h| h.flush())
+ io::stdout().flush()?;
+ io::stderr().flush()
}
/// Flush streams before showing stderr prompt
///
/// This prevents stream interleaving. Interactive prompts write to stderr, so we must
-/// ensure all previous output is flushed first:
-/// - In directive mode: Flushes stderr (messages stream there in real-time)
-/// - In interactive mode: Flushes both stdout and stderr
-///
-/// Note: With stderr separation (messages on stderr in directive mode), prompts
-/// naturally appear after messages without needing special synchronization.
+/// ensure all previous output is flushed first.
pub fn flush_for_stderr_prompt() -> io::Result<()> {
- with_output(|h| h.flush_for_stderr_prompt())
+ io::stdout().flush()?;
+ io::stderr().flush()
}
/// Terminate command output
@@ -163,27 +281,217 @@ pub fn flush_for_stderr_prompt() -> io::Result<()> {
/// In directive mode, emits the buffered shell script (cd and exec commands) to stdout.
/// In interactive mode, this is a no-op.
pub fn terminate_output() -> io::Result<()> {
- with_output(|h| h.terminate_output())
+ match get_mode() {
+ OutputMode::Interactive => Ok(()),
+ OutputMode::Directive(shell) => {
+ let mut stderr = io::stderr();
+
+ // Reset ANSI state before returning to shell
+ write!(stderr, "{}", anstyle::Reset)?;
+ stderr.flush()?;
+
+ // Emit shell script to stdout with buffered directives
+ let mut stdout = io::stdout();
+
+ if let Some(state) = OUTPUT_STATE.get() {
+ let guard = state.lock().expect("OUTPUT_STATE lock poisoned");
+
+ // cd command
+ if let Some(ref path) = guard.target_dir {
+ let path_str = path.to_string_lossy();
+ match shell {
+ DirectiveShell::Posix => {
+ // Always single-quote for consistent cross-platform behavior
+ // (shell_escape behaves differently on Windows vs Unix)
+ let escaped = path_str.replace('\'', "'\\''");
+ writeln!(stdout, "cd '{}'", escaped)?;
+ }
+ DirectiveShell::Powershell => {
+ // PowerShell: double single quotes for escaping
+ let escaped = path_str.replace('\'', "''");
+ writeln!(stdout, "Set-Location '{}'", escaped)?;
+ }
+ }
+ }
+
+ // exec command
+ if let Some(ref cmd) = guard.exec_command {
+ writeln!(stdout, "{}", cmd)?;
+ }
+ }
+
+ stdout.flush()
+ }
+ }
}
#[cfg(test)]
mod tests {
use super::*;
+ use std::path::PathBuf;
#[test]
- fn test_mode_switching() {
+ fn test_initialize_does_not_panic() {
use crate::cli::DirectiveShell;
- // Default is interactive
+ // Verify initialize() doesn't panic when called (possibly multiple times in tests).
+ // Note: GLOBAL_MODE can only be set once per process.
+ // In production, initialize() is called exactly once.
initialize(OutputMode::Interactive);
- // Just verify initialize doesn't panic
+ initialize(OutputMode::Directive(DirectiveShell::Posix));
+ initialize(OutputMode::Directive(DirectiveShell::Powershell));
+ }
- // Switch to directive (POSIX)
+ #[test]
+ fn test_spawned_thread_uses_correct_mode() {
+ use crate::cli::DirectiveShell;
+ use std::sync::mpsc;
+
+ // Initialize mode (may already be set by another test, which is fine)
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
+ // Spawn a thread and verify it can access output without panicking.
+ // The thread reads the same GLOBAL_MODE.
+ let (tx, rx) = mpsc::channel();
+ std::thread::spawn(move || {
+ // Access output system in spawned thread
+ let _ = flush();
+ tx.send(()).unwrap();
+ })
+ .join()
+ .unwrap();
+
+ rx.recv().unwrap();
+ }
+
+ // Shell escaping tests (moved from directive.rs)
+
+ #[test]
+ fn test_shell_script_format() {
+ // Test that POSIX quoting produces correct output
+ let path = PathBuf::from("/test/path");
+ let path_str = path.to_string_lossy();
+ let escaped = path_str.replace('\'', "'\\''");
+ let cd_cmd = format!("cd '{}'", escaped);
+ assert_eq!(cd_cmd, "cd '/test/path'");
+ }
+
+ #[test]
+ fn test_path_with_single_quotes() {
+ // Paths with single quotes need escaping: ' -> '\''
+ let path = PathBuf::from("/test/it's/path");
+ let path_str = path.to_string_lossy();
+ let escaped = path_str.replace('\'', "'\\''");
+ let cd_cmd = format!("cd '{}'", escaped);
+ assert_eq!(cd_cmd, "cd '/test/it'\\''s/path'");
+ }
+
+ #[test]
+ fn test_path_with_spaces() {
+ // Paths with spaces are safely quoted
+ let path = PathBuf::from("/test/my path/here");
+ let path_str = path.to_string_lossy();
+ let escaped = path_str.replace('\'', "'\\''");
+ let cd_cmd = format!("cd '{}'", escaped);
+ assert_eq!(cd_cmd, "cd '/test/my path/here'");
+ }
+
+ #[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
+ #[test]
+ fn test_success_preserves_anstyle() {
+ use anstyle::{AnsiColor, Color, Style};
+
+ let bold = Style::new().bold();
+ let cyan = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));
+
+ // Create a styled message
+ let styled = format!("{cyan}Styled{cyan:#} {bold}message{bold:#}");
+
+ // The styled message should contain ANSI escape codes
+ assert!(
+ styled.contains('\x1b'),
+ "Styled message should contain ANSI escape codes"
+ );
+ }
+
+ #[test]
+ fn test_color_reset_on_empty_style() {
+ // BUG HYPOTHESIS from CLAUDE.md (lines 154-177):
+ // Using {:#} on Style::new() produces empty string, not reset code
+ use anstyle::Style;
+
+ let empty_style = Style::new();
+ let output = format!("{:#}", empty_style);
+
+ // This is the bug: {:#} on empty style produces empty string!
+ assert_eq!(
+ output, "",
+ "BUG: Empty style reset produces empty string, not \\x1b[0m"
+ );
+
+ // This means colors can leak: "text in color{:#}" where # is on empty Style
+ // doesn't actually reset, it just removes the style prefix!
+ }
+
+ #[test]
+ fn test_proper_reset_with_anstyle_reset() {
+ // The correct way to reset ALL styles is anstyle::Reset
+ use anstyle::Reset;
+
+ let output = format!("{}", Reset);
+
+ // This should produce the actual reset escape code
+ assert!(
+ output.contains("\x1b[0m") || output == "\x1b[0m",
+ "Reset should produce actual ANSI reset code"
+ );
+ }
+
+ #[test]
+ fn test_nested_style_resets_leak_color() {
+ // BUG HYPOTHESIS from CLAUDE.md:
+ // Nested style resets can leak colors
+ use anstyle::{AnsiColor, Color, Style};
+
+ let warning = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
+ let bold = Style::new().bold();
+
+ // BAD pattern: nested reset
+ let bad_output = format!("{warning}Text with {bold}nested{bold:#} styles{warning:#}");
+
+ // When {bold:#} resets, it might also reset the warning color!
+ // We can't easily test the actual ANSI codes here, but document the issue
+ std::println!(
+ "Nested reset output: {}",
+ bad_output.replace('\x1b', "\\x1b")
+ );
+
+ // GOOD pattern: compose styles
+ let warning_bold = warning.bold();
+ let good_output =
+ format!("{warning}Text with {warning_bold}composed{warning_bold:#} styles{warning:#}");
+ std::println!("Composed output: {}", good_output.replace('\x1b', "\\x1b"));
+
+ // The good pattern maintains color through the bold section
}
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index b2430c921..ca33f611d 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -397,8 +397,8 @@ pub fn handle_switch_output(
base_branch.as_deref(),
from_remote.as_deref(),
)))?;
- // Show setup hint if shell integration not active
- if !is_directive_mode && !has_execute_command {
+ // Show setup hint if no execute command (hint suppressed in directive mode)
+ if !has_execute_command {
super::shell_integration_hint(shell_integration_hint())?;
}
}
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
deleted file mode 100644
index cd70e6ef9..000000000
--- a/src/output/interactive.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-//! Interactive output mode for human users
-
-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))]
-use super::handlers::execute_streaming;
-use super::traits::OutputHandler;
-
-/// Interactive output mode for human users
-///
-/// Formats messages with colors, emojis, and formatting.
-/// Executes commands directly instead of emitting directives.
-pub struct InteractiveOutput {
- /// Target directory for command execution (set by change_directory)
- target_dir: Option<std::path::PathBuf>,
-}
-
-impl InteractiveOutput {
- pub fn new() -> Self {
- Self { target_dir: None }
- }
-}
-
-impl OutputHandler for InteractiveOutput {
- fn write_message_line(&mut self, line: &str) -> io::Result<()> {
- // All messages go to stderr (stdout reserved for data like JSON)
- eprintln!("{line}");
- stderr().flush()
- }
-
- fn gutter(&mut self, content: String) -> io::Result<()> {
- // Gutter uses write! (no newline) rather than writeln!
- write!(stderr(), "{content}")?;
- stderr().flush()
- }
-
- fn data(&mut self, content: String) -> io::Result<()> {
- // Structured data (JSON, etc.) goes to stdout for piping
- use worktrunk::styling::println;
- println!("{content}");
- io::stdout().flush()
- }
-
- fn shell_integration_hint(&mut self, message: String) -> io::Result<()> {
- // Shell integration hints work the same as regular hints in interactive mode
- use worktrunk::styling::hint_message;
- self.write_message_line(&hint_message(&message))
- }
-
- fn change_directory(&mut self, path: &Path) -> io::Result<()> {
- // In interactive mode, we can't actually change directory
- // Just store the target for execute commands
- self.target_dir = Some(path.to_path_buf());
- Ok(())
- }
-
- #[cfg(unix)]
- fn execute(&mut self, command: String) -> anyhow::Result<()> {
- use std::os::unix::process::CommandExt;
-
- 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 mut cmd = shell.command(&command);
- let err = cmd
- .current_dir(exec_dir)
- .stdin(Stdio::inherit())
- .stdout(Stdio::inherit())
- .stderr(Stdio::inherit())
- .exec();
-
- // exec() only returns on error
- Err(anyhow::anyhow!(
- "Failed to exec '{}' with {}: {}",
- command,
- shell.name,
- err
- ))
- }
-
- #[cfg(not(unix))]
- fn execute(&mut self, command: String) -> anyhow::Result<()> {
- use worktrunk::git::WorktrunkError;
-
- // On non-Unix platforms, fall back to spawn-and-wait.
- // This uses the shell abstraction (Git Bash if available).
- // inherit_stdin=true enables interactive programs (like `claude`, `vim`, `python -i`)
- let exec_dir = self.target_dir.as_deref().unwrap_or_else(|| Path::new("."));
- if let Err(err) = execute_streaming(&command, exec_dir, false, None, true) {
- // If the command failed with an exit code, just exit with that code.
- // This matches Unix behavior where exec() replaces the process and
- // the shell's exit code becomes the process exit code (no error message).
- if let Some(WorktrunkError::ChildProcessExited { code, .. }) =
- err.downcast_ref::<WorktrunkError>()
- {
- std::process::exit(*code);
- }
- return Err(err);
- }
- Ok(())
- }
-
- fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
- // All messages go to stderr, so just flush stderr
- stderr().flush()
- }
-
- fn terminate_output(&mut self) -> io::Result<()> {
- // No-op in interactive mode - shell script only emitted in directive mode
- Ok(())
- }
-}
-
-impl Default for InteractiveOutput {
- fn default() -> Self {
- Self::new()
- }
-}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index b5857ba80..83fea126b 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -4,31 +4,21 @@
//!
//! Global context-based output system similar to logging frameworks (`log`, `tracing`).
//! Initialize once at program start with `initialize(OutputMode)`, then use
-//! output functions anywhere: `success()`, `change_directory()`, `execute()`, etc.
+//! output functions anywhere: `print()`, `change_directory()`, `execute()`, etc.
//!
//! ## Design
//!
-//! **Thread-local storage** stores the output handler globally:
+//! **Global state** with `OnceLock`:
//!
//! ```rust,ignore
-//! thread_local! {
-//! static OUTPUT_CONTEXT: RefCell<OutputHandler> = ...;
-//! }
+//! static GLOBAL_MODE: OnceLock<OutputMode> = OnceLock::new();
+//! static OUTPUT_STATE: OnceLock<Mutex<OutputState>> = OnceLock::new();
//! ```
//!
-//! Each thread gets its own output context. `RefCell` provides interior mutability
-//! for mutation through shared references (runtime borrow checking).
+//! The mode is set once at initialization and readable by all threads.
+//! State (target_dir, exec_command) is stored globally for main thread operations.
//!
-//! **Enum dispatch** routes calls to the appropriate handler:
-//!
-//! ```rust,ignore
-//! enum OutputHandler {
-//! Interactive(InteractiveOutput), // Human-friendly with colors
-//! Directive(DirectiveOutput), // Machine-readable for shell integration
-//! }
-//! ```
-//!
-//! This enables static dispatch and compiler optimizations.
+//! All output functions check the mode directly - no handler structs or traits.
//!
//! ## Usage Pattern
//!
@@ -37,7 +27,7 @@
//!
//! // 1. Initialize once in main()
//! let mode = if internal {
-//! OutputMode::Directive
+//! OutputMode::Directive(shell)
//! } else {
//! OutputMode::Interactive
//! };
@@ -53,15 +43,14 @@
//! ## Output Modes
//!
//! - **Interactive**: Colors, emojis, shell hints, direct command execution
-//! - **Directive**: Shell script on stdout (at end), user messages on stderr (streaming)
+//! - Messages to stderr, data (JSON) to stdout for piping
+//! - **Directive**: Shell script protocol for shell integration
+//! - All messages to stderr, stdout reserved for shell script at end
//! - stdout: Shell script emitted at end (e.g., `cd '/path'`)
//! - stderr: Success messages, progress updates, warnings (streams in real-time)
-pub mod directive;
-pub mod global;
+mod global;
pub mod handlers;
-pub mod interactive;
-mod traits;
// Re-export the public API
pub use global::{
diff --git a/src/output/traits.rs b/src/output/traits.rs
deleted file mode 100644
index 5952cd21d..000000000
--- a/src/output/traits.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-//! Shared output handler trait with default implementations
-//!
-//! This trait extracts common patterns between Interactive and Directive output modes.
-//! The fundamental operation is `write_message_line` - implementations control where
-//! messages go (stdout for interactive, stderr for directive).
-//!
-//! # Message Formatting
-//!
-//! For semantic messages (errors, hints, warnings, etc.), use the message formatting
-//! functions from `worktrunk::styling` with `output::print()`:
-//!
-//! ```ignore
-//! use worktrunk::styling::{error_message, success_message, hint_message};
-//! output::print(error_message("Operation failed"))?;
-//! output::print(success_message("Operation complete"))?;
-//! output::print(hint_message("Try --force"))?;
-//! ```
-//!
-//! This decouples message formatting from the output system, allowing the same
-//! formatting functions to be used both for output and in Display impls.
-
-use std::io::{self, Write};
-use std::path::Path;
-
-/// Core output handler trait
-///
-/// Implementations provide their message stream via `write_message_line`
-/// and override only the methods that differ between modes.
-///
-/// # Message Formatting
-///
-/// For semantic messages (errors, hints, etc.), use the message formatting functions
-/// from `worktrunk::styling` combined with `print()`:
-///
-/// ```ignore
-/// use worktrunk::styling::{error_message, hint_message};
-/// output::print(error_message("Something went wrong"))?;
-/// output::print(hint_message("Try --force"))?;
-/// ```
-pub trait OutputHandler {
- /// Write a single logical message line to the primary user stream
- fn write_message_line(&mut self, line: &str) -> io::Result<()>;
-
- /// Print a message (written as-is)
- ///
- /// Use with message formatting functions for semantic output:
- /// ```ignore
- /// output::print(error_message("Failed"))?;
- /// output::print(success_message("Done"))?;
- /// ```
- fn print(&mut self, message: String) -> io::Result<()> {
- self.write_message_line(&message)
- }
-
- /// Emit gutter-formatted content (no emoji)
- ///
- /// Gutter content is pre-formatted with its own newlines, so we write it raw
- /// without adding additional newlines.
- fn gutter(&mut self, content: String) -> io::Result<()>;
-
- /// Emit a blank line for visual separation
- fn blank(&mut self) -> io::Result<()> {
- self.write_message_line("")
- }
-
- /// Emit structured data output without emoji decoration
- ///
- /// Used for JSON and other pipeable data. In interactive mode, writes to stdout
- /// for piping. In directive mode, writes to stderr (where user messages go).
- fn data(&mut self, content: String) -> io::Result<()> {
- self.write_message_line(&content)
- }
-
- /// Emit table/UI output to stderr
- ///
- /// Used for table rows and progress indicators that should appear on the same
- /// stream as progress bars. Both modes write to stderr.
- fn table(&mut self, content: String) -> io::Result<()> {
- use worktrunk::styling::eprintln;
- eprintln!("{content}");
- io::stderr().flush()
- }
-
- /// Flush output buffers
- fn flush(&mut self) -> io::Result<()> {
- io::stdout().flush()?;
- io::stderr().flush()
- }
-
- /// Flush streams before showing stderr prompt
- fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
- io::stdout().flush()?;
- io::stderr().flush()
- }
-
- // Methods that must be implemented per-mode (no sensible default)
-
- /// Display a shell integration hint
- ///
- /// Interactive shows it, Directive suppresses it
- fn shell_integration_hint(&mut self, message: String) -> io::Result<()>;
-
- /// Request directory change
- ///
- /// Interactive stores path, Directive emits directive
- fn change_directory(&mut self, path: &Path) -> io::Result<()>;
-
- /// Request command execution
- ///
- /// Interactive runs command, Directive emits directive
- fn execute(&mut self, command: String) -> anyhow::Result<()>;
-
- /// Terminate output
- ///
- /// Interactive no-op, Directive writes NUL
- fn terminate_output(&mut self) -> io::Result<()>;
-}