Skip to content

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

Optimize wt list skeleton display speed (#286)

Maximilian Roos51d42b28e919
diff --git a/docs/content/config.md b/docs/content/config.md
index 6f08740aa..1cf1ad4db 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -697,16 +697,17 @@ Usage: <b><span class=c>wt config state</span></b> <span class=c>[OPTIONS]</span
Worktrunk detects the default branch automatically:
-1. **Local cache** — Checks `git rev-parse origin/HEAD` (fast, no network)
-2. **Remote query** — If not cached, queries `git ls-remote` (100ms–2s)
-3. **Cache result** — Stores via `git remote set-head` for future calls
+1. **Worktrunk cache** — Checks `git config worktrunk.default-branch` (single command)
+2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)
+3. **Remote query** — If not cached, queries `git ls-remote` (100ms–2s)
4. **Local inference** — If no remote, infers from local branches
+Once detected, the result is cached in `worktrunk.default-branch` for fast access.
+
The local inference fallback uses these heuristics in order:
- If only one local branch exists, uses it
-- Checks what HEAD points to in main worktree
- Checks `git config init.defaultBranch`
-- Looks for common names: main, master, develop
+- Looks for common names: main, master, develop, trunk
### When to use
diff --git a/src/cli.rs b/src/cli.rs
index bed3da31e..2eb2a71df 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -441,16 +441,17 @@ pub enum StateCommand {
Worktrunk detects the default branch automatically:
-1. **Local cache** — Checks `git rev-parse origin/HEAD` (fast, no network)
-2. **Remote query** — If not cached, queries `git ls-remote` (100ms–2s)
-3. **Cache result** — Stores via `git remote set-head` for future calls
+1. **Worktrunk cache** — Checks `git config worktrunk.default-branch` (single command)
+2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)
+3. **Remote query** — If not cached, queries `git ls-remote` (100ms–2s)
4. **Local inference** — If no remote, infers from local branches
+Once detected, the result is cached in `worktrunk.default-branch` for fast access.
+
The local inference fallback uses these heuristics in order:
- If only one local branch exists, uses it
-- Checks what HEAD points to in main worktree
- Checks `git config init.defaultBranch`
-- Looks for common names: main, master, develop
+- Looks for common names: main, master, develop, trunk
## When to use
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 890f72af0..e41b7e760 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -5,6 +5,27 @@
//! - Parallel operations within each worktree (using scoped threads)
//! - Progressive updates via channels (update UI as each worktree completes)
//!
+//! ## Skeleton Performance (IMPORTANT)
+//!
+//! The skeleton (placeholder table with loading indicators) must render as fast as possible
+//! to give users immediate feedback. Every git command before skeleton adds latency.
+//!
+//! **Minimal pre-skeleton operations (keep this list small!):**
+//! 1. `git worktree list` — get list of worktrees (essential)
+//! 2. `git config worktrunk.default-branch` — identify main worktree for sorting
+//! 3. Path comparison — detect current worktree (NO git command, just canonicalize paths)
+//! 4. `git branch` / `git branch -r` — only if `--branches` / `--remotes` flags
+//! 5. `git show -s --format='%H %ct'` — batch timestamp fetch for sorting
+//! 6. `git rev-parse --is-bare-repository` — for layout (path column visibility)
+//!
+//! **Deferred until after skeleton:**
+//! - `get_switch_previous()` — previous branch detection (updates gutter symbol)
+//! - `effective_integration_target()` — upstream vs local target check
+//! - All computed fields (ahead/behind, diffs, CI status, etc.)
+//!
+//! When adding new features, ask: "Can this be computed after skeleton?" If yes, defer it.
+//! The skeleton shows `·` placeholder for gutter symbols, filled in when data loads.
+//!
//! ## Unified Collection Architecture
//!
//! Progressive and buffered modes use the same collection and rendering code.
@@ -27,7 +48,7 @@ use rayon::prelude::*;
use worktrunk::git::{LineDiff, Repository, Worktree};
use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, warning_message};
-use crate::commands::is_worktree_at_expected_path;
+use crate::commands::is_worktree_at_expected_path_with;
use super::ci_status::PrStatus;
use super::model::{
@@ -599,9 +620,6 @@ pub fn collect(
let default_branch = repo
.default_branch()
.context("Failed to determine default branch")?;
- // Effective target for integration checks: upstream if ahead of local, else local.
- // This handles the case where a branch was merged remotely but user hasn't pulled yet.
- let integration_target = repo.effective_integration_target(&default_branch);
// Main worktree is the worktree on the default branch (if exists), else first worktree
let main_worktree = worktrees
.worktrees
@@ -609,38 +627,73 @@ pub fn collect(
.find(|wt| wt.branch.as_deref() == Some(default_branch.as_str()))
.cloned()
.unwrap_or_else(|| worktrees.main().clone());
- let current_worktree_path = repo.worktree_root().ok();
- let previous_branch = repo.get_switch_previous();
- // Sort worktrees: current first, main second, then by timestamp descending
- let sorted_worktrees = sort_worktrees(
- worktrees.worktrees.clone(),
- &main_worktree,
- current_worktree_path.as_ref(),
- );
+ // Detect current worktree by checking if repo path is inside any worktree.
+ // This avoids a git command - we just compare canonicalized paths.
+ let repo_path_canonical = canonicalize(repo.base_path()).ok();
+ let current_worktree_path = repo_path_canonical.as_ref().and_then(|repo_path| {
+ worktrees.worktrees.iter().find_map(|wt| {
+ canonicalize(&wt.path)
+ .ok()
+ .filter(|wt_path| repo_path.starts_with(wt_path))
+ })
+ });
+
+ // Defer previous_branch lookup until after skeleton - set is_previous later
+ // (skeleton shows placeholder gutter, actual symbols appear when data loads)
// Get branches early for layout calculation and skeleton creation (when --branches is used)
- // Sort by timestamp (most recent first)
let branches_without_worktrees = if show_branches {
- let branches = get_branches_without_worktrees(repo, &worktrees.worktrees)?;
- sort_by_timestamp_desc(branches, |(_, sha)| repo.commit_timestamp(sha).unwrap_or(0))
+ get_branches_without_worktrees(repo, &worktrees.worktrees)?
} else {
Vec::new()
};
// Get remote branches (when --remotes is used)
- // Sort by timestamp (most recent first)
let remote_branches = if show_remotes {
- let branches = get_remote_branches(repo, &worktrees.worktrees)?;
- sort_by_timestamp_desc(branches, |(_, sha)| repo.commit_timestamp(sha).unwrap_or(0))
+ get_remote_branches(repo, &worktrees.worktrees)?
} else {
Vec::new()
};
+ // Batch fetch all timestamps in a single git command for sorting efficiency.
+ // Collect unique commit SHAs from worktrees and branches.
+ let all_shas: Vec<&str> = worktrees
+ .worktrees
+ .iter()
+ .map(|wt| wt.head.as_str())
+ .chain(
+ branches_without_worktrees
+ .iter()
+ .map(|(_, sha)| sha.as_str()),
+ )
+ .chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))
+ .collect();
+ let timestamps = repo.commit_timestamps(&all_shas).unwrap_or_default();
+
+ // Sort worktrees: current first, main second, then by timestamp descending
+ let sorted_worktrees = sort_worktrees_with_cache(
+ worktrees.worktrees.clone(),
+ &main_worktree,
+ current_worktree_path.as_ref(),
+ &timestamps,
+ );
+
+ // Sort branches by timestamp (most recent first)
+ let branches_without_worktrees =
+ sort_by_timestamp_desc_with_cache(branches_without_worktrees, &timestamps, |(_, sha)| {
+ sha.as_str()
+ });
+ let remote_branches =
+ sort_by_timestamp_desc_with_cache(remote_branches, &timestamps, |(_, sha)| sha.as_str());
+
// Pre-canonicalize main_worktree.path for is_main comparison
// (paths from git worktree list may differ based on symlinks or working directory)
let main_worktree_canonical = canonicalize(&main_worktree.path).ok();
+ // Pre-compute is_bare for path mismatch checks (avoids redundant git calls in the loop)
+ let is_bare = repo.is_bare().unwrap_or(false);
+
// Initialize worktree items with identity fields and None for computed fields
let mut all_items: Vec<ListItem> = sorted_worktrees
.iter()
@@ -656,12 +709,13 @@ pub fn collect(
let is_current = current_worktree_path
.as_ref()
.is_some_and(|cp| wt_canonical.as_ref() == Some(cp));
- let is_previous = previous_branch
- .as_deref()
- .is_some_and(|prev| wt.branch.as_deref() == Some(prev));
+ // is_previous set to false initially - computed after skeleton
+ let is_previous = false;
// Check if worktree is at its expected path based on config template
- let path_mismatch = !is_worktree_at_expected_path(wt, repo, config);
+ // Use optimized variant with pre-computed default_branch and is_bare
+ let path_mismatch =
+ !is_worktree_at_expected_path_with(wt, repo, config, &default_branch, is_bare);
let mut worktree_data =
WorktreeData::from_worktree(wt, is_main, is_current, is_previous);
@@ -769,6 +823,25 @@ pub fn collect(
return Ok(None);
}
+ // === Post-skeleton computations (deferred to minimize time-to-skeleton) ===
+
+ // Compute previous_branch and update is_previous on items
+ let previous_branch = repo.get_switch_previous();
+ if let Some(prev) = previous_branch.as_deref() {
+ for item in &mut all_items {
+ if item.branch.as_deref() == Some(prev)
+ && let Some(wt_data) = item.worktree_data_mut()
+ {
+ wt_data.is_previous = true;
+ }
+ }
+ }
+
+ // Effective target for integration checks: upstream if ahead of local, else local.
+ // This handles the case where a branch was merged remotely but user hasn't pulled yet.
+ // Deferred until after skeleton to avoid blocking initial render.
+ let integration_target = repo.effective_integration_target(&default_branch);
+
// Pre-start fsmonitor daemons on macOS to avoid auto-start races.
//
// Git's builtin fsmonitor on macOS has race conditions under parallel load that can
@@ -1037,35 +1110,38 @@ pub fn collect(
}))
}
-/// Sort items by timestamp descending (most recent first).
-/// Uses parallel timestamp collection for performance.
-fn sort_by_timestamp_desc<T, F>(items: Vec<T>, get_timestamp: F) -> Vec<T>
+/// Sort items by timestamp descending using pre-fetched timestamps.
+fn sort_by_timestamp_desc_with_cache<T, F>(
+ items: Vec<T>,
+ timestamps: &std::collections::HashMap<String, i64>,
+ get_sha: F,
+) -> Vec<T>
where
- T: Send + Sync,
- F: Fn(&T) -> i64 + Send + Sync,
+ F: Fn(&T) -> &str,
{
- let timestamps: Vec<i64> = items.par_iter().map(&get_timestamp).collect();
let mut indexed: Vec<_> = items.into_iter().enumerate().collect();
- indexed.sort_by_key(|(idx, _)| std::cmp::Reverse(timestamps[*idx]));
+ let item_timestamps: Vec<i64> = indexed
+ .iter()
+ .map(|(_, item)| *timestamps.get(get_sha(item)).unwrap_or(&0))
+ .collect();
+ indexed.sort_by_key(|(idx, _)| std::cmp::Reverse(item_timestamps[*idx]));
indexed.into_iter().map(|(_, item)| item).collect()
}
/// Sort worktrees: current first, main second, then by timestamp descending.
-fn sort_worktrees(
+/// Uses pre-fetched timestamps for efficiency.
+fn sort_worktrees_with_cache(
worktrees: Vec<Worktree>,
main_worktree: &Worktree,
current_path: Option<&std::path::PathBuf>,
+ timestamps: &std::collections::HashMap<String, i64>,
) -> Vec<Worktree> {
- let timestamps: Vec<i64> = worktrees
- .par_iter()
- .map(|wt| {
- Repository::at(&wt.path)
- .commit_timestamp(&wt.head)
- .unwrap_or(0)
- })
+ let mut indexed: Vec<_> = worktrees.into_iter().enumerate().collect();
+ let wt_timestamps: Vec<i64> = indexed
+ .iter()
+ .map(|(_, wt)| *timestamps.get(&wt.head).unwrap_or(&0))
.collect();
- let mut indexed: Vec<_> = worktrees.into_iter().enumerate().collect();
indexed.sort_by_key(|(idx, wt)| {
let priority = if current_path.is_some_and(|cp| &wt.path == cp) {
0 // Current first
@@ -1074,7 +1150,7 @@ fn sort_worktrees(
} else {
2 // Rest by timestamp
};
- (priority, std::cmp::Reverse(timestamps[*idx]))
+ (priority, std::cmp::Reverse(wt_timestamps[*idx]))
});
indexed.into_iter().map(|(_, wt)| wt).collect()
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 6e54e313d..54ea5b13b 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -312,6 +312,13 @@ impl ListItem {
}
}
+ pub fn worktree_data_mut(&mut self) -> Option<&mut WorktreeData> {
+ match &mut self.kind {
+ ItemKind::Worktree(data) => Some(data),
+ ItemKind::Branch => None,
+ }
+ }
+
pub fn worktree_path(&self) -> Option<&PathBuf> {
self.worktree_data().map(|data| &data.path)
}
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index cd30f0603..f5ac75d44 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -399,9 +399,6 @@ impl LayoutConfig {
let branch = item.branch_name();
let wt_data = item.worktree_data();
- let is_main = item.is_main();
- let is_current = wt_data.is_some_and(|d| d.is_current);
- let is_previous = wt_data.is_some_and(|d| d.is_previous);
let shortened_path = item
.worktree_path()
.map(|p| shorten_path(p, &self.main_worktree_path))
@@ -415,20 +412,14 @@ impl LayoutConfig {
match col.kind {
ColumnKind::Gutter => {
- // Show actual gutter symbol even in skeleton
- // Priority: @ (current) > ^ (main) > - (previous) > + (regular worktree) > space (branch)
- let symbol = if is_current {
- "@ "
- } else if is_main {
- "^ "
- } else if is_previous {
- "- "
- } else if wt_data.is_some() {
- "+ " // Regular worktree
+ // Skeleton shows placeholder gutter - actual symbols appear when data loads.
+ // This allows deferring previous_branch lookup until after skeleton.
+ let symbol = if wt_data.is_some() {
+ "· " // Placeholder for worktrees
} else {
" " // Branch without worktree (two spaces to match width)
};
- cell.push_raw(symbol.to_string());
+ cell.push_styled(symbol, dim);
}
ColumnKind::Branch => {
// Show actual branch name (no dim - start normal, gray out later if removable)
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 055d3a7df..8d48ef22d 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -38,7 +38,7 @@ pub use standalone::{
};
pub use worktree::{
ResolutionContext, compute_worktree_path, handle_remove, handle_remove_by_path,
- handle_remove_current, handle_switch, is_worktree_at_expected_path, resolve_worktree_arg,
+ handle_remove_current, handle_switch, is_worktree_at_expected_path_with, resolve_worktree_arg,
worktree_display_name,
};
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 155312740..5a30dc822 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -238,25 +238,81 @@ pub fn compute_worktree_path(
/// would generate for its branch. Detached HEAD always returns false (no expected path).
///
/// Uses canonicalization to handle symlinks and relative paths correctly.
-pub fn is_worktree_at_expected_path(
+///
+/// Note: For hot paths where default_branch and is_bare are already known,
+/// use `is_worktree_at_expected_path_with` to avoid redundant git calls.
+fn is_worktree_at_expected_path(
+ wt: &worktrunk::git::Worktree,
+ repo: &Repository,
+ config: &WorktrunkConfig,
+) -> bool {
+ // Compute default_branch and is_bare once, then delegate to the optimized variant
+ let default_branch = repo.default_branch().unwrap_or_else(|_| String::new());
+ let is_bare = repo.is_bare().unwrap_or(false);
+ is_worktree_at_expected_path_with(wt, repo, config, &default_branch, is_bare)
+}
+
+/// Check if a worktree is at its expected path, with pre-computed values.
+///
+/// Use this when `default_branch` and `is_bare` are already known (e.g., in list command)
+/// to avoid redundant git calls.
+pub fn is_worktree_at_expected_path_with(
wt: &worktrunk::git::Worktree,
repo: &Repository,
config: &WorktrunkConfig,
+ default_branch: &str,
+ is_bare: bool,
) -> bool {
use dunce::canonicalize;
match &wt.branch {
- Some(branch) => compute_worktree_path(repo, branch, config)
- .map(|expected| {
- // Use canonicalization to handle symlinks
- match (canonicalize(&wt.path), canonicalize(&expected)) {
+ Some(branch) => compute_worktree_path_with(repo, branch, config, default_branch, is_bare)
+ .map(
+ |expected| match (canonicalize(&wt.path), canonicalize(&expected)) {
(Ok(actual), Ok(expected)) => actual == expected,
- _ => wt.path == expected, // Fallback to direct comparison
- }
- })
+ _ => wt.path == expected,
+ },
+ )
.unwrap_or(false),
- None => false, // Detached HEAD has no expected path
+ None => false,
+ }
+}
+
+/// Optimized variant of `compute_worktree_path` that accepts pre-computed values.
+///
+/// Use this when `default_branch` and `is_bare` are already known to avoid
+/// redundant git calls.
+fn compute_worktree_path_with(
+ repo: &Repository,
+ branch: &str,
+ config: &WorktrunkConfig,
+ default_branch: &str,
+ is_bare: bool,
+) -> anyhow::Result<PathBuf> {
+ let repo_root = repo.worktree_base()?;
+
+ // Default branch lives at repo root (main worktree), not a templated path.
+ // Exception: bare repos have no main worktree, so all branches use templated paths.
+ if !is_bare && branch == default_branch {
+ return Ok(repo_root);
}
+
+ let repo_name = repo_root
+ .file_name()
+ .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?
+ .to_str()
+ .ok_or_else(|| {
+ anyhow::anyhow!(
+ "Repository path contains invalid UTF-8: {}",
+ repo_root.display()
+ )
+ })?;
+
+ let relative_path = config
+ .format_path(repo_name, branch)
+ .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;
+
+ Ok(repo_root.join(relative_path).normalize())
}
/// Compute a user-facing display name for a worktree.
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 1da4fe130..3f0fc234f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -102,6 +102,11 @@ impl Repository {
Self::at(base_path().clone())
}
+ /// Get the base path this repository was created with.
+ pub fn base_path(&self) -> &Path {
+ &self.path
+ }
+
/// Get the repository layout, initializing it if needed.
fn layout(&self) -> anyhow::Result<&RepositoryLayout> {
if let Some(layout) = self.layout.get() {
@@ -412,21 +417,41 @@ impl Repository {
/// - For optional operations, provide a fallback (e.g., `.unwrap_or("main")`)
///
/// Uses a hybrid approach:
- /// 1. Try local cache (`git rev-parse origin/HEAD`) first - fast, no network
- /// 2. If not cached, query remote (`git ls-remote`) - may take 100ms-2s depending on network
- /// 3. Cache the result (`git remote set-head`) for future invocations
- /// 4. If no remote available, infer from local branches (no caching, shows hint)
+ /// 1. Check worktrunk cache (`git config worktrunk.default-branch`) — single command
+ /// 2. Detect primary remote, try its cache (e.g., `origin/HEAD`)
+ /// 3. Query remote (`git ls-remote`) — may take 100ms-2s
+ /// 4. Infer from local branches if no remote
+ ///
+ /// Detection results are cached to `worktrunk.default-branch` for future calls.
pub fn default_branch(&self) -> anyhow::Result<String> {
- // Try to get default branch from remote
+ // Fast path: check worktrunk's own cache (single git config read)
+ if let Ok(branch) = self.run_command(&["config", "--get", "worktrunk.default-branch"]) {
+ let branch = branch.trim();
+ if !branch.is_empty() {
+ return Ok(branch.to_string());
+ }
+ }
+
+ // Detect and cache the default branch
+ let branch = self.detect_default_branch()?;
+ let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);
+ Ok(branch)
+ }
+
+ /// Detect the default branch without using worktrunk's cache.
+ ///
+ /// Used by `default_branch()` to populate the cache, and by
+ /// `wt config state get default-branch --refresh` to force re-detection.
+ pub fn detect_default_branch(&self) -> anyhow::Result<String> {
+ // Try to get from the primary remote
if let Ok(remote) = self.primary_remote() {
- // Try local cache first (fast path)
+ // Try git's cache for this remote (e.g., origin/HEAD)
if let Ok(branch) = self.get_local_default_branch(&remote) {
return Ok(branch);
}
- // Query remote and cache it
+ // Query remote (no caching to git's remote HEAD - we only manage worktrunk's cache)
if let Ok(branch) = self.query_remote_default_branch(&remote) {
- let _ = self.cache_default_branch(&remote, &branch);
return Ok(branch);
}
}
@@ -434,7 +459,7 @@ impl Repository {
// Fallback: No remote or remote query failed, try to infer locally
// TODO: Show message to user when using inference fallback:
// "No remote configured. Using inferred default branch: {branch}"
- // "To cache the default branch, set up a remote and run: wt config state get default-branch --refresh"
+ // "To set explicitly, run: wt config state default-branch set <branch>"
// Problem: git.rs is in lib crate, output module is in binary.
// Options: (1) Return info about whether fallback was used, let callers show message
// (2) Add messages in specific commands (merge.rs, worktree.rs)
@@ -455,10 +480,9 @@ impl Repository {
///
/// Uses local heuristics when no remote is available:
/// 1. If only one local branch exists, use it
- /// 2. Check what HEAD points to (current branch in main worktree)
- /// 3. Check user's git config init.defaultBranch
- /// 4. Look for common branch names (main, master, develop)
- /// 5. Fail if none of the above work
+ /// 2. Check user's git config init.defaultBranch
+ /// 3. Look for common branch names (main, master, develop, trunk)
+ /// 4. Fail if none of the above work
fn infer_default_branch_locally(&self) -> anyhow::Result<String> {
// 1. If there's only one local branch, use it
let branches = self.local_branches()?;
@@ -481,7 +505,7 @@ impl Repository {
}
}
- // 4. Give up - can't infer
+ // 4. Give up — can't infer
Err(GitError::Other {
message:
"Could not infer default branch. Please specify target branch explicitly or set up a remote."
@@ -707,6 +731,38 @@ impl Repository {
stdout.trim().parse().context("Failed to parse timestamp")
}
+ /// Get commit timestamps for multiple commits in a single git command.
+ ///
+ /// Returns a map from commit SHA to timestamp. More efficient than calling
+ /// `commit_timestamp` multiple times when you have many commits.
+ pub fn commit_timestamps(
+ &self,
+ commits: &[&str],
+ ) -> anyhow::Result<std::collections::HashMap<String, i64>> {
+ use std::collections::HashMap;
+
+ if commits.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ // Build command: git show -s --format='%H %ct' sha1 sha2 sha3 ...
+ let mut args = vec!["show", "-s", "--format=%H %ct"];
+ args.extend(commits);
+
+ let stdout = self.run_command(&args)?;
+
+ let mut result = HashMap::with_capacity(commits.len());
+ for line in stdout.lines() {
+ if let Some((sha, timestamp_str)) = line.split_once(' ')
+ && let Ok(timestamp) = timestamp_str.parse::<i64>()
+ {
+ result.insert(sha.to_string(), timestamp);
+ }
+ }
+
+ Ok(result)
+ }
+
/// Get commit message (subject line) for a commit.
pub fn commit_message(&self, commit: &str) -> anyhow::Result<String> {
let stdout = self.run_command(&["show", "-s", "--format=%s", commit])?;
@@ -1335,34 +1391,30 @@ impl Repository {
pub fn refresh_default_branch(&self) -> anyhow::Result<String> {
let remote = self.primary_remote()?;
let branch = self.query_remote_default_branch(&remote)?;
- self.cache_default_branch(&remote, &branch)?;
+ // Update worktrunk's cache
+ let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);
Ok(branch)
}
/// Set the default branch manually.
///
- /// This sets the local cache (`refs/remotes/<remote>/HEAD`) to point to the
- /// specified branch. Use `--refresh` to re-query the remote and overwrite
- /// this value.
+ /// This sets worktrunk's cache (`worktrunk.default-branch`). Use `--refresh`
+ /// to re-query the remote and update git's cache.
pub fn set_default_branch(&self, branch: &str) -> anyhow::Result<()> {
- let remote = self.primary_remote()?;
- self.cache_default_branch(&remote, branch)
+ self.run_command(&["config", "worktrunk.default-branch", branch])?;
+ Ok(())
}
/// Clear the default branch cache.
///
- /// Removes `refs/remotes/<remote>/HEAD` so the next call to `default_branch()`
- /// will re-query the remote.
+ /// Clears worktrunk's cache (`worktrunk.default-branch`). The next call to
+ /// `default_branch()` will re-detect (using git's cache or querying remote).
///
/// Returns `true` if cache was cleared, `false` if no cache existed.
pub fn clear_default_branch_cache(&self) -> anyhow::Result<bool> {
- let remote = self.primary_remote()?;
- if self.get_local_default_branch(&remote).is_ok() {
- self.run_command(&["remote", "set-head", "-d", &remote])?;
- Ok(true)
- } else {
- Ok(false)
- }
+ Ok(self
+ .run_command(&["config", "--unset", "worktrunk.default-branch"])
+ .is_ok())
}
/// Check if two refs have identical tree content (same files/directories).
@@ -1407,11 +1459,6 @@ impl Repository {
DefaultBranchName::from_remote(&stdout).map(DefaultBranchName::into_string)
}
- fn cache_default_branch(&self, remote: &str, branch: &str) -> anyhow::Result<()> {
- self.run_command(&["remote", "set-head", remote, branch])?;
- Ok(())
- }
-
/// Get a project identifier for approval tracking.
///
/// Uses the git remote URL if available (e.g., "github.com/user/repo"),
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 9d3d575e2..06bfdca89 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -79,50 +79,40 @@ fn test_state_get_default_branch_no_remote(repo: TestRepo) {
}
#[rstest]
-fn test_state_set_default_branch(mut repo: TestRepo) {
- // First set up a remote so set_default_branch works
- repo.setup_remote("main");
-
- // Create and push a develop branch so we can set it as default
- repo.git_command(&["checkout", "-b", "develop"])
- .status()
- .unwrap();
- repo.git_command(&["push", "origin", "develop"])
- .status()
- .unwrap();
- repo.git_command(&["checkout", "main"]).status().unwrap();
-
+fn test_state_set_default_branch(repo: TestRepo) {
let output = wt_state_cmd(&repo, "default-branch", "set", &["develop"])
.output()
.unwrap();
assert!(output.status.success());
assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✓ Set default branch to develop");
- // Verify it was set by checking origin/HEAD
+ // Verify it was set in worktrunk's cache
let output = repo
- .git_command(&["symbolic-ref", "refs/remotes/origin/HEAD"])
+ .git_command(&["config", "--get", "worktrunk.default-branch"])
.output()
.unwrap();
- assert_eq!(
- String::from_utf8_lossy(&output.stdout).trim(),
- "refs/remotes/origin/develop"
- );
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "develop");
}
#[rstest]
fn test_state_clear_default_branch(mut repo: TestRepo) {
- // Set up remote and set default branch first
+ // Set up remote and populate worktrunk's cache
repo.setup_remote("main");
+ // Trigger cache population by reading default branch
+ let _ = wt_state_cmd(&repo, "default-branch", "get", &[])
+ .output()
+ .unwrap();
+ // Now clear the cache
let output = wt_state_cmd(&repo, "default-branch", "clear", &[])
.output()
.unwrap();
assert!(output.status.success());
assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"✓ Cleared default branch cache");
- // Verify it was cleared - origin/HEAD should not exist
+ // Verify worktrunk's cache was cleared
let output = repo
- .git_command(&["symbolic-ref", "refs/remotes/origin/HEAD"])
+ .git_command(&["config", "--get", "worktrunk.default-branch"])
.output()
.unwrap();
assert!(!output.status.success());
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index 22042294b..905019f79 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -22,19 +22,29 @@ fn test_get_default_branch_without_origin_head(#[from(repo_with_remote)] repo: T
let branch = Repository::at(repo.root_path()).default_branch().unwrap();
assert_eq!(branch, "main");
- // Verify that origin/HEAD is now cached
- assert!(repo.has_origin_head());
+ // Verify that worktrunk's cache is now set
+ let cached = repo
+ .git_command(&["config", "--get", "worktrunk.default-branch"])
+ .output()
+ .unwrap();
+ assert_eq!(String::from_utf8_lossy(&cached.stdout).trim(), "main");
}
#[rstest]
fn test_get_default_branch_caches_result(#[from(repo_with_remote)] repo: TestRepo) {
- // Clear origin/HEAD
+ // Clear both caches to force remote query
repo.clear_origin_head();
- assert!(!repo.has_origin_head());
+ let _ = repo
+ .git_command(&["config", "--unset", "worktrunk.default-branch"])
+ .output();
- // First call queries remote and caches
+ // First call queries remote and caches to worktrunk config
Repository::at(repo.root_path()).default_branch().unwrap();
- assert!(repo.has_origin_head());
+ let cached = repo
+ .git_command(&["config", "--get", "worktrunk.default-branch"])
+ .output()
+ .unwrap();
+ assert!(cached.status.success());
// Second call uses cache (fast path)
let branch = Repository::at(repo.root_path()).default_branch().unwrap();
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap
index 75b5851fb..6b2a968e3 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap
@@ -11,6 +11,7 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "150"
GIT_EDITOR: ""
+ RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml
---
@@ -46,16 +47,17 @@ Usage: wt config state default-branch [OPTIONS] [COMM
Worktrunk detects the default branch automatically:
-1. Local cache — Checks git rev-parse origin/HEAD (fast, no network)
-2. Remote query — If not cached, queries git ls-remote (100ms–2s)
-3. Cache result — Stores via git remote set-head for future calls
+1. Worktrunk cache — Checks git config worktrunk.default-branch (single command)
+2. Git cache — Detects primary remote and checks its HEAD (e.g., origin/HEAD)
+3. Remote query — If not cached, queries git ls-remote (100ms–2s)
4. Local inference — If no remote, infers from local branches
+Once detected, the result is cached in worktrunk.default-branch for fast access.
+
The local inference fallback uses these heuristics in order:
- If only one local branch exists, uses it
-- Checks what HEAD points to in main worktree
- Checks git config init.defaultBranch
-- Looks for common names: main, master, develop
+- Looks for common names: main, master, develop, trunk
When to use