Skip to content

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

fix(merge): respect stage scope before auto-commit (#4251)

DDLd65adb038c74
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 748fe6859..02a0f910e 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -102,10 +102,9 @@ fn approve_merge_plan(
feature_root: &Path,
destination_path: &Path,
project_id: &str,
- commit: bool,
verify: bool,
will_remove: bool,
- squash_enabled: bool,
+ will_create_commit: bool,
yes: bool,
) -> anyhow::Result<Option<ApprovedHookPlan>> {
let pid = Some(project_id);
@@ -124,8 +123,7 @@ fn approve_merge_plan(
// are listed only so the single prompt is complete; their anchor is never
// looked up.
let mut feature_hooks = Vec::new();
- let will_create_commit = repo.current_worktree().is_dirty()? || squash_enabled;
- if commit && will_create_commit {
+ if will_create_commit {
feature_hooks.push(HookType::PreCommit);
feature_hooks.push(HookType::PostCommit);
}
@@ -276,6 +274,15 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// pre-remove/post-remove hooks in the batch approval prompt.
let on_target = current_branch == target_branch;
let remove_requested = remove && !on_target;
+ // Freeze the commit decision before approval so every later gate agrees
+ // with the hooks shown to the user. Squash owns its commit decision and
+ // staging, so it does not need this extra index simulation.
+ let has_committable_changes = if commit && !squash_enabled {
+ current_wt.has_committable_changes(stage_mode)?
+ } else {
+ false
+ };
+ let will_create_commit = squash_enabled || has_committable_changes;
// Build and approve the frozen hook plan once, at the gate. Every covered
// hook (`pre-merge` / `post-merge` / `pre-remove` / `post-remove` /
@@ -291,10 +298,9 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
&feature_root,
&destination_path,
&project_id,
- commit,
verify,
remove_requested,
- squash_enabled,
+ will_create_commit,
yes,
)?;
let approved = plan.is_some();
@@ -341,7 +347,6 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// The project commit-append is gated independently of hook approval:
// declining it drops only the append, never the (possibly already-approved)
// hooks. Mirrors the standalone `wt step commit` path via the shared gate.
- let will_create_commit = current_wt.is_dirty()? || squash_enabled;
let llm_configured = env
.config
.commit_generation(Some(&project_id))
@@ -354,21 +359,17 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let guidance = super::step::PreApprovedGuidance::Resolved(project_append);
// Handle uncommitted changes (skip if --no-commit) - track whether commit occurred
- let committed = if commit && current_wt.is_dirty()? {
- if squash_enabled {
- false // Squash path handles staging and committing
- } else {
- let ctx = env.context(yes);
- let mut options = CommitOptions::new(&ctx);
- options.target_branch = Some(&target_branch);
- options.hooks = commit_hooks;
- options.stage_mode = stage_mode;
- options.show_no_squash_note = true;
- options.guidance = guidance.clone();
-
- let _ = options.commit(&mut announcer)?;
- true // Committed directly
- }
+ let committed = if has_committable_changes {
+ let ctx = env.context(yes);
+ let mut options = CommitOptions::new(&ctx);
+ options.target_branch = Some(&target_branch);
+ options.hooks = commit_hooks;
+ options.stage_mode = stage_mode;
+ options.show_no_squash_note = true;
+ options.guidance = guidance.clone();
+
+ let _ = options.commit(&mut announcer)?;
+ true // Committed directly
} else {
false // No dirty changes or --no-commit
};
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 992bc87c1..f89f65f75 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -1070,6 +1070,23 @@ impl<'a> WorkingTree<'a> {
}
}
+ /// Determine whether staging with `mode` would leave content to commit.
+ ///
+ /// Staging modes are evaluated against a temporary index so staged and
+ /// unstaged changes combine exactly as `git add` would, without modifying
+ /// the user's index.
+ pub fn has_committable_changes(&self, mode: crate::config::StageMode) -> anyhow::Result<bool> {
+ match mode {
+ crate::config::StageMode::None => self.has_staged_changes(),
+ crate::config::StageMode::All | crate::config::StageMode::Tracked => {
+ let base = self.index_base()?;
+ let index = self.temp_index()?;
+ index.stage(mode)?;
+ index.has_staged_changes(&base)
+ }
+ }
+ }
+
/// Check whether this worktree has initialized submodules.
///
/// Uses `git submodule status --recursive` and parses its stable single-character
@@ -1156,7 +1173,8 @@ impl<'a> WorkingTree<'a> {
/// the working-tree conflict task (write-tree of tracked changes, for
/// merge-conflict probing), `wt step diff` (diff vs target merge-base with
/// untracked), `wt step commit --dry-run` (mirror its `--stage` mode without
-/// changing the user's index), and the `wt switch` unified/working preview tabs.
+/// changing the user's index), `wt merge` (check whether its `--stage` mode
+/// would produce a commit), and the `wt switch` unified/working preview tabs.
pub struct TempIndex {
temp: tempfile::TempPath,
worktree_root: PathBuf,
@@ -1203,6 +1221,25 @@ impl TempIndex {
.map(|output| output.trim().to_string())
}
+ fn has_staged_changes(&self, base: &str) -> anyhow::Result<bool> {
+ let args = PlumbingDiff::Index.args(&[
+ "--cached",
+ "--ita-invisible-in-index",
+ "--quiet",
+ "--end-of-options",
+ base,
+ ]);
+ let output = self
+ .command(args.iter().copied())
+ .run()
+ .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;
+ match output.status.code() {
+ Some(0) => Ok(false),
+ Some(1) => Ok(true),
+ _ => Err(CommandError::from_failed_output("git", &args, &output).into()),
+ }
+ }
+
/// Register untracked files in the temporary index without adding their
/// contents. A following `git diff <base>` can then include those files as
/// new while preserving the user's real index and staging state. If the
@@ -1416,6 +1453,73 @@ mod tests {
);
}
+ #[test]
+ fn has_committable_changes_matches_stage_modes_without_mutating_index() {
+ let test = TestRepo::with_initial_commit();
+ std::fs::write(test.root_path().join("tracked.txt"), "base\n").unwrap();
+ test.run_git(&["add", "tracked.txt"]);
+ test.run_git(&["commit", "-m", "add tracked file"]);
+ std::fs::write(test.root_path().join("tracked.txt"), "changed\n").unwrap();
+ std::fs::write(test.root_path().join("untracked.txt"), "new\n").unwrap();
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ let worktree = repo.current_worktree();
+ assert!(
+ worktree
+ .has_committable_changes(crate::config::StageMode::Tracked)
+ .unwrap()
+ );
+ assert!(
+ worktree
+ .has_committable_changes(crate::config::StageMode::All)
+ .unwrap()
+ );
+ assert!(
+ !worktree
+ .has_committable_changes(crate::config::StageMode::None)
+ .unwrap(),
+ "temporary staging must not modify the real index"
+ );
+
+ test.run_git(&["add", "tracked.txt"]);
+ assert!(
+ worktree
+ .has_committable_changes(crate::config::StageMode::None)
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn has_committable_changes_all_ignores_dirty_submodule_contents() {
+ let test = TestRepo::with_initial_commit();
+ let sub_source = test.root_path().parent().unwrap().join("sub-source");
+ std::fs::create_dir_all(&sub_source).unwrap();
+ test.run_git_in(&sub_source, &["init", "-b", "main"]);
+ std::fs::write(sub_source.join("sub.txt"), "base\n").unwrap();
+ test.run_git_in(&sub_source, &["add", "sub.txt"]);
+ test.run_git_in(&sub_source, &["commit", "-m", "sub init"]);
+ test.run_git(&[
+ "-c",
+ "protocol.file.allow=always",
+ "submodule",
+ "add",
+ sub_source.to_str().unwrap(),
+ "submod",
+ ]);
+ test.run_git(&["commit", "-m", "add submodule"]);
+ std::fs::write(test.root_path().join("submod/sub.txt"), "dirty\n").unwrap();
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ let worktree = repo.current_worktree();
+ assert!(worktree.is_dirty().unwrap());
+ assert!(
+ !worktree
+ .has_committable_changes(crate::config::StageMode::All)
+ .unwrap(),
+ "dirty submodule contents cannot be staged in the parent repository"
+ );
+ }
+
#[test]
fn submodule_status_empty_is_not_initialized() {
assert!(!has_initialized_submodules_from_status(""));
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 5ec7fad2c..c095b64c4 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -600,6 +600,63 @@ fn test_merge_auto_commit_deterministic(mut repo_with_main_worktree: TestRepo) {
));
}
+/// `--stage=none` and `--stage=tracked` exclude untracked files from the
+/// auto-commit. An untracked-only worktree therefore has nothing to commit,
+/// but the existing feature commits should still merge while the file stays
+/// in the preserved source worktree.
+#[rstest]
+fn test_merge_ignores_untracked_only_changes_outside_stage_scope(
+ mut repo_with_main_worktree: TestRepo,
+ #[values("none", "tracked")] stage: &str,
+) {
+ let repo = &mut repo_with_main_worktree;
+ let feature_wt =
+ repo.add_worktree_with_commit("feature", "feature.txt", "feature", "Add feature");
+ fs::create_dir_all(feature_wt.join(".config")).unwrap();
+ repo.commit_in_worktree(
+ &feature_wt,
+ ".config/wt.toml",
+ r#"pre-commit = "touch pre-commit-ran""#,
+ "Add pre-commit hook",
+ );
+ let feature_tip = repo.git_output(&["rev-parse", "feature"]);
+ fs::write(feature_wt.join("untracked.txt"), "scratch").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args([
+ "merge",
+ "main",
+ &format!("--stage={stage}"),
+ "--no-squash",
+ "--no-remove",
+ "--yes",
+ ])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "merge with --stage={stage} should skip the empty auto-commit: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(repo.git_output(&["rev-parse", "main"]), feature_tip);
+ assert_eq!(
+ repo.git_output(&["rev-parse", "feature"]),
+ feature_tip,
+ "skipping the auto-commit must not add a commit to the feature branch"
+ );
+ assert!(
+ feature_wt.join("untracked.txt").exists(),
+ "the untracked file must remain in the preserved source worktree"
+ );
+ assert!(
+ !feature_wt.join("pre-commit-ran").exists(),
+ "pre-commit must not run when the stage mode leaves nothing to commit"
+ );
+}
+
#[rstest]
fn test_merge_auto_commit_with_llm(mut repo_with_main_worktree: TestRepo) {
let repo = &mut repo_with_main_worktree;