Skip to content

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

Refactor output handlers to use a shared trait

Maximilian Roos9899b52c1a26
diff --git a/src/output/directive.rs b/src/output/directive.rs
index a3d00514f..8acceecb5 100644
--- a/src/output/directive.rs
+++ b/src/output/directive.rs
@@ -37,140 +37,70 @@
use std::io::{self, Write};
use std::path::Path;
-use worktrunk::styling::{
- HINT, HINT_EMOJI, INFO_EMOJI, PROGRESS_EMOJI, SUCCESS_EMOJI, WARNING_EMOJI,
-};
+
+use super::traits::OutputHandler;
/// Directive output mode for shell integration
///
/// Outputs NUL-terminated directives for shell wrapper to parse and execute.
///
/// See module-level documentation for protocol details.
-pub struct DirectiveOutput;
+pub struct DirectiveOutput {
+ /// Cached stderr handle
+ stderr: io::Stderr,
+}
impl DirectiveOutput {
pub fn new() -> Self {
- Self
- }
-
- pub fn success(&mut self, message: String) -> io::Result<()> {
- // Success messages go to stderr for real-time streaming (not buffered by shell wrapper)
- writeln!(io::stderr(), "{SUCCESS_EMOJI} {message}")?;
- io::stderr().flush()
+ Self {
+ stderr: io::stderr(),
+ }
}
+}
- pub fn progress(&mut self, message: String) -> io::Result<()> {
- // Progress messages go to stderr for real-time streaming (not buffered by shell wrapper)
- writeln!(io::stderr(), "{PROGRESS_EMOJI} {message}")?;
- io::stderr().flush()
+impl OutputHandler for DirectiveOutput {
+ fn write_message_line(&mut self, line: &str) -> io::Result<()> {
+ writeln!(self.stderr, "{line}")?;
+ self.stderr.flush()
}
- pub fn hint(&mut self, message: String) -> io::Result<()> {
- // Hint messages go to stderr for real-time streaming (not buffered by shell wrapper)
- // Hints are always dimmed
- writeln!(io::stderr(), "{HINT_EMOJI} {HINT}{message}{HINT:#}")?;
- io::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()
}
- pub fn shell_integration_hint(&mut self, _message: String) -> io::Result<()> {
+ 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(())
}
- pub fn info(&mut self, message: String) -> io::Result<()> {
- // Info messages go to stderr for real-time streaming (not buffered by shell wrapper)
- writeln!(io::stderr(), "{INFO_EMOJI} {message}")?;
- io::stderr().flush()
- }
-
- pub fn warning(&mut self, message: String) -> io::Result<()> {
- // Warning messages go to stderr for real-time streaming (not buffered by shell wrapper)
- writeln!(io::stderr(), "{WARNING_EMOJI} {message}")?;
- io::stderr().flush()
- }
-
- pub fn error(&mut self, message: String) -> io::Result<()> {
- use worktrunk::styling::{ERROR, ERROR_EMOJI};
- // Error messages go to stderr; add emoji and styling if not already present
- if message.starts_with(ERROR_EMOJI) {
- writeln!(io::stderr(), "{message}")?;
- } else {
- writeln!(io::stderr(), "{ERROR_EMOJI} {ERROR}{message}{ERROR:#}")?;
- }
- io::stderr().flush()
- }
-
#[cfg(unix)]
- pub fn blank_line(&mut self) -> io::Result<()> {
+ fn blank_line(&mut self) -> io::Result<()> {
// Blank lines are only meaningful in interactive mode; no-op here to avoid empty directives
Ok(())
}
- pub fn gutter(&mut self, content: String) -> io::Result<()> {
- // Gutter content goes to stderr for real-time streaming (not buffered by shell wrapper)
- write!(io::stderr(), "{content}")?;
- io::stderr().flush()
- }
+ // Note: raw() uses the default which calls write_message_line() -> stderr
+ // This is correct for directive mode where stdout is reserved for directives
- pub fn raw(&mut self, content: String) -> io::Result<()> {
- // Raw output without emoji decoration - for structured data like JSON
- // In directive mode, even JSON goes to stderr (stdout is reserved for directives)
- use worktrunk::styling::eprintln;
- eprintln!("{content}");
- io::stderr().flush()
- }
-
- pub fn raw_terminal(&mut self, content: String) -> io::Result<()> {
- // Raw output to stderr - for table output
- // In directive mode, this is the same as raw() since everything goes to stderr
- use worktrunk::styling::eprintln;
- eprintln!("{content}");
- io::stderr().flush()
- }
-
- pub fn change_directory(&mut self, path: &Path) -> io::Result<()> {
+ fn change_directory(&mut self, path: &Path) -> io::Result<()> {
write!(io::stdout(), "__WORKTRUNK_CD__{}\0", path.display())?;
io::stdout().flush()
}
- pub fn execute(&mut self, command: String) -> anyhow::Result<()> {
+ fn execute(&mut self, command: String) -> anyhow::Result<()> {
write!(io::stdout(), "__WORKTRUNK_EXEC__{}\0", command)?;
io::stdout().flush()?;
Ok(())
}
- pub fn flush(&mut self) -> io::Result<()> {
- io::stdout().flush()?;
- io::stderr().flush()
- }
-
- pub fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
- // In directive mode, flush both streams before showing stderr prompt
- // Since messages now go to stderr, no NUL needed - just ensure everything is flushed
- io::stdout().flush()?;
- io::stderr().flush()
- }
-
- pub fn terminate_output(&mut self) -> io::Result<()> {
+ fn terminate_output(&mut self) -> io::Result<()> {
// Write NUL terminator to separate command output from subsequent directives
write!(io::stdout(), "\0")?;
io::stdout().flush()
}
-
- /// Format a switch success message for directive mode
- ///
- /// Directive mode mirrors the interactive wording ("at {path}") so the
- /// shell wrapper and direct CLI output stay consistent.
- pub fn format_switch_success(
- &self,
- branch: &str,
- path: &Path,
- created_branch: bool,
- base_branch: Option<&str>,
- ) -> String {
- super::format_switch_success_message(branch, path, created_branch, base_branch)
- }
}
impl Default for DirectiveOutput {
diff --git a/src/output/global.rs b/src/output/global.rs
index ff3a359a0..67c146531 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -8,18 +8,20 @@
//! Uses `thread_local!` to store per-thread output state:
//! - Each thread gets its own `OUTPUT_CONTEXT`
//! - `RefCell<T>` enables interior mutability (runtime borrow checking)
-//! - Enum dispatch avoids trait object overhead (static dispatch)
+//! - Trait object (`Box<dyn OutputHandler>`) for runtime polymorphism
//!
//! # 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;
use std::cell::RefCell;
use std::io;
use std::path::Path;
@@ -31,25 +33,27 @@ pub enum OutputMode {
Directive,
}
-/// Output handler - enum dispatch instead of trait object
-enum OutputHandler {
- Interactive(InteractiveOutput),
- Directive(DirectiveOutput),
-}
-
thread_local! {
- static OUTPUT_CONTEXT: RefCell<OutputHandler> = RefCell::new(
- OutputHandler::Interactive(InteractiveOutput::new())
+ static OUTPUT_CONTEXT: RefCell<Box<dyn OutputHandler>> = RefCell::new(
+ Box::new(InteractiveOutput::new())
);
}
+/// 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())
+ })
+}
+
/// Initialize the global output context
///
/// Call this once at program startup to set the output mode.
pub fn initialize(mode: OutputMode) {
- let handler = match mode {
- OutputMode::Interactive => OutputHandler::Interactive(InteractiveOutput::new()),
- OutputMode::Directive => OutputHandler::Directive(DirectiveOutput::new()),
+ let handler: Box<dyn OutputHandler> = match mode {
+ OutputMode::Interactive => Box::new(InteractiveOutput::new()),
+ OutputMode::Directive => Box::new(DirectiveOutput::new()),
};
OUTPUT_CONTEXT.with(|ctx| {
@@ -59,13 +63,7 @@ pub fn initialize(mode: OutputMode) {
/// Emit a success message
pub fn success(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.success(msg),
- OutputHandler::Directive(d) => d.success(msg),
- }
- })
+ with_output(|h| h.success(message.into()))
}
/// Emit a progress message
@@ -73,26 +71,14 @@ pub fn success(message: impl Into<String>) -> io::Result<()> {
/// Progress messages are intermediate status updates like "🔄 Cleaning up worktree..."
/// They are shown to users in both modes (users need to see what's happening).
pub fn progress(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.progress(msg),
- OutputHandler::Directive(d) => d.progress(msg),
- }
- })
+ with_output(|h| h.progress(message.into()))
}
/// Display a hint message
///
/// Hints are suggestions for users, like "Backup created @ \<sha\>" or "Using fallback commit message"
pub fn hint(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.hint(msg),
- OutputHandler::Directive(d) => d.hint(msg),
- }
- })
+ with_output(|h| h.hint(message.into()))
}
/// Display a shell integration hint (suppressed in directive mode)
@@ -100,13 +86,7 @@ pub fn hint(message: impl Into<String>) -> io::Result<()> {
/// Shell integration hints like "To enable automatic cd, run: wt config shell install" are only
/// shown in interactive mode since directive mode users already have shell integration
pub fn shell_integration_hint(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.shell_integration_hint(msg),
- OutputHandler::Directive(d) => d.shell_integration_hint(msg),
- }
- })
+ with_output(|h| h.shell_integration_hint(message.into()))
}
/// Emit an info message
@@ -114,13 +94,7 @@ pub fn shell_integration_hint(message: impl Into<String>) -> io::Result<()> {
/// Info messages are neutral status updates like "⚪ No changes detected"
/// They use INFO_EMOJI (⚪) and dimmed styling.
pub fn info(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.info(msg),
- OutputHandler::Directive(d) => d.info(msg),
- }
- })
+ with_output(|h| h.info(message.into()))
}
/// Emit a warning message
@@ -128,13 +102,7 @@ pub fn info(message: impl Into<String>) -> io::Result<()> {
/// Warning messages are non-blocking issues like "🟡 Uncommitted changes detected"
/// They use WARNING_EMOJI (🟡) and warning styling.
pub fn warning(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.warning(msg),
- OutputHandler::Directive(d) => d.warning(msg),
- }
- })
+ with_output(|h| h.warning(message.into()))
}
/// Emit an error message
@@ -145,22 +113,13 @@ pub fn warning(message: impl Into<String>) -> io::Result<()> {
/// In interactive mode: goes to stdout (with other worktrunk output)
/// In directive mode: goes to stderr (with other user-facing messages)
pub fn error(message: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let msg = message.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.error(msg),
- OutputHandler::Directive(d) => d.error(msg),
- }
- })
+ with_output(|h| h.error(message.into()))
}
/// Insert a blank line between UI output and worktrunk messages
#[cfg(unix)]
pub fn blank_line() -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.blank_line(),
- OutputHandler::Directive(d) => d.blank_line(),
- })
+ with_output(|h| h.blank_line())
}
/// Emit gutter-formatted content
@@ -168,13 +127,7 @@ pub fn blank_line() -> io::Result<()> {
/// 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()`.
pub fn gutter(content: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let c = content.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.gutter(c),
- OutputHandler::Directive(d) => d.gutter(c),
- }
- })
+ with_output(|h| h.gutter(content.into()))
}
/// Emit raw output without emoji decoration
@@ -187,13 +140,7 @@ pub fn gutter(content: impl Into<String>) -> io::Result<()> {
/// output::raw(json_string)?;
/// ```
pub fn raw(content: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let c = content.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.raw(c),
- OutputHandler::Directive(d) => d.raw(c),
- }
- })
+ with_output(|h| h.raw(content.into()))
}
/// Emit raw terminal output to stderr
@@ -213,43 +160,22 @@ pub fn raw(content: impl Into<String>) -> io::Result<()> {
/// }
/// ```
pub fn raw_terminal(content: impl Into<String>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let c = content.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.raw_terminal(c),
- OutputHandler::Directive(d) => d.raw_terminal(c),
- }
- })
+ with_output(|h| h.raw_terminal(content.into()))
}
/// Request directory change (for shell integration)
pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let p = path.as_ref();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.change_directory(p),
- OutputHandler::Directive(d) => d.change_directory(p),
- }
- })
+ with_output(|h| h.change_directory(path.as_ref()))
}
/// Request command execution
pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| {
- let cmd = command.into();
- match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.execute(cmd),
- OutputHandler::Directive(d) => d.execute(cmd),
- }
- })
+ with_output(|h| h.execute(command.into()))
}
/// Flush any buffered output
pub fn flush() -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.flush(),
- OutputHandler::Directive(d) => d.flush(),
- })
+ with_output(|h| h.flush())
}
/// Flush streams before showing stderr prompt
@@ -262,10 +188,7 @@ pub fn flush() -> io::Result<()> {
/// Note: With stderr separation (messages on stderr in directive mode), prompts
/// naturally appear after messages without needing NUL terminators for synchronization.
pub fn flush_for_stderr_prompt() -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.flush_for_stderr_prompt(),
- OutputHandler::Directive(d) => d.flush_for_stderr_prompt(),
- })
+ with_output(|h| h.flush_for_stderr_prompt())
}
/// Terminate command output
@@ -273,10 +196,7 @@ pub fn flush_for_stderr_prompt() -> io::Result<()> {
/// In directive mode, writes a NUL terminator to separate command output from
/// subsequent directives. In interactive mode, this is a no-op.
pub fn terminate_output() -> io::Result<()> {
- OUTPUT_CONTEXT.with(|ctx| match &mut *ctx.borrow_mut() {
- OutputHandler::Interactive(i) => i.terminate_output(),
- OutputHandler::Directive(d) => d.terminate_output(),
- })
+ with_output(|h| h.terminate_output())
}
/// Format a switch success message (identical across modes)
@@ -289,14 +209,7 @@ pub fn format_switch_success(
created_branch: bool,
base_branch: Option<&str>,
) -> String {
- OUTPUT_CONTEXT.with(|ctx| match &*ctx.borrow() {
- OutputHandler::Interactive(i) => {
- i.format_switch_success(branch, path, created_branch, base_branch)
- }
- OutputHandler::Directive(d) => {
- d.format_switch_success(branch, path, created_branch, base_branch)
- }
- })
+ super::format_switch_success_message(branch, path, created_branch, base_branch)
}
#[cfg(test)]
diff --git a/src/output/interactive.rs b/src/output/interactive.rs
index 5b1f8c996..4ba88232b 100644
--- a/src/output/interactive.rs
+++ b/src/output/interactive.rs
@@ -2,12 +2,10 @@
use std::io::{self, Write};
use std::path::Path;
-use worktrunk::styling::{
- HINT, HINT_EMOJI, INFO_EMOJI, PROGRESS_EMOJI, SUCCESS_EMOJI, WARNING_EMOJI, println, stderr,
- stdout,
-};
+use worktrunk::styling::{println, stderr, stdout};
use super::handlers::execute_streaming;
+use super::traits::OutputHandler;
/// Interactive output mode for human users
///
@@ -16,108 +14,52 @@ use super::handlers::execute_streaming;
pub struct InteractiveOutput {
/// Target directory for command execution (set by change_directory)
target_dir: Option<std::path::PathBuf>,
+ /// Cached stdout handle
+ stdout: io::Stdout,
}
impl InteractiveOutput {
pub fn new() -> Self {
- Self { target_dir: None }
+ Self {
+ target_dir: None,
+ stdout: io::stdout(),
+ }
}
+}
- pub fn success(&mut self, message: String) -> io::Result<()> {
- // Success messages automatically include the ✅ emoji
- println!("{SUCCESS_EMOJI} {message}");
- stdout().flush()?;
- Ok(())
+impl OutputHandler for InteractiveOutput {
+ fn write_message_line(&mut self, line: &str) -> io::Result<()> {
+ // Use styled println for proper color detection
+ println!("{line}");
+ self.stdout.flush()
}
- pub fn progress(&mut self, message: String) -> io::Result<()> {
- // Progress messages automatically include the 🔄 emoji
- println!("{PROGRESS_EMOJI} {message}");
- stdout().flush()?;
- Ok(())
+ fn gutter(&mut self, content: String) -> io::Result<()> {
+ // Gutter content is pre-formatted with its own newlines
+ write!(self.stdout, "{content}")?;
+ self.stdout.flush()
}
- pub fn hint(&mut self, message: String) -> io::Result<()> {
- // Hint messages automatically include the 💡 emoji and dimmed styling
- println!("{HINT_EMOJI} {HINT}{message}{HINT:#}");
- stdout().flush()?;
- Ok(())
- }
-
- pub fn shell_integration_hint(&mut self, message: String) -> io::Result<()> {
+ fn shell_integration_hint(&mut self, message: String) -> io::Result<()> {
// Shell integration hints work the same as regular hints in interactive mode
- println!("{HINT_EMOJI} {HINT}{message}{HINT:#}");
- stdout().flush()?;
- Ok(())
- }
-
- pub fn info(&mut self, message: String) -> io::Result<()> {
- // Info messages automatically include the ⚪ emoji
- println!("{INFO_EMOJI} {message}");
- stdout().flush()?;
- Ok(())
- }
-
- pub fn warning(&mut self, message: String) -> io::Result<()> {
- // Warning messages automatically include the 🟡 emoji
- println!("{WARNING_EMOJI} {message}");
- stdout().flush()?;
- Ok(())
- }
-
- pub fn error(&mut self, message: String) -> io::Result<()> {
- use worktrunk::styling::{ERROR, ERROR_EMOJI};
- // Add emoji and styling if not already present
- if message.starts_with(ERROR_EMOJI) {
- println!("{message}");
- } else {
- println!("{ERROR_EMOJI} {ERROR}{message}{ERROR:#}");
- }
- stdout().flush()?;
- Ok(())
+ self.hint(message)
}
#[cfg(unix)]
- pub fn blank_line(&mut self) -> io::Result<()> {
+ fn blank_line(&mut self) -> io::Result<()> {
// Ensure subsequent output starts on a fresh line after interactive UIs like skim
println!();
stdout().flush()
}
- pub fn gutter(&mut self, content: String) -> io::Result<()> {
- // Gutter content has its own visual structure - just print it
- use worktrunk::styling::print;
- print!("{content}");
- stdout().flush()?;
- Ok(())
- }
-
- pub fn raw(&mut self, content: String) -> io::Result<()> {
- // Raw output without emoji decoration - for structured data like JSON
- println!("{content}");
- stdout().flush()?;
- Ok(())
- }
-
- pub fn raw_terminal(&mut self, content: String) -> io::Result<()> {
- // Raw output to stderr - for table output that should match progressive bars stream
- // TODO: This split between raw() and raw_terminal() is messy. Consider unifying
- // the output system to have a clearer separation between structured data (JSON)
- // and terminal UI (tables, progress bars).
- use worktrunk::styling::eprintln;
- eprintln!("{content}");
- stderr().flush()?;
- Ok(())
- }
-
- pub fn change_directory(&mut self, path: &Path) -> io::Result<()> {
+ 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(())
}
- pub fn execute(&mut self, command: String) -> anyhow::Result<()> {
+ fn execute(&mut self, command: String) -> anyhow::Result<()> {
// Execute command in the target directory with streaming output
let exec_dir = self.target_dir.as_deref().unwrap_or_else(|| Path::new("."));
@@ -137,35 +79,16 @@ impl InteractiveOutput {
Ok(())
}
- pub fn flush(&mut self) -> io::Result<()> {
- stdout().flush()?;
- stderr().flush()?;
- Ok(())
- }
-
- pub fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
+ fn flush_for_stderr_prompt(&mut self) -> io::Result<()> {
// In interactive mode, flush both streams before stderr prompt
stdout().flush()?;
stderr().flush()
}
- pub fn terminate_output(&mut self) -> io::Result<()> {
+ fn terminate_output(&mut self) -> io::Result<()> {
// No-op in interactive mode - no NUL terminators needed
Ok(())
}
-
- /// Format a switch success message for interactive mode
- ///
- /// In interactive mode, we can't actually change directories, so we say "at {path}"
- pub fn format_switch_success(
- &self,
- branch: &str,
- path: &Path,
- created_branch: bool,
- base_branch: Option<&str>,
- ) -> String {
- super::format_switch_success_message(branch, path, created_branch, base_branch)
- }
}
impl Default for InteractiveOutput {
diff --git a/src/output/mod.rs b/src/output/mod.rs
index bef1d8967..35f3e1cdd 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -59,6 +59,7 @@ pub mod directive;
pub 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
new file mode 100644
index 000000000..de168d2f2
--- /dev/null
+++ b/src/output/traits.rs
@@ -0,0 +1,115 @@
+//! 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).
+
+use std::io::{self, Write};
+use std::path::Path;
+use worktrunk::styling::{
+ ERROR, ERROR_EMOJI, HINT, HINT_EMOJI, INFO_EMOJI, PROGRESS_EMOJI, SUCCESS_EMOJI, WARNING_EMOJI,
+};
+
+/// Core output handler trait
+///
+/// Implementations provide their message stream via `write_message_line`
+/// and override only the methods that differ between modes.
+pub trait OutputHandler {
+ /// Write a single logical message line to the primary user stream
+ fn write_message_line(&mut self, line: &str) -> io::Result<()>;
+
+ /// Emit a success message
+ fn success(&mut self, message: String) -> io::Result<()> {
+ self.write_message_line(&format!("{SUCCESS_EMOJI} {message}"))
+ }
+
+ /// Emit a progress message
+ fn progress(&mut self, message: String) -> io::Result<()> {
+ self.write_message_line(&format!("{PROGRESS_EMOJI} {message}"))
+ }
+
+ /// Emit a hint message
+ fn hint(&mut self, message: String) -> io::Result<()> {
+ self.write_message_line(&format!("{HINT_EMOJI} {HINT}{message}{HINT:#}"))
+ }
+
+ /// Emit an info message
+ fn info(&mut self, message: String) -> io::Result<()> {
+ self.write_message_line(&format!("{INFO_EMOJI} {message}"))
+ }
+
+ /// Emit a warning message
+ fn warning(&mut self, message: String) -> io::Result<()> {
+ self.write_message_line(&format!("{WARNING_EMOJI} {message}"))
+ }
+
+ /// Emit an error message
+ fn error(&mut self, message: String) -> io::Result<()> {
+ // Add emoji and styling if not already present
+ if message.starts_with(ERROR_EMOJI) {
+ self.write_message_line(&message)
+ } else {
+ self.write_message_line(&format!("{ERROR_EMOJI} {ERROR}{message}{ERROR:#}"))
+ }
+ }
+
+ /// 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 raw output without emoji decoration
+ fn raw(&mut self, content: String) -> io::Result<()> {
+ self.write_message_line(&content)
+ }
+
+ /// Emit raw terminal output to stderr
+ ///
+ /// Both modes write to stderr for table output
+ fn raw_terminal(&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<()>;
+
+ /// Insert a blank line
+ ///
+ /// Interactive prints newline, Directive is no-op
+ #[cfg(unix)]
+ fn blank_line(&mut self) -> 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<()>;
+}
diff --git a/tests/integration_tests/.merge.rs.pending-snap b/tests/integration_tests/.merge.rs.pending-snap
new file mode 100644
index 000000000..05de8b59c
--- /dev/null
+++ b/tests/integration_tests/.merge.rs.pending-snap
@@ -0,0 +1,11 @@
+{"run_id":"1763938884-368831000","line":2260,"new":{"module_name":"integration__integration_tests__merge","snapshot_name":"merge_no_commit_with_clean_tree","metadata":{"source":"tests/integration_tests/merge.rs","assertion_line":2260,"info":{"program":"wt","args":["merge","main","--no-commit","--no-remove"],"env":{"CLICOLOR_FORCE":"1","COLUMNS":"150","GIT_AUTHOR_DATE":"2025-01-01T00:00:00Z","GIT_COMMITTER_DATE":"2025-01-01T00:00:00Z","GIT_CONFIG_GLOBAL":"[TEST_GIT_CONFIG]","GIT_CONFIG_SYSTEM":"/dev/null","GIT_EDITOR":"","LANG":"C","LC_ALL":"C","SOURCE_DATE_EPOCH":"1761609600","WORKTRUNK_CONFIG_PATH":"[TEST_CONFIG]"}}},"snapshot":"success: true\nexit_code: 0\n----- stdout -----\n🔄 \u001b[36mMerging 1 commit to \u001b[1m\u001b[36mmain\u001b[0m\u001b[36m @ \u001b[2m[SHA]\u001b[0m (no commit/squash/rebase needed)\n\u001b[107m \u001b[0m * [SHA]\u001b[33m (\u001b[m\u001b[1;36mHEAD\u001b[m\u001b[33m -> \u001b[m\u001b[1;32mfeature\u001b[m\u001b[33m)\u001b[m Add feature file\n\n\u001b[107m \u001b[0m feature.txt | 1 \u001b[32m+\u001b[m\n\u001b[107m \u001b[0m 1 file changed, 1 insertion(+)\n\n✅ \u001b[32mMerged to \u001b[1m\u001b[32mmain\u001b[0m\u001b[0m (1 commit, 1 file, \u001b[32m+1\u001b[0m)\n✅ \u001b[32mWorktree preserved (--no-remove)\u001b[0m\n\n----- stderr -----"},"old":{"module_name":"integration__integration_tests__merge","metadata":{},"snapshot":"success: true\nexit_code: 0\n----- stdout -----\n🔄 \u001b[36mMerging 1 commit to \u001b[1m\u001b[36mmain\u001b[0m\u001b[36m @ \u001b[2m[SHA]\u001b[0m (no commit/squash/rebase needed)\n\u001b[107m \u001b[0m * [SHA]\u001b[33m (\u001b[m\u001b[1;36mHEAD\u001b[m\u001b[33m -> \u001b[m\u001b[1;32mfeature\u001b[m\u001b[33m)\u001b[m Add feature file\n\u001b[107m \u001b[0m feature.txt | 1 \u001b[32m+\u001b[m\n\u001b[107m \u001b[0m 1 file changed, 1 insertion(+)\n✅ \u001b[32mMerged to \u001b[1m\u001b[32mmain\u001b[0m\u001b[0m (1 commit, 1 file, \u001b[32m+1\u001b[0m)\n✅ \u001b[32mWorktree preserved (--no-remove)\u001b[0m\n\n----- stderr -----"}}
+{"run_id":"1763938884-368831000","line":2364,"new":{"module_name":"integration__integration_tests__merge","snapshot_name":"merge_no_commit_no_squash_no_remove_redundant","metadata":{"source":"tests/integration_tests/merge.rs","assertion_line":2364,"info":{"program":"wt","args":["merge","main","--no-commit","--no-squash","--no-remove"],"env":{"CLICOLOR_FORCE":"1","COLUMNS":"150","GIT_AUTHOR_DATE":"2025-01-01T00:00:00Z","GIT_COMMITTER_DATE":"2025-01-01T00:00:00Z","GIT_CONFIG_GLOBAL":"[TEST_GIT_CONFIG]","GIT_CONFIG_SYSTEM":"/dev/null","GIT_EDITOR":"","LANG":"C","LC_ALL":"C","SOURCE_DATE_EPOCH":"1761609600","WORKTRUNK_CONFIG_PATH":"[TEST_CONFIG]"}}},"snapshot":"success: true\nexit_code: 0\n----- stdout -----\n🔄 \u001b[36mMerging 1 commit to \u001b[1m\u001b[36mmain\u001b[0m\u001b[36m @ \u001b[2m[SHA]\u001b[0m (no commit/squash/rebase needed)\n\u001b[107m \u001b[0m * [SHA]\u001b[33m (\u001b[m\u001b[1;36mHEAD\u001b[m\u001b[33m -> \u001b[m\u001b[1;32mfeature\u001b[m\u001b[33m)\u001b[m Add feature file\n\n\u001b[107m \u001b[0m feature.txt | 1 \u001b[32m+\u001b[m\n\u001b[107m \u001b[0m 1 file changed, 1 insertion(+)\n\n✅ \u001b[32mMerged to \u001b[1m\u001b[32mmain\u001b[0m\u001b[0m (1 commit, 1 file, \u001b[32m+1\u001b[0m)\n✅ \u001b[32mWorktree preserved (--no-remove)\u001b[0m\n\n----- stderr -----"},"old":{"module_name":"integration__integration_tests__merge","metadata":{},"snapshot":"success: true\nexit_code: 0\n----- stdout -----\n🔄 \u001b[36mMerging 1 commit to \u001b[1m\u001b[36mmain\u001b[0m\u001b[36m @ \u001b[2m[SHA]\u001b[0m (no commit/squash/rebase needed)\n\u001b[107m \u001b[0m * [SHA]\u001b[33m (\u001b[m\u001b[1;36mHEAD\u001b[m\u001b[33m -> \u001b[m\u001b[1;32mfeature\u001b[m\u001b[33m)\u001b[m Add feature file\n\u001b[107m \u001b[0m feature.txt | 1 \u001b[32m+\u001b[m\n\u001b[107m \u001b[0m 1 file changed, 1 insertion(+)\n✅ \u001b[32mMerged to \u001b[1m\u001b[32mmain\u001b[0m\u001b[0m (1 commit, 1 file, \u001b[32m+1\u001b[0m)\n✅ \u001b[32mWorktree preserved (--no-remove)\u001b[0m\n\n----- stderr -----"}}
+{"run_id":"1763938990-684614000","line":2309,"new":null,"old":null}
+{"run_id":"1763938990-684614000","line":2364,"new":null,"old":null}
+{"run_id":"1763938990-684614000","line":2260,"new":null,"old":null}
+{"run_id":"1763939190-448861000","line":2309,"new":null,"old":null}
+{"run_id":"1763939190-448861000","line":2364,"new":null,"old":null}
+{"run_id":"1763939190-448861000","line":2260,"new":null,"old":null}
+{"run_id":"1763939283-599995000","line":2309,"new":null,"old":null}
+{"run_id":"1763939283-599995000","line":2364,"new":null,"old":null}
+{"run_id":"1763939283-599995000","line":2260,"new":null,"old":null}