Skip to content

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

20.7 KB
Raw Blame
//! List command for displaying worktrees and branches.
//!
//! # Performance
//!
//! `wt list` runs multiple git commands per worktree in parallel using Rayon. Performance
//! depends heavily on git's internal caches, and — for the commit-graph-derived commands —
//! on worktrunk's own on-disk caches, which elide those commands entirely on a warm cache
//! (see "Worktrunk's Own Caches" below).
//!
//! ## Time to First Information
//!
//! Before displaying actual data, we perform these sequential operations:
//!
//! 1. **`git worktree list --porcelain`** (~5-15ms)
//!    - Lists all worktrees with their paths, HEADs, and branches
//!    - Uses ref cache, very fast
//!
//! 2. **Default branch lookup** (~1-5ms)
//!    - Reads cached value from `git config worktrunk.default-branch`
//!    - Falls back to git's remote HEAD ref (e.g., `origin/HEAD`) if available
//!    - If still unknown, queries `git ls-remote --symref <remote> HEAD` (~100ms-2s network)
//!    - Clear cache with `wt config state default-branch clear` to force re-detection
//!
//! 3. **Sort worktrees** (<1ms)
//!    - Orders by: current → main → rest by timestamp (most recent first)
//!    - Pure Rust, no git calls
//!
//! 4. **Branch listing** (only with `--branches`, ~10-30ms)
//!    - `git for-each-ref refs/heads` - lists local branches
//!    - Filters out branches that already have worktrees
//!
//! 5. **Remote branch listing** (only with `--remotes`, ~10-50ms)
//!    - `git for-each-ref refs/remotes` - lists remote branches
//!    - Scales with number of remotes/branches
//!
//! 6. **Layout calculation** (<1ms)
//!    - Determines column widths from branch names and paths
//!    - Pure Rust, no git calls
//!
//! **Time to skeleton: ~50ms** (placeholder rows with loading indicators)
//!
//! Skeleton timing is stable at ~46-52ms regardless of worktree count (1-8) or cache state.
//! This is because skeleton operations (worktree list, default branch lookup, layout) use
//! git's ref cache rather than packed-refs or the index.
//!
//! **Time to complete: ~60-170ms** (all data filled in, depends on worktree count)
//!
//! First run in a repo without cached default branch adds ~100-300ms for network lookup.
//!
//! After the skeleton appears, cells fill in progressively as git operations complete.
//! The slowest operation (CI status) runs with `--full`, or — for the table and
//! the picker only — when `[list] columns` names `ci`, which forces the column
//! and its fetch on without `--full`.
//!
//! ## Git Commands Per Worktree
//!
//! For each worktree, we execute:
//! - `git status --porcelain` - Working tree state (uses index cache)
//! - `git rev-list --count <base>..<head>` - Ahead/behind counts (uses commit graph)
//! - Working tree line diffs:
//!   - Without untracked files: `git diff-index --shortstat --find-renames HEAD`
//!   - With untracked files: `git ls-files --others`, a temporary index copy plus
//!     `git add --intent-to-add`, and two `git diff-index --numstat -z --find-renames HEAD` calls
//! - `git diff-tree -r --shortstat --find-renames <merge-base> <head>` - Branch line diffs
//!   (uses tree objects)
//! - `git rev-parse <ref>` - Ref resolution (uses ref cache)
//!
//! Both line-diff columns use plumbing with rename detection on, so the user's diff
//! configuration can't change them. For `HEAD±`, renames also pair a tracked deletion
//! with an untracked destination, making a move line-neutral.
//!
//! Plus one global command:
//! - `git worktree list --porcelain` - List all worktrees (uses ref cache)
//!
//! ## Git's Internal Caches
//!
//! Git caches significantly affect performance. These caches are maintained by git itself:
//!
//! 1. **Index (`.git/index`)** - Cached file metadata (mtime, size, mode)
//!    - Speeds up `git status` by avoiding full file content comparisons
//!    - Invalidated when files change or staging area updates
//!
//! 2. **Commit graph (`.git/objects/info/commit-graph`)** - Precomputed commit metadata
//!    - Speeds up `git rev-list --count` by avoiding commit object parsing
//!    - Generated by `git commit-graph write` (some repos auto-generate)
//!    - Without: O(commits) parsing, With: O(1) metadata lookup
//!    - Cold: ~50ms for 1000 commits, Warm: ~5ms (with commit graph)
//!
//! 3. **Ref cache (`.git/refs/` and `.git/packed-refs`)** - Cached ref resolutions
//!    - Speeds up `git rev-parse` and branch lookups
//!    - Packed refs improve performance in repos with many branches
//!    - Cold: ~10ms, Warm: <1ms
//!
//! 4. **Filesystem cache (OS-level)** - Recently accessed files stay in memory
//!    - Speeds up all git operations after first access
//!    - Cleared when system is under memory pressure
//!    - Most impactful for large repos with many pack files
//!
//! 5. **Pack files (`.git/objects/pack/`)** - Compressed object storage
//!    - Faster than loose objects for bulk access
//!    - `git gc` consolidates loose objects into packs
//!    - More efficient for tree/blob access in diffs
//!
//! ## Worktrunk's Own Caches
//!
//! The default branch name (main/master) is cached in
//! `git config worktrunk.default-branch`. The remote HEAD ref (e.g., `origin/HEAD`)
//! is git's cache; worktrunk reads it but does not set it. Clear it with
//! `wt config state default-branch clear`.
//!
//! A collect also reads and writes the on-disk caches under `.git/wt/cache/`, so some of the
//! per-worktree git commands above — the ahead/behind counts and the branch line diff — are
//! what a *cold* cache costs, while `git status` and the working-tree diff run on every
//! invocation regardless. The authoritative inventory — every directory, its key scheme, and
//! when an entry goes stale — is the `## Caching` table in [`collect`]; don't restate it
//! here. Clear those with `wt config state cache clear`.
//!
//! ## Performance Characteristics
//!
//! Scaling (from benches/list.rs):
//! - Each worktree adds a `git status --porcelain`, parallelized on the Rayon pool
//! - Git command overhead dominates the Rust code
//! - Warm/cold 1-vs-8-worktree contrasts use the generated corpus
//! - The imported corpus (currently rust-lang/rust) covers deep history and large trees
//!
//! Bottlenecks:
//! 1. `git status --porcelain` - Slowest when index is cold or many files changed
//! 2. `git rev-list --count` - Slow without commit graph in repos with deep history
//! 3. Working tree diff - Slow for large tracked diffs or cold pack files; untracked
//!    paths also require enumeration, a temporary index write, and two numstat diffs
//!
//! Optimization tips:
//! - Run `git commit-graph write --reachable --changed-paths` to speed up commit counting
//! - Run `git gc` periodically to consolidate objects into pack files
//! - Minimize uncommitted changes across worktrees (each dirty worktree adds diff overhead)

