merge: avoid write merge state when unable to write index

Writing the merge state after the index write fails is meaningless and could potentially cause Git to lose changes. Signed-off-by: Kyle Zhao <kylezhao@tencent.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Kyle Zhao committed Jun 17, 2024 at 03:08 UTC 2e5a63659301c46544fdb3c3e7a69b4693a2c384
2 files changed +11 -1
builtin/merge.c
+1 -1
@@ -703,7 +703,7 @@ static int try_merge_strategy(const char *strategy, struct commit_list *common,
703 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET,
704 SKIP_IF_UNCHANGED, 0, NULL, NULL,
705 NULL) < 0)
706 - return error(_("Unable to write index."));
706 + die(_("Unable to write index."));
707
708 if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
709 !strcmp(strategy, "ort")) {
t/t7600-merge.sh
+10
@@ -236,6 +236,16 @@ test_expect_success 'merge c1 with c2' '
236 verify_parents $c1 $c2
237 '
238
239 +test_expect_success 'merge c1 with c2 when index.lock exists' '
240 + test_when_finished rm .git/index.lock &&
241 + git reset --hard c1 &&
242 + >.git/index.lock &&
243 + test_must_fail git merge c2 &&
244 + test_path_is_missing .git/MERGE_HEAD &&
245 + test_path_is_missing .git/MERGE_MODE &&
246 + test_path_is_missing .git/MERGE_MSG
247 +'
248 +
249 test_expect_success 'merge --squash c3 with c7' '
250 git reset --hard c3 &&
251 test_must_fail git merge --squash c7 &&