Skip to content

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

Simplify output system and clarify newline conventions (#356)

Maximilian Roos11f026f0446a
diff --git a/.claude/rules/cli-output-formatting.md b/.claude/rules/cli-output-formatting.md
index 19ccf607c..4bdd6ba2e 100644
--- a/.claude/rules/cli-output-formatting.md
+++ b/.claude/rules/cli-output-formatting.md
@@ -220,9 +220,13 @@ Use `suggest_command()` from `worktrunk::styling` for proper shell escaping.
## Blank Line Principles
+**Core principle:** When presenting the user with text to read and consider, add
+spacing for readability. When piping output (stdout), keep output dense for
+parsing.
+
+Specific rules:
+
- **No leading/trailing blanks** — Start immediately, end cleanly
-- **One blank after blocks** — Separate multi-line content (gutter blocks,
- sections)
- **One blank after prompts** — Separate user input from results
- **Never double blanks** — One blank line maximum between elements
@@ -376,14 +380,42 @@ Use gutter for **quoted content** (git output, commit messages, shell commands):
**Gutter vs Table:** Tables for structured app data; gutter for quoting external
content.
-**No trailing `\n`:** `output::print()` adds newlines automatically:
+## Newline Convention
+
+**Core principle:** All formatting functions return content WITHOUT trailing
+newlines. Callers handle element separation.
+
+This applies to:
+- Message functions: `error_message()`, `success_message()`, `hint_message()`, etc.
+- Gutter functions: `format_with_gutter()`, `format_bash_with_gutter()`
+
+**With `output::print()`:** Adds trailing newline automatically (uses `eprintln!`).
+
+```rust
+output::print(progress_message("Merging..."))?;
+output::print(format_with_gutter(&log, None))?;
+```
+
+**In Display impls:** Use explicit newlines for element separation.
+
+```rust
+// Pattern: leading \n separates from previous element
+write!(f, "{}", error_message(...))?; // first element, no leading \n
+write!(f, "\n{}", format_with_gutter(...))?; // gutter, separated by \n
+write!(f, "\n{}", hint_message(...)) // hint, separated by \n
+
+// For blank line between elements, add extra \n
+write!(f, "\n{}\n", format_with_gutter(...))?; // trailing \n creates blank line
+write!(f, "\n{}", hint_message(...)) // hint after blank line
+```
+
+**Don't add trailing `\n` to content:**
```rust
-// GOOD - no trailing \n
+// GOOD - output::print adds newline
output::print(progress_message("Merging..."))?;
-output::gutter(format_with_gutter(&log, "", None))?;
-// BAD - trailing \n creates blank line
+// BAD - double newline
output::print(progress_message("Merging...\n"))?;
```
@@ -404,7 +436,7 @@ let error_lines: Vec<String> = errors
.collect();
let warning = format!(
"Some git operations failed:\n{}",
- format_with_gutter(&error_lines.join("\n"), "", None)
+ format_with_gutter(&error_lines.join("\n"), None)
);
output::print(warning_message(warning))?;
```
diff --git a/.claude/rules/output-system-architecture.md b/.claude/rules/output-system-architecture.md
index ecd3ff9a2..2502faaf7 100644
--- a/.claude/rules/output-system-architecture.md
+++ b/.claude/rules/output-system-architecture.md
@@ -35,7 +35,6 @@ 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 |
-| `gutter(content)` | stderr | Gutter-formatted quoted content |
| `blank()` | stderr | Visual separation |
| `table(content)` | stdout | Primary output (pipeable) |
| `data(content)` | stdout | Structured data (JSON) |
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 4e95f0890..445365328 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -26,8 +26,8 @@ use color_print::cformat;
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{GitError, HookType};
use worktrunk::styling::{
- INFO_SYMBOL, PROMPT_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter,
- hint_message, stderr, warning_message,
+ INFO_SYMBOL, PROMPT_SYMBOL, WARNING_SYMBOL, eprint, format_bash_with_gutter, hint_message,
+ stderr, warning_message,
};
/// Batch approval helper used when multiple commands are queued for execution.
@@ -112,13 +112,10 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any
// Flushes both stdout (for data output) and stderr (for messages)
crate::output::flush_for_stderr_prompt()?;
- eprintln!(
- "{}",
- cformat!(
- "{WARNING_SYMBOL} <yellow><bold>{project_name}</> needs approval to execute <bold>{count}</> command{plural}:</>"
- )
- );
- eprintln!();
+ output::print(cformat!(
+ "{WARNING_SYMBOL} <yellow><bold>{project_name}</> needs approval to execute <bold>{count}</> command{plural}:</>"
+ ))?;
+ output::blank()?;
for cmd in commands {
// Format as: {phase} {bold}{name}{bold:#}:
@@ -129,8 +126,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}:"),
};
- eprintln!("{label}");
- eprint!("{}", format_bash_with_gutter(&cmd.command.template));
+ output::print(label)?;
+ output::print(format_bash_with_gutter(&cmd.command.template))?;
}
// Check if stdin is a TTY before attempting to prompt
@@ -152,7 +149,7 @@ fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> any
let mut response = String::new();
io::stdin().read_line(&mut response)?;
- eprintln!();
+ output::blank()?;
Ok(response.trim().eq_ignore_ascii_case("y"))
}
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index d072bbf6c..89be4a31d 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -123,7 +123,7 @@ impl<'a> CommitGenerator<'a> {
let commit_message = crate::llm::generate_commit_message(self.config)?;
let formatted_message = self.format_message_for_display(&commit_message);
- crate::output::gutter(format_with_gutter(&formatted_message, None))?;
+ crate::output::print(format_with_gutter(&formatted_message, None))?;
repo.run_command(&["commit", "-m", &commit_message])
.context("Failed to commit")?;
diff --git a/src/commands/config.rs b/src/commands/config.rs
index e7ca5bac4..2d51c2c6f 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -219,7 +219,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
"Commit generation working (<bold>{command_display}</>)"
))
)?;
- write!(out, "{}", format_with_gutter(&message, None))?;
+ writeln!(out, "{}", format_with_gutter(&message, None))?;
}
Err(e) => {
writeln!(
@@ -229,7 +229,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
"Commit generation failed (<bold>{command_display}</>)"
))
)?;
- write!(out, "{}", format_with_gutter(&e.to_string(), None))?;
+ writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;
}
}
@@ -391,7 +391,7 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
"Completions won't work; add to ~/.zshrc before the wt line:"
)
)?;
- write!(
+ writeln!(
out,
"{}",
format_with_gutter("autoload -Uz compinit && compinit", None)
@@ -613,7 +613,7 @@ fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
)?;
if !log_dir.exists() {
- write!(out, "{}", format_with_gutter("(none)", None))?;
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
return Ok(());
}
@@ -623,7 +623,7 @@ fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {
.collect();
if entries.is_empty() {
- write!(out, "{}", format_with_gutter("(none)", None))?;
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
return Ok(());
}
@@ -1078,16 +1078,16 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
// Show default branch cache
writeln!(out, "{}", format_heading("DEFAULT BRANCH", None))?;
match repo.default_branch() {
- Ok(branch) => write!(out, "{}", format_with_gutter(&branch, None))?,
- Err(_) => write!(out, "{}", format_with_gutter("(not cached)", None))?,
+ Ok(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,
+ Err(_) => writeln!(out, "{}", format_with_gutter("(not cached)", None))?,
}
writeln!(out)?;
// Show previous branch (for `wt switch -`)
writeln!(out, "{}", format_heading("PREVIOUS BRANCH", None))?;
match repo.get_switch_previous() {
- Some(prev) => write!(out, "{}", format_with_gutter(&prev, None))?,
- None => write!(out, "{}", format_with_gutter("(none)", None))?,
+ Some(prev) => writeln!(out, "{}", format_with_gutter(&prev, None))?,
+ None => writeln!(out, "{}", format_with_gutter("(none)", None))?,
}
writeln!(out)?;
@@ -1095,7 +1095,7 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
writeln!(out, "{}", format_heading("BRANCH MARKERS", None))?;
let markers = get_all_markers(repo);
if markers.is_empty() {
- write!(out, "{}", format_with_gutter("(none)", None))?;
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
} else {
let mut table = String::from("| Branch | Marker | Age |\n");
table.push_str("|--------|--------|-----|\n");
@@ -1121,7 +1121,7 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {
.then_with(|| a.0.cmp(&b.0))
});
if entries.is_empty() {
- write!(out, "{}", format_with_gutter("(none)", None))?;
+ writeln!(out, "{}", format_with_gutter("(none)", None))?;
} else {
// Build markdown table
let mut table = String::from("| Branch | Status | Age | Head |\n");
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 003864045..44beb3f2a 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -9,6 +9,8 @@ use worktrunk::styling::{
hint_message, warning_message,
};
+use crate::output;
+
pub struct ConfigureResult {
pub shell: Shell,
pub path: PathBuf,
@@ -496,7 +498,6 @@ fn prompt_for_confirmation(
cmd: &str,
) -> Result<bool, String> {
use anstyle::Style;
- use worktrunk::styling::{eprint, eprintln};
// CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving
// Flushes both stdout (for data output) and stderr (for messages)
@@ -520,15 +521,16 @@ fn prompt_for_confirmation(
"shell extension & completions"
};
- eprintln!(
+ output::print(format!(
"{} {} {what} for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- );
+ ))
+ .map_err(|e| e.to_string())?;
// Show the config line that will be added with gutter
- eprint!("{}", format_bash_with_gutter(&result.config_line));
- eprintln!(); // Blank line after each shell block
+ output::print(format_bash_with_gutter(&result.config_line)).map_err(|e| e.to_string())?;
+ output::blank().map_err(|e| e.to_string())?; // Blank line after each shell block
}
// Show completion changes (only fish has separate completion files)
@@ -540,16 +542,18 @@ fn prompt_for_confirmation(
let shell = result.shell;
let path = format_path_for_display(&result.path);
- eprintln!(
+ output::print(format!(
"{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- );
+ ))
+ .map_err(|e| e.to_string())?;
// Show the completion content that will be written
let fish_completion = fish_completion_content(cmd);
- eprint!("{}", format_bash_with_gutter(fish_completion.trim()));
- eprintln!(); // Blank line after
+ output::print(format_bash_with_gutter(fish_completion.trim()))
+ .map_err(|e| e.to_string())?;
+ output::blank().map_err(|e| e.to_string())?; // Blank line after
}
prompt_yes_no()
@@ -559,7 +563,7 @@ fn prompt_for_confirmation(
fn prompt_yes_no() -> Result<bool, String> {
use anstyle::Style;
use std::io::Write;
- use worktrunk::styling::{PROMPT_SYMBOL, eprint, eprintln};
+ use worktrunk::styling::{PROMPT_SYMBOL, eprint};
let bold = Style::new().bold();
eprint!("{PROMPT_SYMBOL} Proceed? {bold}[y/N]{bold:#} ");
@@ -570,7 +574,7 @@ fn prompt_yes_no() -> Result<bool, String> {
.read_line(&mut input)
.map_err(|e| e.to_string())?;
- eprintln!();
+ crate::output::blank().map_err(|e| e.to_string())?;
let response = input.trim().to_lowercase();
Ok(response == "y" || response == "yes")
@@ -866,7 +870,6 @@ fn prompt_for_uninstall_confirmation(
completion_results: &[CompletionUninstallResult],
) -> Result<bool, String> {
use anstyle::Style;
- use worktrunk::styling::eprintln;
crate::output::flush_for_stderr_prompt().map_err(|e| e.to_string())?;
@@ -881,11 +884,12 @@ fn prompt_for_uninstall_confirmation(
"shell extension & completions"
};
- eprintln!(
+ crate::output::print(format!(
"{} {} {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 {
@@ -893,11 +897,12 @@ fn prompt_for_uninstall_confirmation(
let shell = result.shell;
let path = format_path_for_display(&result.path);
- eprintln!(
+ crate::output::print(format!(
"{} {} completions for {bold}{shell}{bold:#} @ {bold}{path}{bold:#}",
result.action.symbol(),
result.action.description(),
- );
+ ))
+ .map_err(|e| e.to_string())?;
}
prompt_yes_no()
@@ -947,7 +952,7 @@ pub fn handle_show_theme() -> Result<(), String> {
// Gutter - quoted content
crate::output::print(info_message("Gutter formatting (quoted content):"))
.map_err(|e| e.to_string())?;
- crate::output::gutter(format_with_gutter(
+ crate::output::print(format_with_gutter(
"[commit-generation]\ncommand = \"llm --model claude\"",
None,
))
@@ -958,7 +963,7 @@ pub fn handle_show_theme() -> Result<(), String> {
// Gutter - bash code
crate::output::print(info_message("Gutter formatting (shell code):"))
.map_err(|e| e.to_string())?;
- crate::output::gutter(format_bash_with_gutter(
+ crate::output::print(format_bash_with_gutter(
"eval \"$(wt config shell init bash)\"",
))
.map_err(|e| e.to_string())?;
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 14c2571fe..a28f484f7 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -102,7 +102,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
output::print(error_message(cformat!(
"Failed in <bold>{display_name}</> (spawn failed)"
)))?;
- output::gutter(format_with_gutter(&err, None))?;
+ output::print(format_with_gutter(&err, None))?;
failed.push(display_name.to_string());
}
Err(CommandError::ExitCode(exit_code)) => {
@@ -133,7 +133,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
if total == 1 { "" } else { "s" }
)))?;
let failed_list = failed.join("\n");
- output::gutter(format_with_gutter(&failed_list, None))?;
+ output::print(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/hooks.rs b/src/commands/hooks.rs
index 736abcd95..ad04836f7 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -47,7 +47,7 @@ impl SourcedCommand {
None => format!("{full_label}:"),
};
crate::output::print(progress_message(message))?;
- crate::output::gutter(format_bash_with_gutter(&self.prepared.expanded))?;
+ crate::output::print(format_bash_with_gutter(&self.prepared.expanded))?;
Ok(())
}
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 44104c91d..aeb65d374 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -84,7 +84,7 @@ pub fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::
.to_string();
if !diff_stat.is_empty() {
- crate::output::gutter(format_with_gutter(&diff_stat, None))?;
+ crate::output::print(format_with_gutter(&diff_stat, None))?;
}
Ok(())
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 5bf67a5bc..2e313808c 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -391,7 +391,7 @@ fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {
)))?;
let joined_files = files.join("\n");
- crate::output::gutter(format_with_gutter(&joined_files, None))?;
+ crate::output::print(format_with_gutter(&joined_files, None))?;
Ok(())
}
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 5414a7b0f..5a9639ee3 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -402,7 +402,7 @@ pub fn handle_squash(
// Display the generated commit message
let formatted_message = generator.format_message_for_display(&commit_message);
- crate::output::gutter(format_with_gutter(&formatted_message, None))?;
+ crate::output::print(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])
@@ -890,7 +890,7 @@ fn render_hook_commands(
cmd.template.clone()
};
- write!(out, "{}", format_bash_with_gutter(&command_text))?;
+ writeln!(out, "{}", format_bash_with_gutter(&command_text))?;
}
Ok(())
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index ce2a00b43..0d2774c6b 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -984,7 +984,7 @@ pub fn handle_push(
"--oneline",
&format!("{}..HEAD", target_branch),
])?;
- crate::output::gutter(format_with_gutter(&log_output, None))?;
+ crate::output::print(format_with_gutter(&log_output, None))?;
// Show diff statistics
super::show_diffstat(&repo, &format!("{}..HEAD", target_branch))?;
diff --git a/src/git/error.rs b/src/git/error.rs
index 47851c3a6..a87653288 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -325,7 +325,7 @@ impl std::fmt::Display for GitError {
files,
worktree_path,
} => {
- writeln!(
+ write!(
f,
"{}",
error_message(cformat!(
@@ -334,7 +334,7 @@ impl std::fmt::Display for GitError {
)?;
if !files.is_empty() {
let joined_files = files.join("\n");
- write!(f, "{}", format_with_gutter(&joined_files, None))?;
+ write!(f, "\n{}\n", format_with_gutter(&joined_files, None))?;
}
let path_display = format_path_for_display(worktree_path);
write!(
@@ -359,7 +359,7 @@ impl std::fmt::Display for GitError {
))
)?;
if !commits_formatted.is_empty() {
- write!(f, "\n{}", format_with_gutter(commits_formatted, None))?;
+ write!(f, "\n{}\n", format_with_gutter(commits_formatted, None))?;
}
// Context-appropriate hint
let merge_cmd = suggest_command("merge", &[target_branch], &[]);
@@ -480,9 +480,9 @@ impl std::fmt::Display for GitError {
write!(
f,
"{}\n{}\n{}",
- error_block.trim_end(),
+ error_block,
info_message("Ran command:"),
- command_gutter.trim_end()
+ command_gutter
)
}
diff --git a/src/main.rs b/src/main.rs
index a984b6b30..4f2849a1d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -835,7 +835,7 @@ fn main() {
crate::output::print(warning_message(
"Completions require compinit; add to ~/.zshrc before the wt line:",
))?;
- crate::output::gutter(
+ crate::output::print(
worktrunk::styling::format_bash_with_gutter(
"autoload -Uz compinit && compinit",
),
@@ -1607,7 +1607,7 @@ fn main() {
// Has context: msg is context, chain contains intermediate + root cause
let _ = output::print(error_message(&msg));
let chain_text = chain.join("\n");
- let _ = output::gutter(format_with_gutter(&chain_text, None));
+ let _ = output::print(format_with_gutter(&chain_text, None));
} else if msg.contains('\n') {
// Multiline error without context - this shouldn't happen if all
// errors have proper context. Fail in tests, log in production.
@@ -1616,7 +1616,7 @@ fn main() {
}
log::warn!("Multiline error without context: {msg}");
let _ = output::print(error_message("Command failed"));
- let _ = output::gutter(format_with_gutter(&msg, None));
+ let _ = output::print(format_with_gutter(&msg, None));
} else {
// Single-line error without context: inline with emoji
let _ = output::print(error_message(&msg));
diff --git a/src/output/global.rs b/src/output/global.rs
index 544c07405..956c87733 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -112,17 +112,6 @@ pub fn print(message: impl Into<String>) -> io::Result<()> {
stderr().flush()
}
-/// Emit gutter-formatted content to stderr
-///
-/// Gutter content has its own visual structure (column 0 gutter + content),
-/// so no additional emoji is added. Use with `format_with_gutter()` or `format_bash_with_gutter()`.
-///
-/// Note: Gutter content is pre-formatted with its own newlines, so we use write! not writeln!.
-pub fn gutter(content: impl Into<String>) -> io::Result<()> {
- write!(stderr(), "{}", content.into())?;
- stderr().flush()
-}
-
/// Emit a blank line for visual separation
pub fn blank() -> io::Result<()> {
eprintln!();
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index a75f15b79..4ac3c05ef 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -186,7 +186,7 @@ fn handle_branch_deletion_result(
super::print(error_message(cformat!(
"Failed to delete branch <bold>{branch_name}</>"
)))?;
- super::gutter(format_with_gutter(&e.to_string(), None))?;
+ super::print(format_with_gutter(&e.to_string(), None))?;
Err(e)
}
}
@@ -400,7 +400,7 @@ pub fn execute_user_command(command: &str) -> anyhow::Result<()> {
// Show what command is being executed (section header + gutter content)
super::print(progress_message("Executing (--execute):"))?;
- super::gutter(format_bash_with_gutter(command))?;
+ super::print(format_bash_with_gutter(command))?;
super::execute(command)?;
diff --git a/src/output/mod.rs b/src/output/mod.rs
index ff146c48b..2d4089303 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -31,7 +31,7 @@ pub mod handlers;
// Re-export the public API
pub use global::{
- blank, change_directory, data, execute, flush, flush_for_stderr_prompt, gutter,
+ blank, change_directory, data, execute, flush, flush_for_stderr_prompt,
is_shell_integration_active, print, shell_integration_hint, table, terminate_output,
};
// Re-export output handlers
diff --git a/src/styling/format.rs b/src/styling/format.rs
index 5754a036e..adaa6aa02 100644
--- a/src/styling/format.rs
+++ b/src/styling/format.rs
@@ -110,7 +110,6 @@ pub(super) fn wrap_text_at_width(text: &str, max_width: usize) -> Vec<String> {
/// ```
pub fn format_with_gutter(content: &str, max_width: Option<usize>) -> String {
let gutter = super::GUTTER;
- let mut output = String::new();
// Use provided width or detect terminal width (respects COLUMNS env var)
let term_width = max_width.unwrap_or_else(get_terminal_width);
@@ -118,16 +117,17 @@ pub fn format_with_gutter(content: &str, max_width: Option<usize>) -> String {
// Account for gutter (1) + space (1)
let available_width = term_width.saturating_sub(2);
- for line in content.lines() {
- // Wrap the line at word boundaries
- let wrapped_lines = wrap_text_at_width(line, available_width);
-
- for wrapped_line in wrapped_lines {
- output.push_str(&format!("{gutter} {gutter:#} {wrapped_line}\n"));
- }
- }
+ // Build lines without trailing newline - caller is responsible for element separation
+ let lines: Vec<String> = content
+ .lines()
+ .flat_map(|line| {
+ wrap_text_at_width(line, available_width)
+ .into_iter()
+ .map(|wrapped_line| format!("{gutter} {gutter:#} {wrapped_line}"))
+ })
+ .collect();
- output
+ lines.join("\n")
}
/// Wrap ANSI-styled text at word boundaries, preserving styles across line breaks
@@ -184,7 +184,6 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->
let gutter = super::GUTTER;
let reset = anstyle::Reset;
let dim = anstyle::Style::new().dimmed();
- let mut output = String::new();
// Calculate available width for content
let term_width = width_override.unwrap_or_else(get_terminal_width);
@@ -230,6 +229,9 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->
let mut highlighter = Highlighter::new();
+ // Build lines without trailing newline - caller is responsible for element separation
+ let mut output_lines: Vec<String> = Vec::new();
+
// Process each line separately - this is required because tree-sitter's bash
// grammar fails to highlight multi-line commands when `&&` appears at line ends.
// Per-line processing gives proper highlighting for each line's content.
@@ -240,7 +242,7 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->
// Fallback: if highlighting fails, use plain dim
styled_line.push_str(line);
for wrapped in wrap_styled_text(&styled_line, available_width) {
- output.push_str(&format!("{gutter} {gutter:#} {wrapped}{reset}\n"));
+ output_lines.push(format!("{gutter} {gutter:#} {wrapped}{reset}"));
}
continue;
};
@@ -291,13 +293,13 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->
}
}
- // Wrap and output with gutter
+ // Wrap and collect gutter lines
for wrapped in wrap_styled_text(&styled_line, available_width) {
- output.push_str(&format!("{gutter} {gutter:#} {wrapped}{reset}\n"));
+ output_lines.push(format!("{gutter} {gutter:#} {wrapped}{reset}"));
}
}
- output
+ output_lines.join("\n")
}
/// Formats bash/shell commands with syntax highlighting and gutter
@@ -403,9 +405,9 @@ mod tests {
#[test]
fn test_format_with_gutter_basic() {
let result = format_with_gutter("hello", Some(80));
- // Should have gutter formatting
+ // Should have gutter formatting, no trailing newline (caller adds it)
assert!(result.contains("hello"));
- assert!(result.ends_with('\n'));
+ assert!(!result.ends_with('\n'));
}
#[test]
@@ -414,8 +416,8 @@ mod tests {
// Each line should be formatted separately
assert!(result.contains("line1"));
assert!(result.contains("line2"));
- // Should have 2 newlines (one per line)
- assert_eq!(result.matches('\n').count(), 2);
+ // Should have 1 newline (between lines, not trailing)
+ assert_eq!(result.matches('\n').count(), 1);
}
#[test]
@@ -435,11 +437,11 @@ mod tests {
fn test_format_with_gutter_wrapping() {
// Use a very narrow width to force wrapping
let result = format_with_gutter("word1 word2 word3 word4", Some(15));
- // Content should be wrapped to multiple lines
+ // Content should be wrapped to multiple lines (newlines between, not trailing)
let line_count = result.matches('\n').count();
assert!(
- line_count > 1,
- "Expected multiple lines, got {}",
+ line_count >= 1,
+ "Expected at least one newline (between wrapped lines), got {}",
line_count
);
}
@@ -482,7 +484,8 @@ mod tests {
let result = format_bash_with_gutter_at_width("echo hello", 80);
assert!(result.contains("echo"));
assert!(result.contains("hello"));
- assert!(result.ends_with('\n'));
+ // No trailing newline - caller is responsible for element separation
+ assert!(!result.ends_with('\n'));
}
#[test]
@@ -491,8 +494,8 @@ mod tests {
let result = format_bash_with_gutter_at_width("echo line1\necho line2", 80);
assert!(result.contains("line1"));
assert!(result.contains("line2"));
- // Two lines should have two newlines
- assert_eq!(result.matches('\n').count(), 2);
+ // Two lines should have one newline (between, not trailing)
+ assert_eq!(result.matches('\n').count(), 1);
}
#[test]
diff --git a/src/styling/mod.rs b/src/styling/mod.rs
index 9ea3ab4d0..13cbad2f3 100644
--- a/src/styling/mod.rs
+++ b/src/styling/mod.rs
@@ -345,13 +345,17 @@ command = "npm install"
let command = "pre-commit run --all-files";
let result = format_bash_with_gutter(command);
- // The output should end with ANSI reset code followed by newline
+ // The output should end with ANSI reset code (no trailing newline - caller adds it)
// ANSI reset is \x1b[0m (ESC[0m)
assert!(
- result.ends_with("\x1b[0m\n"),
- "Bash gutter formatting should end with ANSI reset code followed by newline, got: {:?}",
+ result.ends_with("\x1b[0m"),
+ "Bash gutter formatting should end with ANSI reset code, got: {:?}",
result.chars().rev().take(20).collect::<String>()
);
+ assert!(
+ !result.ends_with('\n'),
+ "Bash gutter formatting should not have trailing newline"
+ );
// Verify the reset appears at the end of EVERY line (for multi-line commands)
let multi_line_command = "npm install && \\\n npm run build";
@@ -370,10 +374,10 @@ command = "npm install"
}
}
- // Most importantly: the final output should end with reset + newline
+ // Most importantly: the final output should end with reset (no trailing newline)
assert!(
- multi_result.ends_with("\x1b[0m\n"),
- "Multi-line bash gutter formatting should end with ANSI reset + newline"
+ multi_result.ends_with("\x1b[0m"),
+ "Multi-line bash gutter formatting should end with ANSI reset"
);
}
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 879ea7f78..9150f28ae 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -624,7 +624,7 @@ fn test_state_clear_all_nothing_to_clear(repo: TestRepo) {
fn test_state_get_empty(repo: TestRepo) {
let output = wt_state_get_cmd(&repo).output().unwrap();
assert!(output.status.success());
- assert_snapshot!(normalize_log_path(&String::from_utf8_lossy(&output.stderr)), @r"
+ assert_snapshot!(normalize_log_path(&String::from_utf8_lossy(&output.stderr)), @"
DEFAULT BRANCH
  main
diff --git a/tests/snapshots/integration__integration_tests__list__git_error_warning.snap b/tests/snapshots/integration__integration_tests__list__git_error_warning.snap
index 6b37d6a00..9e01f5930 100644
--- a/tests/snapshots/integration__integration_tests__list__git_error_warning.snap
+++ b/tests/snapshots/integration__integration_tests__list__git_error_warning.snap
@@ -40,5 +40,4 @@ exit_code: 0
  feature: committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000000^{tree}': unknown revision or path not in the
  working tree.)
  feature: has-file-changes (fatal: Invalid symmetric difference expression main...feature)
-  feature: working-tree-diff (fatal: bad object HEAD)
-
+  feature: working-tree-diff (fatal: bad object HEAD)