Skip to content

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

Refactor: simplify TaskContext and introduce BranchRef type (#523)

Maximilian Roos0166265a51bc
diff --git a/.claude/rules/caching-strategy.md b/.claude/rules/caching-strategy.md
index 1661003b4..4db590f7b 100644
--- a/.claude/rules/caching-strategy.md
+++ b/.claude/rules/caching-strategy.md
@@ -31,6 +31,7 @@ shares the cache — all clones see the same cached values.
- `project_identifier()` — derived from remote URL
- `primary_remote()` — git config, doesn't change
- `default_branch()` — from git config or detection, doesn't change
+- `integration_target()` — effective target for integration checks (local default or upstream if ahead)
- `merge_base()` — keyed by (commit1, commit2) pair
- `ahead_behind` — keyed by (base_ref, branch_name), populated by `batch_ahead_behind()`
- `project_config` — loaded from .config/wt.toml
diff --git a/src/commands/config.rs b/src/commands/config.rs
index d0eca2be2..96a1dcede 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -277,13 +277,12 @@ fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {
/// Run full diagnostic checks (CI tools, commit generation) and render to buffer
fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
use super::list::ci_status::{CiPlatform, CiToolsStatus, get_platform_for_repo};
- use worktrunk::config::ProjectConfig;
writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;
// Check CI tool based on detected platform (with config override support)
let repo = Repository::current()?;
- let project_config = ProjectConfig::load(&repo, true).ok().flatten();
+ let project_config = repo.load_project_config().ok().flatten();
let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());
let platform = get_platform_for_repo(&repo, platform_override);
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index 9b3020370..4dbfcaf25 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -1156,10 +1156,8 @@ impl PrStatus {
local_head: &str,
has_upstream: bool,
) -> Option<Self> {
- use worktrunk::config::ProjectConfig;
-
- // Load project config for platform override
- let project_config = ProjectConfig::load(repo, false).ok().flatten();
+ // Load project config for platform override (cached in Repository)
+ let project_config = repo.load_project_config().ok().flatten();
let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());
// Determine platform (config override or URL detection)
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 7fe3006f1..26a7dcfb9 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -75,7 +75,7 @@ use crossbeam_channel as chan;
use dunce::canonicalize;
use rayon::prelude::*;
use rayon_join_macro::join;
-use worktrunk::git::{LineDiff, Repository, Worktree};
+use worktrunk::git::{LineDiff, Repository, WorktreeInfo};
use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, warning_message};
use crate::commands::is_worktree_at_expected_path_with;
@@ -262,7 +262,7 @@ impl TaskKind {
}
/// Detect if a worktree is in the middle of a git operation (rebase/merge).
-pub(super) fn detect_git_operation(wt: &worktrunk::git::WorktreeView<'_>) -> GitOperationState {
+pub(super) fn detect_git_operation(wt: &worktrunk::git::WorkingTree<'_>) -> GitOperationState {
if wt.is_rebasing().unwrap_or(false) {
GitOperationState::Rebase
} else if wt.is_merging().unwrap_or(false) {
@@ -639,7 +639,7 @@ fn drain_results(
/// Returns (branch_name, commit_sha) pairs for all branches without associated worktrees.
fn get_branches_without_worktrees(
repo: &Repository,
- worktrees: &[Worktree],
+ worktrees: &[WorktreeInfo],
) -> anyhow::Result<Vec<(String, String)>> {
// Get all local branches
let all_branches = repo.list_local_branches()?;
@@ -656,7 +656,7 @@ fn get_branches_without_worktrees(
Ok(branches_without_worktrees)
}
-fn worktree_branch_set(worktrees: &[Worktree]) -> std::collections::HashSet<&str> {
+fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> std::collections::HashSet<&str> {
worktrees
.iter()
.filter_map(|wt| wt.branch.as_deref())
@@ -750,7 +750,7 @@ pub fn collect(
// Main worktree is the worktree on the default branch (if exists), else first worktree.
// find_home returns None only if worktrees is empty, which shouldn't happen for wt list.
- let main_worktree = Worktree::find_home(&worktrees, &default_branch)
+ let main_worktree = WorktreeInfo::find_home(&worktrees, &default_branch)
.cloned()
.ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;
@@ -792,11 +792,7 @@ pub fn collect(
// Check if URL template is configured (for layout column allocation).
// Template expansion is deferred to post-skeleton to minimize time-to-skeleton.
- let url_template = worktrunk::config::ProjectConfig::load(repo, true)
- .ok()
- .flatten()
- .and_then(|config| config.list)
- .and_then(|list| list.url);
+ let url_template = repo.url_template();
// Initialize worktree items with identity fields and None for computed fields
let mut all_items: Vec<ListItem> = sorted_worktrees
.iter()
@@ -1023,8 +1019,6 @@ pub fn collect(
// which could create 100+ threads. Instead, we have one pool with ~8 threads.
let sorted_worktrees_clone = sorted_worktrees.clone();
let tx_worker = tx.clone();
- let default_branch_clone = default_branch.clone();
- let target_clone = integration_target.clone();
let expected_results_clone = expected_results.clone();
// Clone repo for the worker thread (shares cache via Arc)
@@ -1067,8 +1061,6 @@ pub fn collect(
&repo_clone,
wt,
idx,
- &default_branch_clone,
- &target_clone,
&options,
&expected_results_clone,
&tx_worker,
@@ -1082,8 +1074,6 @@ pub fn collect(
branch_name,
commit_sha,
*item_idx,
- &default_branch_clone,
- &target_clone,
&options,
&expected_results_clone,
));
@@ -1337,11 +1327,11 @@ where
/// Sort worktrees: current first, main second, then by timestamp descending.
/// Uses pre-fetched timestamps for efficiency.
fn sort_worktrees_with_cache(
- worktrees: Vec<Worktree>,
- main_worktree: &Worktree,
+ worktrees: Vec<WorktreeInfo>,
+ main_worktree: &WorktreeInfo,
current_path: Option<&std::path::PathBuf>,
timestamps: &std::collections::HashMap<String, i64>,
-) -> Vec<Worktree> {
+) -> Vec<WorktreeInfo> {
// Embed timestamp and priority in tuple to avoid parallel Vec and index lookups
let mut with_sort_key: Vec<_> = worktrees
.into_iter()
@@ -1373,7 +1363,7 @@ pub use super::collect_progressive_impl::CollectOptions;
/// Computed fields (counts, diffs, CI) are left as None. Use `populate_item()`
/// to fill them in.
pub fn build_worktree_item(
- wt: &Worktree,
+ wt: &WorktreeInfo,
is_main: bool,
is_current: bool,
is_previous: bool,
@@ -1410,16 +1400,12 @@ pub fn build_worktree_item(
///
/// # Parameters
/// - `repo`: Repository handle (cloned into background thread, shares cache via Arc)
-/// - `default_branch`: Local default branch for informational stats (ahead/behind, branch diff)
-/// - `target`: Effective target for integration checks (may be upstream if ahead)
///
/// This is the blocking version used by statusline. For progressive rendering
/// with callbacks, see the `collect()` function.
pub fn populate_item(
repo: &Repository,
item: &mut ListItem,
- default_branch: &str,
- target: &str,
options: CollectOptions,
) -> anyhow::Result<()> {
use std::sync::Arc;
@@ -1429,6 +1415,9 @@ pub fn populate_item(
return Ok(());
};
+ // Get integration target for status symbol computation (cached in repo)
+ let target = repo.integration_target()?;
+
// Create channel for task results
let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();
@@ -1439,7 +1428,7 @@ pub fn populate_item(
let mut errors: Vec<TaskError> = Vec::new();
// Extract data for background thread (can't send borrows across threads)
- let wt = Worktree {
+ let wt = WorktreeInfo {
path: data.path.clone(),
head: item.head.clone(),
branch: item.branch.clone(),
@@ -1449,8 +1438,6 @@ pub fn populate_item(
prunable: None,
};
let repo_clone = repo.clone();
- let default_branch_clone = default_branch.to_string();
- let target_clone = target.to_string();
let expected_results_clone = expected_results.clone();
// Spawn collection in background thread
@@ -1462,8 +1449,6 @@ pub fn populate_item(
&repo_clone,
&wt,
0, // Single item, always index 0
- &default_branch_clone,
- &target_clone,
&options,
&expected_results_clone,
&tx,
@@ -1486,7 +1471,7 @@ pub fn populate_item(
&mut errors,
&expected_results,
|_item_idx, item, ctx| {
- ctx.apply_to(item, target);
+ ctx.apply_to(item, &target);
},
);
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index c14b51fcf..d9d30e01a 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -19,9 +19,8 @@
use crossbeam_channel::Sender;
use std::fmt::Display;
-use std::path::PathBuf;
use std::sync::Arc;
-use worktrunk::git::{LineDiff, Repository, Worktree};
+use worktrunk::git::{BranchRef, LineDiff, Repository, WorktreeInfo};
use super::ci_status::PrStatus;
use super::collect::{ExpectedResults, TaskError, TaskKind, TaskResult, detect_git_operation};
@@ -77,29 +76,18 @@ pub struct CollectOptions {
///
/// Contains all data needed by any task. The `repo` field shares its cache
/// across all clones via `Arc<RepoCache>`, so parallel tasks benefit from
-/// cached merge-base results, ahead/behind counts, etc.
+/// cached merge-base results, ahead/behind counts, default branch, and
+/// integration target.
#[derive(Clone)]
pub struct TaskContext {
/// Shared repository handle. All clones share the same cache via Arc.
pub repo: Repository,
- /// Path to the specific worktree this task operates on.
+ /// The branch this task operates on. Contains branch name, commit SHA,
+ /// and optional worktree path.
///
- /// For worktree-specific operations, use `self.worktree()` which calls
- /// `repo.worktree_at(&worktree_path)`.
- ///
- /// **Important:** For branch-only items (branches without worktrees), this
- /// is an empty `PathBuf`. Tasks that require worktree-specific operations
- /// (e.g., `WorkingTreeDiffTask`) are only spawned for items with worktrees,
- /// so the empty path case never reaches those tasks.
- pub worktree_path: PathBuf,
- pub commit_sha: String,
- pub branch: Option<String>,
- /// Local default branch for informational stats (ahead/behind, branch diff).
- /// Always the local ref (e.g., "main"), providing stable comparisons.
- pub default_branch: Option<String>,
- /// Effective target for integration checks (status symbols, safe deletion).
- /// May be upstream (e.g., "origin/main") if it's ahead of local, catching remotely-merged branches.
- pub target: Option<String>,
+ /// For worktree-specific operations, use `self.worktree()` which returns
+ /// `Some(WorkingTree)` only when this ref has a worktree path.
+ pub branch_ref: BranchRef,
pub item_idx: usize,
/// Expanded URL for this item (from project config template).
/// UrlStatusTask uses this to check if the port is listening.
@@ -107,27 +95,45 @@ pub struct TaskContext {
}
impl TaskContext {
- /// Get a worktree view for this task's worktree path.
+ /// Get a working tree handle for this task's worktree.
///
+ /// Returns `Some(WorkingTree)` for worktree items, `None` for branch-only items.
/// Use this for worktree-specific operations (git status, working tree diff).
- fn worktree(&self) -> worktrunk::git::WorktreeView<'_> {
- self.repo.worktree_at(&self.worktree_path)
+ ///
+ /// Tasks that require a worktree should only be spawned for items with worktrees,
+ /// so the `None` case indicates a programming error if encountered in such tasks.
+ fn worktree(&self) -> Option<worktrunk::git::WorkingTree<'_>> {
+ self.branch_ref.working_tree(&self.repo)
+ }
+
+ /// Get the branch name, if any.
+ fn branch(&self) -> Option<&str> {
+ self.branch_ref.branch.as_deref()
+ }
+
+ /// Get the commit SHA.
+ fn commit_sha(&self) -> &str {
+ &self.branch_ref.commit_sha
}
fn error(&self, kind: TaskKind, message: impl Display) -> TaskError {
TaskError::new(self.item_idx, kind, message.to_string())
}
- fn require_default_branch(&self, kind: TaskKind) -> Result<&str, TaskError> {
- self.default_branch
- .as_deref()
- .ok_or_else(|| self.error(kind, "no default branch"))
+ /// Get the default branch (cached in Repository).
+ ///
+ /// Used for informational stats (ahead/behind, branch diff).
+ fn default_branch(&self, kind: TaskKind) -> Result<String, TaskError> {
+ self.repo.default_branch().map_err(|e| self.error(kind, e))
}
- fn require_target(&self, kind: TaskKind) -> Result<&str, TaskError> {
- self.target
- .as_deref()
- .ok_or_else(|| self.error(kind, "no target branch"))
+ /// Get the integration target (cached in Repository).
+ ///
+ /// Used for integration checks (status symbols, safe deletion).
+ fn integration_target(&self, kind: TaskKind) -> Result<String, TaskError> {
+ self.repo
+ .integration_target()
+ .map_err(|e| self.error(kind, e))
}
}
@@ -218,13 +224,10 @@ const EXPENSIVE_TASKS: &[TaskKind] = &[
/// The caller is responsible for executing the work items.
///
/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.
-#[allow(clippy::too_many_arguments)]
pub fn work_items_for_worktree(
repo: &Repository,
- wt: &Worktree,
+ wt: &WorktreeInfo,
item_idx: usize,
- default_branch: &str,
- target: &str,
options: &CollectOptions,
expected_results: &Arc<ExpectedResults>,
tx: &Sender<Result<TaskResult, TaskError>>,
@@ -258,11 +261,7 @@ pub fn work_items_for_worktree(
let ctx = TaskContext {
repo: repo.clone(),
- worktree_path: wt.path.clone(),
- commit_sha: wt.head.clone(),
- branch: wt.branch.clone(),
- default_branch: Some(default_branch.to_string()),
- target: Some(target.to_string()),
+ branch_ref: BranchRef::from(wt),
item_idx,
item_url,
};
@@ -330,14 +329,11 @@ pub fn work_items_for_worktree(
/// branch. Branches have fewer tasks than worktrees (no working tree operations).
///
/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.
-#[allow(clippy::too_many_arguments)]
pub fn work_items_for_branch(
repo: &Repository,
branch_name: &str,
commit_sha: &str,
item_idx: usize,
- default_branch: &str,
- target: &str,
options: &CollectOptions,
expected_results: &Arc<ExpectedResults>,
) -> Vec<WorkItem> {
@@ -345,11 +341,7 @@ pub fn work_items_for_branch(
let ctx = TaskContext {
repo: repo.clone(),
- worktree_path: PathBuf::new(), // Branches without worktrees use empty path
- commit_sha: commit_sha.to_string(),
- branch: Some(branch_name.to_string()),
- default_branch: Some(default_branch.to_string()),
- target: Some(target.to_string()),
+ branch_ref: BranchRef::branch_only(branch_name, commit_sha),
item_idx,
item_url: None, // Branches without worktrees don't have URLs
};
@@ -406,10 +398,10 @@ impl Task for CommitDetailsTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let repo = &ctx.repo;
let timestamp = repo
- .commit_timestamp(&ctx.commit_sha)
+ .commit_timestamp(ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?;
let commit_message = repo
- .commit_message(&ctx.commit_sha)
+ .commit_message(ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::CommitDetails {
item_idx: ctx.item_idx,
@@ -428,21 +420,21 @@ impl Task for AheadBehindTask {
const KIND: TaskKind = TaskKind::AheadBehind;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.require_default_branch(Self::KIND)?;
+ let base = ctx.default_branch(Self::KIND)?;
let repo = &ctx.repo;
// Check cache first (populated by batch_ahead_behind if it ran).
// Cache lookup has minor overhead (rev-parse for cache key + allocations),
// but saves the expensive ahead_behind computation on cache hit.
- let (ahead, behind) = if let Some(branch) = ctx.branch.as_deref() {
- if let Some(counts) = repo.get_cached_ahead_behind(base, branch) {
+ let (ahead, behind) = if let Some(branch) = ctx.branch() {
+ if let Some(counts) = repo.get_cached_ahead_behind(&base, branch) {
counts
} else {
- repo.ahead_behind(base, &ctx.commit_sha)
+ repo.ahead_behind(&base, ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?
}
} else {
- repo.ahead_behind(base, &ctx.commit_sha)
+ repo.ahead_behind(&base, ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?
};
@@ -462,12 +454,12 @@ impl Task for CommittedTreesMatchTask {
const KIND: TaskKind = TaskKind::CommittedTreesMatch;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.require_target(Self::KIND)?;
+ let base = ctx.integration_target(Self::KIND)?;
let repo = &ctx.repo;
- // Use ctx.commit_sha (the item's commit) instead of HEAD,
+ // Use ctx.commit_sha() (the item's commit) instead of HEAD,
// since for branches without worktrees, HEAD is the main worktree's HEAD
let committed_trees_match = repo
- .trees_match(&ctx.commit_sha, base)
+ .trees_match(ctx.commit_sha(), &base)
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::CommittedTreesMatch {
item_idx: ctx.item_idx,
@@ -494,16 +486,16 @@ impl Task for HasFileChangesTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
// No branch name (detached HEAD) - return conservative default (assume has changes)
- let Some(branch) = ctx.branch.as_deref() else {
+ let Some(branch) = ctx.branch() else {
return Ok(TaskResult::HasFileChanges {
item_idx: ctx.item_idx,
has_file_changes: true,
});
};
- let target = ctx.require_target(Self::KIND)?;
+ let target = ctx.integration_target(Self::KIND)?;
let repo = &ctx.repo;
let has_file_changes = repo
- .has_added_changes(branch, target)
+ .has_added_changes(branch, &target)
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::HasFileChanges {
@@ -531,16 +523,16 @@ impl Task for WouldMergeAddTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
// No branch name (detached HEAD) - return conservative default (assume would add)
- let Some(branch) = ctx.branch.as_deref() else {
+ let Some(branch) = ctx.branch() else {
return Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
would_merge_add: true,
});
};
- let base = ctx.require_target(Self::KIND)?;
+ let base = ctx.integration_target(Self::KIND)?;
let repo = &ctx.repo;
let would_merge_add = repo
- .would_merge_add_to_target(branch, base)
+ .would_merge_add_to_target(branch, &base)
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
@@ -563,10 +555,10 @@ impl Task for IsAncestorTask {
const KIND: TaskKind = TaskKind::IsAncestor;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.require_target(Self::KIND)?;
+ let base = ctx.integration_target(Self::KIND)?;
let repo = &ctx.repo;
let is_ancestor = repo
- .is_ancestor(&ctx.commit_sha, base)
+ .is_ancestor(ctx.commit_sha(), &base)
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::IsAncestor {
@@ -583,10 +575,10 @@ impl Task for BranchDiffTask {
const KIND: TaskKind = TaskKind::BranchDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.require_default_branch(Self::KIND)?;
+ let base = ctx.default_branch(Self::KIND)?;
let repo = &ctx.repo;
let diff = repo
- .branch_diff_stats(base, &ctx.commit_sha)
+ .branch_diff_stats(&base, ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::BranchDiff {
@@ -603,7 +595,10 @@ impl Task for WorkingTreeDiffTask {
const KIND: TaskKind = TaskKind::WorkingTreeDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let wt = ctx.worktree();
+ // This task is only spawned for worktree items, so worktree path is always present.
+ let wt = ctx
+ .worktree()
+ .expect("WorkingTreeDiffTask requires a worktree");
// Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's
// `git stash create` which needs the index lock.
let status_output = wt
@@ -621,8 +616,9 @@ impl Task for WorkingTreeDiffTask {
};
// Use default_branch (local default branch) for informational display
+ let default_branch = ctx.default_branch(Self::KIND).ok();
let working_tree_diff_with_main = wt
- .working_tree_diff_with_base(ctx.default_branch.as_deref(), is_dirty)
+ .working_tree_diff_with_base(default_branch.as_deref(), is_dirty)
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::WorkingTreeDiff {
@@ -645,10 +641,10 @@ impl Task for MergeTreeConflictsTask {
const KIND: TaskKind = TaskKind::MergeTreeConflicts;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.require_default_branch(Self::KIND)?;
+ let base = ctx.default_branch(Self::KIND)?;
let repo = &ctx.repo;
let has_merge_tree_conflicts = repo
- .has_merge_conflicts(base, &ctx.commit_sha)
+ .has_merge_conflicts(&base, ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::MergeTreeConflicts {
item_idx: ctx.item_idx,
@@ -668,8 +664,11 @@ impl Task for WorkingTreeConflictsTask {
const KIND: TaskKind = TaskKind::WorkingTreeConflicts;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx.require_default_branch(Self::KIND)?;
- let wt = ctx.worktree();
+ let base = ctx.default_branch(Self::KIND)?;
+ // This task is only spawned for worktree items, so worktree path is always present.
+ let wt = ctx
+ .worktree()
+ .expect("WorkingTreeConflictsTask requires a worktree");
// Use --no-optional-locks to avoid index lock contention with WorkingTreeDiffTask.
// Both tasks run in parallel, and `git stash create` below needs the index lock.
@@ -719,7 +718,7 @@ impl Task for WorkingTreeConflictsTask {
// Run merge-tree with the stash commit (repo-wide operation, doesn't need worktree)
let has_conflicts = ctx
.repo
- .has_merge_conflicts(base, stash_sha)
+ .has_merge_conflicts(&base, stash_sha)
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::WorkingTreeConflicts {
@@ -736,7 +735,10 @@ impl Task for GitOperationTask {
const KIND: TaskKind = TaskKind::GitOperation;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let wt = ctx.worktree();
+ // This task is only spawned for worktree items, so worktree path is always present.
+ let wt = ctx
+ .worktree()
+ .expect("GitOperationTask requires a worktree");
let git_operation = detect_git_operation(&wt);
Ok(TaskResult::GitOperation {
item_idx: ctx.item_idx,
@@ -753,7 +755,7 @@ impl Task for UserMarkerTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let repo = &ctx.repo;
- let user_marker = repo.user_marker(ctx.branch.as_deref());
+ let user_marker = repo.user_marker(ctx.branch());
Ok(TaskResult::UserMarker {
item_idx: ctx.item_idx,
user_marker,
@@ -771,7 +773,7 @@ impl Task for UpstreamTask {
let repo = &ctx.repo;
// No branch means no upstream
- let Some(branch) = ctx.branch.as_deref() else {
+ let Some(branch) = ctx.branch() else {
return Ok(TaskResult::Upstream {
item_idx: ctx.item_idx,
upstream: UpstreamStatus::default(),
@@ -791,7 +793,7 @@ impl Task for UpstreamTask {
let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());
let (ahead, behind) = repo
- .ahead_behind(&upstream_branch, &ctx.commit_sha)
+ .ahead_behind(&upstream_branch, ctx.commit_sha())
.map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::Upstream {
@@ -817,9 +819,9 @@ impl Task for CiStatusTask {
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
let repo = &ctx.repo;
- let pr_status = ctx.branch.as_deref().and_then(|branch| {
+ let pr_status = ctx.branch().and_then(|branch| {
let has_upstream = repo.upstream_branch(branch).ok().flatten().is_some();
- PrStatus::detect(repo, branch, &ctx.commit_sha, has_upstream)
+ PrStatus::detect(repo, branch, ctx.commit_sha(), has_upstream)
});
Ok(TaskResult::CiStatus {
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index df80ff604..92c1fd4fb 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -226,9 +226,9 @@ impl WorktreeData {
self.prunable.is_some()
}
- /// Create WorktreeData from a Worktree, with all computed fields set to None.
+ /// Create WorktreeData from a WorktreeInfo, with all computed fields set to None.
pub(crate) fn from_worktree(
- wt: &worktrunk::git::Worktree,
+ wt: &worktrunk::git::WorktreeInfo,
is_main: bool,
is_current: bool,
is_previous: bool,
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 41b5cacf4..19abf107d 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -11,8 +11,7 @@ use anyhow::{Context, Result};
use std::env;
use std::io::{self, Read};
use std::path::Path;
-use worktrunk::config::ProjectConfig;
-use worktrunk::git::{Repository, Worktree};
+use worktrunk::git::{Repository, WorktreeInfo};
use worktrunk::styling::{get_terminal_width, truncate_visible};
use super::list::{self, CollectOptions, StatuslineSegment};
@@ -276,25 +275,19 @@ fn get_git_status_segments(
)]);
}
};
- // Effective target for integration checks: upstream if ahead of local, else local.
- let integration_target = repo.effective_integration_target(&default_branch);
// Determine if this is the home worktree (default branch's worktree, or first if none)
// Use the already-fetched worktrees to avoid a redundant git command
// Note: called `is_home` here because bare repos have no git "main worktree" -
// all worktrees are linked. The `is_main` param in build_worktree_item is for display.
- let home_worktree = Worktree::find_home(&worktrees, &default_branch);
+ let home_worktree = WorktreeInfo::find_home(&worktrees, &default_branch);
let is_home = home_worktree.is_some_and(|hw| wt.path == hw.path);
// Build item with identity fields
let mut item = list::build_worktree_item(wt, is_home, true, false);
// Load URL template from project config (if configured)
- let url_template = ProjectConfig::load(repo, true)
- .ok()
- .flatten()
- .and_then(|config| config.list)
- .and_then(|list| list.url);
+ let url_template = repo.url_template();
// Build collect options with URL template
let options = CollectOptions {
@@ -304,15 +297,7 @@ fn get_git_status_segments(
// Populate computed fields (parallel git operations)
// Compute everything (same as --full) for complete status symbols
- // Pass default_branch for stable informational stats,
- // and integration_target for integration status checks.
- list::populate_item(
- repo,
- &mut item,
- &default_branch,
- &integration_target,
- options,
- )?;
+ list::populate_item(repo, &mut item, options)?;
// Get prioritized segments
let segments = item.format_statusline_segments(include_links);
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 55db65e17..10ee48172 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -208,7 +208,7 @@ pub fn compute_worktree_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,
+ wt: &worktrunk::git::WorktreeInfo,
repo: &Repository,
config: &WorktrunkConfig,
) -> bool {
@@ -233,7 +233,7 @@ fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {
/// 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,
+ wt: &worktrunk::git::WorktreeInfo,
repo: &Repository,
config: &WorktrunkConfig,
default_branch: &str,
@@ -309,7 +309,7 @@ fn compute_worktree_path_with(
/// "Consistent" means the worktree path matches `compute_worktree_path(branch)`,
/// which returns repo root for default branch and templated path for others.
pub fn worktree_display_name(
- wt: &worktrunk::git::Worktree,
+ wt: &worktrunk::git::WorktreeInfo,
repo: &Repository,
config: &WorktrunkConfig,
) -> String {
diff --git a/src/git/mod.rs b/src/git/mod.rs
index e4ebdc3f6..59e6010b6 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -41,7 +41,7 @@ pub use error::{
exit_code,
};
pub use parse::{parse_porcelain_z, parse_untracked_files};
-pub use repository::{Repository, ResolvedWorktree, WorktreeView, set_base_path};
+pub use repository::{Repository, ResolvedWorktree, WorkingTree, set_base_path};
pub use url::{GitRemoteUrl, parse_owner_repo, parse_remote_host, parse_remote_owner};
/// Why branch content is considered integrated into the target branch.
///
@@ -279,8 +279,8 @@ pub struct CompletionBranch {
// Re-export parsing helpers for internal use
pub(crate) use parse::DefaultBranchName;
-// Note: HookType and Worktree are defined in this module and are already public.
-// They're accessible as git::HookType and git::Worktree without needing re-export.
+// Note: HookType and WorktreeInfo are defined in this module and are already public.
+// They're accessible as git::HookType and git::WorktreeInfo without needing re-export.
/// Hook types for git operations
#[derive(
@@ -305,9 +305,78 @@ pub enum HookType {
PreRemove,
}
-/// Worktree information
+/// Reference to a branch for parallel task execution.
+///
+/// Works for both worktree items (has path) and branch-only items (no worktree).
+/// The `Option<PathBuf>` makes the worktree distinction explicit instead of using
+/// empty paths as a sentinel value.
+///
+/// # Construction
+///
+/// - From a worktree: `BranchRef::from(&worktree_info)`
+/// - For a branch-only item: `BranchRef::branch_only("feature", "abc123")`
+///
+/// # Working Tree Access
+///
+/// For worktree-specific operations, use [`working_tree()`](Self::working_tree)
+/// which returns `Some(WorkingTree)` only when this ref has a worktree path.
+#[derive(Debug, Clone)]
+pub struct BranchRef {
+ /// Branch name (e.g., "main", "feature/auth").
+ /// None for detached HEAD.
+ pub branch: Option<String>,
+ /// Commit SHA this branch/worktree points to.
+ pub commit_sha: String,
+ /// Path to worktree, if this branch has one.
+ /// None for branch-only items (remote branches, local branches without worktrees).
+ pub worktree_path: Option<PathBuf>,
+}
+
+impl BranchRef {
+ /// Create a BranchRef for a branch without a worktree.
+ ///
+ /// Used for remote-only branches or local branches that don't have a worktree.
+ pub fn branch_only(branch: &str, commit_sha: &str) -> Self {
+ Self {
+ branch: Some(branch.to_string()),
+ commit_sha: commit_sha.to_string(),
+ worktree_path: None,
+ }
+ }
+
+ /// Get a working tree handle for this branch's worktree.
+ ///
+ /// Returns `Some(WorkingTree)` if this branch has a worktree path,
+ /// `None` for branch-only items.
+ pub fn working_tree<'a>(&self, repo: &'a Repository) -> Option<WorkingTree<'a>> {
+ self.worktree_path
+ .as_ref()
+ .map(|p| repo.worktree_at(p.clone()))
+ }
+
+ /// Returns true if this branch has a worktree.
+ pub fn has_worktree(&self) -> bool {
+ self.worktree_path.is_some()
+ }
+}
+
+impl From<&WorktreeInfo> for BranchRef {
+ fn from(wt: &WorktreeInfo) -> Self {
+ Self {
+ branch: wt.branch.clone(),
+ commit_sha: wt.head.clone(),
+ worktree_path: Some(wt.path.clone()),
+ }
+ }
+}
+
+/// Parsed worktree data from `git worktree list --porcelain`.
+///
+/// This is a data record containing metadata about a worktree.
+/// For running commands in a worktree, use [`WorkingTree`] via
+/// [`Repository::worktree_at()`] or [`BranchRef::working_tree()`].
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
-pub struct Worktree {
+pub struct WorktreeInfo {
pub path: PathBuf,
pub head: String,
pub branch: Option<String>,
@@ -327,7 +396,7 @@ pub fn path_dir_name(path: &std::path::Path) -> &str {
.unwrap_or("(unknown)")
}
-impl Worktree {
+impl WorktreeInfo {
/// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).
///
/// Prunable worktrees cannot be operated on - the directory doesn't exist.
@@ -361,7 +430,10 @@ impl Worktree {
/// Returns `None` if all worktrees are prunable or `worktrees` is empty.
/// If `default_branch` doesn't match any non-prunable worktree, returns the
/// first non-prunable worktree.
- pub fn find_home<'a>(worktrees: &'a [Worktree], default_branch: &str) -> Option<&'a Worktree> {
+ pub fn find_home<'a>(
+ worktrees: &'a [WorktreeInfo],
+ default_branch: &str,
+ ) -> Option<&'a WorktreeInfo> {
// Filter out prunable worktrees (directory deleted but git still tracks metadata).
// Can't cd to a worktree that doesn't exist.
worktrees
@@ -376,10 +448,10 @@ impl Worktree {
//
// These live in mod.rs rather than parse.rs because they bridge multiple concerns:
// - read_rebase_branch() uses Repository (from repository.rs) to access git internals
-// - finalize_worktree() operates on Worktree (defined here in mod.rs)
-// - Both are tightly coupled to the Worktree type definition
+// - finalize_worktree() operates on WorktreeInfo (defined here in mod.rs)
+// - Both are tightly coupled to the WorktreeInfo type definition
//
-// Placing them here avoids circular dependencies and keeps them close to Worktree.
+// Placing them here avoids circular dependencies and keeps them close to WorktreeInfo.
/// Helper function to read rebase branch information
fn read_rebase_branch(worktree_path: &PathBuf) -> Option<String> {
@@ -404,7 +476,7 @@ fn read_rebase_branch(worktree_path: &PathBuf) -> Option<String> {
}
/// Finalize a worktree after parsing, filling in branch name from rebase state if needed.
-pub(crate) fn finalize_worktree(mut wt: Worktree) -> Worktree {
+pub(crate) fn finalize_worktree(mut wt: WorktreeInfo) -> WorktreeInfo {
// If detached but no branch, check if we're rebasing
if wt.detached
&& wt.branch.is_none()
@@ -492,8 +564,8 @@ mod tests {
assert_eq!(path_dir_name(&PathBuf::from("/")), "(unknown)");
assert!(!path_dir_name(&PathBuf::from("/home/user/repo/")).is_empty());
- // Worktree::dir_name
- let wt = Worktree {
+ // WorktreeInfo::dir_name
+ let wt = WorktreeInfo {
path: PathBuf::from("/repos/myrepo.feature"),
head: "abc123".into(),
branch: Some("feature".into()),
@@ -521,7 +593,7 @@ mod tests {
#[test]
fn test_find_home() {
- let make_wt = |branch: Option<&str>| Worktree {
+ let make_wt = |branch: Option<&str>| WorktreeInfo {
path: PathBuf::from(format!("/repo.{}", branch.unwrap_or("detached"))),
head: "abc123".into(),
branch: branch.map(String::from),
@@ -532,34 +604,86 @@ mod tests {
};
// Empty list returns None
- assert!(Worktree::find_home(&[], "main").is_none());
+ assert!(WorktreeInfo::find_home(&[], "main").is_none());
// Single worktree on default branch
let wts = vec![make_wt(Some("main"))];
assert_eq!(
- Worktree::find_home(&wts, "main").unwrap().path.to_str(),
+ WorktreeInfo::find_home(&wts, "main").unwrap().path.to_str(),
Some("/repo.main")
);
// Default branch not first - should still find it
let wts = vec![make_wt(Some("feature")), make_wt(Some("main"))];
assert_eq!(
- Worktree::find_home(&wts, "main").unwrap().path.to_str(),
+ WorktreeInfo::find_home(&wts, "main").unwrap().path.to_str(),
Some("/repo.main")
);
// No default branch match - returns first
let wts = vec![make_wt(Some("feature")), make_wt(Some("bugfix"))];
assert_eq!(
- Worktree::find_home(&wts, "main").unwrap().path.to_str(),
+ WorktreeInfo::find_home(&wts, "main").unwrap().path.to_str(),
Some("/repo.feature")
);
// Empty default branch - returns first
let wts = vec![make_wt(Some("feature"))];
assert_eq!(
- Worktree::find_home(&wts, "").unwrap().path.to_str(),
+ WorktreeInfo::find_home(&wts, "").unwrap().path.to_str(),
Some("/repo.feature")
);
}
+
+ #[test]
+ fn test_branch_ref_from_worktree_info() {
+ let wt = WorktreeInfo {
+ path: PathBuf::from("/repo.feature"),
+ head: "abc123".into(),
+ branch: Some("feature".into()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ };
+
+ let branch_ref = BranchRef::from(&wt);
+
+ assert_eq!(branch_ref.branch, Some("feature".to_string()));
+ assert_eq!(branch_ref.commit_sha, "abc123");
+ assert_eq!(
+ branch_ref.worktree_path,
+ Some(PathBuf::from("/repo.feature"))
+ );
+ assert!(branch_ref.has_worktree());
+ }
+
+ #[test]
+ fn test_branch_ref_branch_only() {
+ let branch_ref = BranchRef::branch_only("feature", "abc123");
+
+ assert_eq!(branch_ref.branch, Some("feature".to_string()));
+ assert_eq!(branch_ref.commit_sha, "abc123");
+ assert_eq!(branch_ref.worktree_path, None);
+ assert!(!branch_ref.has_worktree());
+ }
+
+ #[test]
+ fn test_branch_ref_detached_head() {
+ let wt = WorktreeInfo {
+ path: PathBuf::from("/repo.detached"),
+ head: "def456".into(),
+ branch: None, // Detached HEAD
+ bare: false,
+ detached: true,
+ locked: None,
+ prunable: None,
+ };
+
+ let branch_ref = BranchRef::from(&wt);
+
+ assert_eq!(branch_ref.branch, None);
+ assert_eq!(branch_ref.commit_sha, "def456");
+ assert!(branch_ref.has_worktree());
+ }
}
diff --git a/src/git/parse.rs b/src/git/parse.rs
index 50dcfa262..419485352 100644
--- a/src/git/parse.rs
+++ b/src/git/parse.rs
@@ -2,12 +2,12 @@
use std::path::PathBuf;
-use super::{GitError, Worktree, finalize_worktree};
+use super::{GitError, WorktreeInfo, finalize_worktree};
-impl Worktree {
+impl WorktreeInfo {
pub(crate) fn parse_porcelain_list(output: &str) -> anyhow::Result<Vec<Self>> {
let mut worktrees = Vec::new();
- let mut current: Option<Worktree> = None;
+ let mut current: Option<WorktreeInfo> = None;
for line in output.lines() {
if line.is_empty() {
@@ -30,7 +30,7 @@ impl Worktree {
}
.into());
};
- current = Some(Worktree {
+ current = Some(WorktreeInfo {
path: PathBuf::from(path),
head: String::new(),
branch: None,
@@ -291,13 +291,13 @@ mod tests {
}
// ============================================================================
- // Worktree::parse_porcelain_list Tests
+ // WorktreeInfo::parse_porcelain_list Tests
// ============================================================================
#[test]
fn test_parse_porcelain_list_single_worktree() {
let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
@@ -309,7 +309,7 @@ mod tests {
#[test]
fn test_parse_porcelain_list_multiple_worktrees() {
let output = "worktree /path/main\nHEAD aaa\nbranch refs/heads/main\n\nworktree /path/feature\nHEAD bbb\nbranch refs/heads/feature\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 2);
@@ -320,7 +320,7 @@ mod tests {
#[test]
fn test_parse_porcelain_list_bare_repo() {
let output = "worktree /path/to/repo.git\nHEAD abc123\nbare\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
@@ -330,7 +330,7 @@ mod tests {
#[test]
fn test_parse_porcelain_list_detached() {
let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
@@ -341,7 +341,7 @@ mod tests {
#[test]
fn test_parse_porcelain_list_locked() {
let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked reason for lock\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
@@ -351,7 +351,7 @@ mod tests {
#[test]
fn test_parse_porcelain_list_prunable() {
let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable gitdir file missing\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
@@ -363,7 +363,7 @@ mod tests {
#[test]
fn test_parse_porcelain_list_empty() {
- let result = Worktree::parse_porcelain_list("");
+ let result = WorktreeInfo::parse_porcelain_list("");
assert!(result.is_ok());
let worktrees = result.unwrap();
assert!(worktrees.is_empty());
@@ -373,7 +373,7 @@ mod tests {
fn test_parse_porcelain_list_no_trailing_blank() {
// Git output may not always end with a blank line
let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
assert_eq!(worktrees.len(), 1);
@@ -382,14 +382,14 @@ mod tests {
#[test]
fn test_parse_porcelain_list_missing_worktree_path() {
let output = "worktree\nHEAD abc123\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_err());
}
#[test]
fn test_parse_porcelain_list_missing_head_sha() {
let output = "worktree /path\nHEAD\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_err());
}
@@ -397,7 +397,7 @@ mod tests {
fn test_parse_porcelain_list_branch_without_refs_prefix() {
// This can happen in some edge cases
let output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
// Should use the branch name as-is when no refs/heads/ prefix
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index ebfeb5c75..12668792b 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -15,7 +15,7 @@ use crate::config::ProjectConfig;
// Import types and functions from parent module (mod.rs)
use super::{
BranchCategory, CompletionBranch, DefaultBranchName, DiffStats, GitError, GitRemoteUrl,
- LineDiff, Worktree,
+ LineDiff, WorktreeInfo,
};
// ============================================================================
@@ -37,6 +37,8 @@ struct RepoCache {
is_bare: OnceCell<bool>,
/// Default branch (main, master, etc.)
default_branch: OnceCell<String>,
+ /// Effective integration target (local default branch or upstream if ahead)
+ integration_target: OnceCell<String>,
/// Primary remote name (None if no remotes configured)
primary_remote: OnceCell<Option<String>>,
/// Project identifier derived from remote URL
@@ -101,7 +103,7 @@ fn base_path() -> &'static PathBuf {
/// Repository state for git operations.
///
/// Represents the shared state of a git repository (the `.git` directory).
-/// For worktree-specific operations, use [`WorktreeView`] obtained via
+/// For worktree-specific operations, use [`WorkingTree`] obtained via
/// [`current_worktree()`](Self::current_worktree) or [`worktree_at()`](Self::worktree_at).
///
/// # Examples
@@ -131,11 +133,13 @@ pub struct Repository {
cache: Arc<RepoCache>,
}
-/// A view into a specific worktree within a repository.
+/// A borrowed handle for running git commands in a specific worktree.
///
/// This type borrows a [`Repository`] and holds a path to a specific worktree.
/// All worktree-specific operations (like `branch`, `is_dirty`) are on this type.
///
+/// For an owned equivalent that can be cloned across threads, see [`super::BranchRef`].
+///
/// # Examples
///
/// ```no_run
@@ -154,7 +158,7 @@ pub struct Repository {
/// ```
#[derive(Debug)]
#[must_use]
-pub struct WorktreeView<'a> {
+pub struct WorkingTree<'a> {
repo: &'a Repository,
path: PathBuf,
}
@@ -171,7 +175,7 @@ fn path_to_logging_context(path: &Path) -> String {
}
}
-impl<'a> WorktreeView<'a> {
+impl<'a> WorkingTree<'a> {
/// Run a git command in this worktree and return stdout.
pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {
use crate::shell_exec::run;
@@ -382,7 +386,7 @@ impl Repository {
/// this uses that path instead of the actual current directory.
///
/// For worktree-specific operations on paths other than cwd, use
- /// `repo.worktree_at(path)` to get a [`WorktreeView`].
+ /// `repo.worktree_at(path)` to get a [`WorkingTree`].
pub fn current() -> anyhow::Result<Self> {
Self::at(base_path().clone())
}
@@ -421,7 +425,7 @@ impl Repository {
/// Resolve the git common directory for a path.
// TODO: Consolidate the "Failed to execute: git ..." context pattern.
- // Currently duplicated in WorktreeView::run_command, Repository::run_command, and here.
+ // Currently duplicated in WorkingTree::run_command, Repository::run_command, and here.
// Consider extracting a helper that handles the context message consistently.
fn resolve_git_common_dir(discovery_path: &Path) -> anyhow::Result<PathBuf> {
use crate::shell_exec::run;
@@ -458,16 +462,16 @@ impl Repository {
/// Get a worktree view at the current directory.
///
- /// This is the primary way to get a [`WorktreeView`] for worktree-specific operations.
- pub fn current_worktree(&self) -> WorktreeView<'_> {
+ /// This is the primary way to get a [`WorkingTree`] for worktree-specific operations.
+ pub fn current_worktree(&self) -> WorkingTree<'_> {
self.worktree_at(base_path().clone())
}
/// Get a worktree view at a specific path.
///
/// Use this when you need to operate on a worktree other than the current one.
- pub fn worktree_at(&self, path: impl Into<PathBuf>) -> WorktreeView<'_> {
- WorktreeView {
+ pub fn worktree_at(&self, path: impl Into<PathBuf>) -> WorkingTree<'_> {
+ WorkingTree {
repo: self,
path: path.into(),
}
@@ -996,7 +1000,7 @@ impl Repository {
let worktrees = self.list_worktrees()?;
let default_branch = self.default_branch().unwrap_or_default();
- if let Some(home) = Worktree::find_home(&worktrees, &default_branch) {
+ if let Some(home) = WorktreeInfo::find_home(&worktrees, &default_branch) {
return Ok(home.path.clone());
}
@@ -1243,6 +1247,22 @@ impl Repository {
local_target.to_string()
}
+ /// Get the cached integration target for this repository.
+ ///
+ /// This is the effective target for integration checks (status symbols, safe deletion).
+ /// May be upstream (e.g., "origin/main") if it's ahead of local, catching remotely-merged branches.
+ ///
+ /// Result is cached in the shared repo cache (shared across all worktrees).
+ pub fn integration_target(&self) -> anyhow::Result<String> {
+ self.cache
+ .integration_target
+ .get_or_try_init(|| {
+ let default_branch = self.default_branch()?;
+ Ok(self.effective_integration_target(&default_branch))
+ })
+ .cloned()
+ }
+
/// Get merge/rebase status for the worktree at this repository's discovery path.
pub fn worktree_state(&self) -> anyhow::Result<Option<String>> {
let git_dir = self.worktree_at(self.discovery_path()).git_dir()?;
@@ -1862,19 +1882,19 @@ impl Repository {
/// is the first linked worktree (no semantic "main" exists).
///
/// Returns an empty vec for bare repos with no linked worktrees.
- pub fn list_worktrees(&self) -> anyhow::Result<Vec<Worktree>> {
+ pub fn list_worktrees(&self) -> anyhow::Result<Vec<WorktreeInfo>> {
let stdout = self.run_command(&["worktree", "list", "--porcelain"])?;
- let raw_worktrees = Worktree::parse_porcelain_list(&stdout)?;
+ let raw_worktrees = WorktreeInfo::parse_porcelain_list(&stdout)?;
Ok(raw_worktrees.into_iter().filter(|wt| !wt.bare).collect())
}
- /// Get the Worktree info struct for the current worktree, if we're inside one.
+ /// Get the WorktreeInfo struct for the current worktree, if we're inside one.
///
/// Returns `None` if not in a worktree (e.g., in bare repo directory).
///
/// Note: For worktree-specific operations, use [`current_worktree()`](Self::current_worktree)
- /// to get a [`WorktreeView`] instead.
- pub fn current_worktree_info(&self) -> anyhow::Result<Option<Worktree>> {
+ /// to get a [`WorkingTree`] instead.
+ pub fn current_worktree_info(&self) -> anyhow::Result<Option<WorktreeInfo>> {
let current_path = match self.current_worktree().root() {
Ok(p) => p.to_path_buf(),
Err(_) => return Ok(None),
@@ -2113,6 +2133,18 @@ impl Repository {
.cloned()
}
+ /// Get the URL template from project config, if configured.
+ ///
+ /// Convenience method that extracts `list.url` from the project config.
+ /// Returns `None` if no config exists or no URL template is configured.
+ pub fn url_template(&self) -> Option<String> {
+ self.load_project_config()
+ .ok()
+ .flatten()
+ .and_then(|config| config.list)
+ .and_then(|list| list.url)
+ }
+
/// Get a short display name for this repository, used in logging context.
///
/// Returns "." for the current directory, or the directory name otherwise.
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index aa7575f96..acb6ddbdf 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -1,6 +1,6 @@
use std::path::PathBuf;
-use super::super::{DefaultBranchName, Worktree, finalize_worktree};
+use super::super::{DefaultBranchName, WorktreeInfo, finalize_worktree};
#[test]
fn test_parse_worktree_list() {
@@ -14,7 +14,7 @@ branch refs/heads/feature
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 2);
assert_eq!(worktrees[0].path, PathBuf::from("/path/to/main"));
@@ -36,7 +36,7 @@ detached
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 1);
assert!(worktrees[0].detached);
assert_eq!(worktrees[0].branch, None);
@@ -45,7 +45,7 @@ detached
#[test]
fn test_finalize_worktree_with_branch() {
// Worktree with a branch should not be modified
- let wt = Worktree {
+ let wt = WorktreeInfo {
path: PathBuf::from("/path/to/worktree"),
head: "abcd1234".to_string(),
branch: Some("feature".to_string()),
@@ -62,7 +62,7 @@ fn test_finalize_worktree_with_branch() {
#[test]
fn test_finalize_worktree_detached_with_branch() {
// Detached worktree with a branch (unusual but possible) should keep the branch
- let wt = Worktree {
+ let wt = WorktreeInfo {
path: PathBuf::from("/path/to/worktree"),
head: "abcd1234".to_string(),
branch: Some("feature".to_string()),
@@ -82,7 +82,7 @@ fn test_finalize_worktree_detached_no_branch() {
// Note: This test validates the logic flow but doesn't test actual file reading
// since that would require setting up git rebase state files.
// Actual rebase detection has been manually verified.
- let wt = Worktree {
+ let wt = WorktreeInfo {
path: PathBuf::from("/nonexistent/path"),
head: "abcd1234".to_string(),
branch: None,
@@ -107,7 +107,7 @@ locked reason for lock
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 1);
assert_eq!(worktrees[0].locked, Some("reason for lock".to_string()));
}
@@ -120,7 +120,7 @@ bare
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 1);
assert!(worktrees[0].bare);
}
@@ -331,7 +331,7 @@ locked
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 1);
// Empty lock reason should still be recorded
assert_eq!(worktrees[0].locked, Some(String::new()));
@@ -346,7 +346,7 @@ prunable gitdir file points to non-existent location
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 1);
assert!(worktrees[0].prunable.is_some());
assert!(
@@ -378,7 +378,7 @@ detached
";
- let worktrees = Worktree::parse_porcelain_list(output).unwrap();
+ let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
assert_eq!(worktrees.len(), 4);
assert_eq!(worktrees[0].branch, Some("main".to_string()));
assert_eq!(worktrees[1].branch, Some("feature-a".to_string()));
diff --git a/src/git/test.rs b/src/git/test.rs
index a738b9c5c..84f69af9c 100644
--- a/src/git/test.rs
+++ b/src/git/test.rs
@@ -3,13 +3,13 @@
//! These tests target edge cases and error conditions in git output parsing
//! that are likely to reveal bugs in real-world usage.
-use super::{DefaultBranchName, LineDiff, Worktree};
+use super::{DefaultBranchName, LineDiff, WorktreeInfo};
use insta::assert_debug_snapshot;
use rstest::rstest;
/// Helper to parse a single worktree from porcelain output
-fn parse_single(input: &str) -> Worktree {
- let list = Worktree::parse_porcelain_list(input).expect("parse ok");
+fn parse_single(input: &str) -> WorktreeInfo {
+ let list = WorktreeInfo::parse_porcelain_list(input).expect("parse ok");
assert_eq!(list.len(), 1);
list.into_iter().next().unwrap()
}
@@ -20,7 +20,7 @@ fn test_parse_worktree_list_no_trailing_blank_line() {
// the last worktree might not be added
// Looking at the code (lines 1128-1130), this should be handled correctly
let output = "worktree /path/to/repo1\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/repo2\nHEAD def456\nbranch refs/heads/dev";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
@@ -36,7 +36,7 @@ fn test_parse_worktree_list_no_trailing_blank_line() {
#[test]
fn test_parse_worktree_list_multiple_worktrees() {
let output = "worktree /path/to/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/feature\nHEAD def456\nbranch refs/heads/feature\ndetached\n\n";
- let result = Worktree::parse_porcelain_list(output);
+ let result = WorktreeInfo::parse_porcelain_list(output);
assert!(result.is_ok());
let worktrees = result.unwrap();
@@ -57,7 +57,7 @@ fn test_parse_worktree_list_multiple_worktrees() {
)]
#[case::branch_missing_ref("worktree /path/to/repo\nHEAD abc123\nbranch\n\n", "missing ref")]
fn test_parse_worktree_list_error_cases(#[case] input: &str, #[case] expected_message: &str) {
- let result = Worktree::parse_porcelain_list(input);
+ let result = WorktreeInfo::parse_porcelain_list(input);
assert!(result.is_err(), "Parsing should fail");
let err = result.unwrap_err();
@@ -205,7 +205,7 @@ fn test_line_diff_from_numstat(
#[test]
fn snapshot_parse_worktree_list_empty_output() {
- let result = Worktree::parse_porcelain_list("").expect("parse ok");
+ let result = WorktreeInfo::parse_porcelain_list("").expect("parse ok");
assert_debug_snapshot!(result, @"[]");
}
@@ -213,7 +213,7 @@ fn snapshot_parse_worktree_list_empty_output() {
fn snapshot_parse_worktree_list_missing_head() {
let wt = parse_single("worktree /path/to/repo\nbranch refs/heads/main\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "",
branch: Some(
@@ -232,7 +232,7 @@ fn snapshot_parse_worktree_list_locked_with_empty_reason() {
let wt =
parse_single("worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: Some(
@@ -254,7 +254,7 @@ fn snapshot_parse_worktree_list_locked_with_reason() {
"worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked working on it\n\n",
);
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: Some(
@@ -275,7 +275,7 @@ fn snapshot_parse_worktree_list_prunable_empty() {
let wt =
parse_single("worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: Some(
@@ -297,7 +297,7 @@ fn snapshot_parse_worktree_list_fields_before_worktree() {
"HEAD abc123\nbranch refs/heads/main\nworktree /path/to/repo\nHEAD def456\n\n",
);
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "def456",
branch: None,
@@ -313,7 +313,7 @@ fn snapshot_parse_worktree_list_fields_before_worktree() {
fn snapshot_parse_worktree_list_bare_repository() {
let wt = parse_single("worktree /path/to/repo\nbare\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "",
branch: None,
@@ -329,7 +329,7 @@ fn snapshot_parse_worktree_list_bare_repository() {
fn snapshot_parse_worktree_list_detached_head() {
let wt = parse_single("worktree /path/to/repo\nHEAD abc123\ndetached\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: None,
@@ -347,7 +347,7 @@ fn snapshot_parse_worktree_list_branch_with_refs_prefix() {
"worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/feature/nested/branch\n\n",
);
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: Some(
@@ -365,7 +365,7 @@ fn snapshot_parse_worktree_list_branch_with_refs_prefix() {
fn snapshot_parse_worktree_list_branch_without_refs_prefix() {
let wt = parse_single("worktree /path/to/repo\nHEAD abc123\nbranch main\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: Some(
@@ -383,7 +383,7 @@ fn snapshot_parse_worktree_list_branch_without_refs_prefix() {
fn snapshot_parse_worktree_list_unknown_attributes() {
let wt = parse_single("worktree /path/to/repo\nHEAD abc123\nfutureattr somevalue\n\n");
assert_debug_snapshot!(wt, @r#"
- Worktree {
+ WorktreeInfo {
path: "/path/to/repo",
head: "abc123",
branch: None,