diff --git a/bench/log_bench.sh b/bench/log_bench.sh new file mode 100755 index 0000000..ca87071 --- /dev/null +++ b/bench/log_bench.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +# +# Benchmark harness for `gw log` +# +# Creates a temp repo, builds stacks at a few sizes, and measures: +# 1. Wall clock time for `gw log` +# 2. Number of git subprocess calls +# +# Usage: ./bench/log_bench.sh + +set -euo pipefail + +GW="${GW:-gw}" + +BOLD="\033[1m" +DIM="\033[2m" +CYAN="\033[36m" +YELLOW="\033[33m" +GREEN="\033[32m" +RESET="\033[0m" + +BENCH_DIR="" +cleanup() { [ -n "$BENCH_DIR" ] && rm -rf "$BENCH_DIR"; } +trap cleanup EXIT + +setup_repo() { + BENCH_DIR=$(mktemp -d) + cd "$BENCH_DIR" + git init -q + git config user.email "bench@test.com" + git config user.name "Bench" + echo "init" > README.md + git add . + git commit -q -m "initial" +} + +# Create a stack with N branches, each with M commits +create_stack() { + local name="$1" branches="$2" commits_per="$3" + $GW stack create "$name" > /dev/null + for b in $(seq 1 "$branches"); do + [ "$b" -gt 1 ] && $GW branch create "${name}-b${b}" > /dev/null + for c in $(seq 1 "$commits_per"); do + echo "${name}-${b}-${c}" > "f-${name}-${b}-${c}.txt" + git add . + git commit -q -m "${name} b${b} c${c}" + done + done +} + +time_log() { + local label="$1" runs=5 total=0 + $GW log > /dev/null 2>&1 # warmup + for _ in $(seq 1 $runs); do + local t + t=$( { time $GW log > /dev/null 2>&1; } 2>&1 | grep real | awk '{print $2}' | sed 's/[ms]/ /g' | awk '{printf "%.0f", $1*60000+$2*1000}' ) + total=$((total + t)) + done + local avg=$((total / runs)) + echo -e " ${GREEN}${label}${RESET}: ${BOLD}${avg}ms${RESET}" +} + +count_git() { + local label="$1" + local wrapper_dir + wrapper_dir=$(mktemp -d) + cat > "$wrapper_dir/git" <<'WRAPPER' +#!/usr/bin/env bash +echo "$@" >> /tmp/gw-bench-git.log +exec /usr/bin/git "$@" +WRAPPER + chmod +x "$wrapper_dir/git" + rm -f /tmp/gw-bench-git.log + PATH="$wrapper_dir:$PATH" $GW log > /dev/null 2>&1 + local count + count=$(wc -l < /tmp/gw-bench-git.log | tr -d ' ') + echo -e " ${YELLOW}git calls${RESET}: ${BOLD}${count}${RESET}" + # Top commands + echo -e " ${DIM}$(awk '{print $1}' /tmp/gw-bench-git.log | sort | uniq -c | sort -rn | head -5 | tr '\n' ' ')${RESET}" + rm -f /tmp/gw-bench-git.log + rm -rf "$wrapper_dir" +} + +# ── Scenario 1: small (1 stack, 3 branches, 2 commits) ── +echo -e "\n${BOLD}${CYAN}── Small: 1 stack, 3 branches, 2 commits each ──${RESET}" +setup_repo +create_stack "feat" 3 2 +git checkout -q main +time_log "gw log" +count_git "gw log" +rm -rf "$BENCH_DIR" + +# ── Scenario 2: medium (3 stacks, 3 branches, 3 commits) ── +echo -e "\n${BOLD}${CYAN}── Medium: 3 stacks x 3 branches x 3 commits ──${RESET}" +setup_repo +for s in 1 2 3; do + git checkout -q main + create_stack "s${s}" 3 3 +done +git checkout -q main +time_log "gw log" +count_git "gw log" +rm -rf "$BENCH_DIR" + +# ── Scenario 3: large (5 stacks, 5 branches, 3 commits) ── +echo -e "\n${BOLD}${CYAN}── Large: 5 stacks x 5 branches x 3 commits ──${RESET}" +setup_repo +for s in 1 2 3 4 5; do + git checkout -q main + create_stack "s${s}" 5 3 +done +git checkout -q main +time_log "gw log" +count_git "gw log" + +echo -e "\n${BOLD}Done.${RESET}" diff --git a/src/commands/tree.rs b/src/commands/tree.rs index fd4b995..02abbef 100644 --- a/src/commands/tree.rs +++ b/src/commands/tree.rs @@ -6,6 +6,13 @@ use crate::context::Ctx; use crate::gh; use crate::ui; +/// All the git data we need, fetched in as few subprocesses as possible. +struct TreeData { + merge_bases: HashMap, + commit_cache: HashMap>, + behind_counts: HashMap, +} + pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { let stacks = ctx.load_all_stacks()?; @@ -15,35 +22,47 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { } let current_branch = ctx.git.current_branch().unwrap_or_default(); + + // === Phase 1: one git call for all branch SHAs + tracking info === let ref_info = batch_ref_info(ctx); - // Collect commits for all branches - let mut commit_cache: HashMap> = HashMap::new(); + // === Phase 2: figure out what we need === + let mut merge_base_pairs: Vec<(String, String)> = Vec::new(); + let mut log_ranges: Vec<(String, String)> = Vec::new(); // (branch, parent) + for stack in &stacks { - for branch in &stack.branches { - if ref_info.contains_key(&branch.name) { - let parent = stack.parent_of(&branch.name).unwrap_or_default(); - if let Ok(commits) = ctx.git.log_oneline(&parent, &branch.name, 10) { - commit_cache.insert(branch.name.clone(), commits); - } + if let Some(root) = stack.branches.first() { + if ref_info.contains_key(&root.name) { + merge_base_pairs.push((root.name.clone(), stack.base_branch.clone())); } } + for (idx, branch) in stack.branches.iter().enumerate() { + if !ref_info.contains_key(&branch.name) { + continue; + } + let parent = stack.parent_of(&branch.name).unwrap_or_default(); + if idx > 0 { + merge_base_pairs.push((branch.name.clone(), parent.clone())); + } + log_ranges.push((branch.name.clone(), parent.clone())); + } } - // Detect which branches need a rebase (parent tip has moved past the fork point) + // === Phase 3: ONE bash subprocess, all git calls in parallel === + let batch = run_batch_script(ctx, &ref_info, &stacks, &merge_base_pairs, &log_ranges); + + // === Phase 4: compute derived data === let mut needs_rebase: HashMap = HashMap::new(); for stack in &stacks { for (idx, branch) in stack.branches.iter().enumerate() { - if idx == 0 { - continue; // root can't need a rebase within its stack - } - if !ref_info.contains_key(&branch.name) { - continue; // missing branch + if idx == 0 || !ref_info.contains_key(&branch.name) { + continue; } let parent_name = stack.parent_of(&branch.name).unwrap_or_default(); - if let Ok(parent_sha) = ctx.git.rev_parse(&parent_name) { - if let Ok(mb) = ctx.git.merge_base(&branch.name, &parent_name) { - if mb != parent_sha { + let pair_key = format!("{}:{}", branch.name, parent_name); + if let Some(mb_sha) = batch.merge_bases.get(&pair_key) { + if let Some(ri) = ref_info.get(&parent_name) { + if *mb_sha != ri.sha { needs_rebase.insert(branch.name.clone(), true); } } @@ -61,27 +80,6 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { } } - // Compute how far behind the base branch tip each stack's root is - let mut behind_counts: HashMap = HashMap::new(); - for stack in &stacks { - if let Some(root) = stack.branches.first() { - if let Ok(mb) = ctx.git.merge_base(&root.name, &stack.base_branch) { - let base_sha = ctx.git.rev_parse(&stack.base_branch).unwrap_or_default(); - if mb != base_sha { - if let Ok(count) = ctx.git.run(&[ - "rev-list", "--count", &format!("{mb}..{}", stack.base_branch), - ]) { - if let Ok(n) = count.parse::() { - if n > 0 { - behind_counts.insert(stack.name.clone(), n); - } - } - } - } - } - } - } - // PR status (only when requested) let pr_status = if show_pr { gh::batch_pr_status() @@ -90,18 +88,13 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { }; // === Render === - // Track total lines + branch positions for PR retroactive update let mut total_lines = 0; let mut branch_positions: HashMap = HashMap::new(); for (base, stack_indices) in &by_base { - // Base branch header (top-level root) - let base_sha = ctx.git.rev_parse_short(base).unwrap_or_default(); - - // Check if any stacks are behind let max_behind = stack_indices .iter() - .filter_map(|&si| behind_counts.get(&stacks[si].name)) + .filter_map(|&si| batch.behind_counts.get(&stacks[si].name)) .max() .copied() .unwrap_or(0); @@ -134,16 +127,9 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { let stack_fork = if is_last_stack { "╰─" } else { "├─" }; let stack_pipe = if is_last_stack { " " } else { "│ " }; - // Stack name line with behind info let mut stack_tags: Vec = vec![]; - if let Some(&behind) = behind_counts.get(&stack.name) { - stack_tags.push( - format!( - "{behind} behind", - ) - .yellow() - .to_string(), - ); + if let Some(&behind) = batch.behind_counts.get(&stack.name) { + stack_tags.push(format!("{behind} behind").yellow().to_string()); } let stack_tag_str = if stack_tags.is_empty() { String::new() @@ -159,7 +145,6 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { ); total_lines += 1; - // Branches under this stack for (idx, branch) in stack.branches.iter().enumerate() { let is_last_branch = idx == branch_count - 1; let is_current = branch.name == current_branch; @@ -167,7 +152,6 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { let info = ref_info.get(&branch.name); let exists = info.is_some(); - let branch_fork = if is_last_branch { "╰─" } else { "├─" }; let branch_pipe = if is_last_branch { " " } else { "│ " }; let stale = needs_rebase.get(&branch.name).copied().unwrap_or(false); @@ -185,8 +169,7 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { branch_positions.insert(branch.name.clone(), total_lines); total_lines += 1; - // Commits - if let Some(commits) = commit_cache.get(&branch.name) { + if let Some(commits) = batch.commit_cache.get(&branch.name) { for (sha, subject) in commits { println!( "{}{}{} {} {}", @@ -222,7 +205,8 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { let exists = info.is_some(); let lines_up = total_lines - line_pos; - let stale = needs_rebase.get(&branch.name).copied().unwrap_or(false); + let stale = + needs_rebase.get(&branch.name).copied().unwrap_or(false); let new_line = format_branch_line( &branch.name, is_current, @@ -247,6 +231,142 @@ pub fn run(ctx: &Ctx, show_pr: bool) -> Result<()> { Ok(()) } +/// Run a single bash subprocess that executes all merge-bases, logs, and +/// behind-counts in parallel using temp files to avoid output interleaving. +fn run_batch_script( + ctx: &Ctx, + ref_info: &HashMap, + stacks: &[crate::state::StackConfig], + merge_base_pairs: &[(String, String)], + log_ranges: &[(String, String)], +) -> TreeData { + let mut script = String::from("TD=$(mktemp -d)\n"); + + // --- All parallel jobs write to individual temp files --- + + // Merge-bases: write to $TD/mb_ + for (i, (a, b)) in merge_base_pairs.iter().enumerate() { + script.push_str(&format!( + "{{ echo \"{a}:{b}=$(git merge-base {a} {b} 2>/dev/null)\"; }} > \"$TD/mb_{i}\" &\n" + )); + } + + // Logs: write to $TD/log_ + for (branch, parent) in log_ranges { + script.push_str(&format!( + "git log --reverse --oneline --format='%h %s' --max-count=10 \ + {parent}..{branch} 2>/dev/null > \"$TD/log_{branch}\" &\n" + )); + } + + // Behind-counts: write to $TD/behind_ + for stack in stacks { + if let Some(root) = stack.branches.first() { + if ref_info.contains_key(&root.name) { + if let Some(base_ri) = ref_info.get(&stack.base_branch) { + let root_name = &root.name; + let base = &stack.base_branch; + let base_sha = &base_ri.sha; + let stack_name = &stack.name; + script.push_str(&format!( + "{{ MB=$(git merge-base {root_name} {base} 2>/dev/null); \ + if [ \"$MB\" != \"{base_sha}\" ] && [ -n \"$MB\" ]; then \ + git rev-list --count \"$MB\"..{base} 2>/dev/null; \ + fi; }} > \"$TD/behind_{stack_name}\" &\n" + )); + } + } + } + } + + script.push_str("wait\n"); + + // --- Collect results to stdout in structured format --- + // Merge-bases + for i in 0..merge_base_pairs.len() { + script.push_str(&format!("echo \"MB:$(cat \"$TD/mb_{i}\")\"\n")); + } + // Logs + for (branch, _) in log_ranges { + script.push_str(&format!( + "echo \"LOG:{branch}\"\ncat \"$TD/log_{branch}\"\necho \"LOG_END\"\n" + )); + } + // Behind-counts + for stack in stacks { + if let Some(root) = stack.branches.first() { + if ref_info.contains_key(&root.name) { + if ref_info.contains_key(&stack.base_branch) { + let stack_name = &stack.name; + script.push_str(&format!( + "V=$(cat \"$TD/behind_{stack_name}\" 2>/dev/null); \ + [ -n \"$V\" ] && echo \"BEHIND:{stack_name}=$V\"\n" + )); + } + } + } + } + + script.push_str("rm -rf \"$TD\"\n"); + + // Run it + let output = std::process::Command::new("bash") + .arg("-c") + .arg(&script) + .current_dir(ctx.git.repo_path()) + .output(); + + let mut merge_bases = HashMap::new(); + let mut commit_cache: HashMap> = HashMap::new(); + let mut behind_counts = HashMap::new(); + + if let Ok(output) = output { + let stdout = String::from_utf8_lossy(&output.stdout); + let mut current_log_branch: Option = None; + let mut current_commits: Vec<(String, String)> = Vec::new(); + + for line in stdout.lines() { + if let Some(rest) = line.strip_prefix("MB:") { + if let Some((key, sha)) = rest.split_once('=') { + if !sha.is_empty() { + merge_bases.insert(key.to_string(), sha.to_string()); + } + } + } else if let Some(rest) = line.strip_prefix("LOG:") { + if let Some(branch) = current_log_branch.take() { + commit_cache.insert(branch, std::mem::take(&mut current_commits)); + } + current_log_branch = Some(rest.to_string()); + current_commits.clear(); + } else if line == "LOG_END" { + if let Some(branch) = current_log_branch.take() { + commit_cache.insert(branch, std::mem::take(&mut current_commits)); + } + } else if let Some(rest) = line.strip_prefix("BEHIND:") { + if let Some((name, count_str)) = rest.split_once('=') { + if let Ok(n) = count_str.trim().parse::() { + if n > 0 { + behind_counts.insert(name.to_string(), n); + } + } + } + } else if current_log_branch.is_some() && !line.is_empty() { + let (sha, subject) = line.split_once(' ').unwrap_or((line, "")); + current_commits.push((sha.to_string(), subject.to_string())); + } + } + if let Some(branch) = current_log_branch.take() { + commit_cache.insert(branch, current_commits); + } + } + + TreeData { + merge_bases, + commit_cache, + behind_counts, + } +} + fn format_branch_line( name: &str, is_current: bool, @@ -311,14 +431,16 @@ enum RemoteStatus { #[derive(Debug)] struct RefInfo { + sha: String, remote_status: RemoteStatus, } +/// Single git call to get all branch SHAs and remote tracking info. fn batch_ref_info(ctx: &Ctx) -> HashMap { let mut result = HashMap::new(); let output = ctx.git.run(&[ "for-each-ref", - "--format=%(refname:short)\t%(objectname:short)\t%(upstream:short)\t%(upstream:track)", + "--format=%(refname:short)\t%(objectname)\t%(upstream:short)\t%(upstream:track)", "refs/heads/", ]); let output = match output { @@ -327,15 +449,13 @@ fn batch_ref_info(ctx: &Ctx) -> HashMap { }; for line in output.lines() { let parts: Vec<&str> = line.split('\t').collect(); - if parts.len() < 4 { - if let Some(name) = parts.first() { - result.insert(name.to_string(), RefInfo { remote_status: RemoteStatus::NoRemote }); - } + if parts.is_empty() { continue; } let name = parts[0]; - let upstream = parts[2]; - let track = parts[3]; + let sha = parts.get(1).unwrap_or(&"").to_string(); + let upstream = parts.get(2).unwrap_or(&""); + let track = parts.get(3).unwrap_or(&""); let remote_status = if upstream.is_empty() { RemoteStatus::NoRemote } else if track.is_empty() { @@ -347,7 +467,7 @@ fn batch_ref_info(ctx: &Ctx) -> HashMap { } else { RemoteStatus::UpToDate }; - result.insert(name.to_string(), RefInfo { remote_status }); + result.insert(name.to_string(), RefInfo { sha, remote_status }); } result }