Skip to content

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

Fix step rebase incorrectly reporting up-to-date for merge commits (#268)

Maximilian Roos7ebfedb2b11a
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 7d8f11560..f1b46f8d9 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -47,9 +47,14 @@ pub trait RepositoryCliExt {
target_branch: &str,
) -> anyhow::Result<Option<TargetWorktreeStash>>;
- /// Check if HEAD is rebased onto the target branch.
+ /// Check if HEAD is a linear extension of the target branch.
///
- /// Returns true if the merge-base equals the target's SHA (HEAD is based on target).
+ /// Returns true when:
+ /// 1. The merge-base equals target's SHA (target hasn't advanced), AND
+ /// 2. There are no merge commits between target and HEAD (history is linear)
+ ///
+ /// This detects branches that have merged the target into themselves — such
+ /// branches need rebasing to linearize history even though merge-base equals target.
fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool>;
}
@@ -317,7 +322,18 @@ impl RepositoryCliExt for Repository {
fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {
let merge_base = self.merge_base("HEAD", target)?;
let target_sha = self.run_command(&["rev-parse", target])?.trim().to_string();
- Ok(merge_base == target_sha)
+
+ if merge_base != target_sha {
+ return Ok(false); // Target has advanced past merge-base
+ }
+
+ // Check for merge commits — if present, history is not linear
+ let merge_commits = self
+ .run_command(&["rev-list", "--merges", &format!("{}..HEAD", target)])?
+ .trim()
+ .to_string();
+
+ Ok(merge_commits.is_empty())
}
}
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index af69e220b..2c3f18fd8 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -458,24 +458,20 @@ pub enum RebaseResult {
/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)
pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
+ use super::repository_ext::RepositoryCliExt;
+
let repo = Repository::current();
// Get target branch (default to default branch if not provided)
let target_branch = repo.resolve_target_branch(target)?;
- // Check if already up-to-date
- let merge_base = repo.merge_base("HEAD", &target_branch)?;
- let target_sha = repo
- .run_command(&["rev-parse", &target_branch])?
- .trim()
- .to_string();
-
- if merge_base == target_sha {
- // Already up-to-date, no rebase needed
+ // Check if already up-to-date (linear extension of target, no merge commits)
+ if repo.is_rebased_onto(&target_branch)? {
return Ok(RebaseResult::UpToDate(target_branch));
}
// Check if this is a fast-forward or true rebase
+ let merge_base = repo.merge_base("HEAD", &target_branch)?;
let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
let is_fast_forward = merge_base == head_sha;
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 216ce697f..906c09546 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2705,3 +2705,72 @@ fn test_step_squash_show_prompt(repo_with_multi_commit_feature: TestRepo) {
&[],
);
}
+
+// =============================================================================
+// step rebase tests
+// =============================================================================
+
+/// Helper to snapshot step rebase command
+fn snapshot_step_rebase(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&Path>) {
+ let settings = setup_snapshot_settings(repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(repo, "step", &[], cwd);
+ cmd.arg("rebase").args(args);
+ assert_cmd_snapshot!(test_name, cmd);
+ });
+}
+
+/// Test that step rebase correctly handles merge commits.
+///
+/// When a branch has merged main into it, the merge-base equals main's HEAD,
+/// but there are still commits that need rebasing to linearize the history.
+/// This test verifies that we don't incorrectly report "Already up-to-date".
+#[rstest]
+fn test_step_rebase_with_merge_commit(mut repo: TestRepo) {
+ // Create a feature worktree with a commit
+ let feature_wt = repo.add_worktree_with_commit(
+ "feature-with-merge",
+ "feature.txt",
+ "feature content",
+ "Add feature",
+ );
+
+ // Advance main with a new commit
+ fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "main-update.txt"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Update main"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ // Merge main INTO the feature branch (creating a merge commit)
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ let output = cmd
+ .args(["merge", "main", "-m", "Merge main into feature"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "git merge failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Now step rebase should linearize the history (not report "Already up-to-date")
+ snapshot_step_rebase(
+ "step_rebase_with_merge_commit",
+ &repo,
+ &["main"],
+ Some(&feature_wt),
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__merge__step_rebase_with_merge_commit.snap b/tests/snapshots/integration__integration_tests__merge__step_rebase_with_merge_commit.snap
new file mode 100644
index 000000000..c4ddf0aef
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_rebase_with_merge_commit.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - rebase
+ - main
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ 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: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Rebasing onto main...
+✓ Rebased onto main