refs/files: remove empty parent dirs when ref creation fails

When creating a new reference in the "files" backend we first create the directory hierarchy for that reference, then create the lockfile for that reference, and finally rename the lockfile into place. When the transaction gets aborted we prune the lockfile, but we don't clean up the directory hierarchy that we may have created for the lockfile. In some egde cases this can lead to lots of empty directories being cluttered in the ".git/refs" directory that really serve no purpose at all. We know to prune such empty directories when packing refs, but that only patches over the issue. Improve this by removing empty parents when cleaning up still-locked references in `files_transaction_cleanup()`. This function is also called when preparing or committing the transaction, so this change also helps when not explicitly aborting the transaction. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Jul 8, 2025 at 12:19 UTC a3a7f2051686e087cba80f3af1557107406205c9
2 files changed +21
refs/files-backend.c
+2
@@ -2760,6 +2760,8 @@ static void files_transaction_cleanup(struct files_ref_store *refs,
2760
2761 if (lock) {
2762 unlock_ref(lock);
2763 + try_remove_empty_parents(refs, update->refname,
2764 + REMOVE_EMPTY_PARENTS_REF);
2765 update->backend_data = NULL;
2766 }
2767 }
t/t1400-update-ref.sh
+19
@@ -2310,4 +2310,23 @@ test_expect_success 'update-ref should also create reflog for HEAD' '
2310 test_cmp expect actual
2311 '
2312
2313 +test_expect_success REFFILES 'empty directories are pruned when aborting a transaction' '
2314 + test_path_is_missing .git/refs/heads/nested &&
2315 + git update-ref --stdin <<-EOF &&
2316 + create refs/heads/nested/something HEAD
2317 + prepare
2318 + abort
2319 + EOF
2320 + test_path_is_missing .git/refs/heads/nested
2321 +'
2322 +
2323 +test_expect_success REFFILES 'empty directories are pruned when not committing' '
2324 + test_path_is_missing .git/refs/heads/nested &&
2325 + git update-ref --stdin <<-EOF &&
2326 + create refs/heads/nested/something HEAD
2327 + prepare
2328 + EOF
2329 + test_path_is_missing .git/refs/heads/nested
2330 +'
2331 +
2332 test_done