Skip to content

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

Refactor StatusContext and TaskContext into helper methods

Maximilian Roosfa91ce7d501e
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 456129214..fa282bcf6 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -37,6 +37,7 @@ use super::model::{
use super::model::WorkingTreeStatus;
/// Context for status symbol computation during result processing
+#[derive(Clone, Default)]
struct StatusContext {
has_merge_tree_conflicts: bool,
user_marker: Option<String>,
@@ -44,6 +45,19 @@ struct StatusContext {
has_conflicts: bool,
}
+impl StatusContext {
+ fn apply_to(&self, item: &mut ListItem, target: &str) {
+ // Main worktree case is handled inside check_integration_state()
+ item.compute_status_symbols(
+ Some(target),
+ self.has_merge_tree_conflicts,
+ self.user_marker.clone(),
+ self.working_tree_status,
+ self.has_conflicts,
+ );
+ }
+}
+
/// Task results sent as each git operation completes.
/// These enable progressive rendering - update UI as data arrives.
///
@@ -339,14 +353,7 @@ fn drain_results(
let mut received_by_item: HashMap<usize, Vec<TaskKind>> = HashMap::new();
// Temporary storage for data needed by status_symbols computation
- let mut status_contexts: Vec<StatusContext> = (0..items.len())
- .map(|_| StatusContext {
- has_merge_tree_conflicts: false,
- user_marker: None,
- working_tree_status: None,
- has_conflicts: false,
- })
- .collect();
+ let mut status_contexts = vec![StatusContext::default(); items.len()];
// Process task results as they arrive (with deadline)
loop {
@@ -887,16 +894,9 @@ pub fn collect(
&mut errors,
&expected_results,
|item_idx, item, ctx| {
- // Compute/recompute status symbols as data arrives (both modes)
- // This is idempotent and updates status as new data (like upstream) arrives
- // Main worktree case is handled inside check_integration_state()
- item.compute_status_symbols(
- Some(integration_target.as_str()),
- ctx.has_merge_tree_conflicts,
- ctx.user_marker.clone(),
- ctx.working_tree_status,
- ctx.has_conflicts,
- );
+ // Compute/recompute status symbols as data arrives (both modes).
+ // This is idempotent and updates status as new data (like upstream) arrives.
+ ctx.apply_to(item, integration_target.as_str());
// Progressive mode only: update UI
if let Some(ref mut table) = progressive_table {
@@ -1204,22 +1204,13 @@ pub fn populate_items(
});
// Drain task results (blocking until all complete)
- // TODO: This callback duplicates logic from collect()'s drain_results callback.
- // Consider unifying by making collect() take options to skip progressive rendering.
let drain_outcome = drain_results(
rx,
items,
&mut errors,
&expected_results,
|_item_idx, item, ctx| {
- // Main worktree case is handled inside check_integration_state()
- item.compute_status_symbols(
- Some(target),
- ctx.has_merge_tree_conflicts,
- ctx.user_marker.clone(),
- ctx.working_tree_status,
- ctx.has_conflicts,
- );
+ ctx.apply_to(item, target);
},
);
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index aed49f34a..c0f876e71 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -15,6 +15,7 @@
//! This eliminates the "spawn but forget to register" failure mode from the old design.
use crossbeam_channel::Sender;
+use std::fmt::Display;
use std::path::PathBuf;
use std::sync::Arc;
use worktrunk::git::{LineDiff, Repository, Worktree};
@@ -60,6 +61,28 @@ pub struct TaskContext {
pub item_idx: usize,
}
+impl TaskContext {
+ fn repo(&self) -> Repository {
+ Repository::at(&self.repo_path)
+ }
+
+ 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"))
+ }
+
+ fn require_target(&self, kind: TaskKind) -> Result<&str, TaskError> {
+ self.target
+ .as_deref()
+ .ok_or_else(|| self.error(kind, "no target branch"))
+ }
+}
+
// ============================================================================
// Task Trait and Spawner
// ============================================================================
@@ -134,13 +157,13 @@ impl Task for CommitDetailsTask {
const KIND: TaskKind = TaskKind::CommitDetails;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = Repository::at(&ctx.repo_path);
+ let repo = ctx.repo();
let timestamp = repo
.commit_timestamp(&ctx.commit_sha)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
let commit_message = repo
.commit_message(&ctx.commit_sha)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::CommitDetails {
item_idx: ctx.item_idx,
commit: CommitDetails {
@@ -158,14 +181,11 @@ impl Task for AheadBehindTask {
const KIND: TaskKind = TaskKind::AheadBehind;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx
- .default_branch
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no default branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_default_branch(Self::KIND)?;
+ let repo = ctx.repo();
let (ahead, behind) = repo
.ahead_behind(base, &ctx.commit_sha)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::AheadBehind {
item_idx: ctx.item_idx,
counts: AheadBehind { ahead, behind },
@@ -182,16 +202,13 @@ impl Task for CommittedTreesMatchTask {
const KIND: TaskKind = TaskKind::CommittedTreesMatch;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx
- .target
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no target branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_target(Self::KIND)?;
+ let repo = ctx.repo();
// 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)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::CommittedTreesMatch {
item_idx: ctx.item_idx,
committed_trees_match,
@@ -223,14 +240,11 @@ impl Task for HasFileChangesTask {
has_file_changes: true,
});
};
- let base = ctx
- .target
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no target branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_target(Self::KIND)?;
+ let repo = ctx.repo();
let has_file_changes = repo
.has_added_changes(branch, base)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::HasFileChanges {
item_idx: ctx.item_idx,
has_file_changes,
@@ -262,14 +276,11 @@ impl Task for WouldMergeAddTask {
would_merge_add: true,
});
};
- let base = ctx
- .target
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no target branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_target(Self::KIND)?;
+ let repo = ctx.repo();
let would_merge_add = repo
.would_merge_add_to_target(branch, base)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
would_merge_add,
@@ -291,14 +302,11 @@ impl Task for IsAncestorTask {
const KIND: TaskKind = TaskKind::IsAncestor;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx
- .target
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no target branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_target(Self::KIND)?;
+ let repo = ctx.repo();
let is_ancestor = repo
.is_ancestor(&ctx.commit_sha, base)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::IsAncestor {
item_idx: ctx.item_idx,
is_ancestor,
@@ -313,14 +321,11 @@ impl Task for BranchDiffTask {
const KIND: TaskKind = TaskKind::BranchDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx
- .default_branch
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no default branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_default_branch(Self::KIND)?;
+ let repo = ctx.repo();
let diff = repo
.branch_diff_stats(base, &ctx.commit_sha)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::BranchDiff {
item_idx: ctx.item_idx,
branch_diff: BranchDiffTotals { diff },
@@ -335,17 +340,17 @@ impl Task for WorkingTreeDiffTask {
const KIND: TaskKind = TaskKind::WorkingTreeDiff;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = Repository::at(&ctx.repo_path);
+ let repo = ctx.repo();
let status_output = repo
.run_command(&["status", "--porcelain"])
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
let (working_tree_status, is_dirty, has_conflicts) =
parse_working_tree_status(&status_output);
let working_tree_diff = if is_dirty {
repo.working_tree_diff_stats()
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?
+ .map_err(|e| ctx.error(Self::KIND, e))?
} else {
LineDiff::default()
};
@@ -353,7 +358,7 @@ impl Task for WorkingTreeDiffTask {
// Use default_branch (local default branch) for informational display
let working_tree_diff_with_main = repo
.working_tree_diff_with_base(ctx.default_branch.as_deref(), is_dirty)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::WorkingTreeDiff {
item_idx: ctx.item_idx,
@@ -375,14 +380,11 @@ impl Task for MergeTreeConflictsTask {
const KIND: TaskKind = TaskKind::MergeTreeConflicts;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let base = ctx
- .default_branch
- .as_deref()
- .ok_or_else(|| TaskError::new(ctx.item_idx, Self::KIND, "no default branch"))?;
- let repo = Repository::at(&ctx.repo_path);
+ let base = ctx.require_default_branch(Self::KIND)?;
+ let repo = ctx.repo();
let has_merge_tree_conflicts = repo
.has_merge_conflicts(base, &ctx.commit_sha)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::MergeTreeConflicts {
item_idx: ctx.item_idx,
has_merge_tree_conflicts,
@@ -397,7 +399,7 @@ impl Task for GitOperationTask {
const KIND: TaskKind = TaskKind::GitOperation;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = Repository::at(&ctx.repo_path);
+ let repo = ctx.repo();
let git_operation = detect_git_operation(&repo);
Ok(TaskResult::GitOperation {
item_idx: ctx.item_idx,
@@ -413,7 +415,7 @@ impl Task for UserMarkerTask {
const KIND: TaskKind = TaskKind::UserMarker;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = Repository::at(&ctx.repo_path);
+ let repo = ctx.repo();
let user_marker = repo.user_marker(ctx.branch.as_deref());
Ok(TaskResult::UserMarker {
item_idx: ctx.item_idx,
@@ -429,7 +431,7 @@ impl Task for UpstreamTask {
const KIND: TaskKind = TaskKind::Upstream;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = Repository::at(&ctx.repo_path);
+ let repo = ctx.repo();
// No branch means no upstream
let Some(branch) = ctx.branch.as_deref() else {
@@ -440,21 +442,20 @@ impl Task for UpstreamTask {
};
// Get upstream branch (None is valid - just means no upstream configured)
- let upstream_branch = match repo.upstream_branch(branch) {
- Ok(Some(b)) => b,
- Ok(None) => {
- return Ok(TaskResult::Upstream {
- item_idx: ctx.item_idx,
- upstream: UpstreamStatus::default(),
- });
- }
- Err(e) => return Err(TaskError::new(ctx.item_idx, Self::KIND, e.to_string())),
+ let upstream_branch = repo
+ .upstream_branch(branch)
+ .map_err(|e| ctx.error(Self::KIND, e))?;
+ let Some(upstream_branch) = upstream_branch else {
+ return Ok(TaskResult::Upstream {
+ item_idx: ctx.item_idx,
+ upstream: UpstreamStatus::default(),
+ });
};
let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());
let (ahead, behind) = repo
.ahead_behind(&upstream_branch, &ctx.commit_sha)
- .map_err(|e| TaskError::new(ctx.item_idx, Self::KIND, e.to_string()))?;
+ .map_err(|e| ctx.error(Self::KIND, e))?;
Ok(TaskResult::Upstream {
item_idx: ctx.item_idx,
@@ -478,7 +479,7 @@ impl Task for CiStatusTask {
const KIND: TaskKind = TaskKind::CiStatus;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- let repo = Repository::at(&ctx.repo_path);
+ let repo = ctx.repo();
let repo_path = repo
.worktree_root()
.ok()
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 3c535c3b8..4ffe48f2f 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -74,19 +74,13 @@ impl ClaudeCodeContext {
/// - `/home/user/workspace/project` -> `~/w/project`
/// - `/home/user` -> `~`
/// - `/tmp/test` -> `/t/test`
-fn format_directory_fish_style(path: &str) -> String {
- use std::path::{Component, PathBuf};
+fn format_directory_fish_style(path: &Path) -> String {
+ use std::path::Component;
- let path = PathBuf::from(path);
-
- // Replace $HOME prefix with ~
- let (suffix, tilde_prefix) = env::var_os("HOME")
- .and_then(|home| {
- path.strip_prefix(&home)
- .ok()
- .map(|s| (s.to_path_buf(), true))
- })
- .unwrap_or_else(|| (path.clone(), false));
+ // Replace home directory prefix with ~
+ let (suffix, tilde_prefix) = worktrunk::path::home_dir()
+ .and_then(|home| path.strip_prefix(&home).ok().map(|s| (s, true)))
+ .unwrap_or((path, false));
// Collect normal components (skip RootDir, CurDir, etc.)
let components: Vec<_> = suffix
@@ -145,7 +139,7 @@ pub fn run(claude_code: bool) -> Result<()> {
// Directory (claude-code mode only)
let dir_str = if claude_code {
- let formatted = format_directory_fish_style(&cwd.display().to_string());
+ let formatted = format_directory_fish_style(&cwd);
output = formatted.clone();
Some(formatted)
} else {
@@ -266,22 +260,29 @@ fn get_git_status(repo: &Repository, cwd: &Path) -> Result<Option<String>> {
#[cfg(test)]
mod tests {
use super::*;
+ use std::path::Path;
#[test]
fn test_format_directory_fish_style() {
// Test absolute paths (Unix-style paths only meaningful on Unix)
#[cfg(unix)]
{
- assert_eq!(format_directory_fish_style("/tmp/test"), "/t/test");
- assert_eq!(format_directory_fish_style("/"), "/");
- assert_eq!(format_directory_fish_style("/var/log/app"), "/v/l/app");
+ assert_eq!(
+ format_directory_fish_style(Path::new("/tmp/test")),
+ "/t/test"
+ );
+ assert_eq!(format_directory_fish_style(Path::new("/")), "/");
+ assert_eq!(
+ format_directory_fish_style(Path::new("/var/log/app")),
+ "/v/l/app"
+ );
}
// Test with actual HOME (if set)
if let Ok(home) = env::var("HOME") {
// Basic home substitution
let test_path = format!("{home}/workspace/project");
- let result = format_directory_fish_style(&test_path);
+ let result = format_directory_fish_style(Path::new(&test_path));
assert!(result.starts_with("~/"), "Expected ~ prefix, got: {result}");
assert!(
result.ends_with("/project"),
@@ -289,12 +290,12 @@ mod tests {
);
// Exact HOME path should become just ~
- assert_eq!(format_directory_fish_style(&home), "~");
+ assert_eq!(format_directory_fish_style(Path::new(&home)), "~");
// Path that shares HOME as string prefix but not as path component
// e.g., /home/user vs /home/usered/nested
let path_outside_home = format!("{home}ed/nested");
- let result = format_directory_fish_style(&path_outside_home);
+ let result = format_directory_fish_style(Path::new(&path_outside_home));
assert!(
!result.starts_with("~"),
"Path sharing HOME string prefix should not use ~: {result}"