Skip to content

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

refactor: remove output::print/stdout/blank/flush wrappers (#796)

Maximilian Roosfb313fa80357
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index d02baa29b..a437fdf8f 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -19,14 +19,13 @@
use super::hook_filter::{HookSource, ParsedFilter};
use super::project_config::{HookCommand, collect_commands_for_hooks};
-use crate::output;
use anyhow::Context;
use color_print::cformat;
use worktrunk::config::UserConfig;
use worktrunk::git::{GitError, HookType};
use worktrunk::styling::{
- INFO_SYMBOL, PROMPT_SYMBOL, WARNING_SYMBOL, eprint, format_bash_with_gutter, hint_message,
- stderr, warning_message,
+ INFO_SYMBOL, PROMPT_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter,
+ hint_message, stderr, warning_message,
};
/// Batch approval helper used when multiple commands are queued for execution.
@@ -90,10 +89,14 @@ pub fn approve_command_batch(
}
if updated && let Err(e) = fresh_config.save() {
- let _ = output::print(warning_message(format!(
- "Failed to save command approval: {e}"
- )));
- let _ = output::print(hint_message("Approval will be requested again next time."));
+ eprintln!(
+ "{}",
+ warning_message(format!("Failed to save command approval: {e}"))
+ );
+ eprintln!(
+ "{}",
+ hint_message("Approval will be requested again next time.")
+ );
}
}
@@ -112,14 +115,13 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any
let count = commands.len();
let plural = if count == 1 { "" } else { "s" };
- // CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving
- // Flushes both stdout (for data output) and stderr (for messages)
- crate::output::flush()?;
-
- output::print(cformat!(
- "{WARNING_SYMBOL} <yellow><bold>{project_name}</> needs approval to execute <bold>{count}</> command{plural}:</>"
- ))?;
- output::blank()?;
+ eprintln!(
+ "{}",
+ cformat!(
+ "{WARNING_SYMBOL} <yellow><bold>{project_name}</> needs approval to execute <bold>{count}</> command{plural}:</>"
+ )
+ );
+ eprintln!();
for cmd in commands {
// Format as: {phase} {bold}{name}{bold:#}:
@@ -130,8 +132,8 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any
Some(name) => cformat!("{INFO_SYMBOL} {phase} <bold>{name}</>:"),
None => format!("{INFO_SYMBOL} {phase}:"),
};
- output::print(label)?;
- output::print(format_bash_with_gutter(&cmd.command.template))?;
+ eprintln!("{}", label);
+ eprintln!("{}", format_bash_with_gutter(&cmd.command.template));
}
// Check if stdin is a TTY before attempting to prompt
@@ -153,7 +155,7 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any
let mut response = String::new();
io::stdin().read_line(&mut response)?;
- output::blank()?;
+ eprintln!();
Ok(response.trim().eq_ignore_ascii_case("y"))
}
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 70e5f3a15..5daa3a055 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -4,7 +4,7 @@ use worktrunk::HookType;
use worktrunk::config::CommitGenerationConfig;
use worktrunk::git::Repository;
use worktrunk::styling::{
- format_with_gutter, hint_message, info_message, progress_message, success_message,
+ eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
};
use super::command_executor::CommandContext;
@@ -66,13 +66,15 @@ impl<'a> CommitGenerator<'a> {
result
}
- pub fn emit_hint_if_needed(&self) -> anyhow::Result<()> {
+ pub fn emit_hint_if_needed(&self) {
if !self.config.is_configured() {
- crate::output::print(hint_message(cformat!(
- "Using fallback commit message. For LLM setup guide, run <bright-black>wt config --help</>"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Using fallback commit message. For LLM setup guide, run <bright-black>wt config --help</>"
+ ))
+ );
}
- Ok(())
}
pub fn commit_staged_changes(
@@ -118,13 +120,13 @@ impl<'a> CommitGenerator<'a> {
cformat!("{action} <bright-black>({parts_str}</>{paren_close}")
};
- crate::output::print(progress_message(full_progress_msg))?;
+ eprintln!("{}", progress_message(full_progress_msg));
- self.emit_hint_if_needed()?;
+ self.emit_hint_if_needed();
let commit_message = crate::llm::generate_commit_message(self.config)?;
let formatted_message = self.format_message_for_display(&commit_message);
- crate::output::print(format_with_gutter(&formatted_message, None))?;
+ eprintln!("{}", format_with_gutter(&formatted_message, None));
repo.run_command(&["commit", "-m", &commit_message])
.context("Failed to commit")?;
@@ -134,9 +136,10 @@ impl<'a> CommitGenerator<'a> {
.trim()
.to_string();
- crate::output::print(success_message(cformat!(
- "Committed changes @ <dim>{commit_hash}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Committed changes @ <dim>{commit_hash}</>"))
+ );
Ok(())
}
@@ -155,7 +158,10 @@ impl CommitOptions<'_> {
// Show skip message
if self.no_verify && any_hooks_exist {
- crate::output::print(info_message("Skipping pre-commit hooks (--no-verify)"))?;
+ eprintln!(
+ "{}",
+ info_message("Skipping pre-commit hooks (--no-verify)")
+ );
}
if !self.no_verify {
diff --git a/src/commands/config/create.rs b/src/commands/config/create.rs
index ccb194d1e..ec3f5a023 100644
--- a/src/commands/config/create.rs
+++ b/src/commands/config/create.rs
@@ -7,10 +7,9 @@ use color_print::cformat;
use std::path::PathBuf;
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
-use worktrunk::styling::{hint_message, info_message, success_message};
+use worktrunk::styling::{eprintln, hint_message, info_message, success_message};
use super::state::require_user_config_path;
-use crate::output;
/// Example user configuration file content (displayed in help with values uncommented)
const USER_CONFIG_EXAMPLE: &str = include_str!("../../../dev/config.example.toml");
@@ -87,10 +86,13 @@ fn create_config_file(
) -> anyhow::Result<()> {
// Check if file already exists
if path.exists() {
- output::print(info_message(cformat!(
- "{config_type} already exists: <bold>{}</>",
- format_path_for_display(&path)
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "{config_type} already exists: <bold>{}</>",
+ format_path_for_display(&path)
+ ))
+ );
// Build hint message based on whether the other config exists
let hint = if other_config_exists {
@@ -107,7 +109,7 @@ fn create_config_file(
"To view, run <bright-black>wt config show</>. To create a project config, run <bright-black>wt config create --project</>"
)
};
- output::print(hint_message(hint))?;
+ eprintln!("{}", hint_message(hint));
return Ok(());
}
@@ -121,14 +123,17 @@ fn create_config_file(
std::fs::write(&path, commented_config).context("Failed to write config file")?;
// Success message
- output::print(success_message(cformat!(
- "Created {}: <bold>{}</>",
- config_type.to_lowercase(),
- format_path_for_display(&path)
- )))?;
- output::blank()?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Created {}: <bold>{}</>",
+ config_type.to_lowercase(),
+ format_path_for_display(&path)
+ ))
+ );
+ eprintln!();
for hint in success_hints {
- output::print(hint_message(*hint))?;
+ eprintln!("{}", hint_message(*hint));
}
Ok(())
diff --git a/src/commands/config/hints.rs b/src/commands/config/hints.rs
index bf4436e55..d5f1e8bb0 100644
--- a/src/commands/config/hints.rs
+++ b/src/commands/config/hints.rs
@@ -4,9 +4,7 @@
use color_print::cformat;
use worktrunk::git::Repository;
-use worktrunk::styling::{info_message, success_message};
-
-use crate::output;
+use worktrunk::styling::{eprintln, info_message, println, success_message};
/// Handle the hints get command (list shown hints)
pub fn handle_hints_get() -> anyhow::Result<()> {
@@ -14,10 +12,10 @@ pub fn handle_hints_get() -> anyhow::Result<()> {
let hints = repo.list_shown_hints();
if hints.is_empty() {
- output::print(info_message("No hints have been shown"))?;
+ eprintln!("{}", info_message("No hints have been shown"));
} else {
for hint in hints {
- output::stdout(&hint)?;
+ println!("{hint}");
}
}
@@ -35,7 +33,7 @@ pub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {
} else {
info_message(cformat!("Hint <bold>{hint_name}</> was not set"))
};
- output::print(msg)?;
+ eprintln!("{msg}");
}
None => {
let cleared = repo.clear_all_hints()?;
@@ -45,7 +43,7 @@ pub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {
let suffix = if cleared == 1 { "" } else { "s" };
success_message(cformat!("Cleared <bold>{cleared}</> hint{suffix}"))
};
- output::print(msg)?;
+ eprintln!("{msg}");
}
}
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index c296787fb..3ca06ccdc 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -11,14 +11,14 @@ use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
- format_heading, format_with_gutter, info_message, success_message, warning_message,
+ eprintln, format_heading, format_with_gutter, info_message, println, success_message,
+ warning_message,
};
use worktrunk::utils::get_now;
use super::super::list::ci_status::CachedCiStatus;
use crate::display::format_relative_time_short;
use crate::help_pager::show_help_in_pager;
-use crate::output;
// ==================== Path Helpers ====================
@@ -176,11 +176,11 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
"Cannot determine default branch. To configure, run <bold>wt config state default-branch set BRANCH</>"
))
})?;
- output::stdout(branch_name)?;
+ println!("{branch_name}");
}
"previous-branch" => match repo.switch_previous() {
- Some(prev) => output::stdout(prev)?,
- None => output::stdout("")?,
+ Some(prev) => println!("{prev}"),
+ None => println!(""),
},
"marker" => {
let branch_name = match branch {
@@ -188,8 +188,8 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
None => repo.require_current_branch("get marker for current branch")?,
};
match repo.branch_marker(&branch_name) {
- Some(marker) => output::stdout(marker)?,
- None => output::stdout("")?,
+ Some(marker) => println!("{marker}"),
+ None => println!(""),
}
}
"ci-status" => {
@@ -223,7 +223,7 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
s.ci_status
});
let status_str: &'static str = ci_status.into();
- output::stdout(status_str)?;
+ println!("{status_str}");
}
// TODO: Consider simplifying to just print the path and let users run `ls -al` themselves
"logs" => {
@@ -232,7 +232,7 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
// Display through pager (fall back to stderr if pager unavailable)
if show_help_in_pager(&out, true).is_err() {
- worktrunk::styling::eprintln!("{}", out);
+ eprintln!("{}", out);
}
}
_ => {
@@ -253,20 +253,23 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any
"default-branch" => {
// Warn if the branch doesn't exist locally
if !repo.branch(&value).exists_locally()? {
- output::print(warning_message(cformat!(
- "Branch <bold>{value}</> does not exist locally"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Branch <bold>{value}</> does not exist locally"))
+ );
}
repo.set_default_branch(&value)?;
- output::print(success_message(cformat!(
- "Set default branch to <bold>{value}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Set default branch to <bold>{value}</>"))
+ );
}
"previous-branch" => {
repo.set_switch_previous(Some(&value))?;
- output::print(success_message(cformat!(
- "Set previous branch to <bold>{value}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Set previous branch to <bold>{value}</>"))
+ );
}
"marker" => {
let branch_name = match branch {
@@ -284,9 +287,12 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any
let config_key = format!("worktrunk.state.{branch_name}.marker");
repo.run_command(&["config", &config_key, &json.to_string()])?;
- output::print(success_message(cformat!(
- "Set marker for <bold>{branch_name}</> to <bold>{value}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Set marker for <bold>{branch_name}</> to <bold>{value}</>"
+ ))
+ );
}
_ => {
anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, previous-branch, marker")
@@ -303,9 +309,9 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
match key {
"default-branch" => {
if repo.clear_default_branch_cache()? {
- output::print(success_message("Cleared default branch cache"))?;
+ eprintln!("{}", success_message("Cleared default branch cache"));
} else {
- output::print(info_message("No default branch cache to clear"))?;
+ eprintln!("{}", info_message("No default branch cache to clear"));
}
}
"previous-branch" => {
@@ -313,21 +319,24 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
.run_command(&["config", "--unset", "worktrunk.history"])
.is_ok()
{
- output::print(success_message("Cleared previous branch"))?;
+ eprintln!("{}", success_message("Cleared previous branch"));
} else {
- output::print(info_message("No previous branch to clear"))?;
+ eprintln!("{}", info_message("No previous branch to clear"));
}
}
"ci-status" => {
if all {
let cleared = CachedCiStatus::clear_all(&repo);
if cleared == 0 {
- output::print(info_message("No CI cache entries to clear"))?;
+ eprintln!("{}", info_message("No CI cache entries to clear"));
} else {
- output::print(success_message(cformat!(
- "Cleared <bold>{cleared}</> CI cache entr{}",
- if cleared == 1 { "y" } else { "ies" }
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Cleared <bold>{cleared}</> CI cache entr{}",
+ if cleared == 1 { "y" } else { "ies" }
+ ))
+ );
}
} else {
// Clear CI status for specific branch
@@ -340,13 +349,15 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
.run_command(&["config", "--unset", &config_key])
.is_ok()
{
- output::print(success_message(cformat!(
- "Cleared CI cache for <bold>{branch_name}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Cleared CI cache for <bold>{branch_name}</>"))
+ );
} else {
- output::print(info_message(cformat!(
- "No CI cache for <bold>{branch_name}</>"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!("No CI cache for <bold>{branch_name}</>"))
+ );
}
}
}
@@ -365,12 +376,15 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
}
if cleared_count == 0 {
- output::print(info_message("No markers to clear"))?;
+ eprintln!("{}", info_message("No markers to clear"));
} else {
- output::print(success_message(cformat!(
- "Cleared <bold>{cleared_count}</> marker{}",
- if cleared_count == 1 { "" } else { "s" }
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Cleared <bold>{cleared_count}</> marker{}",
+ if cleared_count == 1 { "" } else { "s" }
+ ))
+ );
}
} else {
let branch_name = match branch {
@@ -383,25 +397,30 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
.run_command(&["config", "--unset", &config_key])
.is_ok()
{
- output::print(success_message(cformat!(
- "Cleared marker for <bold>{branch_name}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Cleared marker for <bold>{branch_name}</>"))
+ );
} else {
- output::print(info_message(cformat!(
- "No marker set for <bold>{branch_name}</>"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!("No marker set for <bold>{branch_name}</>"))
+ );
}
}
}
"logs" => {
let cleared = clear_logs(&repo)?;
if cleared == 0 {
- output::print(info_message("No logs to clear"))?;
+ eprintln!("{}", info_message("No logs to clear"));
} else {
- output::print(success_message(cformat!(
- "Cleared <bold>{cleared}</> log file{}",
- if cleared == 1 { "" } else { "s" }
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Cleared <bold>{cleared}</> log file{}",
+ if cleared == 1 { "" } else { "s" }
+ ))
+ );
}
}
_ => {
@@ -462,9 +481,9 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
}
if cleared_any {
- output::print(success_message("Cleared all stored state"))?;
+ eprintln!("{}", success_message("Cleared all stored state"));
} else {
- output::print(info_message("No stored state to clear"))?;
+ eprintln!("{}", info_message("No stored state to clear"));
}
Ok(())
@@ -580,7 +599,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
"hints": hints
});
- output::stdout(serde_json::to_string_pretty(&output)?)?;
+ println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}
@@ -678,7 +697,7 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
if let Err(e) = show_help_in_pager(&out, true) {
log::debug!("Pager invocation failed: {}", e);
// Fall back to direct output via eprintln (matches help behavior)
- worktrunk::styling::eprintln!("{}", out);
+ eprintln!("{}", out);
}
Ok(())
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 0624c3d97..3ddef9c70 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -4,12 +4,10 @@ use std::path::{Path, PathBuf};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{self, Shell};
use worktrunk::styling::{
- INFO_SYMBOL, PROMPT_SYMBOL, SUCCESS_SYMBOL, format_bash_with_gutter, format_with_gutter,
- warning_message,
+ INFO_SYMBOL, PROMPT_SYMBOL, SUCCESS_SYMBOL, eprintln, format_bash_with_gutter,
+ format_with_gutter, warning_message,
};
-use crate::output;
-
pub struct ConfigureResult {
pub shell: Shell,
pub path: PathBuf,
@@ -160,10 +158,13 @@ fn cleanup_legacy_fish_conf_d(configured: &[ConfigureResult], cmd: &str) -> Vec<
}
Err(e) => {
// Warn but don't fail - the new integration will still work
- let _ = crate::output::print(warning_message(format!(
- "Failed to remove deprecated {}: {e}",
- format_path_for_display(&legacy_path)
- )));
+ eprintln!(
+ "{}",
+ warning_message(format!(
+ "Failed to remove deprecated {}: {e}",
+ format_path_for_display(&legacy_path)
+ ))
+ );
}
}
@@ -609,11 +610,11 @@ pub fn show_install_preview(
"shell extension & completions"
};
- let _ = output::print(format!(
+ eprintln!(
"{} {} {what} for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- ));
+ );
// Show the config content that will be added with gutter
// Fish: show the wrapper (it's a complete file that sources the full function)
@@ -625,8 +626,8 @@ pub fn show_install_preview(
} else {
result.config_line.clone()
};
- let _ = output::print(format_bash_with_gutter(&content));
- let _ = output::blank(); // Blank line after each shell block
+ eprintln!("{}", format_bash_with_gutter(&content));
+ eprintln!(); // Blank line after each shell block
}
// Show completion changes (only fish has separate completion files)
@@ -638,16 +639,16 @@ pub fn show_install_preview(
let shell = result.shell;
let path = format_path_for_display(&result.path);
- let _ = output::print(format!(
+ eprintln!(
"{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- ));
+ );
// Show the completion content that will be written
let fish_completion = fish_completion_content(cmd);
- let _ = output::print(format_bash_with_gutter(fish_completion.trim()));
- let _ = output::blank(); // Blank line after
+ eprintln!("{}", format_bash_with_gutter(fish_completion.trim()));
+ eprintln!(); // Blank line after
}
}
@@ -673,10 +674,10 @@ pub fn show_uninstall_preview(
// Deprecated files get a different message format
if let Some(canonical) = &result.superseded_by {
let canonical_path = format_path_for_display(canonical);
- let _ = output::print(format!(
+ eprintln!(
"{INFO_SYMBOL} {} {bold}{path}{bold:#} (deprecated; now using {bold}{canonical_path}{bold:#})",
result.action.description(),
- ));
+ );
} else {
// Bash/Zsh: inline completions; Fish: separate completion file
let what = if matches!(shell, Shell::Fish) {
@@ -685,11 +686,11 @@ pub fn show_uninstall_preview(
"shell extension & completions"
};
- let _ = output::print(format!(
+ eprintln!(
"{} {} {what} for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- ));
+ );
}
}
@@ -697,11 +698,11 @@ pub fn show_uninstall_preview(
let shell = result.shell;
let path = format_path_for_display(&result.path);
- let _ = output::print(format!(
+ eprintln!(
"{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- ));
+ );
}
}
@@ -716,9 +717,6 @@ pub fn prompt_for_install(
cmd: &str,
prompt_text: &str,
) -> Result<bool, String> {
- // Flush before interactive prompt
- crate::output::flush().map_err(|e| e.to_string())?;
-
loop {
eprint!(
"{}",
@@ -765,7 +763,7 @@ fn prompt_yes_no() -> Result<bool, String> {
.read_line(&mut input)
.map_err(|e| e.to_string())?;
- crate::output::blank().map_err(|e| e.to_string())?;
+ eprintln!();
let response = input.trim().to_lowercase();
Ok(response == "y" || response == "yes")
@@ -1121,8 +1119,6 @@ fn prompt_for_uninstall_confirmation(
) -> Result<bool, String> {
use anstyle::Style;
- crate::output::flush().map_err(|e| e.to_string())?;
-
for result in results {
let bold = Style::new().bold();
let shell = result.shell;
@@ -1134,12 +1130,11 @@ fn prompt_for_uninstall_confirmation(
"shell extension & completions"
};
- crate::output::print(format!(
+ eprintln!(
"{} {} {what} for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- ))
- .map_err(|e| e.to_string())?;
+ );
}
for result in completion_results {
@@ -1147,84 +1142,86 @@ fn prompt_for_uninstall_confirmation(
let shell = result.shell;
let path = format_path_for_display(&result.path);
- crate::output::print(format!(
+ eprintln!(
"{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- ))
- .map_err(|e| e.to_string())?;
+ );
}
prompt_yes_no()
}
/// Show samples of all output message types
-pub fn handle_show_theme() -> Result<(), String> {
+pub fn handle_show_theme() {
use color_print::cformat;
use worktrunk::styling::{
error_message, hint_message, info_message, progress_message, success_message,
};
// Progress
- crate::output::print(progress_message(cformat!(
- "Rebasing <bold>feature</> onto <bold>main</>..."
- )))
- .map_err(|e| e.to_string())?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Rebasing <bold>feature</> onto <bold>main</>..."))
+ );
// Success
- crate::output::print(success_message(cformat!(
- "Created worktree for <bold>feature</> @ <bold>/path/to/worktree</>"
- )))
- .map_err(|e| e.to_string())?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Created worktree for <bold>feature</> @ <bold>/path/to/worktree</>"
+ ))
+ );
// Error
- crate::output::print(error_message(cformat!("Branch <bold>feature</> not found")))
- .map_err(|e| e.to_string())?;
+ eprintln!(
+ "{}",
+ error_message(cformat!("Branch <bold>feature</> not found"))
+ );
// Warning
- crate::output::print(warning_message(cformat!(
- "Branch <bold>feature</> has uncommitted changes"
- )))
- .map_err(|e| e.to_string())?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Branch <bold>feature</> has uncommitted changes"))
+ );
// Hint
- crate::output::print(hint_message(cformat!(
- "To rebase onto main, run <bright-black>wt merge</>"
- )))
- .map_err(|e| e.to_string())?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To rebase onto main, run <bright-black>wt merge</>"
+ ))
+ );
// Info
- crate::output::print(info_message(cformat!("Showing <bold>5</> worktrees")))
- .map_err(|e| e.to_string())?;
+ eprintln!("{}", info_message(cformat!("Showing <bold>5</> worktrees")));
- crate::output::blank().map_err(|e| e.to_string())?;
+ eprintln!();
// Gutter - quoted content
- crate::output::print(info_message("Gutter formatting (quoted content):"))
- .map_err(|e| e.to_string())?;
- crate::output::print(format_with_gutter(
- "[commit-generation]\ncommand = \"llm --model claude\"",
- None,
- ))
- .map_err(|e| e.to_string())?;
+ eprintln!("{}", info_message("Gutter formatting (quoted content):"));
+ eprintln!(
+ "{}",
+ format_with_gutter(
+ "[commit-generation]\ncommand = \"llm --model claude\"",
+ None,
+ )
+ );
- crate::output::blank().map_err(|e| e.to_string())?;
+ eprintln!();
// Gutter - bash code
- crate::output::print(info_message("Gutter formatting (shell code):"))
- .map_err(|e| e.to_string())?;
- crate::output::print(format_bash_with_gutter(
- "eval \"$(wt config shell init bash)\"",
- ))
- .map_err(|e| e.to_string())?;
+ eprintln!("{}", info_message("Gutter formatting (shell code):"));
+ eprintln!(
+ "{}",
+ format_bash_with_gutter("eval \"$(wt config shell init bash)\"",)
+ );
- crate::output::blank().map_err(|e| e.to_string())?;
+ eprintln!();
// Prompt
- crate::output::print(info_message("Prompt formatting:")).map_err(|e| e.to_string())?;
- crate::output::print(format!("{PROMPT_SYMBOL} Proceed? [y/N] ")).map_err(|e| e.to_string())?;
-
- Ok(())
+ eprintln!("{}", info_message("Prompt formatting:"));
+ eprintln!("{PROMPT_SYMBOL} Proceed? [y/N] ");
}
#[cfg(test)]
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index b54864671..9e05f27eb 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -31,12 +31,11 @@ use worktrunk::git::Repository;
use worktrunk::git::WorktrunkError;
use worktrunk::shell_exec::ShellConfig;
use worktrunk::styling::{
- error_message, format_with_gutter, progress_message, success_message, warning_message,
+ eprintln, error_message, format_with_gutter, progress_message, success_message, warning_message,
};
use crate::commands::command_executor::{CommandContext, build_hook_context};
use crate::commands::worktree_display_name;
-use crate::output;
/// Run a command in each worktree sequentially.
///
@@ -62,7 +61,10 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
for wt in &worktrees {
let display_name = worktree_display_name(wt, &repo, &config);
- output::print(progress_message(format!("Running in {display_name}...")))?;
+ eprintln!(
+ "{}",
+ progress_message(format!("Running in {display_name}..."))
+ );
// Build full hook context for this worktree
// Pass wt.branch directly (not the display string) so detached HEAD maps to None -> "HEAD"
@@ -83,18 +85,16 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
let context_json = serde_json::to_string(&context_map)
.expect("HashMap<String, String> serialization should never fail");
- // Flush output before running command to ensure message ordering
- output::flush()?;
-
// Execute command: stream both stdout and stderr in real-time
// Pipe context JSON to stdin for scripts that want structured data
match run_command_streaming(&command, &wt.path, Some(&context_json)) {
Ok(()) => {}
Err(CommandError::SpawnFailed(err)) => {
- output::print(error_message(cformat!(
- "Failed in <bold>{display_name}</> (spawn failed)"
- )))?;
- output::print(format_with_gutter(&err, None))?;
+ eprintln!(
+ "{}",
+ error_message(cformat!("Failed in <bold>{display_name}</> (spawn failed)"))
+ );
+ eprintln!("{}", format_with_gutter(&err, None));
failed.push(display_name.to_string());
}
Err(CommandError::ExitCode(exit_code)) => {
@@ -102,30 +102,37 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
let exit_info = exit_code
.map(|code| format!(" (exit code {code})"))
.unwrap_or_default();
- output::print(error_message(cformat!(
- "Failed in <bold>{display_name}</>{exit_info}"
- )))?;
+ eprintln!(
+ "{}",
+ error_message(cformat!("Failed in <bold>{display_name}</>{exit_info}"))
+ );
failed.push(display_name.to_string());
}
}
}
// Summary
- output::blank()?;
+ eprintln!();
if failed.is_empty() {
- output::print(success_message(format!(
- "Completed in {total} worktree{}",
- if total == 1 { "" } else { "s" }
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Completed in {total} worktree{}",
+ if total == 1 { "" } else { "s" }
+ ))
+ );
Ok(())
} else {
- output::print(warning_message(format!(
- "{} of {total} worktree{} failed",
- failed.len(),
- if total == 1 { "" } else { "s" }
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(format!(
+ "{} of {total} worktree{} failed",
+ failed.len(),
+ if total == 1 { "" } else { "s" }
+ ))
+ );
let failed_list = failed.join("\n");
- output::print(format_with_gutter(&failed_list, None))?;
+ eprintln!("{}", format_with_gutter(&failed_list, None));
// Return silent error so main exits with code 1 without duplicate message
Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 340a85365..844f0a15e 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -15,7 +15,7 @@ use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};
use worktrunk::git::{GitError, Repository};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
- INFO_SYMBOL, PROMPT_SYMBOL, format_bash_with_gutter, format_heading, hint_message,
+ INFO_SYMBOL, PROMPT_SYMBOL, eprintln, format_bash_with_gutter, format_heading, hint_message,
info_message, success_message,
};
@@ -67,7 +67,7 @@ pub fn run_hook(
let approved = approve_hooks_filtered(&ctx, &[hook_type], name_filter)?;
// If declined, return early - the whole point of `wt hook` is to run hooks
if !approved {
- crate::output::print(worktrunk::styling::info_message("Commands declined"))?;
+ eprintln!("{}", worktrunk::styling::info_message("Commands declined"));
return Ok(());
}
@@ -314,7 +314,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
let commands = collect_commands_for_hooks(&project_config, &all_hooks);
if commands.is_empty() {
- crate::output::print(info_message("No commands configured in project"))?;
+ eprintln!("{}", info_message("No commands configured in project"));
return Ok(());
}
@@ -326,7 +326,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
.collect();
if unapproved.is_empty() {
- crate::output::print(info_message("All commands already approved"))?;
+ eprintln!("{}", info_message("All commands already approved"));
return Ok(());
}
@@ -343,9 +343,9 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
// Show result
if approved {
- crate::output::print(success_message("Commands approved & saved to config"))?;
+ eprintln!("{}", success_message("Commands approved & saved to config"));
} else {
- crate::output::print(info_message("Commands declined"))?;
+ eprintln!("{}", info_message("Commands declined"));
}
Ok(())
@@ -365,7 +365,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
.collect();
if projects_with_approvals.is_empty() {
- crate::output::print(info_message("No approvals to clear"))?;
+ eprintln!("{}", info_message("No approvals to clear"));
return Ok(());
}
@@ -383,10 +383,13 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
}
config.save().context("Failed to save config")?;
- crate::output::print(success_message(format!(
- "Cleared approvals for {project_count} project{}",
- if project_count == 1 { "" } else { "s" }
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Cleared approvals for {project_count} project{}",
+ if project_count == 1 { "" } else { "s" }
+ ))
+ );
} else {
// Clear approvals for current project (default)
let repo = Repository::current()?;
@@ -399,7 +402,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
.is_some_and(|p| !p.approved_commands.is_empty());
if !had_approvals {
- crate::output::print(info_message("No approvals to clear for this project"))?;
+ eprintln!("{}", info_message("No approvals to clear for this project"));
return Ok(());
}
@@ -414,10 +417,13 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {
.revoke_project(&project_id, None)
.context("Failed to clear project approvals")?;
- crate::output::print(success_message(format!(
- "Cleared {approval_count} approval{} for this project",
- if approval_count == 1 { "" } else { "s" }
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Cleared {approval_count} approval{} for this project",
+ if approval_count == 1 { "" } else { "s" }
+ ))
+ );
}
Ok(())
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 1e745c5c3..fd663eecb 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -6,7 +6,7 @@ use worktrunk::config::CommandConfig;
use worktrunk::git::WorktrunkError;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
- error_message, format_bash_with_gutter, progress_message, verbosity, warning_message,
+ eprintln, error_message, format_bash_with_gutter, progress_message, verbosity, warning_message,
};
use super::command_executor::{CommandContext, PreparedCommand, prepare_commands};
@@ -56,8 +56,8 @@ impl SourcedCommand {
}
None => format!("{full_label}:"),
};
- crate::output::print(progress_message(message))?;
- crate::output::print(format_bash_with_gutter(&self.prepared.expanded))?;
+ eprintln!("{}", progress_message(message));
+ eprintln!("{}", format_bash_with_gutter(&self.prepared.expanded));
Ok(())
}
}
@@ -180,7 +180,7 @@ pub fn spawn_hook_commands_background(
}
None => format!("Running {hook_type} hooks: {}", names.join(", ")),
};
- crate::output::print(progress_message(message))?;
+ eprintln!("{}", progress_message(message));
}
let operation_prefix = hook_type.to_string();
@@ -218,11 +218,10 @@ pub fn spawn_hook_commands_background(
Some(name) => format!("Failed to spawn \"{name}\": {err_msg}"),
None => format!("Failed to spawn command: {err_msg}"),
};
- crate::output::print(warning_message(message))?;
+ eprintln!("{}", warning_message(message));
}
}
- crate::output::flush()?;
Ok(())
}
@@ -327,7 +326,6 @@ pub fn run_hook_with_filter(
match &failure_strategy {
HookFailureStrategy::FailFast => {
- crate::output::flush()?;
return Err(WorktrunkError::HookCommandFailed {
hook_type,
command_name: cmd.prepared.name.clone(),
@@ -341,7 +339,7 @@ pub fn run_hook_with_filter(
Some(name) => cformat!("Command <bold>{name}</> failed: {err_msg}"),
None => format!("Command failed: {err_msg}"),
};
- crate::output::print(error_message(message))?;
+ eprintln!("{}", error_message(message));
// Track first failure to propagate exit code later (only for PostMerge)
if first_failure_exit_code.is_none() && hook_type == HookType::PostMerge {
@@ -352,8 +350,6 @@ pub fn run_hook_with_filter(
}
}
- crate::output::flush()?;
-
// For Warn strategy with PostMerge: if any command failed, propagate the exit code
// This matches git's behavior: post-hooks can't stop the operation but affect exit status
// Don't show another error message — warnings were already printed inline
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index b38ef266a..95d2a6bdf 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -104,7 +104,9 @@ use once_cell::sync::OnceCell;
use rayon::prelude::*;
use std::sync::Arc;
use worktrunk::git::{Repository, WorktreeInfo};
-use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, hint_message, warning_message};
+use worktrunk::styling::{
+ INFO_SYMBOL, eprintln, format_with_gutter, hint_message, warning_message,
+};
use crate::commands::is_worktree_at_expected_path;
@@ -305,9 +307,9 @@ pub fn collect(
if let Some(configured) = repo.invalid_default_branch_config() {
let msg =
cformat!("Configured default branch <bold>{configured}</> does not exist locally");
- crate::output::print(warning_message(msg))?;
+ eprintln!("{}", warning_message(msg));
let hint = cformat!("To reset, run <bright-black>wt config state default-branch clear</>");
- crate::output::print(hint_message(hint))?;
+ eprintln!("{}", hint_message(hint));
}
// Main worktree is the primary worktree (for sorting and is_main display).
@@ -780,10 +782,10 @@ pub fn collect(
"\n\nThis likely indicates a git command hung. Run with -v for details, -vv to create a diagnostic file.",
);
- crate::output::print(warning_message(&diag))?;
+ eprintln!("{}", warning_message(&diag));
// Show issue reporting hint (free function - doesn't collect diagnostic data)
- crate::output::print(hint_message(crate::diagnostic::issue_hint()))?;
+ eprintln!("{}", hint_message(crate::diagnostic::issue_hint()));
}
// Compute status symbols for prunable worktrees (skipped during task spawning).
@@ -826,12 +828,12 @@ pub fn collect(
} else {
// Non-TTY: output to stdout (same as buffered mode)
// Progressive skeleton was suppressed; now output the final table
- crate::output::stdout(layout.format_header_line())?;
+ println!("{}", layout.format_header_line());
for item in &all_items {
- crate::output::stdout(layout.format_list_item_line(item))?;
+ println!("{}", layout.format_list_item_line(item));
}
- crate::output::stdout("")?;
- crate::output::stdout(final_msg)?;
+ println!();
+ println!("{}", final_msg);
}
} else if render_table {
// Buffered mode: render final table
@@ -843,12 +845,12 @@ pub fn collect(
timed_out_count,
);
- crate::output::stdout(layout.format_header_line())?;
+ println!("{}", layout.format_header_line());
for item in &all_items {
- crate::output::stdout(layout.format_list_item_line(item))?;
+ println!("{}", layout.format_list_item_line(item));
}
- crate::output::stdout("")?;
- crate::output::stdout(final_msg)?;
+ println!();
+ println!("{}", final_msg);
}
// Status symbols are now computed during data collection (both modes), no fallback needed
@@ -887,10 +889,10 @@ pub fn collect(
}
let warning = warning_parts.join("\n");
- crate::output::print(warning_message(&warning))?;
+ eprintln!("{}", warning_message(&warning));
// Show issue reporting hint (free function - doesn't collect diagnostic data)
- crate::output::print(hint_message(crate::diagnostic::issue_hint()))?;
+ eprintln!("{}", hint_message(crate::diagnostic::issue_hint()));
}
// Populate display fields for all items (used by JSON output and statusline)
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index a1b8257e5..e838f5a25 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -213,7 +213,7 @@ pub fn handle_list(
let json_items = json_output::to_json_items(&items);
let json =
serde_json::to_string_pretty(&json_items).context("Failed to serialize to JSON")?;
- crate::output::stdout(json)?;
+ println!("{}", json);
}
crate::OutputFormat::Table => {
// Table and summary already rendered in collect() for all modes
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 933f98d32..05d54a574 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -3,7 +3,7 @@ use std::path::Path;
use worktrunk::HookType;
use worktrunk::config::ProjectConfig;
use worktrunk::git::Repository;
-use worktrunk::styling::info_message;
+use worktrunk::styling::{eprintln, info_message};
use super::command_approval::approve_command_batch;
use super::command_executor::CommandContext;
@@ -154,7 +154,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// If commands were declined, skip hooks but continue with merge
// Shadow verify to gate all subsequent hook execution on approval
let verify = if !approved {
- crate::output::print(info_message("Commands declined, continuing merge"))?;
+ eprintln!("{}", info_message("Commands declined, continuing merge"));
false
} else {
verify
@@ -281,8 +281,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
} else {
"Worktree preserved (--no-remove)"
};
- crate::output::print(info_message(message))?;
- crate::output::flush()?;
+ eprintln!("{}", info_message(message));
}
if verify {
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 1b6ba437e..9e5ff9353 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -72,7 +72,7 @@ pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> St
/// * `repo` - The repository to query
/// * `range` - The commit range to diff (e.g., "HEAD~1..HEAD" or "main..HEAD")
pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::Result<()> {
- use worktrunk::styling::format_with_gutter;
+ use worktrunk::styling::{eprintln, format_with_gutter};
let term_width = crate::display::get_terminal_width();
let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);
@@ -88,7 +88,7 @@ pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> a
.to_string();
if !diff_stat.is_empty() {
- crate::output::print(format_with_gutter(&diff_stat, None))?;
+ eprintln!("{}", format_with_gutter(&diff_stat, None));
}
Ok(())
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 6eebdf2f6..5babbee33 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -10,7 +10,7 @@ use worktrunk::git::{
GitError, IntegrationReason, Repository, parse_porcelain_z, parse_untracked_files,
};
use worktrunk::path::format_path_for_display;
-use worktrunk::styling::{format_with_gutter, progress_message, warning_message};
+use worktrunk::styling::{eprintln, format_with_gutter, progress_message, warning_message};
/// Target for worktree removal.
#[derive(Debug)]
@@ -275,10 +275,13 @@ impl RepositoryCliExt for Repository {
nanos
);
- crate::output::print(progress_message(cformat!(
- "Stashing changes in <bold>{}</>...",
- format_path_for_display(wt_path)
- )))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!(
+ "Stashing changes in <bold>{}</>...",
+ format_path_for_display(wt_path)
+ ))
+ );
// Stash all changes including untracked files.
// Note: git stash push returns exit code 0 whether or not anything was stashed.
@@ -370,12 +373,13 @@ fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {
let count = files.len();
let path_word = if count == 1 { "path" } else { "paths" };
- crate::output::print(warning_message(format!(
- "Auto-staging {count} untracked {path_word}:"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(format!("Auto-staging {count} untracked {path_word}:"))
+ );
let joined_files = files.join("\n");
- crate::output::print(format_with_gutter(&joined_files, None))?;
+ eprintln!("{}", format_with_gutter(&joined_files, None));
Ok(())
}
@@ -400,10 +404,13 @@ struct StashData {
impl StashData {
/// Restore the stash, printing progress and warning on failure.
fn restore(self) {
- let _ = crate::output::print(progress_message(cformat!(
- "Restoring stashed changes in <bold>{}</>...",
- format_path_for_display(&self.path)
- )));
+ eprintln!(
+ "{}",
+ progress_message(cformat!(
+ "Restoring stashed changes in <bold>{}</>...",
+ format_path_for_display(&self.path)
+ ))
+ );
let success = Repository::current()
.ok()
@@ -415,11 +422,14 @@ impl StashData {
.is_some();
if !success {
- let _ = crate::output::print(warning_message(cformat!(
- "Failed to restore stash <bold>{stash_ref}</>; run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",
- stash_ref = self.stash_ref,
- path = format_path_for_display(&self.path),
- )));
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Failed to restore stash <bold>{stash_ref}</>; run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",
+ stash_ref = self.stash_ref,
+ path = format_path_for_display(&self.path),
+ ))
+ );
}
}
}
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 1de177330..e7216c00b 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -6,7 +6,6 @@
//! This command reuses the data collection infrastructure from `wt list`,
//! avoiding duplication of git operations.
-use crate::output;
use anyhow::{Context, Result};
use std::env;
use std::io::{self, Read};
@@ -132,7 +131,7 @@ const PRIORITY_MODEL: u8 = 1;
/// Run the statusline command.
///
-/// Output uses `output::stdout()` for raw stdout (bypasses anstream color detection).
+/// Output uses `println!` for raw stdout (bypasses anstream color detection).
/// Shell prompts (PS1) and Claude Code always expect ANSI codes.
pub fn run(claude_code: bool) -> Result<()> {
// Get context - either from stdin (claude-code mode) or current directory
@@ -209,7 +208,7 @@ pub fn run(claude_code: bool) -> Result<()> {
let output = fix_dim_after_color_reset(&output);
let output = truncate_visible(&format!("{reset} {output}"), max_width);
- output::stdout(output)?;
+ println!("{}", output);
Ok(())
}
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index cb15c23cd..3bce27170 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -15,7 +15,7 @@ use worktrunk::HookType;
use worktrunk::config::UserConfig;
use worktrunk::git::Repository;
use worktrunk::styling::{
- format_with_gutter, hint_message, info_message, progress_message, success_message,
+ eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
};
use super::commit::{CommitGenerator, CommitOptions};
@@ -41,7 +41,7 @@ pub fn step_commit(
let project_id = repo.project_identifier().ok();
let commit_config = config.commit_generation(project_id.as_deref());
let prompt = crate::llm::build_commit_prompt(&commit_config)?;
- crate::output::stdout(prompt)?;
+ println!("{}", prompt);
return Ok(());
}
@@ -58,9 +58,10 @@ pub fn step_commit(
let no_verify = if !no_verify {
let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;
if !approved {
- crate::output::print(worktrunk::styling::info_message(
- "Commands declined, committing without hooks",
- ))?;
+ eprintln!(
+ "{}",
+ worktrunk::styling::info_message("Commands declined, committing without hooks")
+ );
true // Skip hooks
} else {
false // Run hooks
@@ -147,7 +148,10 @@ pub fn handle_squash(
let has_any_pre_commit = has_project_pre_commit || has_user_pre_commit;
if skip_pre_commit && has_any_pre_commit {
- crate::output::print(info_message("Skipping pre-commit hooks (--no-verify)"))?;
+ eprintln!(
+ "{}",
+ info_message("Skipping pre-commit hooks (--no-verify)")
+ );
}
// Run pre-commit hooks (user first, then project)
@@ -236,22 +240,25 @@ pub fn handle_squash(
"Squashing {commit_count} {commit_text}{with_changes} into a single commit <bright-black>({parts_str}</>{paren_close}..."
)
};
- crate::output::print(progress_message(squash_progress))?;
+ eprintln!("{}", progress_message(squash_progress));
// Create safety backup before potentially destructive reset if there are working tree changes
if has_staged {
let backup_message = format!("{} → {} (squash)", current_branch, integration_target);
let sha = wt.create_safety_backup(&backup_message)?;
- crate::output::print(hint_message(format!("Backup created @ {sha}")))?;
+ eprintln!("{}", hint_message(format!("Backup created @ {sha}")));
}
// Get commit subjects for the squash message
let subjects = repo.commit_subjects(&range)?;
// Generate squash commit message
- crate::output::print(progress_message("Generating squash commit message..."))?;
+ eprintln!(
+ "{}",
+ progress_message("Generating squash commit message...")
+ );
- generator.emit_hint_if_needed()?;
+ generator.emit_hint_if_needed();
// Get current branch and repo name for template variables
let repo_root = wt.root()?;
@@ -271,7 +278,7 @@ pub fn handle_squash(
// Display the generated commit message
let formatted_message = generator.format_message_for_display(&commit_message);
- crate::output::print(format_with_gutter(&formatted_message, None))?;
+ eprintln!("{}", format_with_gutter(&formatted_message, None));
// Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)
repo.run_command(&["reset", "--soft", &merge_base])
@@ -279,9 +286,12 @@ pub fn handle_squash(
// Check if there are actually any changes to commit
if !wt.has_staged_changes()? {
- crate::output::print(info_message(format!(
- "No changes after squashing {commit_count} {commit_text}"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "No changes after squashing {commit_count} {commit_text}"
+ ))
+ );
return Ok(SquashResult::NoNetChanges);
}
@@ -296,9 +306,10 @@ pub fn handle_squash(
.to_string();
// Show success immediately after completing the squash
- crate::output::print(success_message(cformat!(
- "Squashed @ <dim>{commit_hash}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))
+ );
Ok(SquashResult::Squashed)
}
@@ -343,7 +354,7 @@ pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {
repo_name,
&effective_config,
)?;
- crate::output::stdout(prompt)?;
+ println!("{}", prompt);
Ok(())
}
@@ -376,9 +387,10 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
// Only show progress for true rebases (fast-forwards are instant)
if !is_fast_forward {
- crate::output::print(progress_message(cformat!(
- "Rebasing onto <bold>{integration_target}</>..."
- )))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Rebasing onto <bold>{integration_target}</>..."))
+ );
}
let rebase_result = repo.run_command(&["rebase", &integration_target]);
@@ -419,13 +431,15 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
// Success
if is_fast_forward {
- crate::output::print(success_message(cformat!(
- "Fast-forwarded to <bold>{integration_target}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Fast-forwarded to <bold>{integration_target}</>"))
+ );
} else {
- crate::output::print(success_message(cformat!(
- "Rebased onto <bold>{integration_target}</>"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!("Rebased onto <bold>{integration_target}</>"))
+ );
}
Ok(RebaseResult::Rebased)
@@ -484,7 +498,10 @@ pub fn step_copy_ignored(
};
if source_path == dest_path {
- crate::output::print(info_message("Source and destination are the same worktree"))?;
+ eprintln!(
+ "{}",
+ info_message("Source and destination are the same worktree")
+ );
return Ok(());
}
@@ -533,7 +550,7 @@ pub fn step_copy_ignored(
.collect();
if entries_to_copy.is_empty() {
- crate::output::print(info_message("No matching files to copy"))?;
+ eprintln!("{}", info_message("No matching files to copy"));
return Ok(());
}
@@ -552,12 +569,15 @@ pub fn step_copy_ignored(
})
.collect();
let entry_word = if items.len() == 1 { "entry" } else { "entries" };
- crate::output::print(info_message(format!(
- "Would copy {} {}:\n{}",
- items.len(),
- entry_word,
- format_with_gutter(&items.join("\n"), None)
- )))?;
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Would copy {} {}:\n{}",
+ items.len(),
+ entry_word,
+ format_with_gutter(&items.join("\n"), None)
+ ))
+ );
return Ok(());
}
@@ -591,9 +611,10 @@ pub fn step_copy_ignored(
} else {
"entries"
};
- crate::output::print(success_message(format!(
- "Copied {copied_count} {entry_word}"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format!("Copied {copied_count} {entry_word}"))
+ );
Ok(())
}
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index 853e0f0df..fa574f729 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -4,7 +4,9 @@
use color_print::cformat;
use worktrunk::git::{GitError, Repository};
-use worktrunk::styling::{format_with_gutter, info_message, progress_message, success_message};
+use worktrunk::styling::{
+ eprintln, format_with_gutter, info_message, progress_message, success_message,
+};
use super::types::MergeOperations;
use crate::commands::repository_ext::RepositoryCliExt;
@@ -110,9 +112,12 @@ pub fn handle_push(
format!(" ({})", notes.join(", "))
};
- crate::output::print(progress_message(cformat!(
- "{verb_ing} {commit_count} {commit_text} to <bold>{target_branch}</> @ <dim>{head_sha}</>{operations_note}"
- )))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!(
+ "{verb_ing} {commit_count} {commit_text} to <bold>{target_branch}</> @ <dim>{head_sha}</>{operations_note}"
+ ))
+ );
// Show the commit graph with color
let log_output = repo.run_command(&[
@@ -122,7 +127,7 @@ pub fn handle_push(
"--oneline",
&format!("{}..HEAD", target_branch),
])?;
- crate::output::print(format_with_gutter(&log_output, None))?;
+ eprintln!("{}", format_with_gutter(&log_output, None));
// Show diff statistics
crate::commands::show_diffstat(&repo, &format!("{}..HEAD", target_branch))?;
@@ -167,10 +172,13 @@ pub fn handle_push(
// Re-apply bright-black after stats (which end with a reset) so ) is also gray
let stats_str = summary_parts.join(", ");
let paren_close = cformat!("<bright-black>)</>"); // Separate to avoid cformat optimization
- crate::output::print(success_message(cformat!(
- "{verb} <bold>{target_branch}</> <bright-black>({stats_str}</>{}",
- paren_close
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "{verb} <bold>{target_branch}</> <bright-black>({stats_str}</>{}",
+ paren_close
+ ))
+ );
} else {
// For merge workflow context, explain why nothing was pushed
let context = if let Some(ops) = operations {
@@ -191,9 +199,12 @@ pub fn handle_push(
};
// No action: nothing was pushed, just acknowledging state
- crate::output::print(info_message(cformat!(
- "Already up to date with <bold>{target_branch}</>{context}"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Already up to date with <bold>{target_branch}</>{context}"
+ ))
+ );
}
Ok(())
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index df3660c41..cf5650708 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -12,7 +12,7 @@ use worktrunk::git::mr_ref;
use worktrunk::git::pr_ref::{self, fork_remote_url, prefixed_local_branch_name};
use worktrunk::git::{GitError, RefContext, RefType, Repository};
use worktrunk::styling::{
- format_with_gutter, hint_message, info_message, progress_message, suggest_command,
+ eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,
warning_message,
};
@@ -75,13 +75,19 @@ fn resolve_pr_ref(
}
// Fetch PR info (network call via gh CLI)
- crate::output::print(progress_message(cformat!("Fetching PR #{pr_number}...")))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Fetching PR #{pr_number}..."))
+ );
let repo_root = repo.repo_path();
let pr_info = pr_ref::fetch_pr_info(pr_number, repo_root)?;
// Display PR context with URL (as gutter under fetch progress)
- crate::output::print(format_with_gutter(&format_ref_context(&pr_info), None))?;
+ eprintln!(
+ "{}",
+ format_with_gutter(&format_ref_context(&pr_info), None)
+ );
if pr_info.is_cross_repository {
// Fork PR: check if branch already exists and is tracking this PR
@@ -92,9 +98,12 @@ fn resolve_pr_ref(
pr_ref::branch_tracks_pr(repo_root, &local_branch, pr_number)
{
if tracks_this {
- crate::output::print(info_message(cformat!(
- "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"
+ ))
+ );
return Ok(ResolvedTarget {
branch: local_branch,
method: CreationMethod::Regular {
@@ -111,9 +120,12 @@ fn resolve_pr_ref(
pr_ref::branch_tracks_pr(repo_root, &prefixed, pr_number)
{
if prefixed_tracks {
- crate::output::print(info_message(cformat!(
- "Branch <bold>{prefixed}</> already configured for PR #{pr_number}"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Branch <bold>{prefixed}</> already configured for PR #{pr_number}"
+ ))
+ );
return Ok(ResolvedTarget {
branch: prefixed,
method: CreationMethod::Regular {
@@ -181,9 +193,10 @@ fn resolve_pr_ref(
})?;
let branch = &pr_info.head_ref_name;
- crate::output::print(progress_message(cformat!(
- "Fetching <bold>{branch}</> from {remote}..."
- )))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Fetching <bold>{branch}</> from {remote}..."))
+ );
repo.run_command(&["fetch", &remote, branch])
.with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;
@@ -220,13 +233,19 @@ fn resolve_mr_ref(
}
// Fetch MR info (network call via glab CLI)
- crate::output::print(progress_message(cformat!("Fetching MR !{mr_number}...")))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Fetching MR !{mr_number}..."))
+ );
let repo_root = repo.repo_path();
let mr_info = mr_ref::fetch_mr_info(mr_number, repo_root)?;
// Display MR context with URL (as gutter under fetch progress)
- crate::output::print(format_with_gutter(&format_ref_context(&mr_info), None))?;
+ eprintln!(
+ "{}",
+ format_with_gutter(&format_ref_context(&mr_info), None)
+ );
if mr_info.is_cross_project {
// Fork MR: check if branch already exists and is tracking this MR
@@ -234,9 +253,12 @@ fn resolve_mr_ref(
if let Some(tracks_this) = mr_ref::branch_tracks_mr(repo_root, &local_branch, mr_number) {
if tracks_this {
- crate::output::print(info_message(cformat!(
- "Branch <bold>{local_branch}</> already configured for MR !{mr_number}"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Branch <bold>{local_branch}</> already configured for MR !{mr_number}"
+ ))
+ );
return Ok(ResolvedTarget {
branch: local_branch,
method: CreationMethod::Regular {
@@ -334,9 +356,10 @@ fn resolve_switch_target(
let resolved_base = if let Some(base_str) = base {
let resolved = repo.resolve_worktree_name(base_str)?;
if !create {
- crate::output::print(warning_message(
- "--base flag is only used with --create, ignoring",
- ))?;
+ eprintln!(
+ "{}",
+ warning_message("--base flag is only used with --create, ignoring")
+ );
None
} else if !repo.ref_exists(&resolved)? {
return Err(GitError::ReferenceNotFound {
@@ -364,14 +387,20 @@ fn resolve_switch_target(
let remotes = branch_handle.remotes()?;
if !remotes.is_empty() {
let remote_ref = format!("{}/{}", remotes[0], resolved_branch);
- crate::output::print(warning_message(cformat!(
- "Branch <bold>{resolved_branch}</> exists on remote ({remote_ref}); creating new branch from base instead"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Branch <bold>{resolved_branch}</> exists on remote ({remote_ref}); creating new branch from base instead"
+ ))
+ );
let remove_cmd = suggest_command("remove", &[&resolved_branch], &[]);
let switch_cmd = suggest_command("switch", &[&resolved_branch], &[]);
- crate::output::print(hint_message(cformat!(
- "To switch to the remote branch, delete this branch and run without <bright-black>--create</>: <bright-black>{remove_cmd} && {switch_cmd}</>"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To switch to the remote branch, delete this branch and run without <bright-black>--create</>: <bright-black>{remove_cmd} && {switch_cmd}</>"
+ ))
+ );
}
}
@@ -380,12 +409,18 @@ fn resolve_switch_target(
resolved_base.or_else(|| {
// Check for invalid configured default branch
if let Some(configured) = repo.invalid_default_branch_config() {
- let _ = crate::output::print(warning_message(cformat!(
- "Configured default branch <bold>{configured}</> does not exist locally"
- )));
- let _ = crate::output::print(hint_message(cformat!(
- "To reset, run <bright-black>wt config state default-branch clear</>"
- )));
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Configured default branch <bold>{configured}</> does not exist locally"
+ ))
+ );
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To reset, run <bright-black>wt config state default-branch clear</>"
+ ))
+ );
}
repo.resolve_target_branch(None)
.ok()
@@ -660,9 +695,12 @@ pub fn execute_switch(
if let Some(backup_path) = &clobber_backup {
let path_display = worktrunk::path::format_path_for_display(&worktree_path);
let backup_display = worktrunk::path::format_path_for_display(backup_path);
- crate::output::print(warning_message(cformat!(
- "Moving <bold>{path_display}</> to <bold>{backup_display}</> (--clobber)"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Moving <bold>{path_display}</> to <bold>{backup_display}</> (--clobber)"
+ ))
+ );
std::fs::rename(&worktree_path, backup_path).with_context(|| {
format!("Failed to move {path_display} to {backup_display}")
@@ -772,17 +810,26 @@ pub fn execute_switch(
// Show push configuration or warning about prefixed branch
if let Some(url) = fork_push_url {
- crate::output::print(info_message(cformat!(
- "Push configured to fork: <bright-black>{url}</>"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Push configured to fork: <bright-black>{url}</>"
+ ))
+ );
} else {
// Prefixed branch name due to conflict - push won't work
- crate::output::print(warning_message(cformat!(
- "Using prefixed branch name <bold>{branch}</> due to name conflict"
- )))?;
- crate::output::print(hint_message(
- "Push to fork is not supported with prefixed branches; feedback welcome at https://github.com/max-sixty/worktrunk/issues/714",
- ))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Using prefixed branch name <bold>{branch}</> due to name conflict"
+ ))
+ );
+ eprintln!(
+ "{}",
+ hint_message(
+ "Push to fork is not supported with prefixed branches; feedback welcome at https://github.com/max-sixty/worktrunk/issues/714",
+ )
+ );
}
(false, None, Some(label))
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index b0ba1b758..7838e8277 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -39,7 +39,7 @@
//! use crate::diagnostic::issue_hint;
//!
//! // Show hint telling user to run with -vv
-//! output::print(hint_message(issue_hint()))?;
+//! eprintln!("{}", hint_message(issue_hint()));
//! ```
//!
use std::path::PathBuf;
@@ -51,7 +51,7 @@ use minijinja::{Environment, context};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::Cmd;
-use worktrunk::styling::{hint_message, info_message, warning_message};
+use worktrunk::styling::{eprintln, hint_message, info_message, warning_message};
use crate::cli::version_str;
use crate::output;
@@ -238,7 +238,10 @@ pub(crate) fn write_if_verbose(verbose: u8, command_line: &str, error_msg: Optio
match report.write_diagnostic_file(&repo) {
Some(path) => {
let path_display = format_path_for_display(&path);
- let _ = output::print(info_message(format!("Diagnostic saved: {path_display}")));
+ eprintln!(
+ "{}",
+ info_message(format!("Diagnostic saved: {path_display}"))
+ );
// Only show gh command if gh is installed
if is_gh_installed() {
@@ -246,13 +249,16 @@ pub(crate) fn write_if_verbose(verbose: u8, command_line: &str, error_msg: Optio
let path_str = path.to_string_lossy().replace('\'', "'\\''");
// URL with prefilled body: ## Gist\n\n[Paste URL]\n\n## Description\n\n[Describe the issue]
let issue_url = "https://github.com/max-sixty/worktrunk/issues/new?body=%23%23%20Gist%0A%0A%5BPaste%20gist%20URL%5D%0A%0A%23%23%20Description%0A%0A%5BDescribe%20the%20issue%5D";
- let _ = output::print(hint_message(cformat!(
- "To report a bug, create a secret gist with <bright-black>gh gist create --web '{path_str}'</> and reference it from an issue at <bright-black>{issue_url}</>"
- )));
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To report a bug, create a secret gist with <bright-black>gh gist create --web '{path_str}'</> and reference it from an issue at <bright-black>{issue_url}</>"
+ ))
+ );
}
}
None => {
- let _ = output::print(warning_message("Failed to write diagnostic file"));
+ eprintln!("{}", warning_message("Failed to write diagnostic file"));
}
}
}
diff --git a/src/help.rs b/src/help.rs
index 28e1db60b..70073b7d1 100644
--- a/src/help.rs
+++ b/src/help.rs
@@ -8,6 +8,7 @@
use std::process;
use ansi_str::AnsiStr;
+use worktrunk::styling::eprintln;
use crate::cli;
diff --git a/src/llm.rs b/src/llm.rs
index a395125b9..a88a88ca6 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -5,7 +5,7 @@ use worktrunk::config::CommitGenerationConfig;
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::Cmd;
-use worktrunk::styling::warning_message;
+use worktrunk::styling::{eprintln, warning_message};
use minijinja::Environment;
diff --git a/src/main.rs b/src/main.rs
index 7c6f5d571..dcfdad03d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -7,7 +7,8 @@ use worktrunk::git::{Repository, exit_code, set_base_path};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::extract_filename_from_path;
use worktrunk::styling::{
- error_message, format_with_gutter, hint_message, info_message, success_message, warning_message,
+ eprintln, error_message, format_with_gutter, hint_message, info_message, success_message,
+ warning_message,
};
mod cli;
@@ -281,10 +282,10 @@ fn main() {
let explicit_shell = shell.is_some();
handle_unconfigure_shell(shell, yes, dry_run, &binary_name())
.map_err(|e| anyhow::anyhow!("{}", e))
- .and_then(|scan_result| {
+ .map(|scan_result| {
// For --dry-run, preview was already shown by handler
if dry_run {
- return Ok(());
+ return;
}
// Count unique shells, not file results (fish may have 2 files: functions/ and legacy conf.d/)
@@ -311,10 +312,13 @@ fn main() {
"shell extension"
};
- crate::output::print(success_message(cformat!(
- "{} {what} for <bold>{shell}</> @ <bold>{path}</>",
- result.action.description(),
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "{} {what} for <bold>{shell}</> @ <bold>{path}</>",
+ result.action.description(),
+ ))
+ );
}
// Show completion results
@@ -322,10 +326,13 @@ fn main() {
let shell = result.shell;
let path = format_path_for_display(&result.path);
- crate::output::print(success_message(cformat!(
- "{} completions for <bold>{shell}</> @ <bold>{path}</>",
- result.action.description(),
- )))?;
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "{} completions for <bold>{shell}</> @ <bold>{path}</>",
+ result.action.description(),
+ ))
+ );
}
// Show not found - warning if explicit shell, hint if auto-scan
@@ -342,13 +349,17 @@ fn main() {
"shell extension"
};
if explicit_shell {
- crate::output::print(warning_message(format!(
- "No {what} found in {path}"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(format!("No {what} found in {path}"))
+ );
} else {
- crate::output::print(hint_message(cformat!(
- "No <bright-black>{shell}</> {what} in {path}"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "No <bright-black>{shell}</> {what} in {path}"
+ ))
+ );
}
}
@@ -363,13 +374,19 @@ fn main() {
}
let path = format_path_for_display(path);
if explicit_shell {
- crate::output::print(warning_message(format!(
- "No completions found in {path}"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(format!(
+ "No completions found in {path}"
+ ))
+ );
} else {
- crate::output::print(hint_message(cformat!(
- "No <bright-black>{shell}</> completions in {path}"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "No <bright-black>{shell}</> completions in {path}"
+ ))
+ );
}
}
@@ -378,20 +395,24 @@ fn main() {
+ scan_result.completion_not_found.len();
if total_changes == 0 {
if all_not_found == 0 {
- crate::output::blank()?;
- crate::output::print(hint_message(
- "No shell integration found to remove",
- ))?;
+ eprintln!();
+ eprintln!(
+ "{}",
+ hint_message("No shell integration found to remove")
+ );
}
- return Ok(());
+ return;
}
// Summary
- crate::output::blank()?;
+ eprintln!();
let plural = if shell_count == 1 { "" } else { "s" };
- crate::output::print(success_message(format!(
- "Removed integration from {shell_count} shell{plural}"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Removed integration from {shell_count} shell{plural}"
+ ))
+ );
// Hint about restarting shell (only if current shell was affected)
let current_shell = std::env::var("SHELL")
@@ -406,15 +427,16 @@ fn main() {
});
if current_shell_affected {
- crate::output::print(hint_message(
- "Restart shell to complete uninstall",
- ))?;
+ eprintln!(
+ "{}",
+ hint_message("Restart shell to complete uninstall")
+ );
}
- Ok(())
})
}
ConfigShellCommand::ShowTheme => {
- handle_show_theme().map_err(|e| anyhow::anyhow!("{}", e))
+ handle_show_theme();
+ Ok(())
}
ConfigShellCommand::Completions { shell } => handle_completions(shell),
}
@@ -501,9 +523,10 @@ fn main() {
let ctx = env.context(yes);
let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;
if !approved {
- crate::output::print(info_message(
- "Commands declined, squashing without hooks",
- ))?;
+ eprintln!(
+ "{}",
+ info_message("Commands declined, squashing without hooks")
+ );
}
approved
} else {
@@ -513,14 +536,18 @@ fn main() {
match handle_squash(target.as_deref(), yes, !verify, stage)? {
SquashResult::Squashed | SquashResult::NoNetChanges => {}
SquashResult::NoCommitsAhead(branch) => {
- crate::output::print(info_message(format!(
- "Nothing to squash; no commits ahead of {branch}"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Nothing to squash; no commits ahead of {branch}"
+ ))
+ );
}
SquashResult::AlreadySingleCommit => {
- crate::output::print(info_message(
- "Nothing to squash; already a single commit",
- ))?;
+ eprintln!(
+ "{}",
+ info_message("Nothing to squash; already a single commit")
+ );
}
}
Ok(())
@@ -529,13 +556,13 @@ fn main() {
}
StepCommand::Push { target } => handle_push(target.as_deref(), "Pushed to", None),
StepCommand::Rebase { target } => {
- handle_rebase(target.as_deref()).and_then(|result| match result {
- RebaseResult::Rebased => Ok(()),
+ handle_rebase(target.as_deref()).map(|result| match result {
+ RebaseResult::Rebased => (),
RebaseResult::UpToDate(branch) => {
- crate::output::print(info_message(cformat!(
- "Already up to date with <bold>{branch}</>"
- )))?;
- Ok(())
+ eprintln!(
+ "{}",
+ info_message(cformat!("Already up to date with <bold>{branch}</>"))
+ );
}
})
}
@@ -560,9 +587,10 @@ fn main() {
vars,
} => {
if no_background {
- let _ = output::print(warning_message(
- "--no-background is deprecated; use --foreground instead",
- ));
+ eprintln!(
+ "{}",
+ warning_message("--no-background is deprecated; use --foreground instead")
+ );
}
run_hook(
HookType::PostStart,
@@ -580,9 +608,10 @@ fn main() {
vars,
} => {
if no_background {
- let _ = output::print(warning_message(
- "--no-background is deprecated; use --foreground instead",
- ));
+ eprintln!(
+ "{}",
+ warning_message("--no-background is deprecated; use --foreground instead")
+ );
}
run_hook(
HookType::PostSwitch,
@@ -646,10 +675,13 @@ fn main() {
}
#[cfg(not(unix))]
Commands::Select { .. } => {
- let _ = output::print(error_message("wt select is not available on Windows"));
- let _ = output::print(hint_message(cformat!(
- "To see all worktrees, run <bright-black>wt list</>; to switch directly, run <bright-black>wt switch BRANCH</>"
- )));
+ eprintln!("{}", error_message("wt select is not available on Windows"));
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To see all worktrees, run <bright-black>wt list</>; to switch directly, run <bright-black>wt switch BRANCH</>"
+ ))
+ );
std::process::exit(1);
}
Commands::List {
@@ -762,11 +794,14 @@ fn main() {
// Show message if user declined approval
if !approved {
- crate::output::print(info_message(if plan.is_create() {
- "Commands declined, continuing worktree creation"
- } else {
- "Commands declined"
- }))?;
+ eprintln!(
+ "{}",
+ info_message(if plan.is_create() {
+ "Commands declined, continuing worktree creation"
+ } else {
+ "Commands declined"
+ })
+ );
}
// Execute the validated plan
@@ -892,9 +927,10 @@ fn main() {
.and_then(|config| {
// Handle deprecated --no-background flag
if no_background {
- output::print(warning_message(
- "--no-background is deprecated; use --foreground instead",
- ))?;
+ eprintln!(
+ "{}",
+ warning_message("--no-background is deprecated; use --foreground instead")
+ );
}
let background = !(foreground || no_background);
@@ -923,9 +959,7 @@ fn main() {
],
)?;
if !approved {
- crate::output::print(info_message(
- "Commands declined, continuing removal",
- ))?;
+ eprintln!("{}", info_message("Commands declined, continuing removal"));
}
Ok(approved)
};
@@ -969,10 +1003,9 @@ fn main() {
let mut all_errors: Vec<anyhow::Error> = Vec::new();
// Helper: record error and continue
- let mut record_error = |e: anyhow::Error| -> anyhow::Result<()> {
- output::print(e.to_string())?;
+ let mut record_error = |e: anyhow::Error| {
+ eprintln!("{}", e);
all_errors.push(e);
- Ok(())
};
for branch_name in &branches {
@@ -985,7 +1018,7 @@ fn main() {
) {
Ok(r) => r,
Err(e) => {
- record_error(e)?;
+ record_error(e);
continue;
}
};
@@ -1005,7 +1038,7 @@ fn main() {
&config,
) {
Ok(result) => plan_current = Some(result),
- Err(e) => record_error(e)?,
+ Err(e) => record_error(e),
}
continue;
}
@@ -1023,7 +1056,7 @@ fn main() {
&config,
) {
Ok(result) => plans_others.push(result),
- Err(e) => record_error(e)?,
+ Err(e) => record_error(e),
}
}
ResolvedWorktree::BranchOnly { branch } => {
@@ -1035,7 +1068,7 @@ fn main() {
&config,
) {
Ok(result) => plans_branch_only.push(result),
- Err(e) => record_error(e)?,
+ Err(e) => record_error(e),
}
}
}
@@ -1120,11 +1153,11 @@ fn main() {
if let Err(e) = result {
// GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display
if let Some(err) = e.downcast_ref::<worktrunk::git::GitError>() {
- let _ = output::print(err.to_string());
+ eprintln!("{}", err);
} else if let Some(err) = e.downcast_ref::<worktrunk::git::WorktrunkError>() {
- let _ = output::print(err.to_string());
+ eprintln!("{}", err);
} else if let Some(err) = e.downcast_ref::<worktrunk::git::HookErrorWithHint>() {
- let _ = output::print(err.to_string());
+ eprintln!("{}", err);
} else {
// Anyhow error formatting:
// - With context: show context as header, root cause in gutter
@@ -1136,9 +1169,9 @@ fn main() {
let chain: Vec<String> = e.chain().skip(1).map(|e| e.to_string()).collect();
if !chain.is_empty() {
// Has context: msg is context, chain contains intermediate + root cause
- let _ = output::print(error_message(&msg));
+ eprintln!("{}", error_message(&msg));
let chain_text = chain.join("\n");
- let _ = output::print(format_with_gutter(&chain_text, None));
+ eprintln!("{}", format_with_gutter(&chain_text, None));
} else if msg.contains('\n') || msg.contains('\r') {
// Multiline error without context - this shouldn't happen if all
// errors have proper context. Catch in debug builds, log in release.
@@ -1146,11 +1179,11 @@ fn main() {
log::warn!("Multiline error without context: {msg}");
// Normalize line endings for display
let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");
- let _ = output::print(error_message("Command failed"));
- let _ = output::print(format_with_gutter(&normalized, None));
+ eprintln!("{}", error_message("Command failed"));
+ eprintln!("{}", format_with_gutter(&normalized, None));
} else {
// Single-line error without context: inline with emoji
- let _ = output::print(error_message(&msg));
+ eprintln!("{}", error_message(&msg));
}
}
}
diff --git a/src/output/global.rs b/src/output/global.rs
index 5e7637a3d..8811db998 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -1,7 +1,8 @@
//! Global output context with file-based directive passing
//!
-//! This provides a logging-like API where you configure output once
-//! at program start, then use output functions anywhere without passing parameters.
+//! This module handles shell integration directives (cd, exec) that need to be
+//! communicated to the parent shell. For regular output, use `eprintln!`/`println!`
+//! directly (from `worktrunk::styling` for color support).
//!
//! # Implementation
//!
@@ -15,14 +16,6 @@
//! When `WORKTRUNK_DIRECTIVE_FILE` is set (by the shell wrapper), wt writes shell commands
//! (like `cd '/path'`) to that file. The shell wrapper sources the file after wt exits.
//! This allows the parent shell to change directory.
-//!
-//! # Trade-offs
-//!
-//! - Zero parameter threading - call from anywhere
-//! - Lazy initialization - state initialized on first use
-//! - Spawned threads automatically use correct context
-//! - Simple implementation - no traits, no handler structs
-//! - stdout always available for data output (JSON, etc.)
use std::fs::OpenOptions;
use std::io::{self, Write};
@@ -34,7 +27,6 @@ use std::sync::{Mutex, OnceLock};
use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;
#[cfg(unix)]
use worktrunk::shell_exec::ShellConfig;
-use worktrunk::styling::{eprintln, stderr};
// Re-export set_verbosity from the library's styling module.
// This ensures the binary and library share the same global state.
@@ -88,42 +80,6 @@ fn has_directive_file() -> bool {
.is_some()
}
-/// Print a message to stderr (written as-is)
-///
-/// Use with message formatting functions for semantic output:
-/// ```ignore
-/// use worktrunk::styling::{error_message, success_message, hint_message};
-/// output::print(error_message("Failed to create branch"))?;
-/// output::print(success_message("Branch created"))?;
-/// output::print(hint_message("Use --force to override"))?;
-/// ```
-pub fn print(message: impl Into<String>) -> io::Result<()> {
- eprintln!("{}", message.into());
- stderr().flush()
-}
-
-/// Emit a blank line for visual separation
-pub fn blank() -> io::Result<()> {
- eprintln!();
- stderr().flush()
-}
-
-/// Write to stdout (pipeable output)
-///
-/// Used for primary command output: table rows, JSON, prompts, statuslines.
-/// This is pipeable — `wt list | grep feature` works because stdout data
-/// goes to stdout while progress/warnings go to stderr.
-///
-/// Example:
-/// ```rust,ignore
-/// output::stdout(json_string)?;
-/// output::stdout(layout.format_header_line())?;
-/// ```
-pub fn stdout(content: impl Into<String>) -> io::Result<()> {
- println!("{}", content.into());
- io::stdout().flush()
-}
-
/// Write a directive to the directive file (if set)
fn write_directive(directive: &str) -> io::Result<()> {
// Copy path out of lock to avoid holding mutex during I/O
@@ -250,14 +206,6 @@ fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result
Ok(())
}
-/// Flush any buffered output (both stdout and stderr)
-///
-/// Call before interactive prompts to prevent stream interleaving.
-pub fn flush() -> io::Result<()> {
- io::stdout().flush()?;
- io::stderr().flush()
-}
-
/// Terminate command output
///
/// Resets ANSI state on stderr when shell integration is active.
@@ -439,7 +387,7 @@ mod tests {
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
// Access output system in spawned thread
- let _ = flush();
+ let _ = is_shell_integration_active();
tx.send(()).unwrap();
})
.join()
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 27e17626b..4a20d1bab 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1,7 +1,9 @@
//! Output handlers for worktree operations using the global output context
use color_print::cformat;
+use std::io::Write;
use std::path::{Path, PathBuf};
+use worktrunk::styling::stderr;
use crate::commands::branch_deletion::{
BranchDeletionOutcome, BranchDeletionResult, delete_branch_if_safe,
@@ -17,7 +19,7 @@ use worktrunk::git::Repository;
use worktrunk::git::path_dir_name;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
- FormattedMessage, error_message, format_with_gutter, hint_message, info_message,
+ FormattedMessage, eprintln, error_message, format_with_gutter, hint_message, info_message,
progress_message, success_message, suggest_command, warning_message,
};
@@ -97,22 +99,29 @@ fn handle_branch_deletion_result(
Ok(r) => {
// Branch not integrated - we chose not to delete (not a failure)
if !defer_output {
- super::print(info_message(cformat!(
- "Branch <bold>{branch_name}</> retained; has unmerged changes"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Branch <bold>{branch_name}</> retained; has unmerged changes"
+ ))
+ );
let cmd = suggest_command("remove", &[branch_name], &["-D"]);
- super::print(hint_message(cformat!(
- "To delete the unmerged branch, run <bright-black>{cmd}</>"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To delete the unmerged branch, run <bright-black>{cmd}</>"
+ ))
+ );
}
Ok((r, defer_output))
}
Err(e) => {
// Git command failed - this is an error (we decided to delete but couldn't)
- super::print(error_message(cformat!(
- "Failed to delete branch <bold>{branch_name}</>"
- )))?;
- super::print(format_with_gutter(&e.to_string(), None))?;
+ eprintln!(
+ "{}",
+ error_message(cformat!("Failed to delete branch <bold>{branch_name}</>"))
+ );
+ eprintln!("{}", format_with_gutter(&e.to_string(), None));
Err(e)
}
}
@@ -240,26 +249,33 @@ fn print_switch_message_if_changed(
if super::is_shell_integration_active() {
// Shell integration active - cd will work
- super::print(info_message(cformat!(
- "Switched to worktree for <bold>{dest_branch}</> @ <bold>{path_display}</>"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Switched to worktree for <bold>{dest_branch}</> @ <bold>{path_display}</>"
+ ))
+ );
} else if crate::is_git_subcommand() {
// Running as `git wt` - explain why cd can't work
- super::print(warning_message(
- "Cannot change directory — ran git wt; running through git prevents cd",
- ))?;
- super::print(hint_message(git_subcommand_warning()))?;
+ eprintln!(
+ "{}",
+ warning_message(
+ "Cannot change directory — ran git wt; running through git prevents cd",
+ )
+ );
+ eprintln!("{}", hint_message(git_subcommand_warning()));
} else {
// Shell integration not active - compute specific reason
let reason = compute_shell_warning_reason();
- super::print(warning_message(cformat!(
- "Cannot change directory — {reason}"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Cannot change directory — {reason}"))
+ );
// Show appropriate hint based on invocation mode
if should_show_explicit_path_hint() {
- super::print(hint_message(explicit_path_hint(&dest_branch)))?;
+ eprintln!("{}", hint_message(explicit_path_hint(&dest_branch)));
} else {
- super::print(hint_message(shell_integration_hint()))?;
+ eprintln!("{}", hint_message(shell_integration_hint()));
}
}
Ok(())
@@ -330,11 +346,14 @@ pub fn handle_switch_output(
// Already in target directory — no shell warning needed
// Show path mismatch warning first - discovered while checking current state
if let Some(warning) = branch_worktree_mismatch_warning {
- super::print(warning)?;
+ eprintln!("{}", warning);
}
- super::print(info_message(cformat!(
- "Already on worktree for <bold>{branch}</> @ <bold>{path_display}</>"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Already on worktree for <bold>{branch}</> @ <bold>{path_display}</>"
+ ))
+ );
// User is already there - no path annotation needed
None
}
@@ -342,19 +361,22 @@ pub fn handle_switch_output(
if let Some(reason) = &shell_warning_reason {
// Shell integration not active — single warning with context
if let Some(warning) = branch_worktree_mismatch_warning {
- super::print(warning)?;
+ eprintln!("{}", warning);
}
// Show what exists + why cd won't happen
// (--execute command display is handled by execute_user_command)
- super::print(warning_message(cformat!(
- "Worktree for <bold>{branch}</> @ <bold>{path_display}</>, but cannot change directory — {reason}"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Worktree for <bold>{branch}</> @ <bold>{path_display}</>, but cannot change directory — {reason}"
+ ))
+ );
// Show appropriate hint based on invocation mode
// (regular shell integration hint is shown by prompt_shell_integration in main.rs)
if is_git_subcommand {
- super::print(hint_message(git_subcommand_warning()))?;
+ eprintln!("{}", hint_message(git_subcommand_warning()));
} else if should_show_explicit_path_hint() {
- super::print(hint_message(explicit_path_hint(branch)))?;
+ eprintln!("{}", hint_message(explicit_path_hint(branch)));
}
// User won't be there - show path in hook announcements
Some(path.clone())
@@ -362,13 +384,16 @@ pub fn handle_switch_output(
// Shell integration active — user actually switched
// Show path mismatch warning first - discovered while evaluating the switch
if let Some(warning) = branch_worktree_mismatch_warning {
- super::print(warning)?;
+ eprintln!("{}", warning);
}
- super::print(info_message(format_switch_message(
- branch, path, false, // worktree_created
- false, // created_branch
- None, None,
- )))?;
+ eprintln!(
+ "{}",
+ info_message(format_switch_message(
+ branch, path, false, // worktree_created
+ false, // created_branch
+ None, None,
+ ))
+ );
// cd will happen - no path annotation needed
None
}
@@ -380,14 +405,17 @@ pub fn handle_switch_output(
..
} => {
// Always show success for creation
- super::print(success_message(format_switch_message(
- branch,
- path,
- true, // worktree_created
- *created_branch,
- base_branch.as_deref(),
- from_remote.as_deref(),
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format_switch_message(
+ branch,
+ path,
+ true, // worktree_created
+ *created_branch,
+ base_branch.as_deref(),
+ from_remote.as_deref(),
+ ))
+ );
// Show worktree-path config hint on first --create in this repo,
// unless user already has a custom worktree-path config
@@ -399,7 +427,7 @@ pub fn handle_switch_output(
let hint = hint_message(cformat!(
"To customize worktree locations, run <bright-black>wt config create</>"
));
- super::print(hint)?;
+ eprintln!("{}", hint);
let _ = repo.mark_hint_shown("worktree-path");
}
}
@@ -408,15 +436,16 @@ pub fn handle_switch_output(
// (--execute command display is handled by execute_user_command)
if let Some(reason) = shell_warning_reason {
// Don't repeat "Created worktree" — success message above already said that
- super::print(warning_message(cformat!(
- "Cannot change directory — {reason}"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Cannot change directory — {reason}"))
+ );
// Show appropriate hint based on invocation mode
// (regular shell integration hint is shown by prompt_shell_integration in main.rs)
if is_git_subcommand {
- super::print(hint_message(git_subcommand_warning()))?;
+ eprintln!("{}", hint_message(git_subcommand_warning()));
} else if should_show_explicit_path_hint() {
- super::print(hint_message(explicit_path_hint(branch)))?;
+ eprintln!("{}", hint_message(explicit_path_hint(branch)));
}
// User won't be there - show path in hook announcements
Some(path.clone())
@@ -429,7 +458,7 @@ pub fn handle_switch_output(
}
};
- super::flush()?;
+ stderr().flush()?;
Ok(display_path_for_hooks)
}
@@ -449,8 +478,8 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho
}
None => "Executing (--execute):".to_string(),
};
- super::print(progress_message(header))?;
- super::print(format_bash_with_gutter(command))?;
+ eprintln!("{}", progress_message(header));
+ eprintln!("{}", format_bash_with_gutter(command));
super::execute(command)?;
@@ -508,20 +537,26 @@ fn handle_branch_only_output(
// Different message depending on whether we pruned a stale worktree
if pruned {
// Worktree was pruned - informational, not a warning
- super::print(info_message(cformat!(
- "Worktree directory missing for <bold>{branch_name}</>; pruned"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Worktree directory missing for <bold>{branch_name}</>; pruned"
+ ))
+ );
} else {
// No worktree at all - warn since user asked to remove something that doesn't exist
- super::print(warning_message(cformat!(
- "No worktree found for branch <bold>{branch_name}</>"
- )))?;
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "No worktree found for branch <bold>{branch_name}</>"
+ ))
+ );
}
// Attempt branch deletion (unless --no-delete-branch was specified)
if deletion_mode.should_keep() {
// User explicitly requested no branch deletion - nothing more to do
- super::flush()?;
+ stderr().flush()?;
return Ok(());
}
@@ -543,12 +578,15 @@ fn handle_branch_only_output(
);
let flag_text = &flag_note.text;
let flag_after = flag_note.after_green();
- super::print(FormattedMessage::new(cformat!(
- "<green>✓ Removed branch <bold>{branch_name}</>{flag_text}</>{flag_after}"
- )))?;
+ eprintln!(
+ "{}",
+ FormattedMessage::new(cformat!(
+ "<green>✓ Removed branch <bold>{branch_name}</>{flag_text}</>{flag_after}"
+ ))
+ );
}
- super::flush()?;
+ stderr().flush()?;
Ok(())
}
@@ -754,7 +792,8 @@ impl RemovalDisplayInfo {
"<cyan>◎ Removing <bold>{branch_name}</> worktree{force_text} in background</>"
)
};
- Ok(super::print(FormattedMessage::new(msg))?)
+ eprintln!("{}", FormattedMessage::new(msg));
+ Ok(())
} else {
let msg = if self.branch_deleted() {
let flag_text = &flag_note.text;
@@ -765,7 +804,8 @@ impl RemovalDisplayInfo {
} else {
cformat!("<green>✓ Removed <bold>{branch_name}</> worktree{force_text}</>")
};
- Ok(super::print(FormattedMessage::new(msg))?)
+ eprintln!("{}", FormattedMessage::new(msg));
+ Ok(())
}
}
@@ -786,18 +826,24 @@ impl RemovalDisplayInfo {
let target = self.integration_target.as_deref().unwrap_or("target");
let desc = reason.description();
let symbol = reason.symbol();
- super::print(hint_message(cformat!(
- "Branch integrated ({desc} <bold>{target}</>, <dim>{symbol}</>); retained with <bright-black>--no-delete-branch</>"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Branch integrated ({desc} <bold>{target}</>, <dim>{symbol}</>); retained with <bright-black>--no-delete-branch</>"
+ ))
+ );
} else if self.show_unmerged_hint
|| (!deletion_mode.should_keep() && !self.branch_was_integrated)
{
// Unmerged, no flag - show how to force delete
// (Background: !should_keep && !integrated, Foreground: show_unmerged_hint)
let cmd = suggest_command("remove", &[branch_name], &["-D"]);
- super::print(hint_message(cformat!(
- "Branch unmerged; to delete, run <bright-black>{cmd}</>"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Branch unmerged; to delete, run <bright-black>{cmd}</>"
+ ))
+ );
}
// else: Unmerged + flag - no hint (flag had no effect)
@@ -851,16 +897,19 @@ fn handle_removed_worktree_output(
// Emit cd directive only after pre-remove hooks succeed
if changed_directory {
super::change_directory(main_path)?;
- super::flush()?; // Force flush to ensure shell processes the cd
+ stderr().flush()?; // Force flush to ensure shell processes the cd
}
// Handle detached HEAD case (no branch known)
let Some(branch_name) = branch_name else {
// No branch associated - just remove the worktree
if background {
- super::print(progress_message(
- "Removing worktree in background (detached HEAD, no branch to delete)",
- ))?;
+ eprintln!(
+ "{}",
+ progress_message(
+ "Removing worktree in background (detached HEAD, no branch to delete)",
+ )
+ );
let remove_command = build_remove_command(worktree_path, None, force_worktree);
spawn_detached(
&repo,
@@ -872,9 +921,10 @@ fn handle_removed_worktree_output(
)?;
} else {
// Progress message after pre-remove hooks, before actual removal
- super::print(progress_message(
- "Removing worktree (detached HEAD, no branch to delete)...",
- ))?;
+ eprintln!(
+ "{}",
+ progress_message("Removing worktree (detached HEAD, no branch to delete)...",)
+ );
let _ = repo
.worktree_at(worktree_path)
.run_command(&["fsmonitor--daemon", "stop"]);
@@ -886,21 +936,22 @@ fn handle_removed_worktree_output(
}
.into());
}
- super::print(success_message(
- "Removed worktree (detached HEAD, no branch to delete)",
- ))?;
+ eprintln!(
+ "{}",
+ success_message("Removed worktree (detached HEAD, no branch to delete)",)
+ );
}
// Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
spawn_post_remove_hooks(main_path, worktree_path, "HEAD", removed_commit, verify)?;
spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
- super::flush()?;
+ stderr().flush()?;
return Ok(());
};
if background {
// Background mode: show warning before decision announcement
if let Some(expected) = expected_path {
- super::print(format_path_mismatch_warning(branch_name, expected))?;
+ eprintln!("{}", format_path_mismatch_warning(branch_name, expected));
}
// Background mode: spawn detached process
@@ -940,19 +991,20 @@ fn handle_removed_worktree_output(
verify,
)?;
spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
- super::flush()?;
+ stderr().flush()?;
Ok(())
} else {
// Foreground mode: remove immediately and report actual results
// Progress message after pre-remove hooks, before actual removal
- super::print(progress_message(cformat!(
- "Removing <bold>{branch_name}</> worktree..."
- )))?;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Removing <bold>{branch_name}</> worktree..."))
+ );
// Foreground mode: show warning after progress (contextual info during operation)
if let Some(expected) = expected_path {
- super::print(format_path_mismatch_warning(branch_name, expected))?;
+ eprintln!("{}", format_path_mismatch_warning(branch_name, expected));
}
// Stop fsmonitor daemon first (best effort - ignore errors)
@@ -991,7 +1043,7 @@ fn handle_removed_worktree_output(
verify,
)?;
spawn_post_switch_after_remove(main_path, verify, changed_directory)?;
- super::flush()?;
+ stderr().flush()?;
Ok(())
}
}
@@ -1031,7 +1083,7 @@ pub fn execute_command_in_worktree(
// Flush stdout before executing command to ensure all our messages appear
// before the child process output
- super::flush()?;
+ stderr().flush()?;
// Reset ANSI codes on stderr to prevent color bleeding (see function docs for details)
// This fixes color bleeding observed when worktrunk prints colored output to stdout
@@ -1053,7 +1105,7 @@ pub fn execute_command_in_worktree(
cmd.stream()?;
// Flush to ensure all output appears before we continue
- super::flush()?;
+ stderr().flush()?;
Ok(())
}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index fe25e60d1..c76818f47 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -2,15 +2,16 @@
//!
//! # Architecture
//!
-//! Global context-based output system similar to logging frameworks (`log`, `tracing`).
-//! State is lazily initialized on first use — no explicit initialization required.
+//! For regular output, use `eprintln!`/`println!` directly (from `worktrunk::styling`
+//! for color support). This module handles shell integration directives (cd, exec)
+//! that need to be communicated to the parent shell.
//!
//! ## Usage
//!
//! ```rust,ignore
-//! use worktrunk::styling::{success_message, error_message, hint_message};
+//! use worktrunk::styling::{success_message, error_message, hint_message, eprintln};
//!
-//! output::print(success_message("Operation complete"));
+//! eprintln!("{}", success_message("Operation complete"));
//! output::change_directory(&path);
//! output::execute("git pull");
//! ```
@@ -34,8 +35,8 @@ pub(crate) mod shell_integration;
// Re-export the public API
pub(crate) use global::{
- blank, change_directory, execute, flush, is_shell_integration_active, post_hook_display_path,
- pre_hook_display_path, print, set_verbosity, stdout, terminate_output,
+ change_directory, execute, is_shell_integration_active, post_hook_display_path,
+ pre_hook_display_path, set_verbosity, terminate_output,
};
// Re-export output handlers
pub(crate) use handlers::{
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index 3fb0960c1..0fbf58041 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -63,7 +63,7 @@ use color_print::cformat;
use worktrunk::config::UserConfig;
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{Shell, current_shell, extract_filename_from_path};
-use worktrunk::styling::hint_message;
+use worktrunk::styling::{eprintln, hint_message};
/// Shell integration install hint message.
// TODO(hints-count): After showing this hint 5+ times, suggest `wt config show` for diagnostics.
@@ -182,9 +182,12 @@ pub fn print_skipped_shells(
) -> anyhow::Result<()> {
for (shell, path) in skipped {
let path = format_path_for_display(path);
- super::print(hint_message(cformat!(
- "Skipped <bright-black>{shell}</>; <bright-black>{path}</> not found"
- )))?;
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Skipped <bright-black>{shell}</>; <bright-black>{path}</> not found"
+ ))
+ );
}
Ok(())
}
@@ -240,10 +243,10 @@ pub fn print_shell_install_result(
match result.action {
ConfigAction::Added | ConfigAction::Created => {
- super::print(success_message(message))?;
+ eprintln!("{}", success_message(message));
}
ConfigAction::AlreadyExists => {
- super::print(info_message(message))?;
+ eprintln!("{}", info_message(message));
}
ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
unreachable!("Preview actions handled by confirmation prompt")
@@ -263,10 +266,10 @@ pub fn print_shell_install_result(
);
match comp_result.action {
ConfigAction::Added | ConfigAction::Created => {
- super::print(success_message(comp_message))?;
+ eprintln!("{}", success_message(comp_message));
}
ConfigAction::AlreadyExists => {
- super::print(info_message(comp_message))?;
+ eprintln!("{}", info_message(comp_message));
}
ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
unreachable!("Preview actions handled by confirmation prompt")
@@ -285,9 +288,12 @@ pub fn print_shell_install_result(
.find(|r| r.shell == Shell::Fish)
.map(|r| format_path_for_display(&r.path))
.unwrap_or_else(|| "~/.config/fish/functions/".to_string());
- super::print(info_message(cformat!(
- "Removed <bold>{old_path}</> (deprecated; now using <bold>{new_path}</>)"
- )))?;
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Removed <bold>{old_path}</> (deprecated; now using <bold>{new_path}</>)"
+ ))
+ );
}
// Show skipped shells
@@ -295,25 +301,32 @@ pub fn print_shell_install_result(
// Summary
if shells_configured_count > 0 {
- super::blank()?;
+ eprintln!();
let plural = if shells_configured_count == 1 {
""
} else {
"s"
};
- super::print(success_message(format!(
- "Configured {shells_configured_count} shell{plural}"
- )))?;
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Configured {shells_configured_count} shell{plural}"
+ ))
+ );
} else {
- super::print(success_message("All shells already configured"))?;
+ eprintln!("{}", success_message("All shells already configured"));
}
// Zsh compinit advisory
if scan_result.zsh_needs_compinit {
- super::print(warning_message(
- "Completions require compinit; add to ~/.zshrc before the wt line:",
- ))?;
- super::print(format_bash_with_gutter("autoload -Uz compinit && compinit"))?;
+ eprintln!(
+ "{}",
+ warning_message("Completions require compinit; add to ~/.zshrc before the wt line:",)
+ );
+ eprintln!(
+ "{}",
+ format_bash_with_gutter("autoload -Uz compinit && compinit")
+ );
}
// Restart hint for current shell
@@ -331,7 +344,7 @@ pub fn print_shell_install_result(
});
if current_shell_result.is_some() {
- super::print(hint_message(shell_restart_hint()))?;
+ eprintln!("{}", hint_message(shell_restart_hint()));
}
}
@@ -374,7 +387,7 @@ pub fn prompt_shell_integration(
// Point them to manual installation
None => shell_integration_hint(),
};
- super::print(hint_message(msg))?;
+ eprintln!("{}", hint_message(msg));
return Ok(false);
};
@@ -385,7 +398,7 @@ pub fn prompt_shell_integration(
// No config files exist - show install hint
if scan.configured.is_empty() {
- super::print(hint_message(shell_integration_hint()))?;
+ eprintln!("{}", hint_message(shell_integration_hint()));
return Ok(false);
}
@@ -400,7 +413,7 @@ pub fn prompt_shell_integration(
// Shell integration is configured but not active for this invocation
if !crate::was_invoked_with_explicit_path() {
// Invoked via PATH but wrapper isn't active - needs shell restart
- super::print(hint_message(shell_restart_hint()))?;
+ eprintln!("{}", hint_message(shell_restart_hint()));
}
// For explicit paths: no hint needed - handle_switch_output() warning already explains
return Ok(false);
@@ -408,13 +421,13 @@ pub fn prompt_shell_integration(
// Can't or shouldn't prompt - show install hint
if config.skip_shell_integration_prompt || !is_tty || skip_prompt {
- super::print(hint_message(shell_integration_hint()))?;
+ eprintln!("{}", hint_message(shell_integration_hint()));
return Ok(false);
}
// TTY + first time: Show interactive prompt
// Accepting installs for all shells with config files (same as `wt config shell install`)
- super::blank()?;
+ eprintln!();
let confirmed = prompt_for_install(
&scan.configured,
&scan.completion_results,
@@ -426,7 +439,7 @@ pub fn prompt_shell_integration(
if !confirmed {
// Only skip future prompts after explicit decline (not Ctrl+C)
let _ = config.set_skip_shell_integration_prompt(None);
- super::print(hint_message(shell_integration_hint()))?;
+ eprintln!("{}", hint_message(shell_integration_hint()));
return Ok(false);
}
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index 3bb18bb28..cf89403bf 100644
--- a/src/styling/mod.rs
+++ b/src/styling/mod.rs
@@ -11,7 +11,7 @@
//! - **stderr**: Status messages (progress, success, errors, hints, warnings)
//!
//! This separation allows piping (`wt list | grep foo`) without status messages interfering.
-//! Use `output::stdout()` for primary output, `output::print()` for status messages.
+//! Use `println!` for primary output, `eprintln!` for status messages.
mod constants;
mod format;
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index dfa06862a..e931f2a52 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -4,24 +4,38 @@
//! When shell integration is active (`WORKTRUNK_DIRECTIVE_FILE` is set), directives are written
//! to the file, not stdout.
//!
-//! This test enforces: **No stdout writes in command code except via output system**
+//! This test enforces: **No accidental stdout writes in command code**
//!
//! Allowed:
-//! - `output::*` functions (route to correct stream)
//! - `eprintln!` / `eprint!` (stderr is safe)
+//! - `println!` / `print!` in files listed in `STDOUT_ALLOWED_PATHS` (data output)
//!
-//! Exceptions:
-//! - `init.rs` - outputs shell integration code to stdout for `eval`
-//! - `statusline.rs` - outputs status line text to stdout for shell prompts
+//! When adding stdout output:
+//! - Use `worktrunk::styling::println` for color-aware output
+//! - Add the file path to `STDOUT_ALLOWED_PATHS` with a comment explaining why
use std::fs;
use std::path::Path;
-/// Files that are allowed to use println!/print! for stdout
-/// These intentionally output to stdout (e.g., shell code for eval)
-const STDOUT_ALLOWED_FILES: &[&str] = &[
- "init.rs", // Outputs shell integration code for: eval "$(wt config shell init bash)"
- "statusline.rs", // Outputs status line text for shell prompts (PS1)
+use path_slash::PathExt as _;
+
+/// Paths (relative to src/commands/) that are allowed to use println!/print! for stdout.
+/// These intentionally output data to stdout for scripting/piping.
+const STDOUT_ALLOWED_PATHS: &[&str] = &[
+ // Shell integration code for: eval "$(wt config shell init bash)"
+ "init.rs",
+ // Status line text for shell prompts (PS1)
+ "statusline.rs",
+ // Table and summary output for wt list
+ "list/collect/mod.rs",
+ // JSON output for wt list --format=json
+ "list/mod.rs",
+ // State data output (branch names, previous worktree, etc.)
+ "config/state.rs",
+ // Hint list output
+ "config/hints.rs",
+ // LLM prompt output for wt step commit --show-prompt
+ "step_commands.rs",
];
/// Substrings that indicate the line is a special case (e.g., in a comment or test reference)
@@ -40,19 +54,25 @@ fn check_no_stdout_in_commands() {
let mut violations = Vec::new();
// Recursively scan all .rs files under src/commands/
- scan_directory(&commands_dir, &stdout_tokens, &mut violations);
+ scan_directory(
+ &commands_dir,
+ &stdout_tokens,
+ &mut violations,
+ &commands_dir,
+ );
if !violations.is_empty() {
panic!(
- "stdout writes found in command code (use output::* instead):\n\n{}\n\n\
+ "Unexpected stdout writes in command code:\n\n{}\n\n\
stdout is reserved for data output (JSON, tables).\n\
- Use output::print(), output::stdout(), etc. instead.",
+ Use worktrunk::styling::println for stdout, eprintln for stderr.\n\
+ Add file path to STDOUT_ALLOWED_PATHS if stdout is intentional.",
violations.join("\n")
);
}
}
-fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>) {
+fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>, commands_dir: &Path) {
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
@@ -62,18 +82,22 @@ fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>) {
let path = entry.path();
if path.is_dir() {
- scan_directory(&path, tokens, violations);
+ scan_directory(&path, tokens, violations, commands_dir);
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
- check_file(&path, tokens, violations);
+ check_file(&path, tokens, violations, commands_dir);
}
}
}
-fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>) {
- let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
+fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, commands_dir: &Path) {
+ // Get path relative to src/commands/ for matching against STDOUT_ALLOWED_PATHS
+ let relative_path = path
+ .strip_prefix(commands_dir)
+ .map(|p| p.to_slash_lossy())
+ .unwrap_or_default();
// Skip files that are allowed to use stdout
- if STDOUT_ALLOWED_FILES.contains(&file_name) {
+ if STDOUT_ALLOWED_PATHS.contains(&relative_path.as_ref()) {
return;
}