Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: Encapsulate diff-related parsing and rendering
Maximilian Roosb5a413e08b9d
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex d07d76fb9..bcc0141ff 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -64,6 +64,14 @@ struct SummaryMetrics {}impl SummaryMetrics {+ 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(info) = item.worktree_info() {self.worktrees += 1;@@ -79,58 +87,61 @@ impl SummaryMetrics {self.ahead_items += 1;}}-}--impl LayoutConfig {- fn render_summary(&self, items: &[ListItem], include_branches: bool) {- use anstyle::Style;-- if items.is_empty() {- println!();- use worktrunk::styling::{HINT, HINT_EMOJI};- println!("{HINT_EMOJI} {HINT}No worktrees found{HINT:#}");- println!("{HINT_EMOJI} {HINT}Create one with: wt switch --create <branch>{HINT:#}");- return;- }-- let mut metrics = SummaryMetrics::default();- for item in items {- metrics.update(item);- }-- println!();- let dim = Style::new().dimmed();+ fn summary_parts(&self, include_branches: bool, hidden_columns: usize) -> Vec<String> {let mut parts = Vec::new();if include_branches {- parts.push(format!("{} worktrees", metrics.worktrees));- if metrics.branches > 0 {- parts.push(format!("{} branches", metrics.branches));+ parts.push(format!("{} worktrees", self.worktrees));+ if self.branches > 0 {+ parts.push(format!("{} branches", self.branches));}} else {- let plural = if metrics.worktrees == 1 { "" } else { "s" };- parts.push(format!("{} worktree{}", metrics.worktrees, plural));+ let plural = if self.worktrees == 1 { "" } else { "s" };+ parts.push(format!("{} worktree{}", self.worktrees, plural));}- if metrics.dirty_worktrees > 0 {- parts.push(format!("{} with changes", metrics.dirty_worktrees));+ if self.dirty_worktrees > 0 {+ parts.push(format!("{} with changes", self.dirty_worktrees));}- if metrics.ahead_items > 0 {- parts.push(format!("{} ahead", metrics.ahead_items));+ if self.ahead_items > 0 {+ parts.push(format!("{} ahead", self.ahead_items));}- if self.hidden_nonempty_count > 0 {- let plural = if self.hidden_nonempty_count == 1 {+ if hidden_columns > 0 {+ let plural = if hidden_columns == 1 {"column"} else {"columns"};- parts.push(format!("{} {} hidden", self.hidden_nonempty_count, plural));+ parts.push(format!("{} {} hidden", hidden_columns, plural));+ }++ parts+ }+}++impl LayoutConfig {+ fn render_summary(&self, items: &[ListItem], include_branches: bool) {+ use anstyle::Style;++ if items.is_empty() {+ println!();+ use worktrunk::styling::{HINT, HINT_EMOJI};+ println!("{HINT_EMOJI} {HINT}No worktrees found{HINT:#}");+ println!("{HINT_EMOJI} {HINT}Create one with: wt switch --create <branch>{HINT:#}");+ return;}- let summary = parts.join(", ");+ let metrics = SummaryMetrics::from_items(items);++ println!();+ let dim = Style::new().dimmed();++ let summary = metrics+ .summary_parts(include_branches, self.hidden_nonempty_count)+ .join(", ");println!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}");}}diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex 18bef6817..bf40de165 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -876,35 +876,8 @@ impl WorktreeInfo {};// Use tree equality check instead of expensive diff for "matches main"- let working_tree_diff_with_main = if let Some(base) = base_branch {- // Get tree hashes for HEAD and base branch- let head_tree = wt_repo- .run_command(&["rev-parse", "HEAD^{tree}"])?- .trim()- .to_string();- let base_tree = wt_repo- .run_command(&["rev-parse", &format!("{}^{{tree}}", base)])?- .trim()- .to_string();-- if head_tree == base_tree {- // Trees are identical - check if working tree is also clean- if status_info.is_dirty {- // Rare case: trees match but working tree has uncommitted changes- // Need to compute actual diff to get accurate line counts- Some(wt_repo.working_tree_diff_vs_ref(base)?)- } else {- // Trees match and working tree is clean → matches main exactly- Some(LineDiff::default())- }- } else {- // Trees differ - skip the expensive scan- // Return None to indicate "not computed" (optimization)- None- }- } else {- Some(LineDiff::default()) // Primary worktree always matches itself- };+ let working_tree_diff_with_main =+ wt_repo.working_tree_diff_with_base(base_branch, status_info.is_dirty)?;let branch_diff = BranchDiffTotals::compute(&wt_repo, base_branch, &wt.head)?;// Get worktree state (merge/rebase/etc)diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex bfafb8dfc..298eecb6c 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -81,22 +81,7 @@ impl RepositoryCliExt for Repository {let status = self.run_command(&["status", "--porcelain"]).git_context("Failed to get status")?;- let untracked = get_untracked_files(&status);-- if untracked.is_empty() {- return Ok(());- }-- let count = untracked.len();- let file_word = if count == 1 { "file" } else { "files" };- crate::output::warning(format!(- "{WARNING}Auto-staging {count} untracked {file_word}:{WARNING:#}"- ))?;-- let joined_files = untracked.join("\n");- crate::output::gutter(format_with_gutter(&joined_files, "", None))?;-- Ok(())+ AutoStageWarning::from_status(&status).emit()}fn gather_list_data(@@ -358,12 +343,37 @@ fn load_project_config_at(repo_root: &Path) -> Result<Option<ProjectConfig>, GitProjectConfig::load(repo_root).git_context("Failed to load project config")}-fn get_untracked_files(status_output: &str) -> Vec<String> {- status_output- .lines()- .filter_map(|line| line.strip_prefix("?? "))- .map(|filename| filename.to_string())- .collect()+struct AutoStageWarning {+ files: Vec<String>,+}++impl AutoStageWarning {+ fn from_status(status_output: &str) -> Self {+ let files = status_output+ .lines()+ .filter_map(|line| line.strip_prefix("?? "))+ .map(|filename| filename.to_string())+ .collect();++ Self { files }+ }++ fn emit(&self) -> Result<(), GitError> {+ if self.files.is_empty() {+ return Ok(());+ }++ let count = self.files.len();+ let file_word = if count == 1 { "file" } else { "files" };+ crate::output::warning(format!(+ "{WARNING}Auto-staging {count} untracked {file_word}:{WARNING:#}"+ ))?;++ let joined_files = self.files.join("\n");+ crate::output::gutter(format_with_gutter(&joined_files, "", None))?;++ Ok(())+ }}pub(crate) struct TargetWorktreeStash {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 0919d258e..5bcb1bc25 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -576,6 +576,32 @@ impl Repository {LineDiff::from_numstat(&stdout)}+ /// Return the working tree diff versus a base branch when their trees match.+ ///+ /// When `base_branch` is `None` (primary worktree), this always returns `Some(LineDiff::default())`.+ /// If the base branch tree matches HEAD and the working tree is dirty, the precise diff is+ /// computed; otherwise we return zero to indicate the trees (and working tree) match.+ /// When the trees differ, we return `None` so callers can skip expensive comparisons.+ pub fn working_tree_diff_with_base(+ &self,+ base_branch: Option<&str>,+ working_tree_dirty: bool,+ ) -> Result<Option<LineDiff>, GitError> {+ let Some(branch) = base_branch else {+ return Ok(Some(LineDiff::default()));+ };++ if !self.branch_tree_matches_head(branch)? {+ return Ok(None);+ }++ if working_tree_dirty {+ self.working_tree_diff_vs_ref(branch).map(Some)+ } else {+ Ok(Some(LineDiff::default()))+ }+ }+/// Get line diff statistics between two refs (using three-dot diff for merge base).///pub fn branch_diff_stats(&self, base: &str, head: &str) -> Result<LineDiff, GitError> {@@ -727,6 +753,17 @@ impl Repository {Ok(branch)}+ fn branch_tree_matches_head(&self, branch: &str) -> Result<bool, GitError> {+ let head_tree = self.rev_parse_tree("HEAD^{tree}")?;+ let branch_tree = self.rev_parse_tree(&format!("{branch}^{{tree}}"))?;+ Ok(head_tree == branch_tree)+ }++ fn rev_parse_tree(&self, spec: &str) -> Result<String, GitError> {+ self.run_command(&["rev-parse", spec])+ .map(|output| output.trim().to_string())+ }+// Private helper methods for default_branch()fn get_local_default_branch(&self, remote: &str) -> Result<String, GitError> {