Skip to content

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

Consolidate output system: replace table/data with stdout (#359)

Maximilian Roose7a0ee6d9515
diff --git a/.claude/rules/cli-output-formatting.md b/.claude/rules/cli-output-formatting.md
index 4bdd6ba2e..b6d459a29 100644
--- a/.claude/rules/cli-output-formatting.md
+++ b/.claude/rules/cli-output-formatting.md
@@ -232,17 +232,21 @@ Specific rules:
## Output System
-Use `output::` functions, never direct `println!`. See `output-system-architecture.md`
-for stdout vs stderr decisions.
+Use `output::` functions for consistency. See `output-system-architecture.md`
+for stdout vs stderr decisions and simplification notes.
```rust
-// GOOD
+// Preferred - consistent routing and flushing
output::print(success_message("Branch created"))?;
-// BAD - bypasses output system
-println!("Branch created");
+// Acceptable for simple cases - just remember to flush if needed
+eprintln!("{}", success_message("Branch created"));
```
+**Note:** The output wrappers are thin (`eprintln!` + flush). The main value is
+consistency, not complex logic. See "Simplification Notes" in
+`output-system-architecture.md`.
+
**Interactive prompts** must flush stderr before blocking on stdin:
```rust
@@ -350,7 +354,7 @@ output::print(hint_message("Run 'wt list' to see worktrees"))?;
## Design Principles
- **`cformat!` for styling** — Never manual escape codes (`\x1b[...`)
-- **`output::` for printing** — Never direct `println!`/`eprintln!`
+- **`output::` for printing** — Preferred for consistency; direct `println!`/`eprintln!` acceptable
- **YAGNI** — Most output needs no styling
- **Graceful degradation** — Colors auto-adjust (NO_COLOR, TTY detection)
- **Unicode-aware** — Width calculations respect symbols and CJK (via `StyledLine`)
diff --git a/.claude/rules/output-system-architecture.md b/.claude/rules/output-system-architecture.md
index 2502faaf7..82d3d7935 100644
--- a/.claude/rules/output-system-architecture.md
+++ b/.claude/rules/output-system-architecture.md
@@ -36,12 +36,10 @@ output::change_directory(&path)?; // Writes to directive file if set, else no-o
| `print(message)` | stderr | Status messages (use with formatting functions) |
| `shell_integration_hint(message)` | stderr | Hints suppressed when shell integration active |
| `blank()` | stderr | Visual separation |
-| `table(content)` | stdout | Primary output (pipeable) |
-| `data(content)` | stdout | Structured data (JSON) |
+| `stdout(content)` | stdout | Primary output (tables, JSON, pipeable) |
| `change_directory(path)` | directive file | Shell cd after wt exits |
| `execute(command)` | directive file | Shell command after wt exits |
-| `flush()` | both | Flush buffers |
-| `flush_for_stderr_prompt()` | both | Flush before interactive prompts |
+| `flush()` | both | Flush buffers (call before interactive prompts) |
| `terminate_output()` | stderr | Reset ANSI state on stderr |
| `is_shell_integration_active()` | — | Check if directive file set (rarely needed) |
@@ -74,3 +72,25 @@ Examples:
`WORKTRUNK_DIRECTIVE_FILE` is automatically removed from spawned subprocesses
(via `shell_exec::run()`). This prevents hooks from writing to the directive
file.
+
+## Simplification Notes
+
+The output system was originally more complex to handle shell integration
+edge cases. After consolidation, the thin wrappers (`print`, `stdout`,
+`blank`) are essentially `eprintln!`/`println!` + flush.
+
+**What still provides value:**
+
+- `change_directory()`, `execute()` — IPC with shell wrapper via directive file
+- `shell_integration_hint()` — conditional suppression logic
+- `terminate_output()` — ANSI reset when needed
+
+**What could be further simplified:**
+
+- `print()` → `eprintln!()` + flush (callers must remember to flush)
+- `stdout()` → `println!()` + flush
+- `blank()` → `eprintln!()` + flush
+
+The abstraction cost is low, but if we wanted to reduce indirection, these
+wrappers could be removed. The main value they provide is consistency (correct
+stream, always flushing).
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 445365328..fb032b476 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -110,7 +110,7 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any
// CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving
// Flushes both stdout (for data output) and stderr (for messages)
- crate::output::flush_for_stderr_prompt()?;
+ crate::output::flush()?;
output::print(cformat!(
"{WARNING_SYMBOL} <yellow><bold>{project_name}</> needs approval to execute <bold>{count}</> command{plural}:</>"
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 2d51c2c6f..073f0971d 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -681,11 +681,11 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any
} else {
repo.default_branch()?
};
- crate::output::data(branch_name)?;
+ crate::output::stdout(branch_name)?;
}
"previous-branch" => match repo.get_switch_previous() {
- Some(prev) => crate::output::data(prev)?,
- None => crate::output::data("")?,
+ Some(prev) => crate::output::stdout(prev)?,
+ None => crate::output::stdout("")?,
},
"marker" => {
let branch_name = match branch {
@@ -693,8 +693,8 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any
None => repo.require_current_branch("get marker for current branch")?,
};
match repo.branch_keyed_marker(&branch_name) {
- Some(marker) => crate::output::data(marker)?,
- None => crate::output::data("")?,
+ Some(marker) => crate::output::stdout(marker)?,
+ None => crate::output::stdout("")?,
}
}
"ci-status" => {
@@ -726,7 +726,7 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any
let ci_status = PrStatus::detect(&branch_name, &head, repo_root, has_upstream)
.map_or(super::list::ci_status::CiStatus::NoCI, |s| s.ci_status);
let status_str: &'static str = ci_status.into();
- crate::output::data(status_str)?;
+ crate::output::stdout(status_str)?;
}
// TODO: Consider simplifying to just print the path and let users run `ls -al` themselves
"logs" => {
@@ -1066,7 +1066,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
"logs": logs
});
- crate::output::data(serde_json::to_string_pretty(&output)?)?;
+ crate::output::stdout(serde_json::to_string_pretty(&output)?)?;
Ok(())
}
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 44beb3f2a..01df108d5 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -501,7 +501,7 @@ fn prompt_for_confirmation(
// CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving
// Flushes both stdout (for data output) and stderr (for messages)
- crate::output::flush_for_stderr_prompt().map_err(|e| e.to_string())?;
+ crate::output::flush().map_err(|e| e.to_string())?;
let bold = Style::new().bold();
@@ -871,7 +871,7 @@ fn prompt_for_uninstall_confirmation(
) -> Result<bool, String> {
use anstyle::Style;
- crate::output::flush_for_stderr_prompt().map_err(|e| e.to_string())?;
+ crate::output::flush().map_err(|e| e.to_string())?;
for result in results {
let bold = Style::new().bold();
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index acb8e204a..6bfe21c00 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -1104,14 +1104,14 @@ pub fn collect(
} else {
// Non-TTY: output to stdout (same as buffered mode)
// Progressive skeleton was suppressed; now output the final table
- crate::output::table(layout.format_header_line())?;
+ crate::output::stdout(layout.format_header_line())?;
for item in &all_items {
- crate::output::table(
+ crate::output::stdout(
layout.format_list_item_line(item, previous_branch.as_deref()),
)?;
}
- crate::output::table("")?;
- crate::output::table(final_msg)?;
+ crate::output::stdout("")?;
+ crate::output::stdout(final_msg)?;
}
} else if render_table {
// Buffered mode: render final table
@@ -1121,12 +1121,12 @@ pub fn collect(
layout.hidden_column_count,
);
- crate::output::table(layout.format_header_line())?;
+ crate::output::stdout(layout.format_header_line())?;
for item in &all_items {
- crate::output::table(layout.format_list_item_line(item, previous_branch.as_deref()))?;
+ crate::output::stdout(layout.format_list_item_line(item, previous_branch.as_deref()))?;
}
- crate::output::table("")?;
- crate::output::table(final_msg)?;
+ crate::output::stdout("")?;
+ crate::output::stdout(final_msg)?;
}
// Status symbols are now computed during data collection (both modes), no fallback needed
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 669e8b270..453c6e93d 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -197,7 +197,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::data(json)?;
+ crate::output::stdout(json)?;
}
crate::OutputFormat::Table => {
// Table and summary already rendered in collect() for all modes
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 5a9639ee3..7d28f3160 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -184,7 +184,7 @@ pub fn step_commit(
if show_prompt {
let config = WorktrunkConfig::load().context("Failed to load config")?;
let prompt = crate::llm::build_commit_prompt(&config.commit_generation)?;
- crate::output::data(prompt)?;
+ crate::output::stdout(prompt)?;
return Ok(());
}
@@ -471,7 +471,7 @@ pub fn step_show_squash_prompt(
repo_name,
config,
)?;
- crate::output::data(prompt)?;
+ crate::output::stdout(prompt)?;
Ok(())
}
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index b50fc9ee8..d0f3233fe 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -123,7 +123,7 @@ fn format_directory_fish_style(path: &Path) -> String {
/// Run the statusline command.
///
-/// Output uses `output::data()` for raw stdout (bypasses anstream color detection).
+/// Output uses `output::stdout()` 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
@@ -200,7 +200,7 @@ pub fn run(claude_code: bool) -> Result<()> {
use worktrunk::styling::fix_dim_after_color_reset;
let reset = anstyle::Reset;
let output = fix_dim_after_color_reset(&output);
- output::data(format!("{reset} {output}"))?;
+ output::stdout(format!("{reset} {output}"))?;
}
Ok(())
diff --git a/src/output/global.rs b/src/output/global.rs
index 956c87733..c4a792c93 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -118,35 +118,18 @@ pub fn blank() -> io::Result<()> {
stderr().flush()
}
-/// Emit structured data output without emoji decoration
+/// Write to stdout (pipeable output)
///
-/// Used for JSON, prompts, statuslines, and other pipeable data. Always writes to stdout.
-/// With WORKTRUNK_DIRECTIVE_FILE, stdout is never used for directives, so it's always
-/// available for data output.
-///
-/// Example:
-/// ```rust,ignore
-/// output::data(json_string)?;
-/// ```
-pub fn data(content: impl Into<String>) -> io::Result<()> {
- println!("{}", content.into());
- io::stdout().flush()
-}
-
-/// Emit primary output to stdout
-///
-/// Used for the main data a command produces (table rows, formatted output).
-/// This is pipeable — `wt list | grep feature` works because table data
+/// 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::table(layout.format_header_line())?;
-/// for item in items {
-/// output::table(layout.format_item_line(item))?;
-/// }
+/// output::stdout(json_string)?;
+/// output::stdout(layout.format_header_line())?;
/// ```
-pub fn table(content: impl Into<String>) -> io::Result<()> {
+pub fn stdout(content: impl Into<String>) -> io::Result<()> {
println!("{}", content.into());
io::stdout().flush()
}
@@ -274,17 +257,10 @@ fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result
Ok(())
}
-/// Flush any buffered output
-pub fn flush() -> io::Result<()> {
- io::stdout().flush()?;
- io::stderr().flush()
-}
-
-/// Flush streams before showing stderr prompt
+/// Flush any buffered output (both stdout and stderr)
///
-/// This prevents stream interleaving. Interactive prompts write to stderr, so we must
-/// ensure all previous output is flushed first.
-pub fn flush_for_stderr_prompt() -> io::Result<()> {
+/// Call before interactive prompts to prevent stream interleaving.
+pub fn flush() -> io::Result<()> {
io::stdout().flush()?;
io::stderr().flush()
}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 2d4089303..048345974 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -31,8 +31,8 @@ pub mod handlers;
// Re-export the public API
pub use global::{
- blank, change_directory, data, execute, flush, flush_for_stderr_prompt,
- is_shell_integration_active, print, shell_integration_hint, table, terminate_output,
+ blank, change_directory, execute, flush, is_shell_integration_active, print,
+ shell_integration_hint, stdout, terminate_output,
};
// Re-export output handlers
pub use handlers::{
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index 13cbad2f3..c6c767e5e 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::table()` for primary output, `output::print()` for status messages.
+//! Use `output::stdout()` for primary output, `output::print()` 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 193244730..dfa06862a 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -46,7 +46,7 @@ fn check_no_stdout_in_commands() {
panic!(
"stdout writes found in command code (use output::* instead):\n\n{}\n\n\
stdout is reserved for data output (JSON, tables).\n\
- Use output::print(), output::table(), output::data(), etc. instead.",
+ Use output::print(), output::stdout(), etc. instead.",
violations.join("\n")
);
}