Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor output API to use message formatting functions
Maximilian Roos6a23808e7c89
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8d6dae3d0..9f85c2684 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -199,24 +199,25 @@ Seven canonical message patterns with their emojis:6. **Info**: ⚪ (neutral status, system feedback, metadata)7. **Prompts**: ❓ (questions requiring user input)-**Output functions automatically add emoji AND semantic color.** Callers provide content with optional inner styling (like `<bold>`):+**Message formatting functions** add emoji AND semantic color. Callers provide content with optional inner styling (like `<bold>`), then pass to `output::print()`:```rust-// Simple message - function adds emoji + color-output::success("Created worktree")?;-output::hint("Run 'wt config' to configure")?;+// Simple message - formatting function adds emoji + color+output::print(success_message("Created worktree"))?;+output::print(hint_message("Run 'wt config' to configure"))?;// With inner styling - use cformat! for bold/dim within the message-output::success(cformat!("Created worktree for <bold>{branch}</>"))?;-output::warning(cformat!("Branch <bold>{name}</> not found"))?;+output::print(success_message(cformat!("Created worktree for <bold>{branch}</>")))?;+output::print(warning_message(cformat!("Branch <bold>{name}</> not found")))?;```-**Semantic colors added automatically:**-- `success()` → green-- `progress()` → cyan-- `hint()` → dimmed-- `warning()` → yellow-- `info()` → no color (neutral status)+**Semantic colors from formatting functions:**+- `success_message()` → green+- `progress_message()` → cyan+- `hint_message()` → dimmed+- `warning_message()` → yellow+- `info_message()` → no color (neutral status)+- `error_message()` → red**Every user-facing message requires either an emoji or a gutter** for consistent visual separation.@@ -236,11 +237,11 @@ output::warning(cformat!("Branch <bold>{name}</> not found"))?;**Directive mode** additionally emits a shell script to stdout at the end.-Use the output system (`output::success()`, `output::progress()`, etc.) to handle both modes automatically. Never write directly to stdout/stderr in command code.+Use the output system (`output::print()` with message formatting functions) to handle both modes automatically. Never write directly to stdout/stderr in command code.```rust// ✅ GOOD - use output system (handles both modes)-output::success("Branch created")?;+output::print(success_message("Branch created"))?;// ❌ BAD - direct writes bypass output systemprintln!("Branch created");@@ -260,9 +261,9 @@ Output should appear immediately adjacent to the operations it describes. ProgreSequential operations should show immediate feedback:```rustfor item in items {- output::progress(format!("Removing {item}..."))?;+ output::print(progress_message(format!("Removing {item}...")))?;perform_operation(item)?;- output::success(format!("Removed {item}"))?; // Immediate feedback+ output::print(success_message(format!("Removed {item}")))?; // Immediate feedback}```@@ -283,9 +284,9 @@ Progress messages should include all relevant details (what's being done, counts```rust// ✅ GOOD - detailed progress, minimal success-output::progress("Squashing 3 commits & working tree changes into a single commit (5 files, +60)...")?;+output::print(progress_message("Squashing 3 commits & working tree changes into a single commit (5 files, +60)..."))?;perform_squash()?;-output::success("Squashed @ a1b2c3d")?;+output::print(success_message("Squashed @ a1b2c3d"))?;```### Style Constants@@ -301,17 +302,17 @@ For all other styling, use color-print tags in `cformat!`: `<red>`, `<green>`, `### Styling in Command Code-Use `output::` functions with `cformat!` for styled content. The output function adds the emoji + semantic color, and `cformat!` handles inner styling:+Use `output::print()` with message formatting functions. The formatting function adds the emoji + semantic color, and `cformat!` handles inner styling:```rust-// ✅ GOOD - output:: handles emoji + outer color, cformat! handles inner styling-output::success(cformat!("Created <bold>{branch}</> from <bold>{base}</>"))?;-output::warning(cformat!("Branch <bold>{name}</> has <dim>uncommitted changes</>"))?;-output::hint(cformat!("Run <bright-black>wt merge</> to continue"))?;+// ✅ GOOD - formatting function handles emoji + outer color, cformat! handles inner styling+output::print(success_message(cformat!("Created <bold>{branch}</> from <bold>{base}</>")))?;+output::print(warning_message(cformat!("Branch <bold>{name}</> has <dim>uncommitted changes</>")))?;+output::print(hint_message(cformat!("Run <bright-black>wt merge</> to continue")))?;// ✅ GOOD - plain strings work too (no inner styling needed)-output::progress("Rebasing onto main...")?;-output::hint("No changes to commit")?;+output::print(progress_message("Rebasing onto main..."))?;+output::print(hint_message("No changes to commit"))?;```**Available color-print tags:** `<bold>`, `<dim>`, `<bright-black>`, `<red>`, `<green>`, `<yellow>`, `<cyan>`, `<magenta>`@@ -388,19 +389,19 @@ Use `format_with_gutter()` for quoted content. Gutter content displays external```rust// Show warning message, then external error in gutter-output::warning(cformat!("Could not delete branch <bold>{branch_name}</>"))?;+output::print(warning_message(cformat!("Could not delete branch <bold>{branch_name}</>")))?;output::gutter(format_with_gutter(&e.to_string(), "", None))?;```-**Linebreaks:** Gutter content requires a single newline before it, never double newlines. Output functions (`progress()`, `success()`, etc.) use `println!()` internally, adding a trailing newline. Messages passed to these functions should not include `\n`:+**Linebreaks:** Gutter content requires a single newline before it, never double newlines. The `output::print()` function uses `println!()` internally, adding a trailing newline. Messages passed to it should not include `\n`:```rust// ✅ GOOD - no trailing \n-output::progress("Merging...")?;+output::print(progress_message("Merging..."))?;output::gutter(format_with_gutter(&log, "", None))?;// ❌ BAD - trailing \n creates blank line-output::progress("Merging...\n")?;+output::print(progress_message("Merging...\n"))?;```### Error Message Formatting@@ -480,7 +481,7 @@ if mode == OutputMode::Interactive {}// ✅ ALWAYS DO THIS-output::success("Success!")?;+output::print(success_message("Success!"))?;```Decide once at the edge (`main()`), initialize globally, trust internally:@@ -490,7 +491,7 @@ Decide once at the edge (`main()`), initialize globally, trust internally:output::initialize(if internal { OutputMode::Directive } else { OutputMode::Interactive });// Everywhere else - just use the output functions-output::success("Created worktree")?;+output::print(success_message("Created worktree"))?;output::change_directory(&path)?;```@@ -498,12 +499,7 @@ output::change_directory(&path)?;The output module (`src/output/global.rs`) provides:-- `success(message)` - Successful completion (✅, both modes)-- `progress(message)` - Operations in progress (🔄, both modes)-- `info(message)` - Neutral status/metadata (⚪, both modes)-- `warning(message)` - Non-blocking issues (🟡, both modes)-- `hint(message)` - Actionable suggestions (💡, both modes)-- `print(message)` - Write message as-is (caller formats, both modes)+- `print(message)` - Write message as-is (use with message formatting functions)- `shell_integration_hint(message)` - Shell integration hints (💡, suppressed in directive)- `gutter(content)` - Gutter-formatted content (use with `format_with_gutter()`)- `blank()` - Blank line for visual separation@@ -515,7 +511,16 @@ The output module (`src/output/global.rs`) provides:- `flush_for_stderr_prompt()` - Flush before interactive prompts- `terminate_output()` - Emit shell script in directive mode (no-op in interactive)-For the complete API, see `src/output/global.rs`.+**Message formatting functions** (from `worktrunk::styling`):++- `success_message(content)` - ✅ green+- `progress_message(content)` - 🔄 cyan+- `info_message(content)` - ⚪ no color+- `warning_message(content)` - 🟡 yellow+- `hint_message(content)` - 💡 dimmed+- `error_message(content)` - ❌ red++For the complete API, see `src/output/global.rs` and `src/styling/constants.rs`.### Adding New Output Functionsdiff --git a/src/cli.rs b/src/cli.rsindex 276f42ff8..2760aed57 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -226,6 +226,17 @@ Detects various forms of the integration pattern regardless of:#[arg(short, long)]force: bool,},++ /// Show output theme samples+ #[command(after_long_help = r#"## Output Theme++Displays samples of all output message types:+- Progress, success, error, warning, hint, info+- Gutter formatting for quoted content+- Prompts for user input++Use this to preview how worktrunk output will appear in the terminal."#)]+ ShowTheme,}#[derive(Subcommand)]diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 1173dd70e..83df81d0d 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -4,7 +4,8 @@ use std::path::{Path, PathBuf};use worktrunk::path::format_path_for_display;use worktrunk::shell::{self, Shell};use worktrunk::styling::{- INFO_EMOJI, PROGRESS_EMOJI, SUCCESS_EMOJI, format_bash_with_gutter, warning_message,+ INFO_EMOJI, PROGRESS_EMOJI, PROMPT_EMOJI, SUCCESS_EMOJI, format_bash_with_gutter,+ format_with_gutter, warning_message,};pub struct ConfigureResult {@@ -882,3 +883,74 @@ fn prompt_for_uninstall_confirmation(prompt_yes_no()}++/// Show samples of all output message types+pub fn handle_show_theme() -> Result<(), String> {+ 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())?;++ // Success+ crate::output::print(success_message(cformat!(+ "Created worktree for <bold>feature</> @ <bold>/path/to/worktree</>"+ )))+ .map_err(|e| e.to_string())?;++ // Error+ crate::output::print(error_message(cformat!("Branch <bold>feature</> not found")))+ .map_err(|e| e.to_string())?;++ // Warning+ crate::output::print(warning_message(cformat!(+ "Branch <bold>feature</> has uncommitted changes"+ )))+ .map_err(|e| e.to_string())?;++ // Hint+ crate::output::print(hint_message(cformat!(+ "Run <bright-black>wt merge</> to rebase onto main"+ )))+ .map_err(|e| e.to_string())?;++ // Info+ crate::output::print(info_message(cformat!("Showing <bold>5</> worktrees")))+ .map_err(|e| e.to_string())?;++ crate::output::blank().map_err(|e| e.to_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(+ "[commit-generation]\ncommand = \"llm --model claude\"",+ "",+ None,+ ))+ .map_err(|e| e.to_string())?;++ crate::output::blank().map_err(|e| e.to_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(+ "eval \"$(wt config shell init bash)\"",+ "",+ ))+ .map_err(|e| e.to_string())?;++ crate::output::blank().map_err(|e| e.to_string())?;++ // Prompt+ crate::output::print(info_message("Prompt formatting:")).map_err(|e| e.to_string())?;+ crate::output::print(format!("{PROMPT_EMOJI} Proceed? [y/N] ")).map_err(|e| e.to_string())?;++ Ok(())+}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 8fdfb263d..393eb67ec 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -21,7 +21,9 @@ pub use config::{handle_cache_clear, handle_cache_refresh, handle_cache_show, handle_config_create,handle_config_show, handle_var_clear, handle_var_get, handle_var_set,};-pub use configure_shell::{ConfigAction, handle_configure_shell, handle_unconfigure_shell};+pub use configure_shell::{+ ConfigAction, handle_configure_shell, handle_show_theme, handle_unconfigure_shell,+};pub use init::handle_init;pub use list::handle_list;pub use merge::{execute_pre_remove_commands, handle_merge};diff --git a/src/main.rs b/src/main.rsindex 36fad022e..b8130abc4 100644--- a/src/main.rs+++ b/src/main.rs@@ -29,7 +29,7 @@ use commands::{ConfigAction, RebaseResult, SquashResult, handle_cache_clear, handle_cache_refresh,handle_cache_show, handle_config_create, handle_config_show, handle_configure_shell,handle_init, handle_list, handle_merge, handle_rebase, handle_remove, handle_remove_by_path,- handle_remove_current, handle_squash, handle_standalone_add_approvals,+ handle_remove_current, handle_show_theme, handle_squash, handle_standalone_add_approvals,handle_standalone_clear_approvals, handle_standalone_commit, handle_standalone_run_hook,handle_switch, handle_unconfigure_shell, handle_var_clear, handle_var_get, handle_var_set,resolve_worktree_path_first,@@ -870,6 +870,9 @@ fn main() {Ok(())})}+ ConfigShellCommand::ShowTheme => {+ handle_show_theme().map_err(|e| anyhow::anyhow!("{}", e))+ }}}ConfigCommand::Create { project } => handle_config_create(project),diff --git a/tests/integration_tests/config_show_theme.rs b/tests/integration_tests/config_show_theme.rsnew file mode 100644index 000000000..28fca8ec9--- /dev/null+++ b/tests/integration_tests/config_show_theme.rs@@ -0,0 +1,11 @@+use crate::common::wt_command;+use insta_cmd::assert_cmd_snapshot;++/// Test `wt config shell show-theme` shows all output message types+#[test]+fn test_show_theme() {+ let mut cmd = wt_command();+ cmd.arg("config").arg("shell").arg("show-theme");++ assert_cmd_snapshot!(cmd);+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex f35a30e78..862724890 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -14,6 +14,7 @@ pub mod completion_validation;pub mod config_cache;pub mod config_init;pub mod config_show;+pub mod config_show_theme;pub mod config_var;pub mod configure_shell;pub mod default_branch;diff --git a/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snap b/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snapnew file mode 100644index 000000000..047088c12--- /dev/null+++ b/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snap@@ -0,0 +1,36 @@+---+source: tests/integration_tests/config_show_theme.rs+info:+ program: wt+ args:+ - config+ - shell+ - show-theme+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_EDITOR: ""+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+🔄 [36mRebasing [1mfeature[22m onto [1mmain[22m...[39m+✅ [32mCreated worktree for [1mfeature[22m @ [1m/path/to/worktree[22m[39m+❌ [31mBranch [1mfeature[22m not found[39m+🟡 [33mBranch [1mfeature[22m has uncommitted changes[39m+💡 [2mRun [90mwt merge[39m to rebase onto main[22m+⚪ Showing [1m5[22m worktrees++⚪ Gutter formatting (quoted content):+[107m [0m [commit-generation]+[107m [0m command = "llm --model claude"++⚪ Gutter formatting (shell code):+[107m [0m [2m[0m[2m[34meval[0m[2m [0m[2m[32m"$([0m[2m[34mwt[0m[2m config shell init bash)"[0m[2m[0m++⚪ Prompt formatting:+❓ Proceed? [y/N]diff --git a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap b/tests/snapshots/integration__integration_tests__help__help_config_shell.snapindex c096f7ddf..1f26f48ca 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_shell.snap@@ -22,9 +22,10 @@ wt config shell - Shell integration setupUsage: [1m[36mwt config shell[0m [36m[OPTIONS][0m [36m<COMMAND>[0m[1m[32mCommands:[0m- [1m[36minit[0m Generate shell integration code- [1m[36minstall[0m Write shell integration to config files- [1m[36muninstall[0m Remove shell integration from config files+ [1m[36minit[0m Generate shell integration code+ [1m[36minstall[0m Write shell integration to config files+ [1m[36muninstall[0m Remove shell integration from config files+ [1m[36mshow-theme[0m Show output theme samples[1m[32mOptions:[0m[1m[36m-h[0m, [1m[36m--help[0m Print help