merge: only apply autostash when appropriate

If a merge failed and we are leaving conflicts in the working directory for the user to resolve, we should not attempt to apply any autostash. Further, if we fail to apply the autostash (because either the merge failed, or the user requested --no-commit), then we should instruct the user how to apply it later. Add a testcase verifying we have corrected this behavior. Signed-off-by: Elijah Newren <newren@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Elijah Newren committed Aug 23, 2022 at 02:42 UTC d3a9295ada961012bfe8582540e40a02e772aa09
2 files changed +13 -1
builtin/merge.c
+4 -1
@@ -492,7 +492,8 @@ static void finish(struct commit *head_commit,
492 /* Run a post-merge hook */
493 run_hooks_l("post-merge", squash ? "1" : "0", NULL);
494
495 - apply_autostash(git_path_merge_autostash(the_repository));
495 + if (new_head)
496 + apply_autostash(git_path_merge_autostash(the_repository));
497 strbuf_release(&reflog_message);
498 }
499
@@ -1754,6 +1755,8 @@ int cmd_merge(int argc, const char **argv, const char *prefix)
1755 "stopped before committing as requested\n"));
1756 else
1757 ret = suggest_conflicts();
1758 + if (autostash)
1759 + printf(_("When finished, apply stashed changes with `git stash pop`\n"));
1760
1761 done:
1762 if (!automerge_was_ok) {
t/t7600-merge.sh
+9
@@ -255,6 +255,15 @@ test_expect_success 'merge --squash c3 with c7' '
255 test_cmp expect actual
256 '
257
258 +test_expect_success 'merge --squash --autostash conflict does not attempt to apply autostash' '
259 + git reset --hard c3 &&
260 + >unrelated &&
261 + git add unrelated &&
262 + test_must_fail git merge --squash c7 --autostash >out 2>err &&
263 + ! grep "Applying autostash resulted in conflicts." err &&
264 + grep "When finished, apply stashed changes with \`git stash pop\`" out
265 +'
266 +
267 test_expect_success 'merge c3 with c7 with commit.cleanup = scissors' '
268 git config commit.cleanup scissors &&
269 git reset --hard c3 &&