From 2b5e15eb31f85aa2d872b79287aba25fe410762c Mon Sep 17 00:00:00 2001 From: Jon Deibel Date: Tue, 10 Mar 2026 11:18:53 -0400 Subject: [PATCH 1/2] feat: smart pager for gw log When output exceeds terminal height, automatically pipe through a pager (less -R by default). The pager opens focused on the current branch with context above. Output that fits prints normally, and piped/redirected output is never paged. - Buffer tree output to string instead of println - Include PR data inline (removes retroactive ANSI cursor hack) - Pager selection: $GW_PAGER > $PAGER > less -R - --no-pager flag to force direct output - Focus line capped to prevent over-scrolling Co-Authored-By: Claude Opus 4.6 (1M context) --- src/cli.rs | 3 ++ src/commands/completions.rs | 5 +- src/commands/tree.rs | 76 +++++++++--------------------- src/main.rs | 4 +- src/ui.rs | 92 +++++++++++++++++++++++++++++++++++++ 5 files changed, 121 insertions(+), 59 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 8f099fa..fce2083 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -172,6 +172,9 @@ pub struct TreeArgs { /// Show PR status from GitHub (requires gh CLI, adds latency) #[arg(long)] pub pr: bool, + /// Disable pager, print directly to stdout + #[arg(long)] + pub no_pager: bool, } // -- Diff -- diff --git a/src/commands/completions.rs b/src/commands/completions.rs index 555e6e8..5a9fde3 100644 --- a/src/commands/completions.rs +++ b/src/commands/completions.rs @@ -130,7 +130,7 @@ _gw() { '--no-difftastic[Use regular git diff]' ;; log|tree) - _arguments '--pr[Show PR status]' + _arguments '--pr[Show PR status]' '--no-pager[Disable pager]' ;; split) _arguments \ @@ -253,7 +253,7 @@ _gw() { COMPREPLY=($(compgen -W "--stat --no-difftastic" -- "$cur")) ;; log|tree) - COMPREPLY=($(compgen -W "--pr" -- "$cur")) + COMPREPLY=($(compgen -W "--pr --no-pager" -- "$cur")) ;; split) if [[ "$prev" == "--plan" ]]; then @@ -368,6 +368,7 @@ complete -c gw -f -n '__gw_using_command diff' -l no-difftastic -d 'Use regular # tree complete -c gw -f -n '__gw_using_command log' -l pr -d 'Show PR status' +complete -c gw -f -n '__gw_using_command log' -l no-pager -d 'Disable pager' complete -c gw -f -n '__gw_using_command tree' -l pr -d 'Show PR status' # split diff --git a/src/commands/tree.rs b/src/commands/tree.rs index ca214f0..449d7bc 100644 --- a/src/commands/tree.rs +++ b/src/commands/tree.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::fmt::Write; use std::process::Child; use anyhow::Result; @@ -9,7 +10,7 @@ use crate::gh; use crate::git::Git; use crate::ui; -pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { +pub fn run(ctx: &Ctx, show_pr: bool, no_pager: bool) -> Result<()> { let stacks = ctx.load_all_stacks()?; if stacks.is_empty() { @@ -176,9 +177,10 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { HashMap::new() }; - // === Render === - let mut total_lines = 0; - let mut branch_positions: HashMap = HashMap::new(); + // === Render to buffer === + let mut buf = String::new(); + let mut current_branch_line: Option = None; + let mut line_num: usize = 0; for (base, stack_indices) in &by_base { let max_behind = stack_indices @@ -201,8 +203,8 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { String::new() }; - println!("{} {}{behind_tag}", "◇".cyan(), base.cyan().bold()); - total_lines += 1; + let _ = writeln!(buf, "{} {}{behind_tag}", "◇".cyan(), base.cyan().bold()); + line_num += 1; let total_stacks = stack_indices.len(); for (si, &stack_idx) in stack_indices.iter().enumerate() { @@ -226,13 +228,14 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { format!(" {}", stack_tags.join(" ")) }; - println!( + let _ = writeln!( + buf, "{} {}{}", stack_fork.dimmed(), stack.name.magenta().bold(), stack_tag_str ); - total_lines += 1; + line_num += 1; for (idx, branch) in stack.branches.iter().enumerate() { let is_last_branch = idx == branch_count - 1; @@ -251,16 +254,19 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { exists, info, is_last_branch, - None, + pr_status.get(&branch.name), stale, ); - println!("{}{}", stack_pipe.dimmed(), line); - branch_positions.insert(branch.name.clone(), total_lines); - total_lines += 1; + let _ = writeln!(buf, "{}{}", stack_pipe.dimmed(), line); + line_num += 1; + if is_current { + current_branch_line = Some(line_num); + } if let Some(commits) = commit_cache.get(&branch.name) { for (sha, subject) in commits { - println!( + let _ = writeln!( + buf, "{}{}{} {} {}", stack_pipe.dimmed(), branch_pipe.dimmed(), @@ -268,54 +274,14 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { sha.yellow(), subject.dimmed() ); - total_lines += 1; + line_num += 1; } } } } } - // Retroactive PR update - if show_pr && !pr_status.is_empty() { - for (_, stack_indices) in &by_base { - for &stack_idx in stack_indices { - let stack = &stacks[stack_idx]; - let branch_count = stack.branches.len(); - let is_last_stack = stack_indices.last() == Some(&stack_idx); - let stack_pipe = if is_last_stack { " " } else { "│ " }; - - for (idx, branch) in stack.branches.iter().enumerate() { - if let Some(pr) = pr_status.get(&branch.name) { - if let Some(&line_pos) = branch_positions.get(&branch.name) { - let is_last_branch = idx == branch_count - 1; - let is_current = branch.name == current_branch; - let is_root = idx == 0; - let info = ref_info.get(&branch.name); - let exists = info.is_some(); - - let lines_up = total_lines - line_pos; - let stale = - needs_rebase.get(&branch.name).copied().unwrap_or(false); - let new_line = format_branch_line( - &branch.name, - is_current, - is_root, - exists, - info, - is_last_branch, - Some(pr), - stale, - ); - print!( - "\x1b[{lines_up}A\r\x1b[2K{}{new_line}\x1b[{lines_up}B\r", - stack_pipe.dimmed() - ); - } - } - } - } - } - } + ui::output_with_pager(&buf, no_pager, current_branch_line); Ok(()) } diff --git a/src/main.rs b/src/main.rs index cbe62b2..f4729e1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,7 @@ fn main() -> Result<()> { Some(cmd) => cmd, None => { let ctx = Ctx::discover()?; - return commands::tree::run(&ctx, cli.pr); + return commands::tree::run(&ctx, cli.pr, false); } }; @@ -98,7 +98,7 @@ fn main() -> Result<()> { Commands::Sync(args) => commands::sync::run(args, &ctx), Commands::Push(args) => commands::push::run(args, &ctx), Commands::Switch(args) => commands::switch::run(args.branch, &ctx), - Commands::Log(args) => commands::tree::run(&ctx, args.pr), + Commands::Log(args) => commands::tree::run(&ctx, args.pr, args.no_pager), Commands::Split(args) => commands::split::run(args, &ctx), Commands::Config(args) => commands::config::run(args.command, &ctx), Commands::Completions(_) | Commands::McpSetup | Commands::McpServer => unreachable!(), diff --git a/src/ui.rs b/src/ui.rs index 7822468..1597174 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -85,6 +85,98 @@ pub fn prompt(message: &str, default: Option<&str>) -> io::Result { } } +/// Output content, using a pager if stdout is a TTY and content overflows the terminal. +/// +/// Pager selection: $GW_PAGER > $PAGER > less -R +/// When `focus_line` is provided and the pager is less, opens at that line number. +pub fn output_with_pager(content: &str, no_pager: bool, focus_line: Option) { + use std::io::IsTerminal; + + if no_pager || !std::io::stdout().is_terminal() { + print!("{content}"); + return; + } + + // Use stderr terminal for size detection (stdout may be piped to pager) + let term = console::Term::stderr(); + let (term_height, _) = term.size(); + let line_count = content.lines().count(); + + if line_count <= term_height as usize { + print!("{content}"); + return; + } + + // Cap the focus line so we don't scroll past the end of content. + // Place the target line ~1/3 down the screen for context above. + let adjusted_line = focus_line.map(|line| { + let offset = (term_height as usize) / 3; + let start = line.saturating_sub(offset); + let max_start = line_count.saturating_sub(term_height as usize) + 1; + start.clamp(1, max_start) + }); + + pipe_to_pager(content, adjusted_line); +} + +fn pipe_to_pager(content: &str, focus_line: Option) { + use std::process::{Command, Stdio}; + + let pager_env = std::env::var("GW_PAGER") + .or_else(|_| std::env::var("PAGER")) + .ok(); + + let (cmd, args) = match &pager_env { + Some(pager) => { + let parts: Vec<&str> = pager.split_whitespace().collect(); + let cmd = parts[0].to_string(); + let mut args: Vec = parts[1..].iter().map(|s| s.to_string()).collect(); + if is_less(&cmd) { + if !args.iter().any(|a| a.contains('R')) { + args.push("-R".to_string()); + } + if let Some(line) = focus_line { + args.push(format!("+{line}")); + } + } + (cmd, args) + } + None => { + let mut args = vec!["-R".to_string()]; + if let Some(line) = focus_line { + args.push(format!("+{line}")); + } + ("less".to_string(), args) + } + }; + + let child = Command::new(&cmd) + .args(&args) + .stdin(Stdio::piped()) + .spawn(); + + match child { + Ok(mut child) => { + if let Some(ref mut stdin) = child.stdin { + let _ = stdin.write_all(content.as_bytes()); + } + child.stdin.take(); + let _ = child.wait(); + } + Err(_) => { + print!("{content}"); + } + } +} + +fn is_less(cmd: &str) -> bool { + std::path::Path::new(cmd) + .file_name() + .and_then(|n| n.to_str()) + .map(|n| n.eq_ignore_ascii_case("less")) + .unwrap_or(false) +} + /// Print an info message. pub fn info(msg: &str) { println!("{msg}"); From c7c0318dbf9a5bf32885192dcc2621db286ba4b2 Mon Sep 17 00:00:00 2001 From: Jon Deibel Date: Tue, 10 Mar 2026 11:18:59 -0400 Subject: [PATCH 2/2] release: v0.1.5 Co-Authored-By: Claude Opus 4.6 (1M context) --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f32d83b..40f5236 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -512,7 +512,7 @@ dependencies = [ [[package]] name = "gw" -version = "0.1.4" +version = "0.1.5" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 2babd48..029d111 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gw" -version = "0.1.4" +version = "0.1.5" edition = "2024" description = "Git stacked branch manager" repository = "https://github.com/jondeibel/git-workflow"