Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Enhance `wt list` output with more details and sorting
Maximilian Roos4a21eed71263
diff --git a/src/git.rs b/src/git.rsindex e69ae02a6..dffa375d4 100644--- a/src/git.rs+++ b/src/git.rs@@ -420,6 +420,102 @@ pub fn get_changed_files_in(Ok(stdout.lines().map(|s| s.to_string()).collect())}+/// Get commit timestamp in seconds since epoch+pub fn get_commit_timestamp(commit: &str) -> Result<i64, GitError> {+ get_commit_timestamp_in(std::path::Path::new("."), commit)+}++/// Get commit timestamp in seconds since epoch for a repository at the given path+pub fn get_commit_timestamp_in(path: &std::path::Path, commit: &str) -> Result<i64, GitError> {+ let stdout = run_git_command(&["show", "-s", "--format=%ct", commit], Some(path))?;+ stdout+ .trim()+ .parse()+ .map_err(|e| GitError::ParseError(format!("Failed to parse timestamp: {}", e)))+}++/// Calculate commits ahead and behind between two refs+/// Returns (ahead, behind) where ahead is commits in head not in base,+/// and behind is commits in base not in head+pub fn get_ahead_behind(base: &str, head: &str) -> Result<(usize, usize), GitError> {+ get_ahead_behind_in(std::path::Path::new("."), base, head)+}++/// Calculate commits ahead and behind at the given path+pub fn get_ahead_behind_in(+ path: &std::path::Path,+ base: &str,+ head: &str,+) -> Result<(usize, usize), GitError> {+ let ahead = count_commits_in(path, base, head)?;+ let behind = count_commits_in(path, head, base)?;+ Ok((ahead, behind))+}++/// Get line diff statistics for working tree changes (unstaged + staged)+/// Returns (added_lines, deleted_lines)+pub fn get_working_tree_diff_stats() -> Result<(usize, usize), GitError> {+ get_working_tree_diff_stats_in(std::path::Path::new("."))+}++/// Get line diff statistics for working tree changes at the given path+pub fn get_working_tree_diff_stats_in(path: &std::path::Path) -> Result<(usize, usize), GitError> {+ let stdout = run_git_command(&["diff", "--numstat", "HEAD"], Some(path))?;+ parse_numstat(&stdout)+}++/// Get line diff statistics between two refs (using three-dot diff for merge base)+/// Returns (added_lines, deleted_lines)+pub fn get_branch_diff_stats(base: &str, head: &str) -> Result<(usize, usize), GitError> {+ get_branch_diff_stats_in(std::path::Path::new("."), base, head)+}++/// Get line diff statistics between two refs at the given path+pub fn get_branch_diff_stats_in(+ path: &std::path::Path,+ base: &str,+ head: &str,+) -> Result<(usize, usize), GitError> {+ let range = format!("{}...{}", base, head);+ let stdout = run_git_command(&["diff", "--numstat", &range], Some(path))?;+ parse_numstat(&stdout)+}++/// Parse git diff --numstat output+/// Format: "added\tdeleted\tfilename" per line+fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {+ let mut total_added = 0;+ let mut total_deleted = 0;++ for line in output.lines() {+ if line.trim().is_empty() {+ continue;+ }++ let parts: Vec<&str> = line.split('\t').collect();+ if parts.len() < 2 {+ continue;+ }++ // Binary files show "-" for added/deleted+ if parts[0] == "-" || parts[1] == "-" {+ continue;+ }++ let added: usize = parts[0]+ .parse()+ .map_err(|e| GitError::ParseError(format!("Failed to parse added lines: {}", e)))?;+ let deleted: usize = parts[1]+ .parse()+ .map_err(|e| GitError::ParseError(format!("Failed to parse deleted lines: {}", e)))?;++ total_added += added;+ total_deleted += deleted;+ }++ Ok((total_added, total_deleted))+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/main.rs b/src/main.rsindex 00467f1e2..d4ecd1046 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,8 +1,10 @@+use anstyle::{AnsiColor, Color, Style};use clap::{Parser, Subcommand};use std::process;use worktrunk::git::{- GitError, branch_exists, count_commits, get_changed_files, get_current_branch,- get_current_branch_in, get_default_branch, get_git_common_dir, get_worktree_root,+ GitError, branch_exists, count_commits, get_ahead_behind_in, get_branch_diff_stats_in,+ get_changed_files, get_commit_timestamp_in, get_current_branch, get_current_branch_in,+ get_default_branch, get_git_common_dir, get_working_tree_diff_stats_in, get_worktree_root,has_merge_commits, is_ancestor, is_dirty, is_dirty_in, is_in_worktree, list_worktrees,worktree_for_branch,};@@ -131,45 +133,157 @@ fn handle_init(shell_name: &str, cmd: &str, hook_str: &str) -> Result<(), StringOk(())}+struct WorktreeInfo {+ path: std::path::PathBuf,+ head: String,+ branch: Option<String>,+ timestamp: i64,+ ahead: usize,+ behind: usize,+ working_tree_diff: (usize, usize),+ branch_diff: (usize, usize),+ is_primary: bool,+ detached: bool,+ bare: bool,+ locked: Option<String>,+ prunable: Option<String>,+}+fn handle_list() -> Result<(), GitError> {let worktrees = list_worktrees()?;- for wt in worktrees {- println!("{}", wt.path.display());- println!(" HEAD: {}", &wt.head[..8.min(wt.head.len())]);+ if worktrees.is_empty() {+ return Ok(());+ }- if let Some(branch) = wt.branch {- println!(" branch: {}", branch);- }+ // First worktree is the primary+ let primary = &worktrees[0];+ let primary_branch = primary.branch.as_ref();- if wt.detached {- println!(" (detached)");- }+ // Gather enhanced information for all worktrees+ let mut infos: Vec<WorktreeInfo> = Vec::new();- if wt.bare {- println!(" (bare)");- }+ for (idx, wt) in worktrees.iter().enumerate() {+ let is_primary = idx == 0;- if let Some(reason) = wt.locked {- if reason.is_empty() {- println!(" (locked)");- } else {- println!(" (locked: {})", reason);- }+ // Get commit timestamp+ let timestamp = get_commit_timestamp_in(&wt.path, &wt.head).unwrap_or(0);++ // Calculate ahead/behind relative to primary branch (only if primary has a branch)+ let (ahead, behind) = if is_primary || primary_branch.is_none() {+ (0, 0)+ } else {+ get_ahead_behind_in(&wt.path, primary_branch.unwrap(), &wt.head).unwrap_or((0, 0))+ };++ // Get working tree diff stats+ let working_tree_diff = get_working_tree_diff_stats_in(&wt.path).unwrap_or((0, 0));++ // Get branch diff stats (downstream of primary, only if primary has a branch)+ let branch_diff = if is_primary || primary_branch.is_none() {+ (0, 0)+ } else {+ get_branch_diff_stats_in(&wt.path, primary_branch.unwrap(), &wt.head).unwrap_or((0, 0))+ };++ infos.push(WorktreeInfo {+ path: wt.path.clone(),+ head: wt.head.clone(),+ branch: wt.branch.clone(),+ timestamp,+ ahead,+ behind,+ working_tree_diff,+ branch_diff,+ is_primary,+ detached: wt.detached,+ bare: wt.bare,+ locked: wt.locked.clone(),+ prunable: wt.prunable.clone(),+ });+ }++ // Sort by most recent commit (descending)+ infos.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));++ // Display formatted output+ for info in infos {+ format_worktree_line(&info);+ }++ Ok(())+}++fn format_worktree_line(info: &WorktreeInfo) {+ let primary_style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));++ let branch_display = info.branch.as_deref().unwrap_or("(detached)");+ let short_head = &info.head[..8.min(info.head.len())];++ // Build the line components+ let mut parts = Vec::new();++ // Branch name and HEAD+ parts.push(format!("{} {}", branch_display, short_head));++ // Ahead/behind (only for non-primary)+ if !info.is_primary {+ if info.ahead > 0 || info.behind > 0 {+ parts.push(format!("↑{} ↓{}", info.ahead, info.behind));}+ }- if let Some(reason) = wt.prunable {- if reason.is_empty() {- println!(" (prunable)");- } else {- println!(" (prunable: {})", reason);- }+ // Working tree diff+ let (wt_added, wt_deleted) = info.working_tree_diff;+ if wt_added > 0 || wt_deleted > 0 {+ parts.push(format!("+{} -{}", wt_added, wt_deleted));+ }++ // Branch diff (only for non-primary)+ if !info.is_primary {+ let (br_added, br_deleted) = info.branch_diff;+ if br_added > 0 || br_deleted > 0 {+ parts.push(format!("(+{} -{})", br_added, br_deleted));}+ }- println!();+ // Worktree states+ if info.detached {+ parts.push("(detached)".to_string());+ }+ if info.bare {+ parts.push("(bare)".to_string());+ }+ if let Some(ref reason) = info.locked {+ if reason.is_empty() {+ parts.push("(locked)".to_string());+ } else {+ parts.push(format!("(locked: {})", reason));+ }+ }+ if let Some(ref reason) = info.prunable {+ if reason.is_empty() {+ parts.push("(prunable)".to_string());+ } else {+ parts.push(format!("(prunable: {})", reason));+ }}- Ok(())+ // Path+ parts.push(info.path.display().to_string());++ let line = parts.join(" ");++ if info.is_primary {+ println!(+ "{}{}{}",+ primary_style.render(),+ line,+ primary_style.render_reset()+ );+ } else {+ println!("{}", line);+ }}fn handle_switch(diff --git a/tests/snapshots/integration__integration_tests__list__detached_head.snap b/tests/snapshots/integration__integration_tests__list__detached_head.snapindex e1a8ff5c8..e05698636 100644--- a/tests/snapshots/integration__integration_tests__list__detached_head.snap+++ b/tests/snapshots/integration__integration_tests__list__detached_head.snap@@ -17,9 +17,6 @@ info:success: trueexit_code: 0----- stdout ------[REPO]- HEAD: [SHA]- (detached)-+[36m(detached) [SHA] (detached) [REPO][0m----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap b/tests/snapshots/integration__integration_tests__list__locked_no_reason.snapindex fb320bb7a..db2b7bead 100644--- a/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap+++ b/tests/snapshots/integration__integration_tests__list__locked_no_reason.snap@@ -17,14 +17,7 @@ info:success: trueexit_code: 0----- stdout ------[REPO]- HEAD: [SHA]- branch: main--[WORKTREE_LOCKED_NO_REASON]- HEAD: [SHA]- branch: locked-no-reason- (locked)-+[36mmain [SHA] [REPO][0m+locked-no-reason [SHA] (locked) [WORKTREE_LOCKED_NO_REASON]----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list__locked_worktree.snap b/tests/snapshots/integration__integration_tests__list__locked_worktree.snapindex 714e8fd04..229486303 100644--- a/tests/snapshots/integration__integration_tests__list__locked_worktree.snap+++ b/tests/snapshots/integration__integration_tests__list__locked_worktree.snap@@ -17,14 +17,7 @@ info:success: trueexit_code: 0----- stdout ------[REPO]- HEAD: [SHA]- branch: main--[WORKTREE_LOCKED_FEATURE]- HEAD: [SHA]- branch: locked-feature- (locked: Testing lock functionality)-+[36mmain [SHA] [REPO][0m+locked-feature [SHA] (locked: Testing lock functionality) [WORKTREE_LOCKED_FEATURE]----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap b/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snapindex 4c7e314b6..cdfd0c544 100644--- a/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap+++ b/tests/snapshots/integration__integration_tests__list__multiple_worktrees.snap@@ -17,17 +17,8 @@ info:success: trueexit_code: 0----- stdout ------[REPO]- HEAD: [SHA]- branch: main--[WORKTREE_FEATURE_A]- HEAD: [SHA]- branch: feature-a--[WORKTREE_FEATURE_B]- HEAD: [SHA]- branch: feature-b-+[36mmain [SHA] [REPO][0m+feature-a [SHA] [WORKTREE_FEATURE_A]+feature-b [SHA] [WORKTREE_FEATURE_B]----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list__single_worktree.snap b/tests/snapshots/integration__integration_tests__list__single_worktree.snapindex 65e738115..f0213ffa1 100644--- a/tests/snapshots/integration__integration_tests__list__single_worktree.snap+++ b/tests/snapshots/integration__integration_tests__list__single_worktree.snap@@ -17,9 +17,6 @@ info:success: trueexit_code: 0----- stdout ------[REPO]- HEAD: [SHA]- branch: main-+[36mmain [SHA] [REPO][0m----- stderr -----