reset: fix write race

Similar to the previous commit "commit: fix write race", fix a similar race in
"reset" (except for --soft, which does not lock/write the index) by changing
"read -> lock -> write" to "lock -> read -> write", so "reset" now qualifies
the new user-friendly "waiting for index lock" behavior.

Unlike "commit", "reset" uses repo_read_index(), not repo_read_index_preload(),
so it won't add significant work (e.g. lstat() working tree) while holding the
index lock.

I chose to not add a test to t0032-index-lock-timeout.sh, since every waiting
test case there (undesirably) takes 1 second to run, there are already
representative test cases, and the change looks straightforward.

Signed-off-by: Jun Wu <quark@meta.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Jun Wu authored and Junio C Hamano committed 2026-10-17 10:02:14 -07:00
1 parent 3cf854e2ae
commit 4868eea4d7
1 file changed
+4 -3
+4 -3
View File
@@ -346,6 +346,7 @@ int cmd_reset(int argc,
struct object_id oid;
struct pathspec pathspec;
int intent_to_add = 0;
struct lock_file lock = LOCK_INIT;
struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
const struct option options[] = {
OPT__QUIET(&quiet, N_("be quiet, only report errors")),
@@ -477,6 +478,9 @@ int cmd_reset(int argc,
if (intent_to_add && reset_type != MIXED)
die(_("the option '%s' requires '%s'"), "-N", "--mixed");
if (reset_type != SOFT)
repo_hold_locked_index(the_repository, &lock,
LOCK_DIE_ON_ERROR);
if (repo_read_index(the_repository) < 0)
die(_("index file corrupt"));
@@ -487,9 +491,6 @@ int cmd_reset(int argc,
die_if_unmerged_cache(reset_type);
if (reset_type != SOFT) {
struct lock_file lock = LOCK_INIT;
repo_hold_locked_index(the_repository, &lock,
LOCK_DIE_ON_ERROR);
if (reset_type == MIXED) {
int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN;
if (read_from_tree(&pathspec, &oid, intent_to_add)) {