Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Improve branch completion with metadata
Maximilian Roos7e4672609895
diff --git a/src/completion.rs b/src/completion.rsindex b0a5c627d..1a60581e0 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -6,7 +6,8 @@ use clap_complete::engine::{ArgValueCompleter, CompletionCandidate, ValueCompletuse clap_complete::env::CompleteEnv;use crate::cli;-use worktrunk::git::Repository;+use crate::display::format_relative_time_short;+use worktrunk::git::{BranchCategory, Repository};/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`pub fn maybe_handle_env_completion() -> bool {@@ -56,18 +57,26 @@ fn complete_branches(suppress_with_create: bool) -> Vec<CompletionCandidate> {return Vec::new();}- let branches = load_branches();+ let branches = match Repository::current().branches_for_completion() {+ Ok(b) => b,+ Err(_) => return Vec::new(),+ };+if branches.is_empty() {return Vec::new();}- branches.into_iter().map(CompletionCandidate::new).collect()-}--fn load_branches() -> Vec<String> {- Repository::current()- .all_branches()- .unwrap_or_else(|_| Vec::new())+ branches+ .into_iter()+ .map(|branch| {+ let time_str = format_relative_time_short(branch.timestamp);+ let help = match branch.category {+ BranchCategory::Worktree | BranchCategory::Local => time_str,+ BranchCategory::Remote(remote) => format!("{}, {}", time_str, remote),+ };+ CompletionCandidate::new(branch.name).help(Some(help.into()))+ })+ .collect()}fn suppress_switch_branch_completion() -> bool {diff --git a/src/display.rs b/src/display.rsindex a02aeb988..e47ca3a4b 100644--- a/src/display.rs+++ b/src/display.rs@@ -10,16 +10,19 @@ use std::path::{Path, PathBuf};use std::time::{SystemTime, UNIX_EPOCH};use worktrunk::path::format_path_for_display;+/// Format timestamp as verbose relative time (e.g., "2 hours ago")pub fn format_relative_time(timestamp: i64) -> String {- const MINUTE: i64 = 60;- const HOUR: i64 = MINUTE * 60;- const DAY: i64 = HOUR * 24;- const WEEK: i64 = DAY * 7;- const MONTH: i64 = DAY * 30; // Approximate calendar month- const YEAR: i64 = DAY * 365; // Approximate calendar year+ format_relative_time_impl(timestamp, get_now(), false)+}++/// Format timestamp as abbreviated relative time (e.g., "2h")+pub fn format_relative_time_short(timestamp: i64) -> String {+ format_relative_time_impl(timestamp, get_now(), true)+}- // Respect SOURCE_DATE_EPOCH for reproducible builds/tests- let now = std::env::var("SOURCE_DATE_EPOCH")+/// Get current time, respecting SOURCE_DATE_EPOCH for reproducible builds/tests+fn get_now() -> i64 {+ std::env::var("SOURCE_DATE_EPOCH").ok().and_then(|val| val.parse::<i64>().ok()).unwrap_or_else(|| {@@ -27,36 +30,49 @@ pub fn format_relative_time(timestamp: i64) -> String {.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64- });+ })+}++fn format_relative_time_impl(timestamp: i64, now: i64, short: bool) -> String {+ const MINUTE: i64 = 60;+ const HOUR: i64 = MINUTE * 60;+ const DAY: i64 = HOUR * 24;+ const WEEK: i64 = DAY * 7;+ const MONTH: i64 = DAY * 30;+ const YEAR: i64 = DAY * 365;let seconds_ago = now - timestamp;if seconds_ago < 0 {- return "in the future".to_string();+ return if short { "future" } else { "in the future" }.to_string();}if seconds_ago < MINUTE {- return "just now".to_string();+ return if short { "now" } else { "just now" }.to_string();}- const UNITS: &[(i64, &str)] = &[- (YEAR, "year"),- (MONTH, "month"),- (WEEK, "week"),- (DAY, "day"),- (HOUR, "hour"),- (MINUTE, "minute"),+ const UNITS: &[(i64, &str, &str)] = &[+ (YEAR, "year", "y"),+ (MONTH, "month", "mo"),+ (WEEK, "week", "w"),+ (DAY, "day", "d"),+ (HOUR, "hour", "h"),+ (MINUTE, "minute", "m"),];- for &(unit_seconds, label) in UNITS {+ for &(unit_seconds, label, abbrev) in UNITS {let value = seconds_ago / unit_seconds;if value > 0 {- let plural = if value == 1 { "" } else { "s" };- return format!("{} {}{} ago", value, label, plural);+ return if short {+ format!("{}{}", value, abbrev)+ } else {+ let plural = if value == 1 { "" } else { "s" };+ format!("{} {}{} ago", value, label, plural)+ };}}- "just now".to_string()+ if short { "now" } else { "just now" }.to_string()}/// Find the common prefix among all pathsdiff --git a/src/git/mod.rs b/src/git/mod.rsindex 162ec48ab..360c63500 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -39,6 +39,28 @@ pub use error::{};pub use repository::{Repository, set_base_path};+/// Category of branch for completion display+#[derive(Debug, Clone, PartialEq)]+pub enum BranchCategory {+ /// Branch has an active worktree+ Worktree,+ /// Local branch without worktree+ Local,+ /// Remote-only branch (includes remote name)+ Remote(String),+}++/// Branch information for shell completions+#[derive(Debug, Clone)]+pub struct CompletionBranch {+ /// Branch name (local name for remotes, e.g., "fix" not "origin/fix")+ pub name: String,+ /// Unix timestamp of last commit+ pub timestamp: i64,+ /// Category for sorting and display+ pub category: BranchCategory,+}+// Re-export parsing helpers for internal usepub(crate) use parse::DefaultBranchName;diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 31d91b1ca..dfe598df9 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -7,8 +7,8 @@ use anyhow::{Context, bail};// Import types and functions from parent module (mod.rs)use super::{- DefaultBranchName, DiffStats, LineDiff, SwitchHistory, Worktree, WorktreeList, detached_head,- error_message, parse_error, uncommitted_changes,+ BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, LineDiff, SwitchHistory,+ Worktree, WorktreeList, detached_head, error_message, parse_error, uncommitted_changes,};/// Global base path for repository operations, set by -C flag@@ -794,6 +794,124 @@ impl Repository {.collect())}+ /// Get branches with metadata for shell completions.+ ///+ /// Returns branches in completion order: worktrees first, then local branches,+ /// then remote-only branches. Each category is sorted by recency.+ ///+ /// For remote branches, returns the local name (e.g., "fix" not "origin/fix")+ /// since `git worktree add path fix` auto-creates a tracking branch.+ pub fn branches_for_completion(&self) -> anyhow::Result<Vec<CompletionBranch>> {+ use std::collections::HashSet;++ // Get worktree branches+ let worktrees = self.list_worktrees()?;+ let worktree_branches: HashSet<String> = worktrees+ .worktrees+ .iter()+ .filter_map(|wt| wt.branch.clone())+ .collect();++ // Get local branches with timestamps+ let local_output = self.run_command(&[+ "for-each-ref",+ "--sort=-committerdate",+ "--format=%(refname:short)\t%(committerdate:unix)",+ "refs/heads/",+ ])?;++ let local_branches: Vec<(String, i64)> = local_output+ .lines()+ .filter_map(|line| {+ let parts: Vec<&str> = line.split('\t').collect();+ if parts.len() == 2 {+ let timestamp = parts[1].parse().unwrap_or(0);+ Some((parts[0].to_string(), timestamp))+ } else {+ None+ }+ })+ .collect();++ let local_branch_names: HashSet<String> =+ local_branches.iter().map(|(n, _)| n.clone()).collect();++ // Get remote branches with timestamps+ let remote = self+ .primary_remote()+ .unwrap_or_else(|_| "origin".to_string());+ let remote_ref_path = format!("refs/remotes/{}/", remote);+ let remote_prefix = format!("{}/", remote);++ let remote_output = self.run_command(&[+ "for-each-ref",+ "--sort=-committerdate",+ "--format=%(refname:short)\t%(committerdate:unix)",+ &remote_ref_path,+ ])?;++ let remote_head = format!("{}/HEAD", remote);+ let remote_branches: Vec<(String, String, i64)> = remote_output+ .lines()+ .filter_map(|line| {+ let parts: Vec<&str> = line.split('\t').collect();+ if parts.len() == 2 {+ let full_name = parts[0];+ // Skip <remote>/HEAD+ if full_name == remote_head {+ return None;+ }+ // Strip remote prefix to get local name+ let local_name = full_name.strip_prefix(&remote_prefix)?;+ // Skip if local branch exists (user should use local)+ if local_branch_names.contains(local_name) {+ return None;+ }+ let timestamp = parts[1].parse().unwrap_or(0);+ Some((local_name.to_string(), remote.clone(), timestamp))+ } else {+ None+ }+ })+ .collect();++ // Build result: worktrees first, then local, then remote+ let mut result = Vec::new();++ // Worktree branches (sorted by recency from local_branches order)+ for (name, timestamp) in &local_branches {+ if worktree_branches.contains(name) {+ result.push(CompletionBranch {+ name: name.clone(),+ timestamp: *timestamp,+ category: BranchCategory::Worktree,+ });+ }+ }++ // Local branches without worktrees+ for (name, timestamp) in &local_branches {+ if !worktree_branches.contains(name) {+ result.push(CompletionBranch {+ name: name.clone(),+ timestamp: *timestamp,+ category: BranchCategory::Local,+ });+ }+ }++ // Remote-only branches+ for (local_name, remote_name, timestamp) in remote_branches {+ result.push(CompletionBranch {+ name: local_name,+ timestamp,+ category: BranchCategory::Remote(remote_name),+ });+ }++ Ok(result)+ }+/// Get the merge base between two commits.pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<String> {let output = self.run_command(&["merge-base", commit1, commit2])?;