Skip to content

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

fix(step): refuse to rebase or merge from a worktree mid-operation (#3558)

Maximilian Roos84cbb0489ea1
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 31e452d1e..b0dd95c09 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -10,7 +10,8 @@ use std::sync::Arc;
use anyhow::Context;
use worktrunk::git::{
- ErrorExt, IntegrationTargets, LineDiff, RefSnapshot, Repository, select_comparison_base,
+ ErrorExt, InProgressOperation, IntegrationTargets, LineDiff, RefSnapshot, Repository,
+ select_comparison_base,
};
use super::super::ci_status::{CiBranchName, PrStatus};
@@ -993,15 +994,18 @@ fn first_line(s: &str) -> String {
}
/// Detect if a worktree is in the middle of a git operation (rebase/merge).
+///
+/// The gutter symbols cover the two operations `wt merge` itself performs, so
+/// the states with no symbol of their own (cherry-pick, revert, bisect) report
+/// as `None` here — they still block the commit-replaying commands, via
+/// `ensure_no_operation_in_progress`.
pub(crate) fn detect_active_git_operation(
wt: &worktrunk::git::WorkingTree<'_>,
) -> ActiveGitOperation {
- if wt.is_rebasing().unwrap_or(false) {
- ActiveGitOperation::Rebase
- } else if wt.is_merging().unwrap_or(false) {
- ActiveGitOperation::Merge
- } else {
- ActiveGitOperation::None
+ match wt.operation_in_progress() {
+ Ok(Some(InProgressOperation::Rebase)) => ActiveGitOperation::Rebase,
+ Ok(Some(InProgressOperation::Merge)) => ActiveGitOperation::Merge,
+ _ => ActiveGitOperation::None,
}
}
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 7ae5026b9..58f969765 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -167,6 +167,10 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let env = CommandEnv::for_action(config)?;
let repo = &env.repo;
let config = &env.config;
+ // Ahead of the branch check: mid-rebase and mid-bisect both detach HEAD, so
+ // an unguarded merge blames the detached HEAD and points at `git switch`,
+ // which abandons the operation instead of finishing it.
+ repo.ensure_no_operation_in_progress("merge")?;
// Merge requires being on a branch (can't merge from detached HEAD)
let current_branch = env.require_branch("merge")?.to_string();
diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rs
index 7ec3e1179..f0cf0b1e4 100644
--- a/src/commands/step/rebase.rs
+++ b/src/commands/step/rebase.rs
@@ -2,7 +2,7 @@
use anyhow::Context;
use color_print::cformat;
-use worktrunk::git::{ErrorExt, Repository};
+use worktrunk::git::{ErrorExt, InProgressOperation, Repository};
use worktrunk::styling::{eprintln, progress_message, success_message};
use super::super::repository_ext::RepositoryCliExt;
@@ -19,6 +19,11 @@ pub enum RebaseResult {
pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
let repo = Repository::current()?;
+ // Refuse before reading ancestry: a worktree stopped mid-rebase has HEAD
+ // detached on a linear extension of the target, so the up-to-date check
+ // below would report success over a tree that still holds conflict markers.
+ repo.ensure_no_operation_in_progress("rebase")?;
+
// Get and validate target ref (any commit-ish for rebase)
let integration_target = repo.require_target_ref(target)?;
// #3519: when the branch's history extends past the local target into the
@@ -53,14 +58,13 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
// If rebase failed, classify the failure (interrupt vs conflict vs other).
if let Err(e) = rebase_result {
- let is_rebasing = repo
- .worktree_state()?
- .is_some_and(|s| s.starts_with("REBASING"));
+ let state = repo.operation_in_progress()?;
+ let is_rebasing = matches!(state, Some(InProgressOperation::Rebase));
return Err(classify_rebase_failure(e, is_rebasing, &integration_target));
}
// Verify rebase completed successfully (safety check for edge cases)
- if repo.worktree_state()?.is_some() {
+ if repo.operation_in_progress()?.is_some() {
return Err(worktrunk::git::GitError::RebaseConflict {
target_branch: integration_target,
git_output: String::new(),
diff --git a/src/git/error.rs b/src/git/error.rs
index 3a4e42e39..0ee3261da 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -404,6 +404,16 @@ pub enum GitError {
DetachedHead {
action: Option<String>,
},
+ /// The worktree is partway through a git operation, so a command that
+ /// replays commits (`wt merge`, `wt step rebase`) refuses to start.
+ ///
+ /// Carries no operation and offers no remedy: `git status` names which
+ /// operation is open and how to finish it, so restating either here only
+ /// adds a line that can drift from what git accepts.
+ OperationInProgress {
+ /// The action the user asked for ("merge", "rebase").
+ action: String,
+ },
UncommittedChanges {
action: Option<String>,
/// Branch name (for multi-worktree operations)
@@ -631,6 +641,10 @@ impl GitError {
None => "Not on a branch (detached HEAD)".to_string(),
},
+ GitError::OperationInProgress { action } => {
+ cformat!("Cannot {action}: a git operation is already in progress")
+ }
+
GitError::UncommittedChanges { action, branch, .. } => match (action, branch) {
(Some(action), Some(b)) => {
cformat!("Cannot {action}: <bold>{b}</> has uncommitted changes")
@@ -862,6 +876,11 @@ impl GitError {
)
}
+ GitError::OperationInProgress { .. } => {
+ let title = self.title();
+ write!(f, "{}", error_message(&title))
+ }
+
GitError::UncommittedChanges {
branch,
force_hint,
@@ -1192,21 +1211,18 @@ impl GitError {
}
}
+ // Git's own stderr carries the way out — `--continue`, `--skip`,
+ // `--abort` — so it is forwarded in the gutter rather than
+ // paraphrased. Nothing stands in for it when it is empty: the
+ // rebase is still on disk, and `git status` names the remedy in
+ // git's words for whichever operation is actually open.
GitError::RebaseConflict { git_output, .. } => {
let title = self.title();
write!(f, "{}", error_message(&title))?;
if !git_output.is_empty() {
- write!(f, "\n{}", format_with_gutter(git_output, None))
- } else {
- write!(
- f,
- "\n{}\n{}",
- hint_message(cformat!(
- "To continue after resolving conflicts, run <underline>git rebase --continue</>"
- )),
- hint_message(cformat!("To abort, run <underline>git rebase --abort</>"))
- )
+ write!(f, "\n{}", format_with_gutter(git_output, None))?;
}
+ Ok(())
}
GitError::NotRebased { target_branch } => {
@@ -2428,11 +2444,7 @@ mod tests {
target_branch: "main".into(),
git_output: "".into(),
};
- assert_snapshot!(err.render(), @"
- ✗ Rebase onto main incomplete
- ↳ To continue after resolving conflicts, run git rebase --continue
- ↳ To abort, run git rebase --abort
- ");
+ assert_snapshot!(err.render(), @"✗ Rebase onto main incomplete");
}
#[test]
diff --git a/src/git/mod.rs b/src/git/mod.rs
index bca3227c3..97db43339 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -78,8 +78,9 @@ pub use remove::{
};
pub use repository::sha_cache;
pub use repository::{
- Branch, BranchDiffSpec, CommitMessageDetail, IntegrationTargets, RefSnapshot, Repository,
- ResolvedWorktree, TempIndex, WorkingTree, select_comparison_base, set_base_path,
+ Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,
+ RefSnapshot, Repository, ResolvedWorktree, TempIndex, WorkingTree, select_comparison_base,
+ set_base_path,
};
pub use url::parse_owner_repo;
pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 815fa89bf..4d7d81d2f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -165,7 +165,7 @@ pub use diff::CommitMessageDetail;
pub use integration::{BranchDiffSpec, IntegrationTargets, select_comparison_base};
pub use ref_snapshot::RefSnapshot;
pub(super) use working_tree::path_to_logging_context;
-pub use working_tree::{TempIndex, WorkingTree};
+pub use working_tree::{InProgressOperation, TempIndex, WorkingTree};
// ============================================================================
// Repository Cache
@@ -1457,52 +1457,35 @@ impl Repository {
}
}
- /// 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()?;
-
- // Check for merge
- if git_dir.join("MERGE_HEAD").exists() {
- return Ok(Some("MERGING".to_string()));
- }
+ /// The git operation the worktree at this repository's discovery path is
+ /// partway through, if any. See [`WorkingTree::operation_in_progress`].
+ pub fn operation_in_progress(&self) -> anyhow::Result<Option<InProgressOperation>> {
+ self.worktree_at(self.discovery_path())
+ .operation_in_progress()
+ }
- // Check for rebase. `rebase-merge` (interactive/merge backend) and
- // `rebase-apply` (am backend) are mutually exclusive; probe each once.
- let rebase_merge = git_dir.join("rebase-merge");
- let rebase_apply = git_dir.join("rebase-apply");
- if let Some(rebase_dir) = rebase_merge
- .exists()
- .then_some(rebase_merge)
- .or_else(|| rebase_apply.exists().then_some(rebase_apply))
- {
- if let (Ok(msgnum), Ok(end)) = (
- std::fs::read_to_string(rebase_dir.join("msgnum")),
- std::fs::read_to_string(rebase_dir.join("end")),
- ) {
- let current = msgnum.trim();
- let total = end.trim();
- return Ok(Some(format!("REBASING {}/{}", current, total)));
+ /// Fail when the worktree is already partway through a git operation.
+ ///
+ /// A precondition for the commit-replaying commands (`wt step rebase`,
+ /// `wt merge`). Mid-rebase, HEAD is detached on a linear extension of the
+ /// target, so `is_rebased_onto` — and every
+ /// ancestry check like it — reads as "already up to date"; without this
+ /// gate a caller reports success over a tree that still holds conflict
+ /// markers. The other states are gated for the same reason rather than
+ /// their own symptom: a rebase started from any of them either compounds
+ /// the half-finished operation or dies inside git with its own plumbing
+ /// error, and neither tells the user what to do next.
+ ///
+ /// The refusal names no operation, so nothing here has to track what git
+ /// calls each state or how to leave it; `git status` answers both.
+ pub fn ensure_no_operation_in_progress(&self, action: &str) -> anyhow::Result<()> {
+ match self.operation_in_progress()? {
+ Some(_) => Err(crate::git::GitError::OperationInProgress {
+ action: action.to_string(),
}
-
- return Ok(Some("REBASING".to_string()));
- }
-
- // Check for cherry-pick
- if git_dir.join("CHERRY_PICK_HEAD").exists() {
- return Ok(Some("CHERRY-PICKING".to_string()));
- }
-
- // Check for revert
- if git_dir.join("REVERT_HEAD").exists() {
- return Ok(Some("REVERTING".to_string()));
+ .into()),
+ None => Ok(()),
}
-
- // Check for bisect
- if git_dir.join("BISECT_LOG").exists() {
- return Ok(Some("BISECTING".to_string()));
- }
-
- Ok(None)
}
// =========================================================================
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 5e72cade2..23d08b93a 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -24,6 +24,51 @@ fn has_initialized_submodules_from_status(status: &str) -> bool {
})
}
+/// A git operation a worktree is partway through, detected from the state files
+/// git writes under its git dir (`MERGE_HEAD`, `rebase-merge/`, `BISECT_LOG`, …).
+///
+/// Produced by [`WorkingTree::operation_in_progress`]. Detection only: it
+/// reports what git left on disk and deliberately maps nothing to a remedy.
+/// `git status` already names the operation and the way out of it, in git's own
+/// words and git's own translations, including states worktrunk has no variant
+/// for, so a table here would only be a second copy to keep current with git.
+///
+/// Structured rather than a display string so [`Rebase`](Self::Rebase) can be
+/// recognized without matching on user-visible text.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InProgressOperation {
+ Merge,
+ /// Rebase, from either backend. `git am` shares the am backend's
+ /// `rebase-apply` directory and lands here too, which costs nothing: the
+ /// only caller that cares is classifying a rebase worktrunk itself just
+ /// started, and this gate stops that from happening during an am session.
+ Rebase,
+ CherryPick,
+ Revert,
+ Bisect,
+}
+
+/// The operation a queued sequencer belongs to, or `None` when nothing is
+/// queued.
+///
+/// `git cherry-pick`/`git revert` over several commits keep the remaining
+/// instructions in `sequencer/todo`, one `<command> <sha> <subject>` line each,
+/// and delete the directory once the sequence finishes or is aborted. Reading
+/// the first line mirrors git's own `sequencer_get_last_command`, which is how
+/// `git status` reports a sequence whose stopped pick was committed by hand.
+///
+/// Only cherry-pick and revert write this file — a rebase has its own todo
+/// under `rebase-merge/` — so an unrecognized first word means the file isn't a
+/// sequence worktrunk should read, and it reports nothing rather than guessing.
+fn sequencer_operation(git_dir: &Path) -> Option<InProgressOperation> {
+ let todo = std::fs::read_to_string(git_dir.join("sequencer").join("todo")).ok()?;
+ match todo.split_whitespace().next()? {
+ "pick" => Some(InProgressOperation::CherryPick),
+ "revert" => Some(InProgressOperation::Revert),
+ _ => None,
+ }
+}
+
/// Typed snapshot returned by [`WorkingTree::prewarm_info`].
///
/// Mirrors what the batched `git rev-parse` actually resolved so callers can
@@ -401,16 +446,46 @@ impl<'a> WorkingTree<'a> {
}
}
- /// Check if a rebase is in progress.
- pub fn is_rebasing(&self) -> anyhow::Result<bool> {
+ /// The git operation this worktree is partway through, if any.
+ ///
+ /// Reads the state files git writes under the worktree's git dir, in the
+ /// order [`git status`](https://git-scm.com/docs/git-status) consults them,
+ /// so the answer tracks what git itself calls "in progress".
+ pub fn operation_in_progress(&self) -> anyhow::Result<Option<InProgressOperation>> {
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())
+ if git_dir.join("MERGE_HEAD").exists() {
+ return Ok(Some(InProgressOperation::Merge));
+ }
+
+ // `rebase-merge` (interactive/merge backend) and `rebase-apply` (am
+ // backend, also used by `git am`) are mutually exclusive; either one
+ // means commits are mid-replay.
+ if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
+ return Ok(Some(InProgressOperation::Rebase));
+ }
+
+ if git_dir.join("CHERRY_PICK_HEAD").exists() {
+ return Ok(Some(InProgressOperation::CherryPick));
+ }
+
+ if git_dir.join("REVERT_HEAD").exists() {
+ return Ok(Some(InProgressOperation::Revert));
+ }
+
+ // The two `_HEAD` files above exist only while a single pick is
+ // stopped: resolving one with `git commit` instead of `--continue`
+ // removes it and leaves the rest of the sequence queued, which git
+ // still reports as in progress.
+ if let Some(operation) = sequencer_operation(&git_dir) {
+ return Ok(Some(operation));
+ }
+
+ if git_dir.join("BISECT_LOG").exists() {
+ return Ok(Some(InProgressOperation::Bisect));
+ }
+
+ Ok(None)
}
/// Check if this is a linked worktree (vs the main worktree).
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index 4b84235fd..89ef7c539 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -228,6 +228,23 @@ fn display_detached_head_no_action() {
assert_snapshot!("detached_head_no_action", err.render());
}
+/// The refusal names the blocked action and defers to `git status` for what is
+/// open and how to leave it, so no operation appears in the message at all.
+#[test]
+fn display_operation_in_progress() {
+ let rendered: Vec<String> = ["rebase", "merge"]
+ .into_iter()
+ .map(|action| {
+ GitError::OperationInProgress {
+ action: action.into(),
+ }
+ .render()
+ })
+ .collect();
+
+ assert_snapshot!("operation_in_progress", rendered.join("\n\n"));
+}
+
#[test]
fn display_uncommitted_changes() {
let err = GitError::UncommittedChanges {
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index c8fe11b44..466d5d6a3 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -3406,6 +3406,118 @@ fn test_step_rebase_already_up_to_date(mut repo: TestRepo) {
));
}
+/// Give `feature` and main conflicting edits to the same path, so replaying
+/// either onto the other stops. Both branches add the path, so it is an add/add
+/// conflict on the first pick.
+fn feature_conflicting_with_main(repo: &mut TestRepo) -> PathBuf {
+ let feature_wt = repo.add_worktree("feature");
+ repo.commit_in_worktree(&feature_wt, "conflict.txt", "feature\n", "Feature edit");
+ fs::write(repo.root_path().join("conflict.txt"), "main\n").unwrap();
+ repo.run_git(&["add", "conflict.txt"]);
+ repo.run_git(&["commit", "-m", "Main edit"]);
+
+ feature_wt
+}
+
+/// A worktree's own git dir, where git records in-progress operation state.
+fn worktree_git_dir(repo: &TestRepo, worktree: &Path) -> PathBuf {
+ let output = repo
+ .git_command()
+ .current_dir(worktree)
+ .args(["rev-parse", "--absolute-git-dir"])
+ .run()
+ .unwrap();
+ PathBuf::from(String::from_utf8_lossy(&output.stdout).trim().to_string())
+}
+
+/// Leave `feature` stopped partway through a conflicted rebase onto main, which
+/// detaches HEAD.
+fn stop_feature_mid_rebase(repo: &mut TestRepo) -> PathBuf {
+ let feature_wt = feature_conflicting_with_main(repo);
+
+ let rebase = repo
+ .git_command()
+ .current_dir(&feature_wt)
+ .args(["rebase", "main"])
+ .run()
+ .unwrap();
+ assert!(
+ !rebase.status.success(),
+ "rebase should have stopped on the conflict"
+ );
+ assert!(
+ worktree_git_dir(repo, &feature_wt)
+ .join("rebase-merge")
+ .exists(),
+ "rebase state should be on disk"
+ );
+
+ feature_wt
+}
+
+/// Leave `feature` stopped in a conflicted merge, which keeps HEAD on the branch.
+fn stop_feature_mid_merge(repo: &mut TestRepo) -> PathBuf {
+ let feature_wt = feature_conflicting_with_main(repo);
+
+ let merge = repo
+ .git_command()
+ .current_dir(&feature_wt)
+ .args(["merge", "main"])
+ .run()
+ .unwrap();
+ assert!(
+ !merge.status.success(),
+ "merge should have stopped on the conflict"
+ );
+ assert!(
+ worktree_git_dir(repo, &feature_wt)
+ .join("MERGE_HEAD")
+ .exists(),
+ "merge state should be on disk"
+ );
+
+ feature_wt
+}
+
+/// Mid-rebase, HEAD is detached on a linear extension of the target, so the
+/// ancestry check alone reads as up to date. `wt step rebase` has to refuse
+/// rather than report success over a tree that still holds conflict markers.
+#[rstest]
+fn test_step_rebase_refuses_mid_rebase(mut repo: TestRepo) {
+ let feature_wt = stop_feature_mid_rebase(&mut repo);
+
+ assert_cmd_snapshot!(
+ "step_rebase_refuses_mid_rebase",
+ make_snapshot_cmd(&repo, "step", &["rebase", "main"], Some(&feature_wt))
+ );
+}
+
+/// From the same state `wt merge` names the open rebase instead of blaming the
+/// detached HEAD, whose `git switch` hint would abandon the rebase rather than
+/// finish it.
+#[rstest]
+fn test_merge_refuses_mid_rebase(mut repo: TestRepo) {
+ let feature_wt = stop_feature_mid_rebase(&mut repo);
+
+ assert_cmd_snapshot!(
+ "merge_refuses_mid_rebase",
+ make_snapshot_cmd(&repo, "merge", &[], Some(&feature_wt))
+ );
+}
+
+/// The gate covers every operation git can leave open, not just rebase. A
+/// conflicted merge keeps HEAD on the branch, so the detached-HEAD check waves
+/// it through and `wt merge` would otherwise try to commit the conflict markers.
+#[rstest]
+fn test_merge_refuses_mid_merge(mut repo: TestRepo) {
+ let feature_wt = stop_feature_mid_merge(&mut repo);
+
+ assert_cmd_snapshot!(
+ "merge_refuses_mid_merge",
+ make_snapshot_cmd(&repo, "merge", &[], Some(&feature_wt))
+ );
+}
+
// =============================================================================
// JSON output tests
// =============================================================================
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 529548879..1cafb4a28 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -1,8 +1,9 @@
//! Tests for git repository methods to improve code coverage.
use std::fs;
+use std::path::Path;
-use worktrunk::git::{RefType, Repository};
+use worktrunk::git::{InProgressOperation, RefType, Repository};
use crate::common::{BareRepoTest, TestRepo};
@@ -43,116 +44,135 @@ fn test_is_bare_returns_true_for_bare_repo() {
}
// =============================================================================
-// worktree_state() tests - simulate various git operation states
+// operation_in_progress() tests - simulate various git operation states
// =============================================================================
-#[test]
-fn test_worktree_state_normal() {
+/// Build a repo, let `setup` plant state files under its git dir, and report
+/// what `operation_in_progress` makes of them.
+fn operation_after(setup: impl FnOnce(&Path)) -> Option<InProgressOperation> {
let repo = TestRepo::new();
let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
-
- // Normal state - no special files
- let state = repository.worktree_state().unwrap();
- assert!(state.is_none());
+ setup(&repo.root_path().join(".git"));
+ repository.operation_in_progress().unwrap()
}
-#[test]
-fn test_worktree_state_merging() {
- let repo = TestRepo::new();
- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
-
- // Simulate merge state by creating MERGE_HEAD
- let git_dir = repo.root_path().join(".git");
- fs::write(git_dir.join("MERGE_HEAD"), "abc123\n").unwrap();
-
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("MERGING".to_string()));
+/// Plant the todo list a multi-commit `git cherry-pick`/`git revert` leaves
+/// behind while instructions are still queued.
+fn write_sequencer_todo(git_dir: &Path, todo: &str) {
+ let sequencer = git_dir.join("sequencer");
+ fs::create_dir_all(&sequencer).unwrap();
+ fs::write(sequencer.join("todo"), todo).unwrap();
}
+/// `operation_in_progress` reads each in-progress operation off the state files
+/// git writes under the git dir. Both rebase backends report as a rebase:
+/// `rebase-merge` (interactive/merge) and `rebase-apply` (am backend, shared
+/// with `git am`).
#[test]
-fn test_worktree_state_rebasing_with_progress() {
- let repo = TestRepo::new();
- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
-
- // Simulate rebase state with progress
- let git_dir = repo.root_path().join(".git");
- let rebase_dir = git_dir.join("rebase-merge");
- fs::create_dir_all(&rebase_dir).unwrap();
- fs::write(rebase_dir.join("msgnum"), "2\n").unwrap();
- fs::write(rebase_dir.join("end"), "5\n").unwrap();
-
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("REBASING 2/5".to_string()));
-}
-
-#[test]
-fn test_worktree_state_rebasing_apply() {
- let repo = TestRepo::new();
- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
-
- // Simulate rebase-apply state (git am or git rebase without -m)
- let git_dir = repo.root_path().join(".git");
- let rebase_dir = git_dir.join("rebase-apply");
- fs::create_dir_all(&rebase_dir).unwrap();
- fs::write(rebase_dir.join("msgnum"), "3\n").unwrap();
- fs::write(rebase_dir.join("end"), "7\n").unwrap();
+fn test_operation_in_progress_detects_each_operation() {
+ assert_eq!(operation_after(|_| {}), None, "clean worktree");
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("REBASING 3/7".to_string()));
-}
-
-#[test]
-fn test_worktree_state_rebasing_no_progress() {
- let repo = TestRepo::new();
- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
-
- // Simulate rebase state without progress files
- let git_dir = repo.root_path().join(".git");
- let rebase_dir = git_dir.join("rebase-merge");
- fs::create_dir_all(&rebase_dir).unwrap();
- // No msgnum/end files - just the directory
-
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("REBASING".to_string()));
-}
-
-#[test]
-fn test_worktree_state_cherry_picking() {
- let repo = TestRepo::new();
- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
-
- // Simulate cherry-pick state
- let git_dir = repo.root_path().join(".git");
- fs::write(git_dir.join("CHERRY_PICK_HEAD"), "def456\n").unwrap();
+ assert_eq!(
+ operation_after(|d| fs::write(d.join("MERGE_HEAD"), "abc123\n").unwrap()),
+ Some(InProgressOperation::Merge),
+ "merge",
+ );
+ assert_eq!(
+ operation_after(|d| fs::create_dir_all(d.join("rebase-merge")).unwrap()),
+ Some(InProgressOperation::Rebase),
+ "rebase, merge backend",
+ );
+ assert_eq!(
+ operation_after(|d| fs::create_dir_all(d.join("rebase-apply")).unwrap()),
+ Some(InProgressOperation::Rebase),
+ "rebase, am backend",
+ );
+ assert_eq!(
+ operation_after(|d| fs::write(d.join("CHERRY_PICK_HEAD"), "def456\n").unwrap()),
+ Some(InProgressOperation::CherryPick),
+ "cherry-pick",
+ );
+ assert_eq!(
+ operation_after(|d| fs::write(d.join("REVERT_HEAD"), "789abc\n").unwrap()),
+ Some(InProgressOperation::Revert),
+ "revert",
+ );
+ assert_eq!(
+ operation_after(|d| fs::write(d.join("BISECT_LOG"), "# bisect log\n").unwrap()),
+ Some(InProgressOperation::Bisect),
+ "bisect",
+ );
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("CHERRY-PICKING".to_string()));
+ assert_eq!(
+ operation_after(|d| write_sequencer_todo(d, "pick abc123 first\npick def456 second\n")),
+ Some(InProgressOperation::CherryPick),
+ "queued cherry-pick",
+ );
+ assert_eq!(
+ operation_after(|d| write_sequencer_todo(d, "revert abc123 first\n")),
+ Some(InProgressOperation::Revert),
+ "queued revert",
+ );
+ assert_eq!(
+ operation_after(|d| write_sequencer_todo(d, "")),
+ None,
+ "drained sequencer",
+ );
+ // `label` belongs to a rebase todo, which lives under `rebase-merge` and is
+ // detected there; an unrecognized instruction is not a sequence to report.
+ assert_eq!(
+ operation_after(|d| write_sequencer_todo(d, "label onto\n")),
+ None,
+ "todo that isn't a pick or revert sequence",
+ );
}
+/// Resolving a stopped cherry-pick with `git commit` instead of `git cherry-pick
+/// --continue` clears `CHERRY_PICK_HEAD` while the rest of the sequence stays
+/// queued. `git status` still calls that a cherry-pick in progress, and so must
+/// this: the `_HEAD` files alone report an idle worktree with picks pending.
#[test]
-fn test_worktree_state_reverting() {
- let repo = TestRepo::new();
+fn test_operation_in_progress_reads_the_queued_sequencer() {
+ let repo = TestRepo::with_initial_commit();
let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ let root = repo.root_path().to_path_buf();
- // Simulate revert state
- let git_dir = repo.root_path().join(".git");
- fs::write(git_dir.join("REVERT_HEAD"), "789abc\n").unwrap();
+ repo.run_git(&["switch", "-c", "side"]);
+ repo.commit_in_worktree(&root, "conflict.txt", "side one\n", "Side edit");
+ repo.commit_in_worktree(&root, "conflict.txt", "side two\n", "Side edit again");
+ repo.run_git(&["switch", "main"]);
+ repo.commit_in_worktree(&root, "conflict.txt", "main\n", "Main edit");
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("REVERTING".to_string()));
-}
+ // Two picks, so instructions remain queued once the first one stops.
+ let picked = repo
+ .git_command()
+ .args(["cherry-pick", "side~1", "side"])
+ .run()
+ .unwrap();
+ assert!(!picked.status.success(), "the first pick must conflict");
+ assert_eq!(
+ repository.operation_in_progress().unwrap(),
+ Some(InProgressOperation::CherryPick),
+ "stopped pick",
+ );
-#[test]
-fn test_worktree_state_bisecting() {
- let repo = TestRepo::new();
- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ fs::write(root.join("conflict.txt"), "resolved\n").unwrap();
+ repo.run_git(&["add", "conflict.txt"]);
+ repo.run_git(&["commit", "--no-edit"]);
- // Simulate bisect state
- let git_dir = repo.root_path().join(".git");
- fs::write(git_dir.join("BISECT_LOG"), "# bisect log\n").unwrap();
+ assert!(
+ !root.join(".git").join("CHERRY_PICK_HEAD").exists(),
+ "committing by hand is what clears the state file",
+ );
+ assert_eq!(
+ repository.operation_in_progress().unwrap(),
+ Some(InProgressOperation::CherryPick),
+ "the remaining picks are still queued",
+ );
- let state = repository.worktree_state().unwrap();
- assert_eq!(state, Some("BISECTING".to_string()));
+ // `git cherry-pick --quit` is how the queue is abandoned; state clears with it.
+ repo.run_git(&["cherry-pick", "--quit"]);
+ assert_eq!(repository.operation_in_progress().unwrap(), None);
}
// =============================================================================
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__operation_in_progress.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__operation_in_progress.snap
new file mode 100644
index 000000000..7002f5d63
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__operation_in_progress.snap
@@ -0,0 +1,7 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: "rendered.join(\"\\n\\n\")"
+---
+✗ Cannot rebase: a git operation is already in progress
+
+✗ Cannot merge: a git operation is already in progress
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_refuses_mid_merge.snap b/tests/snapshots/integration__integration_tests__merge__merge_refuses_mid_merge.snap
new file mode 100644
index 000000000..013c89c06
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_refuses_mid_merge.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Cannot merge: a git operation is already in progress
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_refuses_mid_rebase.snap b/tests/snapshots/integration__integration_tests__merge__merge_refuses_mid_rebase.snap
new file mode 100644
index 000000000..013c89c06
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_refuses_mid_rebase.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Cannot merge: a git operation is already in progress
diff --git a/tests/snapshots/integration__integration_tests__merge__step_rebase_refuses_mid_rebase.snap b/tests/snapshots/integration__integration_tests__merge__step_rebase_refuses_mid_rebase.snap
new file mode 100644
index 000000000..883a9630d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_rebase_refuses_mid_rebase.snap
@@ -0,0 +1,52 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - rebase
+ - main
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ 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_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Cannot rebase: a git operation is already in progress