Skip to content

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

refactor: Centralize command output through output module

Maximilian Roos22df27d3a23a
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 5938f5b05..94bf0c387 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -4,12 +4,10 @@ use std::path::PathBuf;
use worktrunk::git::{Repository, detached_head};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::Shell;
-use worktrunk::styling::{
- AnstyleStyle, CYAN, GREEN, GREEN_BOLD, HINT, HINT_EMOJI, INFO_EMOJI, SUCCESS_EMOJI,
- format_toml, print, println,
-};
+use worktrunk::styling::{AnstyleStyle, CYAN, GREEN, GREEN_BOLD, format_toml};
use super::configure_shell::{ConfigAction, process_shell_completions, scan_shell_configs};
+use crate::output;
/// Example configuration file content (displayed in help with values uncommented)
const CONFIG_EXAMPLE: &str = include_str!("../../dev/config.example.toml");
@@ -45,15 +43,13 @@ pub fn handle_config_create() -> anyhow::Result<()> {
// Check if file already exists
if config_path.exists() {
let bold = AnstyleStyle::new().bold();
- println!(
- "{INFO_EMOJI} Global config already exists: {bold}{}{bold:#}",
+ output::info(format!(
+ "Global config already exists: {bold}{}{bold:#}",
format_path_for_display(&config_path)
- );
- println!();
- println!("{HINT_EMOJI} {HINT}Use 'wt config show' to view existing configuration{HINT:#}");
- println!(
- "{HINT_EMOJI} {HINT}Use 'wt config create --help' for config format reference{HINT:#}"
- );
+ ))?;
+ output::blank()?;
+ output::hint("Use 'wt config show' to view existing configuration")?;
+ output::hint("Use 'wt config create --help' for config format reference")?;
return Ok(());
}
@@ -69,14 +65,12 @@ pub fn handle_config_create() -> anyhow::Result<()> {
// Success message
let green_bold = GREEN.bold();
- println!(
- "{SUCCESS_EMOJI} {GREEN}Created config file: {green_bold}{}{green_bold:#}",
+ output::success(format!(
+ "{GREEN}Created config file: {green_bold}{}{green_bold:#}{GREEN:#}",
format_path_for_display(&config_path)
- );
- println!();
- println!(
- "{HINT_EMOJI} {HINT}Edit this file to customize worktree paths and LLM settings{HINT:#}"
- );
+ ))?;
+ output::blank()?;
+ output::hint("Edit this file to customize worktree paths and LLM settings")?;
Ok(())
}
@@ -85,11 +79,11 @@ pub fn handle_config_create() -> anyhow::Result<()> {
pub fn handle_config_show() -> anyhow::Result<()> {
// Display global config
display_global_config()?;
- println!();
+ output::blank()?;
// Display project config if in a git repository
display_project_config()?;
- println!();
+ output::blank()?;
// Display shell integration status
display_shell_status()?;
@@ -104,19 +98,19 @@ fn display_global_config() -> anyhow::Result<()> {
let config_path = get_global_config_path()
.ok_or_else(|| anyhow::anyhow!("Could not determine global config path"))?;
- println!(
- "{INFO_EMOJI} Global Config: {bold}{}{bold:#}",
+ output::info(format!(
+ "Global Config: {bold}{}{bold:#}",
format_path_for_display(&config_path)
- );
+ ))?;
// Check if file exists
if !config_path.exists() {
- println!("{HINT_EMOJI} {HINT}Not found (using defaults){HINT:#}");
- println!("{HINT_EMOJI} {HINT}Run 'wt config create' to create a config file{HINT:#}");
- println!();
+ output::hint("Not found (using defaults)")?;
+ output::hint("Run 'wt config create' to create a config file")?;
+ output::blank()?;
let default_config =
"# Default configuration:\nworktree-path = \"../{{ main_worktree }}.{{ branch }}\"";
- print!("{}", format_toml(default_config, ""));
+ output::gutter(format_toml(default_config, ""))?;
return Ok(());
}
@@ -124,12 +118,12 @@ fn display_global_config() -> anyhow::Result<()> {
let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;
if contents.trim().is_empty() {
- println!("{HINT_EMOJI} {HINT}Empty file (using defaults){HINT:#}");
+ output::hint("Empty file (using defaults)")?;
return Ok(());
}
// Display TOML with syntax highlighting (gutter at column 0)
- print!("{}", format_toml(&contents, ""));
+ output::gutter(format_toml(&contents, ""))?;
Ok(())
}
@@ -143,20 +137,22 @@ fn display_project_config() -> anyhow::Result<()> {
let repo_root = match repo.worktree_root() {
Ok(root) => root,
Err(_) => {
- println!("{INFO_EMOJI} {dim}Project Config: Not in a git repository{dim:#}");
+ output::info(format!(
+ "{dim}Project Config: Not in a git repository{dim:#}"
+ ))?;
return Ok(());
}
};
let config_path = repo_root.join(".config").join("wt.toml");
- println!(
- "{INFO_EMOJI} Project Config: {bold}{}{bold:#}",
+ output::info(format!(
+ "Project Config: {bold}{}{bold:#}",
format_path_for_display(&config_path)
- );
+ ))?;
// Check if file exists
if !config_path.exists() {
- println!("{HINT_EMOJI} {HINT}Not found{HINT:#}");
+ output::hint("Not found")?;
return Ok(());
}
@@ -164,18 +160,18 @@ fn display_project_config() -> anyhow::Result<()> {
let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;
if contents.trim().is_empty() {
- println!("{HINT_EMOJI} {HINT}Empty file{HINT:#}");
+ output::hint("Empty file")?;
return Ok(());
}
// Display TOML with syntax highlighting (gutter at column 0)
- print!("{}", format_toml(&contents, ""));
+ output::gutter(format_toml(&contents, ""))?;
Ok(())
}
fn display_shell_status() -> anyhow::Result<()> {
- use worktrunk::styling::{WARNING, WARNING_EMOJI, format_with_gutter};
+ use worktrunk::styling::{WARNING, format_with_gutter};
let bold = AnstyleStyle::new().bold();
let dim = AnstyleStyle::new().dimmed();
@@ -184,7 +180,7 @@ fn display_shell_status() -> anyhow::Result<()> {
let scan_result = match scan_shell_configs(None, true) {
Ok(r) => r,
Err(e) => {
- println!("{HINT_EMOJI} {HINT}Could not determine shell status: {e}{HINT:#}");
+ output::hint(format!("Could not determine shell status: {e}"))?;
return Ok(());
}
};
@@ -210,26 +206,27 @@ fn display_shell_status() -> anyhow::Result<()> {
match result.action {
ConfigAction::AlreadyExists => {
any_configured = true;
- println!(
- "{INFO_EMOJI} Already configured {what} for {bold}{shell}{bold:#} @ {path}"
- );
+ output::info(format!(
+ "Already configured {what} for {bold}{shell}{bold:#} @ {path}"
+ ))?;
// Check if zsh has compinit enabled (required for completions)
if matches!(shell, Shell::Zsh) && check_zsh_compinit_missing() {
- println!(
- "{WARNING_EMOJI} {WARNING}Completions won't work; add to ~/.zshrc before the wt line:{WARNING:#}"
- );
- print!(
- "{}",
- format_with_gutter("autoload -Uz compinit && compinit", "", None)
- );
+ output::warning(format!(
+ "{WARNING}Completions won't work; add to ~/.zshrc before the wt line:{WARNING:#}"
+ ))?;
+ output::gutter(format_with_gutter(
+ "autoload -Uz compinit && compinit",
+ "",
+ None,
+ ))?;
}
}
ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
any_not_configured = true;
- println!(
- "{HINT_EMOJI} {HINT}Not configured {what} for {bold}{shell}{bold:#} @ {path}{HINT:#}"
- );
+ output::hint(format!(
+ "Not configured {what} for {bold}{shell}{bold:#} @ {path}"
+ ))?;
}
_ => {} // Added/Created won't appear in dry_run mode
}
@@ -243,15 +240,15 @@ fn display_shell_status() -> anyhow::Result<()> {
match result.action {
ConfigAction::AlreadyExists => {
any_configured = true;
- println!(
- "{INFO_EMOJI} Already configured completions for {bold}{shell}{bold:#} @ {path}"
- );
+ output::info(format!(
+ "Already configured completions for {bold}{shell}{bold:#} @ {path}"
+ ))?;
}
ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
any_not_configured = true;
- println!(
- "{HINT_EMOJI} {HINT}Not configured completions for {bold}{shell}{bold:#} @ {path}{HINT:#}"
- );
+ output::hint(format!(
+ "Not configured completions for {bold}{shell}{bold:#} @ {path}"
+ ))?;
}
_ => {}
}
@@ -260,15 +257,13 @@ fn display_shell_status() -> anyhow::Result<()> {
// Show skipped (not installed) shells
for (shell, path) in &scan_result.skipped {
let path = format_path_for_display(path);
- println!("{dim}⚪ Skipped {shell}; {path} not found{dim:#}");
+ output::raw(format!("{dim}⚪ Skipped {shell}; {path} not found{dim:#}"))?;
}
// Summary hint
if any_not_configured && !any_configured {
- println!();
- println!(
- "{HINT_EMOJI} {HINT}Run 'wt config shell install' to enable shell integration{HINT:#}"
- );
+ output::blank()?;
+ output::hint("Run 'wt config shell install' to enable shell integration")?;
}
Ok(())
diff --git a/tests/integration_tests/config_init.rs b/tests/integration_tests/config_init.rs
index 0759c874f..4443e2432 100644
--- a/tests/integration_tests/config_init.rs
+++ b/tests/integration_tests/config_init.rs
@@ -57,7 +57,7 @@ fn test_config_init_creates_file() {
success: true
exit_code: 0
----- stdout -----
- ✅ Created config file: ~/.config/worktrunk/config.toml
+ ✅ Created config file: ~/.config/worktrunk/config.toml
💡 Edit this file to customize worktree paths and LLM settings
diff --git a/tests/output_system_guard.rs b/tests/output_system_guard.rs
index f654181ab..a592d662d 100644
--- a/tests/output_system_guard.rs
+++ b/tests/output_system_guard.rs
@@ -1,68 +1,133 @@
+//! Guard test to prevent stdout leaks in command code
+//!
+//! In directive mode (`--internal`), stdout is reserved for shell script output.
+//! Any `println!` or `print!` in command code would leak into the script and
+//! potentially be eval'd by the shell wrapper.
+//!
+//! This test enforces: **No stdout writes in command code except via output system**
+//!
+//! Allowed:
+//! - `output::*` functions (route to correct stream based on mode)
+//! - `eprintln!` / `eprint!` (stderr is safe)
+//!
+//! Exceptions:
+//! - `init.rs` - intentionally outputs shell code to stdout for `eval`
+
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)
+];
+
+/// Substrings that indicate the line is a special case (e.g., in a comment or test reference)
+const ALLOWED_LINE_PATTERNS: &[&str] = &[
+ "spacing_test.rs", // Test file reference
+];
+
#[test]
-fn check_output_system_usage() {
+fn check_no_stdout_in_commands() {
let project_root = env!("CARGO_MANIFEST_DIR");
- let restricted_files = [
- "src/commands/worktree.rs",
- "src/commands/merge.rs",
- "src/commands/list/mod.rs",
- "src/commands/list/collect.rs",
- "src/commands/list/collect_progressive_impl.rs",
- ];
- let forbidden_tokens = ["print!", "println!", "eprint!", "eprintln!"];
- let allowed_substrings = ["spacing_test.rs", "command_approval.rs"];
+ let commands_dir = Path::new(project_root).join("src/commands");
+
+ // Forbidden tokens that write to stdout
+ let stdout_tokens = ["print!", "println!"];
let mut violations = Vec::new();
- for relative_path in restricted_files {
- let full_path = Path::new(project_root).join(relative_path);
- if !full_path.exists() {
- continue;
+ // Recursively scan all .rs files under src/commands/
+ scan_directory(&commands_dir, &stdout_tokens, &mut violations);
+
+ if !violations.is_empty() {
+ panic!(
+ "stdout writes found in command code (use output::* instead):\n\n{}\n\n\
+ In directive mode, stdout is reserved for shell script output.\n\
+ Use output::info(), output::hint(), output::raw(), etc. instead.",
+ violations.join("\n")
+ );
+ }
+}
+
+fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>) {
+ let entries = match fs::read_dir(dir) {
+ Ok(e) => e,
+ Err(_) => return,
+ };
+
+ for entry in entries.flatten() {
+ let path = entry.path();
+
+ if path.is_dir() {
+ scan_directory(&path, tokens, violations);
+ } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
+ check_file(&path, tokens, violations);
}
+ }
+}
- let contents = fs::read_to_string(&full_path)
- .unwrap_or_else(|err| panic!("failed to read {}: {err}", relative_path));
-
- // Check if file imports the correct anstream-wrapped macros from worktrunk::styling
- let has_styling_import = contents.contains("use worktrunk::styling::")
- && (contents.contains("eprintln") || contents.contains("println"));
-
- 'line: for (idx, line) in contents.lines().enumerate() {
- for token in forbidden_tokens {
- if let Some(pos) = line.find(token) {
- if allowed_substrings
- .iter()
- .any(|pattern| line.contains(pattern))
- {
- continue 'line;
- }
+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("");
- if line
- .find("//")
- .map(|comment_pos| comment_pos <= pos)
- .unwrap_or(false)
- {
- continue 'line;
- }
+ // Skip files that are allowed to use stdout
+ if STDOUT_ALLOWED_FILES.contains(&file_name) {
+ return;
+ }
+
+ let contents = match fs::read_to_string(path) {
+ Ok(c) => c,
+ Err(_) => return,
+ };
+
+ let relative_path = path
+ .strip_prefix(env!("CARGO_MANIFEST_DIR"))
+ .unwrap_or(path)
+ .display();
+
+ for (line_num, line) in contents.lines().enumerate() {
+ // Skip lines with allowed patterns
+ if ALLOWED_LINE_PATTERNS
+ .iter()
+ .any(|pattern| line.contains(pattern))
+ {
+ continue;
+ }
- // Allow if file imports the correct macro from worktrunk::styling
- if has_styling_import && (token == "eprintln!" || token == "println!") {
- continue 'line;
+ for token in tokens {
+ if let Some(pos) = line.find(token) {
+ // Skip eprint!/eprintln! - they go to stderr and are safe
+ // When we match print!/println!, check if preceded by 'e' (part of eprint/eprintln)
+ // Also verify the 'e' is at a word boundary (start of line, or after non-alphanumeric)
+ if pos > 0 {
+ let prev_char = line.as_bytes()[pos - 1];
+ if prev_char == b'e' {
+ // Check this 'e' is at a word boundary (not part of some_eprint)
+ if pos == 1
+ || !line.as_bytes()[pos - 2].is_ascii_alphanumeric()
+ && line.as_bytes()[pos - 2] != b'_'
+ {
+ continue;
+ }
}
+ }
- violations.push(format!("{}:{}: {}", relative_path, idx + 1, line.trim()));
- continue 'line;
+ // Skip if the token is in a comment
+ if let Some(comment_pos) = line.find("//")
+ && comment_pos < pos
+ {
+ continue;
}
+
+ violations.push(format!(
+ "{}:{}: {}",
+ relative_path,
+ line_num + 1,
+ line.trim()
+ ));
+ break; // Only report once per line
}
}
}
-
- if !violations.is_empty() {
- panic!(
- "Direct output macros found in commands using --internal:\n{}",
- violations.join("\n")
- );
- }
}
diff --git a/tests/snapshots/integration__integration_tests__internal_flag__config_show_with_internal_flag.snap b/tests/snapshots/integration__integration_tests__internal_flag__config_show_with_internal_flag.snap
index ef6a034df..c93695274 100644
--- a/tests/snapshots/integration__integration_tests__internal_flag__config_show_with_internal_flag.snap
+++ b/tests/snapshots/integration__integration_tests__internal_flag__config_show_with_internal_flag.snap
@@ -24,6 +24,8 @@ info:
success: true
exit_code: 0
----- stdout -----
+
+----- stderr -----
⚪ Global Config: ~/.config/worktrunk/config.toml
  worktree-path = "../{{ main_worktree }}.{{ branch }}"
@@ -33,5 +35,3 @@ exit_code: 0
⚪ Skipped bash; ~/.bashrc not found
⚪ Skipped zsh; ~/.zshrc not found
⚪ Skipped fish; ~/.config/fish/conf.d not found
-
------ stderr -----