Skip to content

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

Use `EnumDiscriminants` to ensure task result type safety

Maximilian Roos169ae90014b9
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 4919dc1bf..658100812 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -44,8 +44,20 @@ struct StatusContext {
/// Each spawned task produces exactly one TaskResult. Multiple results
/// may feed into a single table column, and one result may feed multiple
/// columns. See `drain_results()` for how results map to ListItem fields.
-#[derive(Debug, Clone, strum::IntoStaticStr)]
-#[strum(serialize_all = "snake_case")]
+///
+/// The `EnumDiscriminants` derive generates a companion `TaskKind` enum
+/// with the same variants but no payloads, used for type-safe tracking
+/// of expected vs received results.
+/// Discriminant enum for `TaskResult`, used for type-safe tracking of
+/// expected vs received results. Generated by `strum::EnumDiscriminants`.
+pub(super) use TaskResultDiscriminants as TaskKind;
+
+#[derive(Debug, Clone, strum::EnumDiscriminants)]
+#[strum_discriminants(
+ name(TaskResultDiscriminants),
+ derive(Hash, strum::IntoStaticStr),
+ strum(serialize_all = "snake_case")
+)]
pub(super) enum TaskResult {
/// Commit timestamp and message
CommitDetails {
@@ -142,8 +154,8 @@ enum DrainOutcome {
TimedOut {
/// Number of task results received before timeout
received_count: usize,
- /// Items with missing results: (item_idx, branch_name, missing_result_types)
- items_with_missing: Vec<(usize, String, Vec<&'static str>)>,
+ /// Items with missing results: (item_idx, branch_name, missing_result_kinds)
+ items_with_missing: Vec<(usize, String, Vec<TaskKind>)>,
},
}
@@ -153,19 +165,19 @@ enum DrainOutcome {
/// without hardcoding result lists that could drift from the spawn functions.
#[derive(Default)]
pub(super) struct ExpectedResults {
- inner: std::sync::Mutex<std::collections::HashMap<usize, Vec<&'static str>>>,
+ inner: std::sync::Mutex<std::collections::HashMap<usize, Vec<TaskKind>>>,
}
impl ExpectedResults {
- /// Record that we expect a result of the given type for the given item.
- /// Called immediately after spawning each task.
- pub fn expect(&self, item_idx: usize, result_type: &'static str) {
+ /// Record that we expect a result of the given kind for the given item.
+ /// Called internally by `TaskSpawner::spawn()`.
+ pub fn expect(&self, item_idx: usize, kind: TaskKind) {
self.inner
.lock()
.unwrap()
.entry(item_idx)
.or_default()
- .push(result_type);
+ .push(kind);
}
/// Total number of expected results (for progress display).
@@ -174,7 +186,7 @@ impl ExpectedResults {
}
/// Expected results for a specific item.
- fn results_for(&self, item_idx: usize) -> Vec<&'static str> {
+ fn results_for(&self, item_idx: usize) -> Vec<TaskKind> {
self.inner
.lock()
.unwrap()
@@ -209,8 +221,8 @@ fn drain_results(
// Deadline for the entire drain operation (30 seconds should be more than enough)
let deadline = Instant::now() + Duration::from_secs(30);
- // Track which result types we've received per item (for timeout diagnostics)
- let mut received_by_item: HashMap<usize, Vec<&'static str>> = HashMap::new();
+ // Track which result kinds we've received per item (for timeout diagnostics)
+ 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())
@@ -230,7 +242,7 @@ fn drain_results(
let received_count: usize = received_by_item.values().map(|v| v.len()).sum();
// Find items with missing results by comparing received vs expected
- let mut items_with_missing: Vec<(usize, String, Vec<&'static str>)> = Vec::new();
+ let mut items_with_missing: Vec<(usize, String, Vec<TaskKind>)> = Vec::new();
for (item_idx, item) in items.iter().enumerate() {
// Get expected results for this item (populated at spawn time)
@@ -243,9 +255,9 @@ fn drain_results(
.unwrap_or(&[]);
// Find missing results
- let missing: Vec<&'static str> = expected
+ let missing: Vec<TaskKind> = expected
.iter()
- .filter(|&result| !received.contains(result))
+ .filter(|kind| !received.contains(kind))
.copied()
.collect();
@@ -274,13 +286,10 @@ fn drain_results(
Err(chan::RecvTimeoutError::Disconnected) => break, // All senders dropped - done
};
- // Track this result for diagnostics (strum::IntoStaticStr provides the conversion)
+ // Track this result for diagnostics (TaskKind derived via EnumDiscriminants)
let item_idx = result.item_idx();
- let result_type: &'static str = (&result).into();
- received_by_item
- .entry(item_idx)
- .or_default()
- .push(result_type);
+ let kind = TaskKind::from(&result);
+ received_by_item.entry(item_idx).or_default().push(kind);
match result {
TaskResult::CommitDetails { item_idx, commit } => {
@@ -778,7 +787,8 @@ pub fn collect(
if !items_with_missing.is_empty() {
diag.push_str("\nMissing results:");
for (_, name, missing) in &items_with_missing {
- diag.push_str(&format!("\n - {name}: {}", missing.join(", ")));
+ let missing_names: Vec<&str> = missing.iter().map(|k| k.into()).collect();
+ diag.push_str(&format!("\n - {name}: {}", missing_names.join(", ")));
}
}
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 1ab9d95a2..7381bc1ee 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -1,18 +1,18 @@
//! Progressive worktree collection with parallel git operations.
//!
-//! This module contains the implementation of task-by-task progressive rendering.
+//! This module provides a typed task framework for cell-by-cell progressive rendering.
//! Git operations run in parallel and send results as they complete.
//!
-//! ## Invariant: Every task must send exactly one result
+//! ## Architecture
//!
-//! Each `spawn_*` function records its expected result via `expected_results.expect()`.
-//! The `drain_results` loop waits until all senders are dropped, which only
-//! happens after all spawned threads complete. If a spawn function doesn't send
-//! a result (e.g., due to an early return or failed condition), the timeout
-//! diagnostic will show that result as missing.
+//! The framework guarantees that every spawned task is registered in `ExpectedResults`
+//! and sends exactly one `TaskResult`:
//!
-//! **Always send a result**, even when conditions aren't met or errors occur.
-//! Use default values rather than skipping the send.
+//! - `Task` trait: Each task type implements `compute()` returning a `TaskResult`
+//! - `TaskSpawner`: Ties together registration + spawn + send in a single operation
+//! - `define_task_suite!`: Generates spawn lists and expected sets from the same source
+//!
+//! This eliminates the "spawn but forget to register" failure mode from the old design.
//!
//! TODO(error-handling): Current implementation silently swallows git errors
//! and logs warnings to stderr. Consider whether failures should:
@@ -28,9 +28,13 @@ use worktrunk::path::format_path_for_display;
use worktrunk::styling::eprintln;
use super::ci_status::PrStatus;
-use super::collect::{ExpectedResults, TaskResult, detect_git_operation};
+use super::collect::{ExpectedResults, TaskKind, TaskResult, detect_git_operation};
use super::model::{AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus};
+// ============================================================================
+// Options and Context
+// ============================================================================
+
/// Options for controlling what data to collect.
#[derive(Clone, Copy)]
pub struct CollectOptions {
@@ -38,313 +42,328 @@ pub struct CollectOptions {
pub check_merge_tree_conflicts: bool,
}
-/// Context for spawning parallel tasks.
-struct TaskContext {
- repo_path: PathBuf,
- commit_sha: String,
- branch: Option<String>,
- default_branch: Option<String>,
- item_idx: usize,
+/// Context for task computation. Cloned and moved into spawned threads.
+///
+/// Contains all data needed by any task, including options that control
+/// conditional behavior.
+#[derive(Clone)]
+pub struct TaskContext {
+ pub repo_path: PathBuf,
+ pub commit_sha: String,
+ pub branch: Option<String>,
+ pub default_branch: Option<String>,
+ pub item_idx: usize,
+ // Options that affect task behavior
+ pub fetch_ci: bool,
+ pub check_merge_tree_conflicts: bool,
+ pub verbose_errors: bool,
}
-/// Spawn task 1: Commit details (timestamp, message)
-fn spawn_commit_details<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
+// ============================================================================
+// Task Trait and Spawner
+// ============================================================================
+
+/// A task that computes a single `TaskResult`.
+///
+/// Each task type has a compile-time `KIND` that determines which `TaskResult`
+/// variant it produces. The `compute()` function receives a cloned context and
+/// returns the result.
+pub trait Task: Send + Sync + 'static {
+ /// The kind of result this task produces (compile-time constant).
+ const KIND: TaskKind;
+
+ /// Compute the task result. Called in a spawned thread.
+ fn compute(ctx: TaskContext) -> TaskResult;
+}
+
+/// Spawner that ties together registration + spawn + send.
+///
+/// Using `TaskSpawner::spawn<T>()` is the only way to run a task, and it
+/// automatically registers the expected result kind before spawning.
+pub struct TaskSpawner {
tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "commit_details");
- let item_idx = ctx.item_idx;
- let sha = ctx.commit_sha.clone();
- let path = ctx.repo_path.clone();
- s.spawn(move || {
- let repo = Repository::at(&path);
- let timestamp = match repo.commit_timestamp(&sha) {
+ expected: Arc<ExpectedResults>,
+}
+
+impl TaskSpawner {
+ pub fn new(tx: Sender<TaskResult>, expected: Arc<ExpectedResults>) -> Self {
+ Self { tx, expected }
+ }
+
+ /// Spawn a task, registering its expected result and sending on completion.
+ ///
+ /// This is the only way to run a `Task`. It guarantees:
+ /// 1. The expected result is registered before the task runs
+ /// 2. Exactly one result is sent when the task completes
+ pub fn spawn<'scope, T: Task>(
+ &self,
+ scope: &'scope std::thread::Scope<'scope, '_>,
+ ctx: &TaskContext,
+ ) {
+ // 1. Register expectation
+ self.expected.expect(ctx.item_idx, T::KIND);
+
+ // 2. Clone for the spawned thread
+ let tx = self.tx.clone();
+ let ctx = ctx.clone();
+
+ // 3. Spawn the work
+ scope.spawn(move || {
+ let result = T::compute(ctx);
+ debug_assert_eq!(TaskKind::from(&result), T::KIND);
+ let _ = tx.send(result);
+ });
+ }
+}
+
+// ============================================================================
+// Task Implementations
+// ============================================================================
+
+/// Task 1: Commit details (timestamp, message)
+pub struct CommitDetailsTask;
+
+impl Task for CommitDetailsTask {
+ const KIND: TaskKind = TaskKind::CommitDetails;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let repo = Repository::at(&ctx.repo_path);
+ let timestamp = match repo.commit_timestamp(&ctx.commit_sha) {
Ok(ts) => ts,
Err(e) => {
- log::warn!("commit_timestamp failed for {}: {}", sha, e);
+ log::warn!("commit_timestamp failed for {}: {}", ctx.commit_sha, e);
0
}
};
- let commit_message = match repo.commit_message(&sha) {
+ let commit_message = match repo.commit_message(&ctx.commit_sha) {
Ok(msg) => msg,
Err(e) => {
- log::warn!("commit_message failed for {}: {}", sha, e);
+ log::warn!("commit_message failed for {}: {}", ctx.commit_sha, e);
String::new()
}
};
- let _ = tx.send(TaskResult::CommitDetails {
- item_idx,
+ TaskResult::CommitDetails {
+ item_idx: ctx.item_idx,
commit: CommitDetails {
timestamp,
commit_message,
},
- });
- });
+ }
+ }
}
-/// Spawn task 2: Ahead/behind counts
-fn spawn_ahead_behind<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "ahead_behind");
- let item_idx = ctx.item_idx;
- if let Some(base) = ctx.default_branch.as_deref() {
- let sha = ctx.commit_sha.clone();
- let path = ctx.repo_path.clone();
- let base = base.to_string();
- s.spawn(move || {
- let repo = Repository::at(&path);
- let (ahead, behind) = match repo.ahead_behind(&base, &sha) {
+/// Task 2: Ahead/behind counts vs default branch
+pub struct AheadBehindTask;
+
+impl Task for AheadBehindTask {
+ const KIND: TaskKind = TaskKind::AheadBehind;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let (ahead, behind) = if let Some(base) = ctx.default_branch.as_deref() {
+ let repo = Repository::at(&ctx.repo_path);
+ match repo.ahead_behind(base, &ctx.commit_sha) {
Ok((a, b)) => (a, b),
Err(e) => {
- log::warn!("ahead_behind failed for {} vs {}: {}", sha, base, e);
+ log::warn!(
+ "ahead_behind failed for {} vs {}: {}",
+ ctx.commit_sha,
+ base,
+ e
+ );
(0, 0)
}
- };
- let _ = tx.send(TaskResult::AheadBehind {
- item_idx,
- counts: AheadBehind { ahead, behind },
- });
- });
- } else {
- // Always send a result to satisfy the expected count
- let _ = tx.send(TaskResult::AheadBehind {
- item_idx,
- counts: AheadBehind::default(),
- });
+ }
+ } else {
+ (0, 0)
+ };
+
+ TaskResult::AheadBehind {
+ item_idx: ctx.item_idx,
+ counts: AheadBehind { ahead, behind },
+ }
}
}
-/// Spawn task 2b: Tree identity check (does HEAD tree match main's tree?)
-fn spawn_committed_trees_match<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "committed_trees_match");
- let item_idx = ctx.item_idx;
- if let Some(base) = ctx.default_branch.as_deref() {
- let path = ctx.repo_path.clone();
- let base = base.to_string();
- s.spawn(move || {
- let repo = Repository::at(&path);
- let committed_trees_match = repo.head_tree_matches_branch(&base).unwrap_or(false);
- let _ = tx.send(TaskResult::CommittedTreesMatch {
- item_idx,
- committed_trees_match,
- });
- });
- } else {
- // Always send a result to satisfy the expected count
- let _ = tx.send(TaskResult::CommittedTreesMatch {
- item_idx,
- committed_trees_match: false,
- });
+/// Task 3: Tree identity check (does HEAD tree match default branch's tree?)
+pub struct CommittedTreesMatchTask;
+
+impl Task for CommittedTreesMatchTask {
+ const KIND: TaskKind = TaskKind::CommittedTreesMatch;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let committed_trees_match = if let Some(base) = ctx.default_branch.as_deref() {
+ let repo = Repository::at(&ctx.repo_path);
+ repo.head_tree_matches_branch(base).unwrap_or(false)
+ } else {
+ false
+ };
+
+ TaskResult::CommittedTreesMatch {
+ item_idx: ctx.item_idx,
+ committed_trees_match,
+ }
}
}
-/// Spawn task 3: Branch diff
-fn spawn_branch_diff<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "branch_diff");
- let item_idx = ctx.item_idx;
- if let Some(base) = ctx.default_branch.as_deref() {
- let sha = ctx.commit_sha.clone();
- let path = ctx.repo_path.clone();
- let base = base.to_string();
- s.spawn(move || {
- let repo = Repository::at(&path);
- let diff = match repo.branch_diff_stats(&base, &sha) {
+/// Task 4: Branch diff stats vs default branch
+pub struct BranchDiffTask;
+
+impl Task for BranchDiffTask {
+ const KIND: TaskKind = TaskKind::BranchDiff;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let diff = if let Some(base) = ctx.default_branch.as_deref() {
+ let repo = Repository::at(&ctx.repo_path);
+ match repo.branch_diff_stats(base, &ctx.commit_sha) {
Ok(d) => d,
Err(e) => {
- log::warn!("branch_diff_stats failed for {} vs {}: {}", sha, base, e);
+ log::warn!(
+ "branch_diff_stats failed for {} vs {}: {}",
+ ctx.commit_sha,
+ base,
+ e
+ );
LineDiff::default()
}
- };
- let _ = tx.send(TaskResult::BranchDiff {
- item_idx,
- branch_diff: BranchDiffTotals { diff },
- });
- });
- } else {
- // Always send a result to satisfy the expected count
- let _ = tx.send(TaskResult::BranchDiff {
- item_idx,
- branch_diff: BranchDiffTotals::default(),
- });
+ }
+ } else {
+ LineDiff::default()
+ };
+
+ TaskResult::BranchDiff {
+ item_idx: ctx.item_idx,
+ branch_diff: BranchDiffTotals { diff },
+ }
}
}
-/// Spawn task 4 (worktree only): Working tree diff + status symbols
-fn spawn_working_tree_diff<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "working_tree_diff");
- let item_idx = ctx.item_idx;
- let path = ctx.repo_path.clone();
- let base = ctx.default_branch.clone();
- s.spawn(move || {
- let repo = Repository::at(&path);
+/// Task 5 (worktree only): Working tree diff + status symbols
+pub struct WorkingTreeDiffTask;
+
+impl Task for WorkingTreeDiffTask {
+ const KIND: TaskKind = TaskKind::WorkingTreeDiff;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let repo = Repository::at(&ctx.repo_path);
let status_output = match repo.run_command(&["status", "--porcelain"]) {
Ok(output) => output,
Err(e) => {
- log::warn!("git status failed for {}: {}", path.display(), e);
- // Send default values on error
- let _ = tx.send(TaskResult::WorkingTreeDiff {
- item_idx,
+ log::warn!("git status failed for {}: {}", ctx.repo_path.display(), e);
+ return TaskResult::WorkingTreeDiff {
+ item_idx: ctx.item_idx,
working_tree_diff: LineDiff::default(),
working_tree_diff_with_main: None,
working_tree_symbols: String::new(),
has_conflicts: false,
- });
- return;
+ };
}
};
- // Parse status to get symbols and is_dirty
let (working_tree_symbols, is_dirty, has_conflicts) =
parse_status_for_symbols(&status_output);
- // Get working tree diff
let working_tree_diff = if is_dirty {
repo.working_tree_diff_stats().unwrap_or_default()
} else {
LineDiff::default()
};
- // Get diff with main
let working_tree_diff_with_main = repo
- .working_tree_diff_with_base(base.as_deref(), is_dirty)
+ .working_tree_diff_with_base(ctx.default_branch.as_deref(), is_dirty)
.ok()
.flatten();
- let _ = tx.send(TaskResult::WorkingTreeDiff {
- item_idx,
+ TaskResult::WorkingTreeDiff {
+ item_idx: ctx.item_idx,
working_tree_diff,
working_tree_diff_with_main,
working_tree_symbols,
has_conflicts,
- });
- });
+ }
+ }
}
-/// Spawn task 5: Potential conflicts check (merge-tree vs main)
-fn spawn_merge_tree_conflicts<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- check_merge_tree_conflicts: bool,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "merge_tree_conflicts");
- let item_idx = ctx.item_idx;
- if check_merge_tree_conflicts && let Some(base) = ctx.default_branch.as_deref() {
- let sha = ctx.commit_sha.clone();
- let path = ctx.repo_path.clone();
- let base = base.to_string();
- s.spawn(move || {
- let repo = Repository::at(&path);
- // TODO: Handle errors
- let has_merge_tree_conflicts = repo.has_merge_conflicts(&base, &sha).unwrap_or(false);
- let _ = tx.send(TaskResult::MergeTreeConflicts {
- item_idx,
- has_merge_tree_conflicts,
- });
- });
- } else {
- // Always send a result to satisfy the expected count
- let _ = tx.send(TaskResult::MergeTreeConflicts {
- item_idx,
- has_merge_tree_conflicts: false,
- });
+/// Task 6: Potential merge conflicts check (merge-tree vs default branch)
+pub struct MergeTreeConflictsTask;
+
+impl Task for MergeTreeConflictsTask {
+ const KIND: TaskKind = TaskKind::MergeTreeConflicts;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let has_merge_tree_conflicts =
+ if ctx.check_merge_tree_conflicts && ctx.default_branch.is_some() {
+ let base = ctx.default_branch.as_deref().unwrap();
+ let repo = Repository::at(&ctx.repo_path);
+ repo.has_merge_conflicts(base, &ctx.commit_sha)
+ .unwrap_or(false)
+ } else {
+ false
+ };
+
+ TaskResult::MergeTreeConflicts {
+ item_idx: ctx.item_idx,
+ has_merge_tree_conflicts,
+ }
}
}
-/// Spawn task 6 (worktree only): Worktree state detection
-fn spawn_worktree_state<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "git_operation");
- let item_idx = ctx.item_idx;
- let path = ctx.repo_path.clone();
- s.spawn(move || {
- let repo = Repository::at(&path);
+/// Task 7 (worktree only): Git operation state detection (rebase/merge)
+pub struct GitOperationTask;
+
+impl Task for GitOperationTask {
+ const KIND: TaskKind = TaskKind::GitOperation;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let repo = Repository::at(&ctx.repo_path);
let git_operation = detect_git_operation(&repo);
- let _ = tx.send(TaskResult::GitOperation {
- item_idx,
+ TaskResult::GitOperation {
+ item_idx: ctx.item_idx,
git_operation,
- });
- });
+ }
+ }
}
-/// Spawn task 7 (worktree only): User status
-fn spawn_user_status<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "user_status");
- let item_idx = ctx.item_idx;
- let path = ctx.repo_path.clone();
- let branch = ctx.branch.clone();
- s.spawn(move || {
- let repo = Repository::at(&path);
- let user_status = repo.user_status(branch.as_deref());
- let _ = tx.send(TaskResult::UserStatus {
- item_idx,
+/// Task 8 (worktree only): User-defined status from git config
+pub struct UserStatusTask;
+
+impl Task for UserStatusTask {
+ const KIND: TaskKind = TaskKind::UserStatus;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let repo = Repository::at(&ctx.repo_path);
+ let user_status = repo.user_status(ctx.branch.as_deref());
+ TaskResult::UserStatus {
+ item_idx: ctx.item_idx,
user_status,
- });
- });
+ }
+ }
}
-/// Spawn task 8: Upstream status
-fn spawn_upstream<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- verbose_errors: bool,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "upstream");
- let item_idx = ctx.item_idx;
- let branch = ctx.branch.clone();
- let sha = ctx.commit_sha.clone();
- let path = ctx.repo_path.clone();
- s.spawn(move || {
- let repo = Repository::at(&path);
- let upstream = branch
+/// Task 9: Upstream tracking status
+pub struct UpstreamTask;
+
+impl Task for UpstreamTask {
+ const KIND: TaskKind = TaskKind::Upstream;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ let repo = Repository::at(&ctx.repo_path);
+ let upstream = ctx
+ .branch
.as_deref()
.and_then(|branch| match repo.upstream_branch(branch) {
Ok(Some(upstream_branch)) => {
let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());
- match repo.ahead_behind(&upstream_branch, &sha) {
+ match repo.ahead_behind(&upstream_branch, &ctx.commit_sha) {
Ok((ahead, behind)) => Some(UpstreamStatus {
remote,
ahead,
behind,
}),
Err(e) => {
- if verbose_errors {
+ if ctx.verbose_errors {
eprintln!(
"Warning: ahead_behind failed for {}: {}",
- format_path_for_display(&path),
+ format_path_for_display(&ctx.repo_path),
e
);
}
@@ -352,12 +371,12 @@ fn spawn_upstream<'scope>(
}
}
}
- Ok(None) => None, // No upstream configured
+ Ok(None) => None,
Err(e) => {
- if verbose_errors {
+ if ctx.verbose_errors {
eprintln!(
"Warning: upstream_branch failed for {}: {}",
- format_path_for_display(&path),
+ format_path_for_display(&ctx.repo_path),
e
);
}
@@ -365,66 +384,53 @@ fn spawn_upstream<'scope>(
}
})
.unwrap_or_default();
- let _ = tx.send(TaskResult::Upstream { item_idx, upstream });
- });
-}
-/// Spawn task 9: CI/PR status
-fn spawn_ci_status<'scope>(
- s: &'scope std::thread::Scope<'scope, '_>,
- ctx: &TaskContext,
- fetch_ci: bool,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- expected_results.expect(ctx.item_idx, "ci_status");
- let item_idx = ctx.item_idx;
-
- if !fetch_ci {
- // Send None to indicate "loaded but not fetched" (shows empty, not "⋯")
- let _ = tx.send(TaskResult::CiStatus {
- item_idx,
- pr_status: None,
- });
- return;
+ TaskResult::Upstream {
+ item_idx: ctx.item_idx,
+ upstream,
+ }
}
+}
- let branch = ctx.branch.clone();
- let sha = ctx.commit_sha.clone();
- let path = ctx.repo_path.clone();
- s.spawn(move || {
- // Use the repository root if available; fall back to the provided path.
- // This works for both worktrees and branches and keeps fork detection
- // behavior consistent with GH/GL CLI expectations.
- let repo_path = Repository::at(&path).worktree_root().ok().unwrap_or(path);
+/// Task 10: CI/PR status
+pub struct CiStatusTask;
- let pr_status = branch
+impl Task for CiStatusTask {
+ const KIND: TaskKind = TaskKind::CiStatus;
+
+ fn compute(ctx: TaskContext) -> TaskResult {
+ if !ctx.fetch_ci {
+ return TaskResult::CiStatus {
+ item_idx: ctx.item_idx,
+ pr_status: None,
+ };
+ }
+
+ let repo_path = Repository::at(&ctx.repo_path)
+ .worktree_root()
+ .ok()
+ .unwrap_or_else(|| ctx.repo_path.clone());
+
+ let pr_status = ctx
+ .branch
.as_deref()
- .and_then(|branch| PrStatus::detect(branch, &sha, &repo_path));
+ .and_then(|branch| PrStatus::detect(branch, &ctx.commit_sha, &repo_path));
- let _ = tx.send(TaskResult::CiStatus {
- item_idx,
+ TaskResult::CiStatus {
+ item_idx: ctx.item_idx,
pr_status,
- });
- });
+ }
+ }
}
+// ============================================================================
+// Collection Entry Points
+// ============================================================================
+
/// Collect worktree data progressively, sending results as each task completes.
///
-/// Spawns 10 parallel git operations:
-/// 1. Commit details (timestamp, message)
-/// 2. Ahead/behind counts
-/// 3. Committed trees match (same tree SHA as default branch)
-/// 4. Branch diff stats
-/// 5. Working tree diff + status symbols
-/// 6. Merge-tree conflicts check
-/// 7. Worktree state detection
-/// 8. User status from git config
-/// 9. Upstream tracking status
-/// 10. CI/PR status
-///
-/// Each task sends a TaskResult when it completes, enabling progressive UI updates.
-/// Errors are handled with TODO for simplicity (simplest thing for now).
+/// Spawns 10 parallel git operations. Each task sends a TaskResult when it
+/// completes, enabling progressive UI updates.
pub fn collect_worktree_progressive(
wt: &Worktree,
item_idx: usize,
@@ -439,28 +445,72 @@ pub fn collect_worktree_progressive(
branch: wt.branch.clone(),
default_branch: Some(default_branch.to_string()),
item_idx,
+ fetch_ci: options.fetch_ci,
+ check_merge_tree_conflicts: options.check_merge_tree_conflicts,
+ verbose_errors: true, // Worktrees show verbose errors
};
+ let spawner = TaskSpawner::new(tx, expected_results.clone());
+
std::thread::scope(|s| {
- spawn_commit_details(s, &ctx, tx.clone(), expected_results);
- spawn_ahead_behind(s, &ctx, tx.clone(), expected_results);
- spawn_committed_trees_match(s, &ctx, tx.clone(), expected_results);
- spawn_branch_diff(s, &ctx, tx.clone(), expected_results);
- spawn_working_tree_diff(s, &ctx, tx.clone(), expected_results);
- spawn_merge_tree_conflicts(
- s,
- &ctx,
- options.check_merge_tree_conflicts,
- tx.clone(),
- expected_results,
- );
- spawn_worktree_state(s, &ctx, tx.clone(), expected_results);
- spawn_user_status(s, &ctx, tx.clone(), expected_results);
- spawn_upstream(s, &ctx, true, tx.clone(), expected_results);
- spawn_ci_status(s, &ctx, options.fetch_ci, tx, expected_results);
+ // All 10 worktree tasks
+ spawner.spawn::<CommitDetailsTask>(s, &ctx);
+ spawner.spawn::<AheadBehindTask>(s, &ctx);
+ spawner.spawn::<CommittedTreesMatchTask>(s, &ctx);
+ spawner.spawn::<BranchDiffTask>(s, &ctx);
+ spawner.spawn::<WorkingTreeDiffTask>(s, &ctx);
+ spawner.spawn::<MergeTreeConflictsTask>(s, &ctx);
+ spawner.spawn::<GitOperationTask>(s, &ctx);
+ spawner.spawn::<UserStatusTask>(s, &ctx);
+ spawner.spawn::<UpstreamTask>(s, &ctx);
+ spawner.spawn::<CiStatusTask>(s, &ctx);
+ });
+}
+
+/// Collect branch data progressively, sending results as each task completes.
+///
+/// Spawns 7 parallel git operations (similar to worktrees but without working
+/// tree operations).
+#[allow(clippy::too_many_arguments)]
+pub fn collect_branch_progressive(
+ branch_name: &str,
+ commit_sha: &str,
+ repo_path: &std::path::Path,
+ item_idx: usize,
+ default_branch: &str,
+ options: &CollectOptions,
+ tx: Sender<TaskResult>,
+ expected_results: &Arc<ExpectedResults>,
+) {
+ let ctx = TaskContext {
+ repo_path: repo_path.to_path_buf(),
+ commit_sha: commit_sha.to_string(),
+ branch: Some(branch_name.to_string()),
+ default_branch: Some(default_branch.to_string()),
+ item_idx,
+ fetch_ci: options.fetch_ci,
+ check_merge_tree_conflicts: options.check_merge_tree_conflicts,
+ verbose_errors: false, // Branches don't show verbose errors
+ };
+
+ let spawner = TaskSpawner::new(tx, expected_results.clone());
+
+ std::thread::scope(|s| {
+ // 7 branch tasks (no working tree operations)
+ spawner.spawn::<CommitDetailsTask>(s, &ctx);
+ spawner.spawn::<AheadBehindTask>(s, &ctx);
+ spawner.spawn::<CommittedTreesMatchTask>(s, &ctx);
+ spawner.spawn::<BranchDiffTask>(s, &ctx);
+ spawner.spawn::<UpstreamTask>(s, &ctx);
+ spawner.spawn::<MergeTreeConflictsTask>(s, &ctx);
+ spawner.spawn::<CiStatusTask>(s, &ctx);
});
}
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
/// Parse git status output to extract working tree symbols and conflict state.
/// Returns (symbols, is_dirty, has_conflicts).
fn parse_status_for_symbols(status_output: &str) -> (String, bool, bool) {
@@ -528,49 +578,3 @@ fn parse_status_for_symbols(status_output: &str) -> (String, bool, bool) {
(working_tree, is_dirty, has_conflicts)
}
-
-/// Collect branch data progressively, sending results as each task completes.
-///
-/// Spawns 7 parallel git operations (similar to worktrees but without working tree operations):
-/// 1. Commit details (timestamp, message)
-/// 2. Ahead/behind counts
-/// 3. Committed trees match (same tree SHA as default branch)
-/// 4. Branch diff stats
-/// 5. Upstream tracking status
-/// 6. Merge-tree conflicts check
-/// 7. CI/PR status
-#[allow(clippy::too_many_arguments)]
-pub fn collect_branch_progressive(
- branch_name: &str,
- commit_sha: &str,
- repo_path: &std::path::Path,
- item_idx: usize,
- default_branch: &str,
- options: &CollectOptions,
- tx: Sender<TaskResult>,
- expected_results: &Arc<ExpectedResults>,
-) {
- let ctx = TaskContext {
- repo_path: repo_path.to_path_buf(),
- commit_sha: commit_sha.to_string(),
- branch: Some(branch_name.to_string()),
- default_branch: Some(default_branch.to_string()),
- item_idx,
- };
-
- std::thread::scope(|s| {
- spawn_commit_details(s, &ctx, tx.clone(), expected_results);
- spawn_ahead_behind(s, &ctx, tx.clone(), expected_results);
- spawn_committed_trees_match(s, &ctx, tx.clone(), expected_results);
- spawn_branch_diff(s, &ctx, tx.clone(), expected_results);
- spawn_upstream(s, &ctx, false, tx.clone(), expected_results);
- spawn_merge_tree_conflicts(
- s,
- &ctx,
- options.check_merge_tree_conflicts,
- tx.clone(),
- expected_results,
- );
- spawn_ci_status(s, &ctx, options.fetch_ci, tx, expected_results);
- });
-}