Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor: Simplify worktree list and diff stats handling
Maximilian Roosc4dadffc5984
diff --git a/src/commands/dev.rs b/src/commands/dev.rsindex 7c98eceeb..bcc4089e8 100644--- a/src/commands/dev.rs+++ b/src/commands/dev.rs@@ -1,6 +1,6 @@use worktrunk::HookType;use worktrunk::config::{ProjectConfig, WorktrunkConfig};-use worktrunk::git::{GitError, GitResultExt, Repository, parse_diff_shortstat};+use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, HINT, HINT_EMOJI, eprintln, format_with_gutter,};@@ -192,8 +192,10 @@ pub fn handle_dev_squash(// Count commits since merge baselet commit_count = repo.count_commits(&merge_base, "HEAD")?;- // Check if there are staged changes- let has_staged = repo.has_staged_changes()?;+ // Check if there are staged changes (git diff --cached returns 0 if no changes, 1 if changes exist)+ let no_staged_changes =+ repo.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;+ let has_staged = !no_staged_changes;// Handle different scenariosif commit_count == 0 && !has_staged {@@ -218,11 +220,7 @@ pub fn handle_dev_squash(// Either multiple commits OR single commit with staged changes - squash them// Get diff stats early for display in progress messagelet range = format!("{}..HEAD", merge_base);- let diff_shortstat = repo- .run_command(&["diff", "--shortstat", &range])- .unwrap_or_default();- let stats = parse_diff_shortstat(&diff_shortstat);- let stats_parts = stats.format_summary();+ let stats_parts = repo.diff_stats_summary(&["diff", "--shortstat", &range]);let commit_text = if commit_count == 1 {"commit"@@ -278,7 +276,9 @@ pub fn handle_dev_squash(.git_context("Failed to reset to merge base")?;// Check if there are actually any changes to commit- if !repo.has_staged_changes()? {+ let no_staged_changes =+ repo.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;+ if no_staged_changes {let dim = AnstyleStyle::new().dimmed();crate::output::info(format!("{dim}No changes after squashing {commit_count} {commit_text} (commits resulted in no net changes){dim:#}"diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex 722831ba1..a143551c4 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -547,19 +547,19 @@ pub fn gather_list_data() -> Result<Option<ListData>, GitError> {let worktrees = repo.list_worktrees()?;- if worktrees.is_empty() {+ if worktrees.worktrees.is_empty() {return Ok(None);}// Get primary worktree - clone it for use in closure- let primary = worktrees.primary().clone();+ let primary = worktrees.worktrees[0].clone();// Get current worktree to identify active onelet current_worktree_path = repo.worktree_root().ok();// Gather enhanced information for all worktrees in parallellet worktree_results: Vec<Result<WorktreeInfo, GitError>> = worktrees- .all()+ .worktrees.par_iter().map(|wt| WorktreeInfo::from_worktree(wt, &primary, fetch_ci, check_conflicts)).collect();diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex c416e3daa..c5abc92e7 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,6 +1,6 @@use worktrunk::HookType;use worktrunk::config::{Command, CommandPhase, ProjectConfig, WorktrunkConfig};-use worktrunk::git::{GitError, GitResultExt, Repository, parse_diff_shortstat};+use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, HINT, HINT_EMOJI, WARNING,format_bash_with_gutter, format_with_gutter,@@ -233,7 +233,7 @@ pub fn handle_merge(// Get primary worktree path before cleanup (while we can still run git commands)let worktrees = repo.list_worktrees()?;- let primary_worktree_dir = worktrees.primary().path.clone();+ let primary_worktree_dir = worktrees.worktrees[0].path.clone();// Finish worktree unless --no-remove was specifiedif !no_remove {@@ -370,11 +370,7 @@ pub fn commit_staged_changes(let repo = Repository::current();// Get diff stats for staged changes- let diff_shortstat = repo- .run_command(&["diff", "--staged", "--shortstat"])- .unwrap_or_default();- let stats = parse_diff_shortstat(&diff_shortstat);- let stats_parts = stats.format_summary();+ let stats_parts = repo.diff_stats_summary(&["diff", "--staged", "--shortstat"]);// Format progress message based on whether we're using LLM or fallbacklet action = if commit_generation_config.is_configured() {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 1d6707753..278a2ee16 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -102,7 +102,7 @@use std::path::PathBuf;use worktrunk::config::{CommandPhase, ProjectConfig, WorktrunkConfig};-use worktrunk::git::{GitError, GitResultExt, Repository, parse_diff_shortstat};+use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, format_bash_with_gutter};use super::command_executor::{CommandContext, prepare_project_commands};@@ -318,7 +318,7 @@ fn remove_current_worktree(.current_branch()?.ok_or_else(|| GitError::CommandFailed("Not on a branch".to_string()))?;let worktrees = repo.list_worktrees()?;- let primary_worktree_dir = worktrees.primary().path.clone();+ let primary_worktree_dir = worktrees.worktrees[0].path.clone();// Return paths - deletion will happen in output handler after cd directive is emittedOk(RemoveResult::RemovedWorktree {@@ -383,7 +383,7 @@ fn remove_worktree_by_name(let (primary_path, changed_directory) = if removing_current {// Removing current worktree - will cd to primary worktreelet worktrees = repo.list_worktrees()?;- (worktrees.primary().path.clone(), true)+ (worktrees.worktrees[0].path.clone(), true)} else {// Removing different worktree - stay in current location(repo.worktree_root()?, false)@@ -679,10 +679,10 @@ pub fn handle_push(let commit_count = repo.count_commits(&target_branch, "HEAD")?;// Get diff statistics BEFORE push (will be needed for success message later)- let diff_shortstat = if commit_count > 0 {- repo.run_command(&["diff", "--shortstat", &format!("{}..HEAD", target_branch)])?+ let stats_summary = if commit_count > 0 {+ repo.diff_stats_summary(&["diff", "--shortstat", &format!("{}..HEAD", target_branch)])} else {- String::new()+ Vec::new()};// Build and show consolidated message with squash/rebase info@@ -774,14 +774,12 @@ pub fn handle_push(// Show success message after push completesif commit_count > 0 {// Use the diff statistics captured earlier (before push)- let stats = parse_diff_shortstat(&diff_shortstat);-let mut summary_parts = vec![format!("{} commit{}",commit_count,if commit_count == 1 { "" } else { "s" })];- summary_parts.extend(stats.format_summary());+ summary_parts.extend(stats_summary);crate::output::success(format!("{GREEN}{verb} {GREEN_BOLD}{target_branch}{GREEN_BOLD:#}{GREEN:#} ({})",diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 70aca74ee..d62357608 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -3,8 +3,6 @@//! Provides functions for expanding template variables in paths and commands with//! proper shell escaping to prevent injection vulnerabilities.-use std::path::PathBuf;-/// Expand template variables in a string////// All templates support:@@ -50,22 +48,6 @@ pub fn expand_template(result}-/// Expand tilde in file paths to home directory (cross-platform)-///-/// Uses shellexpand for proper tilde expansion following shell conventions.-///-/// # Examples-/// ```-/// use worktrunk::config::expand_tilde;-///-/// let path = expand_tilde("~/config/file.txt");-/// // Unix: /home/user/config/file.txt-/// // Windows: C:\Users\user\config\file.txt-/// ```-pub fn expand_tilde(path: &str) -> PathBuf {- PathBuf::from(shellexpand::tilde(path).as_ref())-}-/// Expand command template variables////// Convenience function for expanding command templates with common variables.diff --git a/src/config/mod.rs b/src/config/mod.rsindex 0fc12bf56..9124bfe60 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -45,7 +45,7 @@ mod user;// Re-export public typespub use commands::{Command, CommandConfig, CommandPhase};-pub use expansion::{expand_command_template, expand_template, expand_tilde};+pub use expansion::{expand_command_template, expand_template};pub use project::ProjectConfig;pub use user::{CommitGenerationConfig, UserProjectConfig, WorktrunkConfig, get_config_path};@@ -653,22 +653,6 @@ task2 = "echo 'Task 2 running' > task2.txt"assert_eq!(result, "/path/to/repo/target -> /path/to/worktree/target");}- #[test]- fn test_expand_tilde_with_home() {- // Test that paths starting with ~/ get HOME prepended if HOME is set- // We can't set HOME in tests (no unsafe allowed), but we can test the logic- let result = expand_tilde("~/config/file.txt");- // If HOME is set, result should start with it. If not, it's just the path.- // Either way is valid behavior.- assert!(result.to_str().unwrap().contains("config/file.txt"));- }-- #[test]- fn test_expand_tilde_without_tilde() {- let result = expand_tilde("/absolute/path");- assert_eq!(result, std::path::PathBuf::from("/absolute/path"));- }-#[test]fn test_commit_generation_config_mutually_exclusive_validation() {// Test that deserialization rejects both template and template-filediff --git a/src/git/mod.rs b/src/git/mod.rsindex 5ae07733a..454631747 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -51,11 +51,11 @@ pub struct Worktree {////// This type ensures:/// - Bare worktrees are filtered out (only worktrees with working trees are included)-/// - The primary worktree is always identifiable (first non-bare worktree)+/// - The primary worktree is always identifiable (first non-bare worktree at index 0)/// - Construction fails if no valid worktrees exist#[derive(Debug, Clone)]pub struct WorktreeList {- worktrees: Vec<Worktree>,+ pub worktrees: Vec<Worktree>,}impl WorktreeList {@@ -69,31 +69,6 @@ impl WorktreeList {Ok(Self { worktrees })}-- /// Get the primary worktree (first non-bare worktree).- pub fn primary(&self) -> &Worktree {- &self.worktrees[0]- }-- /// Get all worktrees (non-bare only).- pub fn all(&self) -> &[Worktree] {- &self.worktrees- }-- /// Number of worktrees.- pub fn len(&self) -> usize {- self.worktrees.len()- }-- /// Check if empty (should never be true for successfully constructed instances).- pub fn is_empty(&self) -> bool {- self.worktrees.is_empty()- }-- /// Iterate over worktrees.- pub fn iter(&self) -> impl Iterator<Item = &Worktree> {- self.worktrees.iter()- }}impl IntoIterator for WorktreeList {@@ -187,10 +162,9 @@ mod tests {let list = WorktreeList::from_raw(worktrees).unwrap();- assert_eq!(list.len(), 2);- assert_eq!(list.all().len(), 2);- assert_eq!(list.all()[0].branch, Some("main".to_string()));- assert_eq!(list.all()[1].branch, Some("feature".to_string()));+ assert_eq!(list.worktrees.len(), 2);+ assert_eq!(list.worktrees[0].branch, Some("main".to_string()));+ assert_eq!(list.worktrees[1].branch, Some("feature".to_string()));}#[test]@@ -218,8 +192,8 @@ mod tests {let list = WorktreeList::from_raw(worktrees).unwrap();- assert_eq!(list.primary().branch, Some("main".to_string()));- assert_eq!(list.primary().path, PathBuf::from("/repo/main"));+ assert_eq!(list.worktrees[0].branch, Some("main".to_string()));+ assert_eq!(list.worktrees[0].path, PathBuf::from("/repo/main"));}#[test]@@ -270,7 +244,11 @@ mod tests {let list = WorktreeList::from_raw(worktrees).unwrap();- let branches: Vec<_> = list.iter().filter_map(|wt| wt.branch.as_ref()).collect();+ let branches: Vec<_> = list+ .worktrees+ .iter()+ .filter_map(|wt| wt.branch.as_ref())+ .collect();assert_eq!(branches, vec!["main", "feature"]);let branches_owned: Vec<_> = list.into_iter().filter_map(|wt| wt.branch).collect();diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 8447635f9..4729ca2de 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -509,6 +509,22 @@ impl Repository {parse_numstat(&stdout)}+ /// Get formatted diff stats summary for display.+ ///+ /// Returns a vector of formatted strings like ["3 files", "+45", "-12"].+ /// Returns empty vector if diff command fails or produces no output.+ ///+ /// This method combines git diff --shortstat, parsing, and formatting into a single call.+ pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {+ self.run_command(args)+ .ok()+ .map(|output| {+ use crate::git::parse_diff_shortstat;+ parse_diff_shortstat(&output).format_summary()+ })+ .unwrap_or_default()+ }+/// Get all branch names (local branches only).pub fn all_branches(&self) -> Result<Vec<String>, GitError> {let stdout = self.run_command(&["branch", "--format=%(refname:short)"])?;@@ -554,13 +570,6 @@ impl Repository {Ok(output.lines().map(String::from).collect())}- /// Check if there are staged changes.- pub fn has_staged_changes(&self) -> Result<bool, GitError> {- // exit code 0 = no changes, 1 = has changes- let no_changes = self.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;- Ok(!no_changes)- }-/// List all worktrees for this repository.////// Returns a WorktreeList that automatically filters out bare repositories@@ -576,6 +585,7 @@ impl Repository {let worktrees = self.list_worktrees()?;Ok(worktrees+ .worktrees.iter().find(|wt| wt.branch.as_deref() == Some(branch)).map(|wt| wt.path.clone()))@@ -588,6 +598,7 @@ impl Repository {// Collect branches that have worktreeslet branches_with_worktrees: std::collections::HashSet<String> = worktrees+ .worktrees.iter().filter_map(|wt| wt.branch.clone()).collect();diff --git a/src/llm.rs b/src/llm.rsindex 11c60e952..70df398fb 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -1,5 +1,5 @@use std::io::Write;-use std::path::Path;+use std::path::{Path, PathBuf};use std::process::{self, Stdio};use worktrunk::config::CommitGenerationConfig;use worktrunk::git::{GitError, Repository};@@ -114,7 +114,7 @@ fn build_commit_prompt(let template = match (&config.template, &config.template_file) {(Some(inline), None) => inline.clone(),(None, Some(path)) => {- let expanded_path = worktrunk::config::expand_tilde(path);+ let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());std::fs::read_to_string(&expanded_path).map_err(|e| {format!("Failed to read template-file '{}': {}",@@ -160,7 +160,7 @@ fn build_squash_prompt(let template = match (&config.squash_template, &config.squash_template_file) {(Some(inline), None) => inline.clone(),(None, Some(path)) => {- let expanded_path = worktrunk::config::expand_tilde(path);+ let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());std::fs::read_to_string(&expanded_path).map_err(|e| {format!("Failed to read squash-template-file '{}': {}",diff --git a/src/main.rs b/src/main.rsindex a0a78faeb..953db519a 100644--- a/src/main.rs+++ b/src/main.rs@@ -671,7 +671,7 @@ fn main() {let mut others = Vec::new();let mut current = None;- for worktree_name in worktrees.iter() {+ for worktree_name in &worktrees {// Resolve "@" to current branch (fail fast on errors like detached HEAD)let resolved = repo.resolve_worktree_name(worktree_name)?;