Skip to content

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

Refactor task spawning and JSON parsing

Maximilian Roos40ae15913dca
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index fa282bcf6..671a57314 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -226,24 +226,23 @@ impl TaskError {
/// 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<TaskKind>>>,
+ inner: std::sync::Mutex<Vec<Vec<TaskKind>>>,
}
impl ExpectedResults {
/// 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(kind);
+ let mut inner = self.inner.lock().unwrap();
+ if inner.len() <= item_idx {
+ inner.resize_with(item_idx + 1, Vec::new);
+ }
+ inner[item_idx].push(kind);
}
/// Total number of expected results (for progress display).
pub fn count(&self) -> usize {
- self.inner.lock().unwrap().values().map(|v| v.len()).sum()
+ self.inner.lock().unwrap().iter().map(|v| v.len()).sum()
}
/// Expected results for a specific item.
@@ -251,7 +250,7 @@ impl ExpectedResults {
self.inner
.lock()
.unwrap()
- .get(&item_idx)
+ .get(item_idx)
.cloned()
.unwrap_or_default()
}
@@ -538,20 +537,24 @@ fn get_branches_without_worktrees(
let all_branches = repo.list_local_branches()?;
// Build a set of branch names that have worktrees
- let worktree_branches: std::collections::HashSet<String> = worktrees
- .iter()
- .filter_map(|wt| wt.branch.clone())
- .collect();
+ let worktree_branches = worktree_branch_set(worktrees);
// Filter to branches without worktrees
let branches_without_worktrees: Vec<_> = all_branches
.into_iter()
- .filter(|(branch_name, _)| !worktree_branches.contains(branch_name))
+ .filter(|(branch_name, _)| !worktree_branches.contains(branch_name.as_str()))
.collect();
Ok(branches_without_worktrees)
}
+fn worktree_branch_set(worktrees: &[Worktree]) -> std::collections::HashSet<&str> {
+ worktrees
+ .iter()
+ .filter_map(|wt| wt.branch.as_deref())
+ .collect()
+}
+
/// Get remote branches from all remotes that don't have local worktrees.
///
/// Returns (branch_name, commit_sha) pairs for remote branches.
@@ -565,10 +568,7 @@ fn get_remote_branches(
let all_remote_branches = repo.list_remote_branches()?;
// Build a set of branch names that have worktrees
- let worktree_branches: std::collections::HashSet<String> = worktrees
- .iter()
- .filter_map(|wt| wt.branch.clone())
- .collect();
+ let worktree_branches = worktree_branch_set(worktrees);
// Filter to remote branches whose local equivalent doesn't have a worktree
let remote_branches: Vec<_> = all_remote_branches
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index c0f876e71..8487aa317 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -10,7 +10,6 @@
//!
//! - `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.
@@ -144,6 +143,49 @@ impl TaskSpawner {
let _ = tx.send(result);
});
}
+
+ fn spawn_core_tasks<'scope>(
+ &self,
+ scope: &'scope std::thread::Scope<'scope, '_>,
+ ctx: &TaskContext,
+ ) {
+ self.spawn::<CommitDetailsTask>(scope, ctx);
+ self.spawn::<AheadBehindTask>(scope, ctx);
+ self.spawn::<CommittedTreesMatchTask>(scope, ctx);
+ self.spawn::<HasFileChangesTask>(scope, ctx);
+ self.spawn::<IsAncestorTask>(scope, ctx);
+ self.spawn::<UpstreamTask>(scope, ctx);
+ }
+
+ fn spawn_worktree_only_tasks<'scope>(
+ &self,
+ scope: &'scope std::thread::Scope<'scope, '_>,
+ ctx: &TaskContext,
+ ) {
+ self.spawn::<WorkingTreeDiffTask>(scope, ctx);
+ self.spawn::<GitOperationTask>(scope, ctx);
+ self.spawn::<UserMarkerTask>(scope, ctx);
+ }
+
+ fn spawn_optional_tasks<'scope>(
+ &self,
+ scope: &'scope std::thread::Scope<'scope, '_>,
+ ctx: &TaskContext,
+ skip: &std::collections::HashSet<TaskKind>,
+ ) {
+ if !skip.contains(&TaskKind::BranchDiff) {
+ self.spawn::<BranchDiffTask>(scope, ctx);
+ }
+ if !skip.contains(&TaskKind::MergeTreeConflicts) {
+ self.spawn::<MergeTreeConflictsTask>(scope, ctx);
+ }
+ if !skip.contains(&TaskKind::CiStatus) {
+ self.spawn::<CiStatusTask>(scope, ctx);
+ }
+ if !skip.contains(&TaskKind::WouldMergeAdd) {
+ self.spawn::<WouldMergeAddTask>(scope, ctx);
+ }
+ }
}
// ============================================================================
@@ -518,8 +560,6 @@ pub fn collect_worktree_progressive(
tx: Sender<Result<TaskResult, TaskError>>,
expected_results: &Arc<ExpectedResults>,
) {
- use super::collect::TaskKind;
-
let ctx = TaskContext {
repo_path: wt.path.clone(),
commit_sha: wt.head.clone(),
@@ -534,29 +574,9 @@ pub fn collect_worktree_progressive(
std::thread::scope(|s| {
// Core tasks (always run)
- spawner.spawn::<CommitDetailsTask>(s, &ctx);
- spawner.spawn::<AheadBehindTask>(s, &ctx);
- spawner.spawn::<CommittedTreesMatchTask>(s, &ctx);
- spawner.spawn::<HasFileChangesTask>(s, &ctx);
- spawner.spawn::<IsAncestorTask>(s, &ctx);
- spawner.spawn::<WorkingTreeDiffTask>(s, &ctx);
- spawner.spawn::<GitOperationTask>(s, &ctx);
- spawner.spawn::<UserMarkerTask>(s, &ctx);
- spawner.spawn::<UpstreamTask>(s, &ctx);
-
- // Optional tasks (check skip set)
- if !skip.contains(&TaskKind::BranchDiff) {
- spawner.spawn::<BranchDiffTask>(s, &ctx);
- }
- if !skip.contains(&TaskKind::MergeTreeConflicts) {
- spawner.spawn::<MergeTreeConflictsTask>(s, &ctx);
- }
- if !skip.contains(&TaskKind::CiStatus) {
- spawner.spawn::<CiStatusTask>(s, &ctx);
- }
- if !skip.contains(&TaskKind::WouldMergeAdd) {
- spawner.spawn::<WouldMergeAddTask>(s, &ctx);
- }
+ spawner.spawn_core_tasks(s, &ctx);
+ spawner.spawn_worktree_only_tasks(s, &ctx);
+ spawner.spawn_optional_tasks(s, &ctx, skip);
});
}
@@ -580,8 +600,6 @@ pub fn collect_branch_progressive(
tx: Sender<Result<TaskResult, TaskError>>,
expected_results: &Arc<ExpectedResults>,
) {
- use super::collect::TaskKind;
-
let ctx = TaskContext {
repo_path: repo_path.to_path_buf(),
commit_sha: commit_sha.to_string(),
@@ -596,26 +614,8 @@ pub fn collect_branch_progressive(
std::thread::scope(|s| {
// Core tasks (always run)
- spawner.spawn::<CommitDetailsTask>(s, &ctx);
- spawner.spawn::<AheadBehindTask>(s, &ctx);
- spawner.spawn::<CommittedTreesMatchTask>(s, &ctx);
- spawner.spawn::<HasFileChangesTask>(s, &ctx);
- spawner.spawn::<IsAncestorTask>(s, &ctx);
- spawner.spawn::<UpstreamTask>(s, &ctx);
-
- // Optional tasks (check skip set)
- if !skip.contains(&TaskKind::BranchDiff) {
- spawner.spawn::<BranchDiffTask>(s, &ctx);
- }
- if !skip.contains(&TaskKind::MergeTreeConflicts) {
- spawner.spawn::<MergeTreeConflictsTask>(s, &ctx);
- }
- if !skip.contains(&TaskKind::CiStatus) {
- spawner.spawn::<CiStatusTask>(s, &ctx);
- }
- if !skip.contains(&TaskKind::WouldMergeAdd) {
- spawner.spawn::<WouldMergeAddTask>(s, &ctx);
- }
+ spawner.spawn_core_tasks(s, &ctx);
+ spawner.spawn_optional_tasks(s, &ctx, skip);
});
}
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 4ffe48f2f..1fa01cb04 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -15,6 +15,24 @@ use worktrunk::git::Repository;
use super::list::{self, CollectOptions};
+#[derive(serde::Deserialize, Default)]
+struct ClaudeCodeContextJson {
+ #[serde(default)]
+ workspace: ClaudeCodeWorkspace,
+ #[serde(default)]
+ model: ClaudeCodeModel,
+}
+
+#[derive(serde::Deserialize, Default)]
+struct ClaudeCodeWorkspace {
+ current_dir: Option<String>,
+}
+
+#[derive(serde::Deserialize, Default)]
+struct ClaudeCodeModel {
+ display_name: Option<String>,
+}
+
/// Claude Code context parsed from stdin JSON
struct ClaudeCodeContext {
/// Working directory from `.workspace.current_dir`
@@ -31,21 +49,12 @@ impl ClaudeCodeContext {
return None;
}
- // Parse JSON
- let json: serde_json::Value = serde_json::from_str(input).ok()?;
-
+ let json: ClaudeCodeContextJson = serde_json::from_str(input).ok()?;
let current_dir = json
- .get("workspace")
- .and_then(|w| w.get("current_dir"))
- .and_then(|d| d.as_str())
- .unwrap_or(".")
- .to_string();
-
- let model_name = json
- .get("model")
- .and_then(|m| m.get("display_name"))
- .and_then(|n| n.as_str())
- .map(|s| s.to_string());
+ .workspace
+ .current_dir
+ .unwrap_or_else(|| ".".to_string());
+ let model_name = json.model.display_name;
Some(Self {
current_dir,
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 621423af5..1da4fe130 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -276,6 +276,11 @@ impl Repository {
///
/// Markers are stored as JSON: `{"marker": "text", "set_at": unix_timestamp}`.
pub fn branch_keyed_marker(&self, branch: &str) -> Option<String> {
+ #[derive(serde::Deserialize)]
+ struct MarkerValue {
+ marker: Option<String>,
+ }
+
let config_key = format!("worktrunk.state.{branch}.marker");
let raw = self
.run_command(&["config", "--get", &config_key])
@@ -283,11 +288,8 @@ impl Repository {
.map(|output| output.trim().to_string())
.filter(|s| !s.is_empty())?;
- let parsed: serde_json::Value = serde_json::from_str(&raw).ok()?;
- parsed
- .get("marker")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
+ let parsed: MarkerValue = serde_json::from_str(&raw).ok()?;
+ parsed.marker
}
/// Read user-defined branch-keyed marker.