read-cache: report lock error when refreshing index

In the repo_refresh_and_write_index of read-cache.c, we return -1 to indicate that writing the index to disk failed. However, callers do not use this information. Commands such as stash print "could not write index" and then exit, which does not help to discover the exact problem. We can let repo_hold_locked_index print the error message if the locking failed. Signed-off-by: Han Young <hanyang.tony@bytedance.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Han Young committed Jul 3, 2025 at 15:45 UTC 9455397a5cfcef186fab3321b3fbe29fd3ef78c7
2 files changed +8 -13
read-cache.c
+2 -1
@@ -1456,7 +1456,8 @@ int repo_refresh_and_write_index(struct repository *repo,
1456 struct lock_file lock_file = LOCK_INIT;
1457 int fd, ret = 0;
1458
1459 - fd = repo_hold_locked_index(repo, &lock_file, 0);
1459 + fd = repo_hold_locked_index(repo, &lock_file,
1460 + gentle ? 0 : LOCK_REPORT_ON_ERROR);
1461 if (!gentle && fd < 0)
1462 return -1;
1463 if (refresh_index(repo->index, refresh_flags, pathspec, seen, header_msg))
t/t3903-stash.sh
+6 -12
@@ -1549,11 +1549,9 @@ test_expect_success 'stash create reports a locked index' '
1549 echo change >A.file &&
1550 touch .git/index.lock &&
1551
1552 - cat >expect <<-EOF &&
1553 - error: could not write index
1554 - EOF
1552 test_must_fail git stash create 2>err &&
1556 - test_cmp expect err
1553 + test_grep "error: could not write index" err &&
1554 + test_grep "error: Unable to create '.*index.lock'" err
1555 )
1556 '
1557
@@ -1566,11 +1564,9 @@ test_expect_success 'stash push reports a locked index' '
1564 echo change >A.file &&
1565 touch .git/index.lock &&
1566
1569 - cat >expect <<-EOF &&
1570 - error: could not write index
1571 - EOF
1567 test_must_fail git stash push 2>err &&
1573 - test_cmp expect err
1568 + test_grep "error: could not write index" err &&
1569 + test_grep "error: Unable to create '.*index.lock'" err
1570 )
1571 '
1572
@@ -1584,11 +1580,9 @@ test_expect_success 'stash apply reports a locked index' '
1580 git stash push &&
1581 touch .git/index.lock &&
1582
1587 - cat >expect <<-EOF &&
1588 - error: could not write index
1589 - EOF
1583 test_must_fail git stash apply 2>err &&
1591 - test_cmp expect err
1584 + test_grep "error: could not write index" err &&
1585 + test_grep "error: Unable to create '.*index.lock'" err
1586 )
1587 '
1588