Skip to content

Commit 2954e5e

Browse files
Martin Ågrengitster
authored andcommitted
cache-tree: simplify locking logic
After we have taken the lock using `LOCK_DIE_ON_ERROR`, we know that `newfd` is non-negative. So when we check for exactly that property before calling `write_locked_index()`, the outcome is guaranteed. If we write and commit successfully, we set `newfd = -1`, so that we can later avoid calling `rollback_lock_file` on an already-committed lock. But we might just as well unconditionally call `rollback_lock_file()` -- it will be a no-op if we have already committed. All in all, we use `newfd` as a bool and the only benefit we get from it is that we can avoid calling a no-op. Remove `newfd` so that we have one variable less to reason about. Signed-off-by: Martin Ågren <martin.agren@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent 02ae242 commit 2954e5e

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

cache-tree.c

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -602,11 +602,11 @@ static struct cache_tree *cache_tree_find(struct cache_tree *it, const char *pat
602602

603603
int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, const char *index_path, int flags, const char *prefix)
604604
{
605-
int entries, was_valid, newfd;
605+
int entries, was_valid;
606606
struct lock_file lock_file = LOCK_INIT;
607607
int ret = 0;
608608

609-
newfd = hold_lock_file_for_update(&lock_file, index_path, LOCK_DIE_ON_ERROR);
609+
hold_lock_file_for_update(&lock_file, index_path, LOCK_DIE_ON_ERROR);
610610

611611
entries = read_index_from(index_state, index_path);
612612
if (entries < 0) {
@@ -625,10 +625,7 @@ int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, co
625625
ret = WRITE_TREE_UNMERGED_INDEX;
626626
goto out;
627627
}
628-
if (0 <= newfd) {
629-
if (!write_locked_index(index_state, &lock_file, COMMIT_LOCK))
630-
newfd = -1;
631-
}
628+
write_locked_index(index_state, &lock_file, COMMIT_LOCK);
632629
/* Not being able to write is fine -- we are only interested
633630
* in updating the cache-tree part, and if the next caller
634631
* ends up using the old index with unupdated cache-tree part
@@ -650,8 +647,7 @@ int write_index_as_tree(unsigned char *sha1, struct index_state *index_state, co
650647
hashcpy(sha1, index_state->cache_tree->oid.hash);
651648

652649
out:
653-
if (0 <= newfd)
654-
rollback_lock_file(&lock_file);
650+
rollback_lock_file(&lock_file);
655651
return ret;
656652
}
657653

0 commit comments

Comments
 (0)