pub mod ci_status;
pub(crate) mod collect;
pub(crate) mod columns;
pub(crate) mod custom_columns;
pub mod json_output;
pub mod json_v2;
pub(crate) mod layout;
pub mod model;
pub mod progressive;
mod progressive_table;
pub(crate) mod render;

// Layout is calculated in collect/mod.rs
use anstyle::Style;
use model::{BranchScope, ItemKind, ListData, ListItem};
use progressive::RenderTarget;
use worktrunk::git::Repository;
use worktrunk::styling::{INFO_SYMBOL, eprintln, terminal_width, wrap_styled_text};

use crate::output::print_json;

// Re-export for statusline and other consumers
pub use collect::{CollectOptions, build_worktree_item, populate_item};
pub use model::StatuslineSegment;

pub fn handle_list(
    repo: Repository,
    format: crate::OutputFormat,
    cli_branches: bool,
    cli_remotes: bool,
    cli_full: bool,
    progressive_flag: Option<bool>,
) -> anyhow::Result<()> {
    let render_target = RenderTarget::detect(format, progressive_flag);

    // A `.config/wt.toml` that doesn't parse reaches the listing only through
    // accessors that shrug it off (`[list] url`, `[forge] platform`), so it
    // would otherwise leave no trace on the command run most often. Warn
    // ahead of `collect()`, where those accessors run, so the line lands
    // above the rows instead of between them.
    repo.warn_if_project_config_unloadable();

    // Resolve the JSON schema before collecting, so an invalid-value warning
    // lands above the output rather than after a long collection.
    let json_schema =
        matches!(render_target, RenderTarget::Json).then(|| resolve_json_schema(&repo));

    let list_data = collect::collect(
        &repo,
        collect::ShowConfig::DeferredToParallel {
            cli_branches,
            cli_remotes,
            cli_full,
        },
        render_target,
    )?;

    let Some(ListData {
        items,
        custom_columns,
        collected,
    }) = list_data
    else {
        return Ok(());
    };

    match json_schema {
        // Table modes already rendered inside `collect()`.
        None => {}
        Some(2) => print_json(&json_v2::to_json_envelope(
            &items,
            &custom_columns,
            &repo,
            collected,
        ))?,
        Some(_) => print_json(&json_output::to_json_items(&items, &custom_columns, &repo))?,
    }

    Ok(())
}

