Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
3 changes: 3 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 --
Expand Down
5 changes: 3 additions & 2 deletions src/commands/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
76 changes: 21 additions & 55 deletions src/commands/tree.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::fmt::Write;
use std::process::Child;

use anyhow::Result;
Expand All @@ -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() {
Expand Down Expand Up @@ -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<String, usize> = HashMap::new();
// === Render to buffer ===
let mut buf = String::new();
let mut current_branch_line: Option<usize> = None;
let mut line_num: usize = 0;

for (base, stack_indices) in &by_base {
let max_behind = stack_indices
Expand All @@ -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() {
Expand All @@ -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;
Expand All @@ -251,71 +254,34 @@ 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(),
"│".dimmed(),
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(())
}
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};

Expand Down Expand Up @@ -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!(),
Expand Down
92 changes: 92 additions & 0 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,98 @@ pub fn prompt(message: &str, default: Option<&str>) -> io::Result<String> {
}
}

/// 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<usize>) {
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<usize>) {
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<String> = 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}");
Expand Down