Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Expose worktree git operation state
Maximilian Roos3ebd6001b0c4
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex f10c69e1c..d3f52a449 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -26,8 +26,8 @@ use worktrunk::styling::INFO_EMOJI;use super::ci_status::PrStatus;use super::model::{- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, ListItem,- UpstreamStatus, WorktreeData,+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, GitOperationState, ItemKind,+ ListItem, UpstreamStatus, WorktreeData,};/// Context for status symbol computation during cell updates@@ -72,9 +72,9 @@ pub(super) enum CellUpdate {has_merge_tree_conflicts: bool,},/// Git operation in progress (rebase/merge)- WorktreeState {+ GitOperation {item_idx: usize,- worktree_state: Option<String>,+ git_operation: GitOperationState,},/// User-defined status from git configUserStatus {@@ -102,7 +102,7 @@ impl CellUpdate {| CellUpdate::BranchDiff { item_idx, .. }| CellUpdate::WorkingTreeDiff { item_idx, .. }| CellUpdate::MergeTreeConflicts { item_idx, .. }- | CellUpdate::WorktreeState { item_idx, .. }+ | CellUpdate::GitOperation { item_idx, .. }| CellUpdate::UserStatus { item_idx, .. }| CellUpdate::Upstream { item_idx, .. }| CellUpdate::CiStatus { item_idx, .. } => *item_idx,@@ -111,15 +111,13 @@ impl CellUpdate {}/// Detect if a worktree is in the middle of a git operation (rebase/merge).-pub(super) fn detect_worktree_state(repo: &Repository) -> Option<String> {- let git_dir = repo.git_dir().ok()?;-- if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {- Some("rebase".to_string())- } else if git_dir.join("MERGE_HEAD").exists() {- Some("merge".to_string())+pub(super) fn detect_git_operation(repo: &Repository) -> GitOperationState {+ if repo.is_rebasing().unwrap_or(false) {+ GitOperationState::Rebase+ } else if repo.is_merging().unwrap_or(false) {+ GitOperationState::Merge} else {- None+ GitOperationState::None}}@@ -183,12 +181,12 @@ fn drain_cell_updates(// Store for status_symbols computationstatus_contexts[item_idx].has_merge_tree_conflicts = has_merge_tree_conflicts;}- CellUpdate::WorktreeState {+ CellUpdate::GitOperation {item_idx,- worktree_state,+ git_operation,} => {if let ItemKind::Worktree(data) = &mut items[item_idx].kind {- data.worktree_state = worktree_state;+ data.git_operation = git_operation;}}CellUpdate::UserStatus {diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rsindex 6b3695777..7a8bea0fb 100644--- a/src/commands/list/collect_progressive_impl.rs+++ b/src/commands/list/collect_progressive_impl.rs@@ -18,7 +18,7 @@ use worktrunk::path::format_path_for_display;use worktrunk::styling::eprintln;use super::ci_status::PrStatus;-use super::collect::{CellUpdate, detect_worktree_state};+use super::collect::{CellUpdate, detect_git_operation};use super::model::{AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus};/// Options for controlling what data to collect.@@ -222,10 +222,10 @@ fn spawn_worktree_state<'scope>(let path = ctx.repo_path.clone();s.spawn(move || {let repo = Repository::at(&path);- let worktree_state = detect_worktree_state(&repo);- let _ = tx.send(CellUpdate::WorktreeState {+ let git_operation = detect_git_operation(&repo);+ let _ = tx.send(CellUpdate::GitOperation {item_idx,- worktree_state,+ git_operation,});});}diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex eeb65519e..26c0daf76 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -816,8 +816,8 @@ mod tests {#[test]fn test_visible_columns_follow_gap_rule() {use crate::commands::list::model::{- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, ListItem,- StatusSymbols, UpstreamStatus, WorktreeData,+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, GitOperationState,+ ItemKind, ListItem, StatusSymbols, UpstreamStatus, WorktreeData,};// Create test data with specific widths to verify position calculation@@ -847,7 +847,7 @@ mod tests {prunable: None,working_tree_diff: Some(LineDiff::from((100, 50))),working_tree_diff_with_main: Some(Some(LineDiff::default())),- worktree_state: None,+ git_operation: GitOperationState::None,is_main: false,is_current: false,is_previous: false,@@ -902,8 +902,8 @@ mod tests {#[test]fn test_column_positions_with_empty_columns() {use crate::commands::list::model::{- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, ListItem,- StatusSymbols, UpstreamStatus, WorktreeData,+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, GitOperationState,+ ItemKind, ListItem, StatusSymbols, UpstreamStatus, WorktreeData,};// Create minimal data - most columns will be empty@@ -933,7 +933,7 @@ mod tests {prunable: None,working_tree_diff: Some(LineDiff::default()),working_tree_diff_with_main: Some(Some(LineDiff::default())),- worktree_state: None,+ git_operation: GitOperationState::None,is_main: true, // Primary worktree: no ahead/behind shownis_current: false,is_previous: false,diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex afa7da670..f7353e740 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -81,7 +81,9 @@ pub struct WorktreeData {/// `Some(None)` means computation was skipped.#[serde(skip_serializing_if = "Option::is_none")]pub working_tree_diff_with_main: Option<Option<LineDiff>>,- pub worktree_state: Option<String>,+ /// Git operation in progress (rebase/merge)+ #[serde(skip_serializing_if = "git_operation_is_none")]+ pub git_operation: GitOperationState,pub is_main: bool,/// Whether this is the current worktree (matches $PWD)#[serde(skip_serializing_if = "std::ops::Not::not")]@@ -447,9 +449,9 @@ impl ListItem {// Apply priority: Conflicts > Rebase > Merge > MergeTreeConflicts > base_statelet branch_op_state = if has_conflicts {BranchOpState::Conflicts- } else if data.worktree_state.as_deref() == Some("rebase") {+ } else if data.git_operation == GitOperationState::Rebase {BranchOpState::Rebase- } else if data.worktree_state.as_deref() == Some("merge") {+ } else if data.git_operation == GitOperationState::Merge {BranchOpState::Merge} else if has_merge_tree_conflicts {BranchOpState::MergeTreeConflicts@@ -784,6 +786,23 @@ impl serde::Serialize for BranchOpState {}}+/// Git operation state for a worktree+///+/// Represents whether a worktree is in the middle of a git operation.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, strum::IntoStaticStr)]+#[serde(rename_all = "lowercase")]+#[strum(serialize_all = "lowercase")]+pub enum GitOperationState {+ #[strum(serialize = "")]+ #[serde(rename = "")]+ #[default]+ None,+ /// Rebase in progress (rebase-merge or rebase-apply directory exists)+ Rebase,+ /// Merge in progress (MERGE_HEAD exists)+ Merge,+}+/// Tracks which status symbol positions are actually used across all items/// and the maximum width needed for each position.///@@ -935,7 +954,9 @@ impl StatusSymbols {let (untracked_str, has_untracked) = style_working('?');let worktree_state_str = match self.worktree_state {WorktreeState::None => String::new(),+ // Branch indicator (⎇) is informational (dimmed)WorktreeState::Branch => format!("{HINT}{}{HINT:#}", self.worktree_state),+ // Worktree attrs (⚐⌫⊠) are warnings (yellow)_ => format!("{WARNING}{}{WARNING:#}", self.worktree_state),};let user_status_str = self.user_status.as_deref().unwrap_or("").to_string();@@ -1135,3 +1156,8 @@ impl serde::Serialize for StatusSymbols {state.end()}}++/// Helper for serde skip_serializing_if+fn git_operation_is_none(state: &GitOperationState) -> bool {+ *state == GitOperationState::None+}diff --git a/src/commands/list/timing.rs b/src/commands/list/timing.rsindex fe48986f8..22f1024f7 100644--- a/src/commands/list/timing.rs+++ b/src/commands/list/timing.rs@@ -7,7 +7,8 @@ const DEBUG_ENV_VAR: &str = "WT_LIST_DEBUG";const DEBUG_ENV_VALUE: &str = "1";/// Operation names for tracking timing-#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]+#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, strum::AsRefStr)]+#[strum(serialize_all = "snake_case")]pub enum OpName {CommitDetails,AheadBehind,@@ -16,31 +17,13 @@ pub enum OpName {WorkingTreeDiff,WorkingTreeDiffWithMain,BranchDiff,- WorktreeState,+ GitOperation,// TODO(timing): Add PrStatus timing when CI/PR status collection is instrumentedPrStatus,MergeConflicts,UserStatus,}-impl OpName {- pub fn as_str(self) -> &'static str {- match self {- OpName::CommitDetails => "commit_details",- OpName::AheadBehind => "ahead_behind",- OpName::UpstreamStatus => "upstream_status",- OpName::GitStatus => "git_status",- OpName::WorkingTreeDiff => "working_tree_diff",- OpName::WorkingTreeDiffWithMain => "working_tree_diff_with_main",- OpName::BranchDiff => "branch_diff",- OpName::WorktreeState => "worktree_state",- OpName::PrStatus => "pr_status",- OpName::MergeConflicts => "merge_conflicts",- OpName::UserStatus => "user_status",- }- }-}-/// Collects timing data for list operations./// Thread-safe for use with parallel iterators (rayon).#[derive(Clone)]@@ -101,13 +84,13 @@ impl TimingCollector {log::debug!("WT_LIST_DEBUG timing summary:");let mut ops: Vec<_> = guard.timings.iter().collect();- ops.sort_by_key(|(op, _)| op.as_str());+ ops.sort_by_key(|(op, _)| op.as_ref());for (op, durations) in ops {let stats = compute_stats(durations);log::debug!(" {:<30} median: {:>6.1}ms p95: {:>6.1}ms count: {}",- op.as_str(),+ op.as_ref(),stats.median_ms,stats.p95_ms,durations.len()diff --git a/src/config/user.rs b/src/config/user.rsindex f8f6896b9..05ffd4ab7 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -55,17 +55,6 @@ pub enum StageMode {None,}-impl StageMode {- /// Returns the lowercase string representation for CLI display.- pub fn as_str(self) -> &'static str {- match self {- StageMode::All => "all",- StageMode::Tracked => "tracked",- StageMode::None => "none",- }- }-}-/// User-level configuration for worktree path formatting and LLM integration.////// This config is stored at `~/.config/worktrunk/config.toml` (or platform equivalent)diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 09555a9ae..de80f13e2 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -469,6 +469,18 @@ impl Repository {Ok(git_dir != common_dir)}+ /// Check if a rebase is in progress.+ pub fn is_rebasing(&self) -> anyhow::Result<bool> {+ let git_dir = self.git_dir()?;+ Ok(git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists())+ }++ /// Check if a merge is in progress.+ pub fn is_merging(&self) -> anyhow::Result<bool> {+ let git_dir = self.git_dir()?;+ Ok(git_dir.join("MERGE_HEAD").exists())+ }+/// Check if base is an ancestor of head (i.e., would be a fast-forward).pub fn is_ancestor(&self, base: &str, head: &str) -> anyhow::Result<bool> {self.run_command_check(&["merge-base", "--is-ancestor", base, head])diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex a678a5751..8cdc3632a 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -768,6 +768,79 @@ fn test_list_json_with_user_status() {snapshot_list_json("json_with_user_status", &repo);}+#[test]+fn test_list_json_with_git_operation() {+ // Test JSON output includes git_operation field when worktree is in rebase state+ let mut repo = TestRepo::new();++ // Create initial commit with a file that will conflict+ std::fs::write(+ repo.root_path().join("conflict.txt"),+ "original line 1\noriginal line 2\n",+ )+ .unwrap();+ repo.commit("Initial commit");++ // Create feature worktree+ let feature = repo.add_worktree("feature");++ // Feature makes changes to the file+ std::fs::write(+ feature.join("conflict.txt"),+ "feature line 1\nfeature line 2\n",+ )+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "."])+ .current_dir(&feature)+ .output()+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Feature changes"])+ .current_dir(&feature)+ .output()+ .unwrap();++ // Main makes conflicting changes+ std::fs::write(+ repo.root_path().join("conflict.txt"),+ "main line 1\nmain line 2\n",+ )+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "."])+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Main conflicting changes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ // Start rebase which will create conflicts and git operation state+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ let rebase_output = cmd+ .args(["rebase", "main"])+ .current_dir(&feature)+ .output()+ .unwrap();++ // Rebase should fail with conflicts - verify we're in rebase state+ assert!(+ !rebase_output.status.success(),+ "Rebase should fail with conflicts"+ );++ // JSON output should show git_operation: "rebase" for the feature worktree+ snapshot_list_json("json_with_git_operation", &repo);+}+#[test]fn test_list_branch_only_with_status() {// Test that branch-only entries (no worktree) can display branch-keyed statusdiff --git a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snapindex 36f18ac69..3e84113dc 100644--- a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap+++ b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap@@ -71,7 +71,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": true,"is_current": true},@@ -122,7 +121,6 @@ exit_code: 0"deleted": 1},"working_tree_diff_with_main": null,- "worktree_state": null,"is_main": false,"working_diff_display": "/u001b[32m+1/u001b[0m /u001b[31m-1/u001b[0m"},@@ -172,7 +170,6 @@ exit_code: 0"deleted": 0},"working_tree_diff_with_main": null,- "worktree_state": null,"is_main": false}]diff --git a/tests/snapshots/integration__integration_tests__list__json_with_git_operation.snap b/tests/snapshots/integration__integration_tests__list__json_with_git_operation.snapnew file mode 100644index 000000000..b21246be6--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list__json_with_git_operation.snap@@ -0,0 +1,130 @@+---+source: tests/integration_tests/list.rs+info:+ program: wt+ args:+ - list+ - "--format=json"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_BIN: ""+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----+[+ {+ "head_sha": "f4fa1ba1ca52a38a0036c3c9dd8b486a83ced1e5",+ "branch": "main",+ "timestamp": 0,+ "commit_message": "Main conflicting changes",+ "ahead": 0,+ "behind": 0,+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "pr_status": null,+ "status": {+ "working_tree": {+ "untracked": false,+ "modified": false,+ "staged": false,+ "renamed": false,+ "deleted": false+ },+ "branch_op_state": "",+ "main_divergence": "IsMain",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_symbols": {+ "working_tree": "",+ "branch_op_state": "",+ "main_divergence": "^",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_line": "main",+ "type": "worktree",+ "path": "[REPO]",+ "bare": false,+ "detached": false,+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "is_main": true,+ "is_current": true+ },+ {+ "head_sha": "f4fa1ba1ca52a38a0036c3c9dd8b486a83ced1e5",+ "branch": "feature",+ "timestamp": 0,+ "commit_message": "Main conflicting changes",+ "ahead": 0,+ "behind": 0,+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "pr_status": null,+ "status": {+ "working_tree": {+ "untracked": false,+ "modified": false,+ "staged": false,+ "renamed": false,+ "deleted": false+ },+ "branch_op_state": "Conflicts",+ "main_divergence": "",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_symbols": {+ "working_tree": "",+ "branch_op_state": "✖",+ "main_divergence": "",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_line": "feature /u001b[31m✖/u001b[0m",+ "type": "worktree",+ "path": "[REPO].feature",+ "bare": false,+ "detached": true,+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "git_operation": "rebase",+ "is_main": false+ }+]++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snapindex eaeeeae44..86379ffb2 100644--- a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap+++ b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap@@ -71,7 +71,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": true,"is_current": true},@@ -123,7 +122,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": false},{@@ -175,7 +173,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": false}]diff --git a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snapindex 4ab537290..cbf892531 100644--- a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap+++ b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap@@ -71,7 +71,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": true,"is_current": true},@@ -125,7 +124,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": false},{@@ -176,7 +174,6 @@ exit_code: 0"added": 0,"deleted": 0},- "worktree_state": null,"is_main": false}]