/// Resolve `[list] json-schema` (per-project resolved config) to 1 or 2.
///
/// Unset defaults to schema 2; an out-of-range value warns and defaults to
/// schema 2, matching how config load treats a
/// type error in the same key (warn and degrade, never brick a command).
/// The warning honors warning suppression because stderr would corrupt the
/// statusline consumer's prompt.
pub(crate) fn resolve_json_schema(repo: &Repository) -> u8 {
    use std::sync::Once;

    use color_print::cformat;
    use worktrunk::styling::warning_message;

    static WARNED: Once = Once::new();
    match repo.config().list.json_schema {
        Some(v @ (1 | 2)) => v,
        Some(other) => {
            WARNED.call_once(|| {
                if worktrunk::config::warnings_suppressed() {
                    return;
                }
                eprintln!(
                    "{}",
                    warning_message(cformat!(
                        "[list] json-schema is <bold>{other}</>, expected 1 or 2; using schema 2"
                    ))
                );
            });
            2
        }
        None => 2,
    }
}

#[derive(Default)]
pub(super) struct SummaryMetrics {
    worktrees: usize,
    local_branches: usize,
    remote_branches: usize,
    dirty_worktrees: usize,
    ahead_items: usize,
}

impl SummaryMetrics {
    pub(super) fn from_items(items: &[ListItem]) -> Self {
        let mut metrics = Self::default();
        for item in items {
            metrics.update(item);
        }
        metrics
    }

    fn update(&mut self, item: &ListItem) {
        if let Some(_data) = item.worktree_data() {
            self.worktrees += 1;
            // Use status_symbols.working_tree which includes untracked files,
            // not just working_tree_diff which only has tracked changes.
            // `None` means gate 1 hasn't resolved yet — don't count.
            if item
                .status_symbols
                .working_tree
                .is_some_and(|wt| wt.is_dirty())
            {
                self.dirty_worktrees += 1;
            }
        } else {
            // Local vs remote is recorded structurally on the item
            // (`BranchScope`), never inferred from the name — a local branch
            // may legitimately be named `origin/foo`, so a name-prefix
            // heuristic would misclassify it. See `BranchScope` in
            // `model/item.rs`.
            match item.kind() {
                ItemKind::Branch(BranchScope::Remote) => self.remote_branches += 1,
                _ => self.local_branches += 1,
            }
        }

        if item.counts.is_some_and(|c| c.ahead > 0) {
            self.ahead_items += 1;
        }
    }

    pub(super) fn inventory_parts(&self, include_branches: bool) -> Vec<String> {
        let mut parts = Vec::new();

        let plural = if self.worktrees == 1 { "" } else { "s" };
        parts.push(format!("{} worktree{}", self.worktrees, plural));

        if include_branches {
            if self.local_branches > 0 {
                let plural = if self.local_branches == 1 { "" } else { "es" };
                parts.push(format!("{} branch{}", self.local_branches, plural));
            }
            if self.remote_branches > 0 {
                let plural = if self.remote_branches == 1 { "" } else { "es" };
                parts.push(format!("{} remote branch{}", self.remote_branches, plural));
            }
        }

        parts
    }

