Skip to content

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

feat: Add help pager for improved CLI help viewing

Maximilian Roos625ab19edb38
diff --git a/src/help_pager.rs b/src/help_pager.rs
new file mode 100644
index 000000000..3cb1ba596
--- /dev/null
+++ b/src/help_pager.rs
@@ -0,0 +1,140 @@
+//! Help text pager integration for CLI help output.
+//!
+//! Provides pager support for `--help` output, following git's pager precedence:
+//! GIT_PAGER → core.pager config → PAGER environment variable → "less" default.
+//!
+//! # Difference from diff pager
+//!
+//! This pager is INTERACTIVE (spawned with TTY access) unlike the diff renderer
+//! in src/git/repository/mod.rs which is DETACHED (spawned via setsid). This is
+//! intentional:
+//!
+//! - Help pager: Top-level user command, needs TTY for interactive scrolling
+//! - Diff renderer: Used in TUI contexts (skim preview), must be detached to
+//! prevent hangs from TTY access
+//!
+//! Both follow git's pager detection but spawn differently based on their usage context.
+
+use std::io::{IsTerminal, Write};
+use std::process::{Command, Stdio};
+
+/// Detect pager for help output, following git's pager precedence.
+///
+/// Checks in order: GIT_PAGER → git config core.pager → PAGER → "less"
+fn detect_help_pager() -> Option<String> {
+ let validate = |s: &str| -> Option<String> {
+ let trimmed = s.trim();
+ (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
+ };
+
+ // Check environment variables in git's precedence order
+ std::env::var("GIT_PAGER")
+ .ok()
+ .and_then(|s| validate(&s))
+ .or_else(|| {
+ // Try git config core.pager
+ Command::new("git")
+ .args(["config", "--get", "core.pager"])
+ .output()
+ .inspect_err(|e| log::debug!("Failed to run git config: {}", e))
+ .ok()
+ .and_then(|output| {
+ if !output.status.success() {
+ log::debug!("git config exited with status: {}", output.status);
+ }
+ String::from_utf8(output.stdout)
+ .inspect_err(|e| log::debug!("git config output not UTF-8: {}", e))
+ .ok()
+ .and_then(|s| validate(&s))
+ })
+ })
+ .or_else(|| std::env::var("PAGER").ok().and_then(|s| validate(&s)))
+ .or_else(|| Some("less".to_string())) // Default fallback (may fail if less not installed)
+}
+
+/// Show help text through a pager with TTY access for interactive scrolling.
+///
+/// Only uses pager when stdout is a terminal. Falls back to direct output if:
+/// - No pager configured (prints directly)
+/// - stdout is not a TTY (prints directly)
+/// - Pager spawn fails (returns error)
+pub fn show_help_in_pager(help_text: &str) -> std::io::Result<()> {
+ let Some(pager_cmd) = detect_help_pager() else {
+ log::debug!("No pager configured, printing help directly");
+ print!("{}", help_text);
+ return Ok(());
+ };
+
+ // Check if stdout OR stderr is a TTY
+ // stdout check: direct invocation (cargo run -- --help)
+ // stderr check: shell wrapper (wt --help) redirects stdout but preserves stderr
+ let is_tty = std::io::stdout().is_terminal() || std::io::stderr().is_terminal();
+
+ if !is_tty {
+ log::debug!("Neither stdout nor stderr is a TTY, skipping pager");
+ print!("{}", help_text);
+ return Ok(());
+ }
+
+ log::debug!("Invoking pager: {}", pager_cmd);
+
+ // LESS flags: F=quit if one screen, R=allow colors, X=no termcap init
+ let less_flags = std::env::var("LESS").unwrap_or_else(|_| "FRX".to_string());
+
+ // Always send pager output to stderr (standard for help text, like git)
+ // This works in all cases: direct invocation, shell wrapper, piping, etc.
+ let final_cmd = format!("{} >&2", pager_cmd);
+
+ // Spawn pager with TTY access (interactive, unlike detached diff renderer)
+ #[cfg(unix)]
+ let mut child = Command::new("sh")
+ .arg("-c")
+ .arg(&final_cmd)
+ .stdin(Stdio::piped())
+ .env("LESS", &less_flags)
+ .spawn()?;
+
+ #[cfg(windows)]
+ let mut child = Command::new("cmd")
+ .arg("/C")
+ .arg(&final_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(())
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn test_validate_excludes_cat() {
+ let validate = |s: &str| -> Option<String> {
+ let trimmed = s.trim();
+ (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
+ };
+
+ assert_eq!(validate("cat"), None);
+ assert_eq!(validate(" cat "), None);
+ assert_eq!(validate(""), None);
+ assert_eq!(validate(" "), None);
+ }
+
+ #[test]
+ fn test_validate_accepts_valid_pagers() {
+ let validate = |s: &str| -> Option<String> {
+ let trimmed = s.trim();
+ (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
+ };
+
+ assert_eq!(validate("less"), Some("less".to_string()));
+ assert_eq!(validate(" less "), Some("less".to_string()));
+ assert_eq!(validate("delta"), Some("delta".to_string()));
+ assert_eq!(validate("less -R"), Some("less -R".to_string()));
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index ec1bd15ef..997d4edec 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -9,6 +9,7 @@ mod cli;
mod commands;
mod completion;
mod display;
+mod help_pager;
mod llm;
mod output;
@@ -29,11 +30,50 @@ use output::{execute_user_command, handle_remove_output, handle_switch_output};
use cli::{Cli, Commands, ConfigCommand, StandaloneCommand, StatusAction};
+/// Try to handle --help flag with pager before clap processes it
+fn maybe_handle_help_with_pager() -> bool {
+ use clap::error::ErrorKind;
+
+ let mut cmd = Cli::command();
+ match cmd.try_get_matches_from_mut(std::env::args()) {
+ Ok(_) => false, // Normal args, not help
+ Err(err) => {
+ match err.kind() {
+ ErrorKind::DisplayHelp => {
+ // Handle help with pager
+ let help_text = err.to_string();
+ if let Err(e) = help_pager::show_help_in_pager(&help_text) {
+ // Pager failed, show help directly
+ log::debug!("Pager invocation failed: {}", e);
+ println!("{}", err);
+ }
+ process::exit(0);
+ }
+ ErrorKind::DisplayVersion => {
+ // Version display
+ println!("{}", err);
+ process::exit(0);
+ }
+ _ => {
+ // Not help or version - this will be re-parsed by Cli::parse() below
+ // which will handle the error with proper ANSI formatting
+ false
+ }
+ }
+ }
+ }
+}
+
fn main() {
if completion::maybe_handle_env_completion() {
return;
}
+ // Handle --help with pager before clap processes it
+ if maybe_handle_help_with_pager() {
+ return;
+ }
+
// TODO: Enhance error messages to show possible values for missing enum arguments
// Currently `wt init` doesn't show available shells, but `wt init invalid` does.
// Clap doesn't support this natively yet - see https://github.com/clap-rs/clap/issues/3320