Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: move pager-fallback into show_help_in_pager (#2575)
Maximilian Roos9fc1088cbe20
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 22c1925d4..7d1951c03 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -77,10 +77,7 @@ pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()render_runtime_info(&mut show_output)?;// Display through pager (config show is always long-form output)- if let Err(e) = show_help_in_pager(&show_output, true) {- log::debug!("Pager invocation failed: {}", e);- worktrunk::styling::println!("{}", show_output);- }+ show_help_in_pager(&show_output, true);Ok(())}diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 37397db42..1618e2ad5 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -604,11 +604,7 @@ pub fn handle_logs_list(format: SwitchFormat) -> anyhow::Result<()> {let mut out = String::new();render_all_log_sections(&mut out, &repo)?;- // Display through pager; fall back to direct stdout if pager unavailable- // (matches #2155 routing --help output to stdout).- if show_help_in_pager(&out, true).is_err() {- println!("{}", out);- }+ show_help_in_pager(&out, true);Ok(())}@@ -1324,11 +1320,7 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {writeln!(out, "{}", rendered.trim_end())?;}- // Display through pager; fall back to direct stdout if pager unavailable- if let Err(e) = show_help_in_pager(&out, true) {- log::debug!("Pager invocation failed: {}", e);- println!("{}", out);- }+ show_help_in_pager(&out, true);Ok(())}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 9970ded1d..8e9133573 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -435,10 +435,7 @@ pub fn handle_hook_show(ctx.as_ref(),)?;- // Display through pager; fall back to direct stdout if pager unavailable- if show_help_in_pager(&output, true).is_err() {- worktrunk::styling::println!("{}", output);- }+ show_help_in_pager(&output, true);Ok(())}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 69bf634e4..27dfc8f1c 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -177,20 +177,6 @@ fn print_dry_run(prompt: &str,commit_config: &worktrunk::config::CommitGenerationConfig,message: &str,-) -> anyhow::Result<()> {- print_dry_run_with(prompt, commit_config, message, |s| {- crate::help_pager::show_help_in_pager(s, true)- })-}--/// Inner form taking an injectable pager so the fallback path is unit-testable-/// (mid-write or wait failures from `show_help_in_pager` only happen against a-/// real TTY + a misbehaving pager, which is impractical to set up in a test).-fn print_dry_run_with(- prompt: &str,- commit_config: &worktrunk::config::CommitGenerationConfig,- message: &str,- pager: impl FnOnce(&str) -> std::io::Result<()>,) -> anyhow::Result<()> {let command_block = match commit_config.command@@ -209,10 +195,7 @@ fn print_dry_run_with(message_block = format_with_gutter(&formatted, None),);- if let Err(e) = pager(&out) {- log::debug!("Pager failed, falling back to stdout: {}", e);- println!("{}", out);- }+ crate::help_pager::show_help_in_pager(&out, true);Ok(())}@@ -2285,22 +2268,6 @@ mod tests {assert_eq!(fs::read_to_string(&dest).unwrap(), "content");}- /// `print_dry_run` falls back to direct stdout when the pager errors mid-write- /// (e.g. a misbehaving pager that closes stdin before reading). The fallback path- /// only fires against a real TTY in production; the inner form lets us drive it- /// with a stand-in pager that always returns Err.- #[test]- fn test_print_dry_run_falls_back_when_pager_errors() {- let config = worktrunk::config::CommitGenerationConfig::default();- let result = print_dry_run_with("the prompt", &config, "the message", |_| {- Err(std::io::Error::other("simulated pager failure"))- });- assert!(- result.is_ok(),- "fallback should swallow pager errors, got: {result:?}"- );- }-#[test]fn test_copy_and_remove_directory() {let tmp = tempfile::tempdir().unwrap();diff --git a/src/help.rs b/src/help.rsindex 2a3388788..c0ed69909 100644--- a/src/help.rs+++ b/src/help.rs@@ -54,7 +54,7 @@ use worktrunk::docs::{BADGE_EXPERIMENTAL_HTML, DEMO_MARKER_PREFIX, MARKER_CLOSE, MARKER_OPEN_PREFIX,SUBDOC_MARKER_PREFIX, convert_dollar_console_to_terminal,};-use worktrunk::styling::{eprintln, println};+use worktrunk::styling::eprintln;use crate::cli;@@ -241,10 +241,7 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::// show_help_in_pager checks if stdout or stderr is a TTY.// If neither is a TTY (e.g., `wt --help &>file`), it skips the pager.// use_pager=false for -h (short help), true for --help (long help)- if let Err(e) = crate::help_pager::show_help_in_pager(&help, use_pager) {- log::debug!("Pager invocation failed: {}", e);- println!("{}", help);- }+ crate::help_pager::show_help_in_pager(&help, use_pager);process::exit(0);}ErrorKind::DisplayVersion => {diff --git a/src/help_pager.rs b/src/help_pager.rsindex 22101edbe..1ce11f655 100644--- a/src/help_pager.rs+++ b/src/help_pager.rs@@ -76,22 +76,23 @@ fn detect_help_pager() -> Option<String> {/// - No pager configured (prints to stdout)/// - stdout is not a TTY (prints to stdout)/// - Pager spawn fails (prints to stdout)+/// - Pager closes stdin early or wait fails (prints to stdout)////// Help text goes to stdout — POSIX convention (`wt --help | less` should work/// without redirection), matching `cargo`, `curl`, `python`, `git <cmd> -h`,/// and `--version` (see #2072).-pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) -> std::io::Result<()> {+pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) {// Short help (-h) never uses a pagerif !use_pager {log::debug!("Short help (-h) requested, printing directly to stdout");print!("{}", help_text);- return Ok(());+ return;}let Some(pager_cmd) = detect_help_pager() else {log::debug!("No pager configured, printing help directly to stdout");print!("{}", help_text);- return Ok(());+ return;};// Only page when our output destination is a terminal.@@ -99,45 +100,32 @@ pub(crate) fn show_help_in_pager(help_text: &str, use_pager: bool) -> std::io::Rif !std::io::stdout().is_terminal() {log::debug!("stdout is not a TTY, skipping pager");print!("{}", help_text);- return Ok(());+ return;}log::debug!("Invoking pager: {}", pager_cmd);+ if let Err(e) = pipe_through_pager(&pager_cmd, help_text) {+ log::debug!("Pager failed, falling back to stdout: {}", e);+ print!("{}", help_text);+ }+}+/// Pipe `help_text` to the given pager command and wait for it to exit.+///+/// Spawn / write / wait failures all surface as `Err` so the caller can fall back+/// to direct stdout. Extracted from `show_help_in_pager` so the failure paths can+/// be exercised by unit tests with stand-in commands (`true`, `cat > /dev/null`)+/// that don't depend on a real TTY.+fn pipe_through_pager(pager_cmd: &str, help_text: &str) -> std::io::Result<()> {let less_flags = compute_less_flags(std::env::var("LESS").ok().as_deref());-- // Spawn pager with TTY access (interactive, unlike detached diff renderer).- // Pager output inherits our stdout — no redirection needed.- // Falls back to direct output if pager unavailable (e.g., less not installed)- let shell = match ShellConfig::get() {- Ok(shell) => shell,- Err(e) => {- log::debug!("Shell unavailable for pager: {}", e);- print!("{}", help_text);- return Ok(());- }- };+ let shell = ShellConfig::get().map_err(std::io::Error::other)?;log::debug!("$ {} (pager)", pager_cmd);- let mut cmd = shell.command(&pager_cmd);+ let mut cmd = shell.command(pager_cmd);worktrunk::shell_exec::scrub_directive_env_vars(&mut cmd);- let mut child = match cmd.stdin(Stdio::piped()).env("LESS", &less_flags).spawn() {- Ok(child) => child,- Err(e) => {- log::debug!(- "Failed to spawn pager '{}' with {}: {}",- pager_cmd,- shell.name,- e- );- print!("{}", help_text);- return Ok(());- }- };-+ let mut child = cmd.stdin(Stdio::piped()).env("LESS", &less_flags).spawn()?;if let Some(mut stdin) = child.stdin.take() {stdin.write_all(help_text.as_bytes())?;}-child.wait()?;Ok(())}@@ -154,6 +142,16 @@ fn compute_less_flags(user_less: Option<&str>) -> String {mod tests {use super::{compute_less_flags, parse_pager_value};+ /// `cat > /dev/null` exercises the full spawn → write → wait path with a+ /// stand-in pager that always succeeds. Covers every line of+ /// `pipe_through_pager`'s body; the `?` propagations are line-hit even on+ /// the Ok branch.+ #[cfg(unix)]+ #[test]+ fn test_pipe_through_pager_pipes_to_real_command() {+ super::pipe_through_pager("cat > /dev/null", "help text").expect("cat should succeed");+ }+#[test]fn test_validate_excludes_cat() {assert_eq!(parse_pager_value("cat"), None);