    pub(super) fn summary_parts(
        &self,
        include_branches: bool,
        hidden_columns: &[String],
    ) -> Vec<String> {
        let mut parts = self.inventory_parts(include_branches);

        if self.dirty_worktrees > 0 {
            parts.push(format!("{} with changes", self.dirty_worktrees));
        }

        if self.ahead_items > 0 {
            parts.push(format!("{} ahead", self.ahead_items));
        }

        if !hidden_columns.is_empty() {
            parts.push(format!("hidden: {}", hidden_columns.join(", ")));
        }

        parts
    }
}

/// Format the summary line that closes the table.
///
/// The footer is the only home a timed-out task has: it leaves an empty cell
/// and no message to print, so the count here is all that reports it. Tasks
/// that failed instead get a named entry in the warning that follows the
/// table, and that warning carries its own count — repeating it here would
/// print the same number twice on adjacent lines.
///
/// `max_width` bounds the line, following [`format_with_gutter`]'s
/// convention: `None` detects the terminal, and no detectable width wraps
/// nothing. The hidden-column list grows with every column a narrow terminal
/// drops, so the footer is longest exactly where there is least room for it —
/// at 40 columns it ran to 67 for a table that fit. Continuations indent
/// under the text, keeping them subordinate to the `○`.
///
/// [`format_with_gutter`]: worktrunk::styling::format_with_gutter
pub(crate) fn format_summary_message(
    items: &[ListItem],
    show_branches: bool,
    hidden_columns: &[String],
    timed_out_count: usize,
    max_width: Option<usize>,
) -> String {
    const INDENT: &str = "  "; // symbol + space, so continuations align under the text

    let metrics = SummaryMetrics::from_items(items);
    let dim = Style::new().dimmed();
    let summary = metrics
        .summary_parts(show_branches, hidden_columns)
        .join(", ");

    let body = if timed_out_count > 0 {
        let plural = if timed_out_count == 1 { "" } else { "s" };
        format!("Showing {summary}; {timed_out_count} task{plural} timed out")
    } else {
        format!("Showing {summary}")
    };

    let width = max_width.or_else(terminal_width).unwrap_or(usize::MAX);
    let body = wrap_styled_text(&body, width.saturating_sub(INDENT.len()))
        .iter()
        // The wrapper keeps the space it broke on, which would land a
        // continuation one column right of the indent.
        .map(|line| line.trim())
        .collect::<Vec<_>>()
        .join(&format!("\n{INDENT}"));

    format!("{INFO_SYMBOL} {dim}{body}{dim:#}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_summary_metrics_default() {
        let metrics = SummaryMetrics::default();
        assert_eq!(metrics.worktrees, 0);
        assert_eq!(metrics.local_branches, 0);
        assert_eq!(metrics.remote_branches, 0);
        assert_eq!(metrics.dirty_worktrees, 0);
        assert_eq!(metrics.ahead_items, 0);
    }

    #[test]
    fn test_summary_metrics_classifies_by_scope_not_name() {
        // A local branch may legitimately contain '/' (e.g. `feature/login`);
        // it must be counted as local on its structural `BranchScope`, not on
        // a name-prefix heuristic that would misread the '/' as "remote".
        // Regression test for the prior `b.contains('/')` classification.
        let items = vec![
            ListItem::new_branch("aaaaaaa".to_string(), "feature/login".to_string()),
            ListItem::new_branch("bbbbbbb".to_string(), "main".to_string()),
            ListItem::new_remote_branch(
                "ccccccc".to_string(),
                "origin".to_string(),
                "feature".to_string(),
            ),
        ];
        let metrics = SummaryMetrics::from_items(&items);
        assert_eq!(
            metrics.local_branches, 2,
            "`feature/login` must count as a local branch"
        );
        assert_eq!(metrics.remote_branches, 1);
        assert_eq!(metrics.worktrees, 0);
    }

    #[test]
    fn test_summary_metrics_summary_parts_single_worktree() {
        let metrics = SummaryMetrics {
            worktrees: 1,
            local_branches: 0,
            remote_branches: 0,
            dirty_worktrees: 0,
            ahead_items: 0,
        };
        let parts = metrics.summary_parts(false, &[]);
        assert_eq!(parts, vec!["1 worktree"]);
    }

    #[test]
    fn test_summary_metrics_summary_parts_multiple_worktrees() {
        let metrics = SummaryMetrics {
            worktrees: 3,
            local_branches: 0,
            remote_branches: 0,
            dirty_worktrees: 0,
            ahead_items: 0,
        };
        let parts = metrics.summary_parts(false, &[]);
        assert_eq!(parts, vec!["3 worktrees"]);
    }

    #[test]
    fn test_summary_metrics_summary_parts_with_branches() {
        let metrics = SummaryMetrics {
            worktrees: 2,
            local_branches: 5,
            remote_branches: 10,
            dirty_worktrees: 0,
            ahead_items: 0,
        };
        let parts = metrics.summary_parts(true, &[]);
        assert_eq!(
            parts,
            vec!["2 worktrees", "5 branches", "10 remote branches"]
        );
    }

    #[test]
    fn test_summary_metrics_summary_parts_with_dirty() {
        let metrics = SummaryMetrics {
            worktrees: 3,
            local_branches: 0,
            remote_branches: 0,
            dirty_worktrees: 2,
            ahead_items: 0,
        };
        let parts = metrics.summary_parts(false, &[]);
        assert_eq!(parts, vec!["3 worktrees", "2 with changes"]);
    }

    #[test]
    fn test_summary_metrics_summary_parts_with_ahead() {
        let metrics = SummaryMetrics {
            worktrees: 2,
            local_branches: 0,
            remote_branches: 0,
            dirty_worktrees: 0,
            ahead_items: 1,
        };
        let parts = metrics.summary_parts(false, &[]);
        assert_eq!(parts, vec!["2 worktrees", "1 ahead"]);
    }

    #[test]
    fn test_summary_metrics_summary_parts_with_hidden_columns() {
        let metrics = SummaryMetrics {
            worktrees: 1,
            local_branches: 0,
            remote_branches: 0,
            dirty_worktrees: 0,
            ahead_items: 0,
        };
        let parts = metrics.summary_parts(false, &["Message".to_string()]);
        assert_eq!(parts, vec!["1 worktree", "hidden: Message"]);

        let parts = metrics.summary_parts(
            false,
            &["Path".to_string(), "Commit".to_string(), "Age".to_string()],
        );
        assert_eq!(parts, vec!["1 worktree", "hidden: Path, Commit, Age"]);
    }

    #[test]
    fn test_summary_metrics_summary_parts_branches_no_local() {
        let metrics = SummaryMetrics {
            worktrees: 2,
            local_branches: 0,
            remote_branches: 5,
            dirty_worktrees: 0,
            ahead_items: 0,
        };
        let parts = metrics.summary_parts(true, &[]);
        assert_eq!(parts, vec!["2 worktrees", "5 remote branches"]);
    }

    #[test]
    fn test_summary_metrics_summary_parts_all_features() {
        let metrics = SummaryMetrics {
            worktrees: 5,
            local_branches: 3,
            remote_branches: 8,
            dirty_worktrees: 2,
            ahead_items: 4,
        };
        let parts = metrics.summary_parts(true, &["Commit".to_string(), "Age".to_string()]);
        assert_eq!(
            parts,
            vec![
                "5 worktrees",
                "3 branches",
                "8 remote branches",
                "2 with changes",
                "4 ahead",
                "hidden: Commit, Age"
            ]
        );
    }

    #[test]
    fn test_format_summary_message_timeout_variants() {
        use insta::assert_snapshot;

        // Nothing timed out. Failures alone leave the footer untouched — the
        // warning after the table names them and carries their count.
        assert_snapshot!(format_summary_message(&[], false, &[], 0, None), @"○ Showing 0 worktrees");
        // Single timeout
        assert_snapshot!(format_summary_message(&[], false, &[], 1, None), @"○ Showing 0 worktrees; 1 task timed out");
        // Several timeouts
        assert_snapshot!(format_summary_message(&[], false, &[], 3, None), @"○ Showing 0 worktrees; 3 tasks timed out");
    }
}