4 #include "refs-internal.h"
6 #include "packed-backend.h"
7 #include "../iterator.h"
8 #include "../dir-iterator.h"
9 #include "../lockfile.h"
10 #include "../object.h"
12 #include "../chdir-notify.h"
16 * This backend uses the following flags in `ref_update::flags` for
17 * internal bookkeeping purposes. Their numerical values must not
18 * conflict with REF_NO_DEREF, REF_FORCE_CREATE_REFLOG, REF_HAVE_NEW,
19 * REF_HAVE_OLD, or REF_IS_PRUNING, which are also stored in
20 * `ref_update::flags`.
24 * Used as a flag in ref_update::flags when a loose ref is being
25 * pruned. This flag must only be used when REF_NO_DEREF is set.
27 #define REF_IS_PRUNING (1 << 4)
30 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
31 * refs (i.e., because the reference is about to be deleted anyway).
33 #define REF_DELETING (1 << 5)
36 * Used as a flag in ref_update::flags when the lockfile needs to be
39 #define REF_NEEDS_COMMIT (1 << 6)
42 * Used as a flag in ref_update::flags when the ref_update was via an
45 #define REF_UPDATE_VIA_HEAD (1 << 8)
48 * Used as a flag in ref_update::flags when a reference has been
49 * deleted and the ref's parent directories may need cleanup.
51 #define REF_DELETED_RMDIR (1 << 9)
56 struct object_id old_oid
;
59 struct files_ref_store
{
60 struct ref_store base
;
61 unsigned int store_flags
;
65 struct ref_cache
*loose
;
67 struct ref_store
*packed_ref_store
;
70 static void clear_loose_ref_cache(struct files_ref_store
*refs
)
73 free_ref_cache(refs
->loose
);
79 * Create a new submodule ref cache and add it to the internal
82 static struct ref_store
*files_ref_store_create(const char *gitdir
,
85 struct files_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
86 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
87 struct strbuf sb
= STRBUF_INIT
;
89 ref_store
->gitdir
= xstrdup(gitdir
);
90 base_ref_store_init(ref_store
, &refs_be_files
);
91 refs
->store_flags
= flags
;
93 get_common_dir_noenv(&sb
, gitdir
);
94 refs
->gitcommondir
= strbuf_detach(&sb
, NULL
);
95 strbuf_addf(&sb
, "%s/packed-refs", refs
->gitcommondir
);
96 refs
->packed_ref_store
= packed_ref_store_create(sb
.buf
, flags
);
99 chdir_notify_reparent("files-backend $GIT_DIR", &refs
->base
.gitdir
);
100 chdir_notify_reparent("files-backend $GIT_COMMONDIR",
101 &refs
->gitcommondir
);
107 * Die if refs is not the main ref store. caller is used in any
108 * necessary error messages.
110 static void files_assert_main_repository(struct files_ref_store
*refs
,
113 if (refs
->store_flags
& REF_STORE_MAIN
)
116 BUG("operation %s only allowed for main ref store", caller
);
120 * Downcast ref_store to files_ref_store. Die if ref_store is not a
121 * files_ref_store. required_flags is compared with ref_store's
122 * store_flags to ensure the ref_store has all required capabilities.
123 * "caller" is used in any necessary error messages.
125 static struct files_ref_store
*files_downcast(struct ref_store
*ref_store
,
126 unsigned int required_flags
,
129 struct files_ref_store
*refs
;
131 if (ref_store
->be
!= &refs_be_files
)
132 BUG("ref_store is type \"%s\" not \"files\" in %s",
133 ref_store
->be
->name
, caller
);
135 refs
= (struct files_ref_store
*)ref_store
;
137 if ((refs
->store_flags
& required_flags
) != required_flags
)
138 BUG("operation %s requires abilities 0x%x, but only have 0x%x",
139 caller
, required_flags
, refs
->store_flags
);
144 static void files_reflog_path_other_worktrees(struct files_ref_store
*refs
,
148 const char *real_ref
;
149 const char *worktree_name
;
152 if (parse_worktree_ref(refname
, &worktree_name
, &length
, &real_ref
))
153 BUG("refname %s is not a other-worktree ref", refname
);
156 strbuf_addf(sb
, "%s/worktrees/%.*s/logs/%s", refs
->gitcommondir
,
157 length
, worktree_name
, real_ref
);
159 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
,
163 static void files_reflog_path(struct files_ref_store
*refs
,
167 switch (ref_type(refname
)) {
168 case REF_TYPE_PER_WORKTREE
:
169 case REF_TYPE_PSEUDOREF
:
170 strbuf_addf(sb
, "%s/logs/%s", refs
->base
.gitdir
, refname
);
172 case REF_TYPE_OTHER_PSEUDOREF
:
173 case REF_TYPE_MAIN_PSEUDOREF
:
174 files_reflog_path_other_worktrees(refs
, sb
, refname
);
176 case REF_TYPE_NORMAL
:
177 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
, refname
);
180 BUG("unknown ref type %d of ref %s",
181 ref_type(refname
), refname
);
185 static void files_ref_path(struct files_ref_store
*refs
,
189 switch (ref_type(refname
)) {
190 case REF_TYPE_PER_WORKTREE
:
191 case REF_TYPE_PSEUDOREF
:
192 strbuf_addf(sb
, "%s/%s", refs
->base
.gitdir
, refname
);
194 case REF_TYPE_MAIN_PSEUDOREF
:
195 if (!skip_prefix(refname
, "main-worktree/", &refname
))
196 BUG("ref %s is not a main pseudoref", refname
);
198 case REF_TYPE_OTHER_PSEUDOREF
:
199 case REF_TYPE_NORMAL
:
200 strbuf_addf(sb
, "%s/%s", refs
->gitcommondir
, refname
);
203 BUG("unknown ref type %d of ref %s",
204 ref_type(refname
), refname
);
209 * Manually add refs/bisect, refs/rewritten and refs/worktree, which, being
210 * per-worktree, might not appear in the directory listing for
211 * refs/ in the main repo.
213 static void add_per_worktree_entries_to_dir(struct ref_dir
*dir
, const char *dirname
)
215 const char *prefixes
[] = { "refs/bisect/", "refs/worktree/", "refs/rewritten/" };
218 if (strcmp(dirname
, "refs/"))
221 for (ip
= 0; ip
< ARRAY_SIZE(prefixes
); ip
++) {
222 const char *prefix
= prefixes
[ip
];
223 int prefix_len
= strlen(prefix
);
224 struct ref_entry
*child_entry
;
227 pos
= search_ref_dir(dir
, prefix
, prefix_len
);
230 child_entry
= create_dir_entry(dir
->cache
, prefix
, prefix_len
);
231 add_entry_to_dir(dir
, child_entry
);
236 * Read the loose references from the namespace dirname into dir
237 * (without recursing). dirname must end with '/'. dir must be the
238 * directory entry corresponding to dirname.
240 static void loose_fill_ref_dir(struct ref_store
*ref_store
,
241 struct ref_dir
*dir
, const char *dirname
)
243 struct files_ref_store
*refs
=
244 files_downcast(ref_store
, REF_STORE_READ
, "fill_ref_dir");
247 int dirnamelen
= strlen(dirname
);
248 struct strbuf refname
;
249 struct strbuf path
= STRBUF_INIT
;
252 files_ref_path(refs
, &path
, dirname
);
253 path_baselen
= path
.len
;
255 d
= opendir(path
.buf
);
257 strbuf_release(&path
);
261 strbuf_init(&refname
, dirnamelen
+ 257);
262 strbuf_add(&refname
, dirname
, dirnamelen
);
264 while ((de
= readdir(d
)) != NULL
) {
265 struct object_id oid
;
269 if (de
->d_name
[0] == '.')
271 if (ends_with(de
->d_name
, ".lock"))
273 strbuf_addstr(&refname
, de
->d_name
);
274 strbuf_addstr(&path
, de
->d_name
);
275 if (stat(path
.buf
, &st
) < 0) {
276 ; /* silently ignore */
277 } else if (S_ISDIR(st
.st_mode
)) {
278 strbuf_addch(&refname
, '/');
279 add_entry_to_dir(dir
,
280 create_dir_entry(dir
->cache
, refname
.buf
,
283 if (!refs_resolve_ref_unsafe(&refs
->base
,
288 flag
|= REF_ISBROKEN
;
289 } else if (is_null_oid(&oid
)) {
291 * It is so astronomically unlikely
292 * that null_oid is the OID of an
293 * actual object that we consider its
294 * appearance in a loose reference
295 * file to be repo corruption
296 * (probably due to a software bug).
298 flag
|= REF_ISBROKEN
;
301 if (check_refname_format(refname
.buf
,
302 REFNAME_ALLOW_ONELEVEL
)) {
303 if (!refname_is_safe(refname
.buf
))
304 die("loose refname is dangerous: %s", refname
.buf
);
306 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
308 add_entry_to_dir(dir
,
309 create_ref_entry(refname
.buf
, &oid
, flag
));
311 strbuf_setlen(&refname
, dirnamelen
);
312 strbuf_setlen(&path
, path_baselen
);
314 strbuf_release(&refname
);
315 strbuf_release(&path
);
318 add_per_worktree_entries_to_dir(dir
, dirname
);
321 static struct ref_cache
*get_loose_ref_cache(struct files_ref_store
*refs
)
325 * Mark the top-level directory complete because we
326 * are about to read the only subdirectory that can
329 refs
->loose
= create_ref_cache(&refs
->base
, loose_fill_ref_dir
);
331 /* We're going to fill the top level ourselves: */
332 refs
->loose
->root
->flag
&= ~REF_INCOMPLETE
;
335 * Add an incomplete entry for "refs/" (to be filled
338 add_entry_to_dir(get_ref_dir(refs
->loose
->root
),
339 create_dir_entry(refs
->loose
, "refs/", 5));
344 static int files_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
345 struct object_id
*oid
, struct strbuf
*referent
,
346 unsigned int *type
, int *failure_errno
)
348 struct files_ref_store
*refs
=
349 files_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
350 struct strbuf sb_contents
= STRBUF_INIT
;
351 struct strbuf sb_path
= STRBUF_INIT
;
357 int remaining_retries
= 3;
360 strbuf_reset(&sb_path
);
362 files_ref_path(refs
, &sb_path
, refname
);
368 * We might have to loop back here to avoid a race
369 * condition: first we lstat() the file, then we try
370 * to read it as a link or as a file. But if somebody
371 * changes the type of the file (file <-> directory
372 * <-> symlink) between the lstat() and reading, then
373 * we don't want to report that as an error but rather
374 * try again starting with the lstat().
376 * We'll keep a count of the retries, though, just to avoid
377 * any confusing situation sending us into an infinite loop.
380 if (remaining_retries
-- <= 0)
383 if (lstat(path
, &st
) < 0) {
387 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
, oid
,
388 referent
, type
, &ignore_errno
)) {
396 /* Follow "normalized" - ie "refs/.." symlinks by hand */
397 if (S_ISLNK(st
.st_mode
)) {
398 strbuf_reset(&sb_contents
);
399 if (strbuf_readlink(&sb_contents
, path
, st
.st_size
) < 0) {
400 if (errno
== ENOENT
|| errno
== EINVAL
)
401 /* inconsistent with lstat; retry */
406 if (starts_with(sb_contents
.buf
, "refs/") &&
407 !check_refname_format(sb_contents
.buf
, 0)) {
408 strbuf_swap(&sb_contents
, referent
);
409 *type
|= REF_ISSYMREF
;
414 * It doesn't look like a refname; fall through to just
415 * treating it like a non-symlink, and reading whatever it
420 /* Is it a directory? */
421 if (S_ISDIR(st
.st_mode
)) {
424 * Even though there is a directory where the loose
425 * ref is supposed to be, there could still be a
428 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
, oid
,
429 referent
, type
, &ignore_errno
)) {
438 * Anything else, just open it and try to use it as
441 fd
= open(path
, O_RDONLY
);
443 if (errno
== ENOENT
&& !S_ISLNK(st
.st_mode
))
444 /* inconsistent with lstat; retry */
449 strbuf_reset(&sb_contents
);
450 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
451 int save_errno
= errno
;
457 strbuf_rtrim(&sb_contents
);
458 buf
= sb_contents
.buf
;
460 ret
= parse_loose_ref_contents(buf
, oid
, referent
, type
);
463 *failure_errno
= errno
;
464 strbuf_release(&sb_path
);
465 strbuf_release(&sb_contents
);
469 int parse_loose_ref_contents(const char *buf
, struct object_id
*oid
,
470 struct strbuf
*referent
, unsigned int *type
)
473 if (skip_prefix(buf
, "ref:", &buf
)) {
474 while (isspace(*buf
))
477 strbuf_reset(referent
);
478 strbuf_addstr(referent
, buf
);
479 *type
|= REF_ISSYMREF
;
484 * FETCH_HEAD has additional data after the sha.
486 if (parse_oid_hex(buf
, oid
, &p
) ||
487 (*p
!= '\0' && !isspace(*p
))) {
488 *type
|= REF_ISBROKEN
;
495 static void unlock_ref(struct ref_lock
*lock
)
497 rollback_lock_file(&lock
->lk
);
498 free(lock
->ref_name
);
503 * Lock refname, without following symrefs, and set *lock_p to point
504 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
505 * and type similarly to read_raw_ref().
507 * The caller must verify that refname is a "safe" reference name (in
508 * the sense of refname_is_safe()) before calling this function.
510 * If the reference doesn't already exist, verify that refname doesn't
511 * have a D/F conflict with any existing references. extras and skip
512 * are passed to refs_verify_refname_available() for this check.
514 * If mustexist is not set and the reference is not found or is
515 * broken, lock the reference anyway but clear old_oid.
517 * Return 0 on success. On failure, write an error message to err and
518 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
520 * Implementation note: This function is basically
525 * but it includes a lot more code to
526 * - Deal with possible races with other processes
527 * - Avoid calling refs_verify_refname_available() when it can be
528 * avoided, namely if we were successfully able to read the ref
529 * - Generate informative error messages in the case of failure
531 static int lock_raw_ref(struct files_ref_store
*refs
,
532 const char *refname
, int mustexist
,
533 const struct string_list
*extras
,
534 struct ref_lock
**lock_p
,
535 struct strbuf
*referent
,
539 struct ref_lock
*lock
;
540 struct strbuf ref_file
= STRBUF_INIT
;
541 int attempts_remaining
= 3;
542 int ret
= TRANSACTION_GENERIC_ERROR
;
546 files_assert_main_repository(refs
, "lock_raw_ref");
550 /* First lock the file so it can't change out from under us. */
552 *lock_p
= CALLOC_ARRAY(lock
, 1);
554 lock
->ref_name
= xstrdup(refname
);
555 files_ref_path(refs
, &ref_file
, refname
);
558 switch (safe_create_leading_directories(ref_file
.buf
)) {
563 * Suppose refname is "refs/foo/bar". We just failed
564 * to create the containing directory, "refs/foo",
565 * because there was a non-directory in the way. This
566 * indicates a D/F conflict, probably because of
567 * another reference such as "refs/foo". There is no
568 * reason to expect this error to be transitory.
570 if (refs_verify_refname_available(&refs
->base
, refname
,
571 extras
, NULL
, err
)) {
574 * To the user the relevant error is
575 * that the "mustexist" reference is
579 strbuf_addf(err
, "unable to resolve reference '%s'",
583 * The error message set by
584 * refs_verify_refname_available() is
587 ret
= TRANSACTION_NAME_CONFLICT
;
591 * The file that is in the way isn't a loose
592 * reference. Report it as a low-level
595 strbuf_addf(err
, "unable to create lock file %s.lock; "
596 "non-directory in the way",
601 /* Maybe another process was tidying up. Try again. */
602 if (--attempts_remaining
> 0)
606 strbuf_addf(err
, "unable to create directory for %s",
611 if (hold_lock_file_for_update_timeout(
612 &lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
,
613 get_files_ref_lock_timeout_ms()) < 0) {
616 if (myerr
== ENOENT
&& --attempts_remaining
> 0) {
618 * Maybe somebody just deleted one of the
619 * directories leading to ref_file. Try
624 unable_to_lock_message(ref_file
.buf
, myerr
, err
);
630 * Now we hold the lock and can read the reference without
631 * fear that its value will change.
634 if (files_read_raw_ref(&refs
->base
, refname
, &lock
->old_oid
, referent
,
635 type
, &failure_errno
)) {
636 if (failure_errno
== ENOENT
) {
638 /* Garden variety missing reference. */
639 strbuf_addf(err
, "unable to resolve reference '%s'",
644 * Reference is missing, but that's OK. We
645 * know that there is not a conflict with
646 * another loose reference because
647 * (supposing that we are trying to lock
648 * reference "refs/foo/bar"):
650 * - We were successfully able to create
651 * the lockfile refs/foo/bar.lock, so we
652 * know there cannot be a loose reference
655 * - We got ENOENT and not EISDIR, so we
656 * know that there cannot be a loose
657 * reference named "refs/foo/bar/baz".
660 } else if (failure_errno
== EISDIR
) {
662 * There is a directory in the way. It might have
663 * contained references that have been deleted. If
664 * we don't require that the reference already
665 * exists, try to remove the directory so that it
666 * doesn't cause trouble when we want to rename the
667 * lockfile into place later.
670 /* Garden variety missing reference. */
671 strbuf_addf(err
, "unable to resolve reference '%s'",
674 } else if (remove_dir_recursively(&ref_file
,
675 REMOVE_DIR_EMPTY_ONLY
)) {
676 if (refs_verify_refname_available(
677 &refs
->base
, refname
,
678 extras
, NULL
, err
)) {
680 * The error message set by
681 * verify_refname_available() is OK.
683 ret
= TRANSACTION_NAME_CONFLICT
;
687 * We can't delete the directory,
688 * but we also don't know of any
689 * references that it should
692 strbuf_addf(err
, "there is a non-empty directory '%s' "
693 "blocking reference '%s'",
694 ref_file
.buf
, refname
);
698 } else if (failure_errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
699 strbuf_addf(err
, "unable to resolve reference '%s': "
700 "reference broken", refname
);
703 strbuf_addf(err
, "unable to resolve reference '%s': %s",
704 refname
, strerror(failure_errno
));
709 * If the ref did not exist and we are creating it,
710 * make sure there is no existing packed ref that
711 * conflicts with refname:
713 if (refs_verify_refname_available(
714 refs
->packed_ref_store
, refname
,
727 strbuf_release(&ref_file
);
731 struct files_ref_iterator
{
732 struct ref_iterator base
;
734 struct ref_iterator
*iter0
;
738 static int files_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
740 struct files_ref_iterator
*iter
=
741 (struct files_ref_iterator
*)ref_iterator
;
744 while ((ok
= ref_iterator_advance(iter
->iter0
)) == ITER_OK
) {
745 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
746 ref_type(iter
->iter0
->refname
) != REF_TYPE_PER_WORKTREE
)
749 if ((iter
->flags
& DO_FOR_EACH_OMIT_DANGLING_SYMREFS
) &&
750 (iter
->iter0
->flags
& REF_ISSYMREF
) &&
751 (iter
->iter0
->flags
& REF_ISBROKEN
))
754 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
755 !ref_resolves_to_object(iter
->iter0
->refname
,
760 iter
->base
.refname
= iter
->iter0
->refname
;
761 iter
->base
.oid
= iter
->iter0
->oid
;
762 iter
->base
.flags
= iter
->iter0
->flags
;
767 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
773 static int files_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
774 struct object_id
*peeled
)
776 struct files_ref_iterator
*iter
=
777 (struct files_ref_iterator
*)ref_iterator
;
779 return ref_iterator_peel(iter
->iter0
, peeled
);
782 static int files_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
784 struct files_ref_iterator
*iter
=
785 (struct files_ref_iterator
*)ref_iterator
;
789 ok
= ref_iterator_abort(iter
->iter0
);
791 base_ref_iterator_free(ref_iterator
);
795 static struct ref_iterator_vtable files_ref_iterator_vtable
= {
796 files_ref_iterator_advance
,
797 files_ref_iterator_peel
,
798 files_ref_iterator_abort
801 static struct ref_iterator
*files_ref_iterator_begin(
802 struct ref_store
*ref_store
,
803 const char *prefix
, unsigned int flags
)
805 struct files_ref_store
*refs
;
806 struct ref_iterator
*loose_iter
, *packed_iter
, *overlay_iter
;
807 struct files_ref_iterator
*iter
;
808 struct ref_iterator
*ref_iterator
;
809 unsigned int required_flags
= REF_STORE_READ
;
811 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
812 required_flags
|= REF_STORE_ODB
;
814 refs
= files_downcast(ref_store
, required_flags
, "ref_iterator_begin");
817 * We must make sure that all loose refs are read before
818 * accessing the packed-refs file; this avoids a race
819 * condition if loose refs are migrated to the packed-refs
820 * file by a simultaneous process, but our in-memory view is
821 * from before the migration. We ensure this as follows:
822 * First, we call start the loose refs iteration with its
823 * `prime_ref` argument set to true. This causes the loose
824 * references in the subtree to be pre-read into the cache.
825 * (If they've already been read, that's OK; we only need to
826 * guarantee that they're read before the packed refs, not
827 * *how much* before.) After that, we call
828 * packed_ref_iterator_begin(), which internally checks
829 * whether the packed-ref cache is up to date with what is on
830 * disk, and re-reads it if not.
833 loose_iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
),
837 * The packed-refs file might contain broken references, for
838 * example an old version of a reference that points at an
839 * object that has since been garbage-collected. This is OK as
840 * long as there is a corresponding loose reference that
841 * overrides it, and we don't want to emit an error message in
842 * this case. So ask the packed_ref_store for all of its
843 * references, and (if needed) do our own check for broken
844 * ones in files_ref_iterator_advance(), after we have merged
845 * the packed and loose references.
847 packed_iter
= refs_ref_iterator_begin(
848 refs
->packed_ref_store
, prefix
, 0,
849 DO_FOR_EACH_INCLUDE_BROKEN
);
851 overlay_iter
= overlay_ref_iterator_begin(loose_iter
, packed_iter
);
853 CALLOC_ARRAY(iter
, 1);
854 ref_iterator
= &iter
->base
;
855 base_ref_iterator_init(ref_iterator
, &files_ref_iterator_vtable
,
856 overlay_iter
->ordered
);
857 iter
->iter0
= overlay_iter
;
864 * Callback function for raceproof_create_file(). This function is
865 * expected to do something that makes dirname(path) permanent despite
866 * the fact that other processes might be cleaning up empty
867 * directories at the same time. Usually it will create a file named
868 * path, but alternatively it could create another file in that
869 * directory, or even chdir() into that directory. The function should
870 * return 0 if the action was completed successfully. On error, it
871 * should return a nonzero result and set errno.
872 * raceproof_create_file() treats two errno values specially:
874 * - ENOENT -- dirname(path) does not exist. In this case,
875 * raceproof_create_file() tries creating dirname(path)
876 * (and any parent directories, if necessary) and calls
877 * the function again.
879 * - EISDIR -- the file already exists and is a directory. In this
880 * case, raceproof_create_file() removes the directory if
881 * it is empty (and recursively any empty directories that
882 * it contains) and calls the function again.
884 * Any other errno causes raceproof_create_file() to fail with the
885 * callback's return value and errno.
887 * Obviously, this function should be OK with being called again if it
888 * fails with ENOENT or EISDIR. In other scenarios it will not be
891 typedef int create_file_fn(const char *path
, void *cb
);
894 * Create a file in dirname(path) by calling fn, creating leading
895 * directories if necessary. Retry a few times in case we are racing
896 * with another process that is trying to clean up the directory that
897 * contains path. See the documentation for create_file_fn for more
900 * Return the value and set the errno that resulted from the most
901 * recent call of fn. fn is always called at least once, and will be
902 * called more than once if it returns ENOENT or EISDIR.
904 static int raceproof_create_file(const char *path
, create_file_fn fn
, void *cb
)
907 * The number of times we will try to remove empty directories
908 * in the way of path. This is only 1 because if another
909 * process is racily creating directories that conflict with
910 * us, we don't want to fight against them.
912 int remove_directories_remaining
= 1;
915 * The number of times that we will try to create the
916 * directories containing path. We are willing to attempt this
917 * more than once, because another process could be trying to
918 * clean up empty directories at the same time as we are
919 * trying to create them.
921 int create_directories_remaining
= 3;
923 /* A scratch copy of path, filled lazily if we need it: */
924 struct strbuf path_copy
= STRBUF_INIT
;
937 if (errno
== EISDIR
&& remove_directories_remaining
-- > 0) {
939 * A directory is in the way. Maybe it is empty; try
943 strbuf_addstr(&path_copy
, path
);
945 if (!remove_dir_recursively(&path_copy
, REMOVE_DIR_EMPTY_ONLY
))
947 } else if (errno
== ENOENT
&& create_directories_remaining
-- > 0) {
949 * Maybe the containing directory didn't exist, or
950 * maybe it was just deleted by a process that is
951 * racing with us to clean up empty directories. Try
954 enum scld_error scld_result
;
957 strbuf_addstr(&path_copy
, path
);
960 scld_result
= safe_create_leading_directories(path_copy
.buf
);
961 if (scld_result
== SCLD_OK
)
963 } while (scld_result
== SCLD_VANISHED
&& create_directories_remaining
-- > 0);
967 strbuf_release(&path_copy
);
972 static int remove_empty_directories(struct strbuf
*path
)
975 * we want to create a file but there is a directory there;
976 * if that is an empty directory (or a directory that contains
977 * only empty directories), remove them.
979 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
982 static int create_reflock(const char *path
, void *cb
)
984 struct lock_file
*lk
= cb
;
986 return hold_lock_file_for_update_timeout(
987 lk
, path
, LOCK_NO_DEREF
,
988 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
992 * Locks a ref returning the lock on success and NULL on failure.
994 static struct ref_lock
*lock_ref_oid_basic(struct files_ref_store
*refs
,
995 const char *refname
, int *type
,
998 struct strbuf ref_file
= STRBUF_INIT
;
999 struct ref_lock
*lock
;
1001 files_assert_main_repository(refs
, "lock_ref_oid_basic");
1004 CALLOC_ARRAY(lock
, 1);
1006 files_ref_path(refs
, &ref_file
, refname
);
1007 if (!refs_resolve_ref_unsafe(&refs
->base
, refname
,
1008 RESOLVE_REF_NO_RECURSE
,
1009 &lock
->old_oid
, type
)) {
1010 if (!refs_verify_refname_available(&refs
->base
, refname
,
1012 strbuf_addf(err
, "unable to resolve reference '%s': %s",
1013 refname
, strerror(errno
));
1019 * If the ref did not exist and we are creating it, make sure
1020 * there is no existing packed ref whose name begins with our
1021 * refname, nor a packed ref whose name is a proper prefix of
1024 if (is_null_oid(&lock
->old_oid
) &&
1025 refs_verify_refname_available(refs
->packed_ref_store
, refname
,
1029 lock
->ref_name
= xstrdup(refname
);
1031 if (raceproof_create_file(ref_file
.buf
, create_reflock
, &lock
->lk
)) {
1032 unable_to_lock_message(ref_file
.buf
, errno
, err
);
1036 if (refs_read_ref_full(&refs
->base
, lock
->ref_name
,
1038 &lock
->old_oid
, NULL
))
1039 oidclr(&lock
->old_oid
);
1047 strbuf_release(&ref_file
);
1051 struct ref_to_prune
{
1052 struct ref_to_prune
*next
;
1053 struct object_id oid
;
1054 char name
[FLEX_ARRAY
];
1058 REMOVE_EMPTY_PARENTS_REF
= 0x01,
1059 REMOVE_EMPTY_PARENTS_REFLOG
= 0x02
1063 * Remove empty parent directories associated with the specified
1064 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1065 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1066 * REMOVE_EMPTY_PARENTS_REFLOG.
1068 static void try_remove_empty_parents(struct files_ref_store
*refs
,
1069 const char *refname
,
1072 struct strbuf buf
= STRBUF_INIT
;
1073 struct strbuf sb
= STRBUF_INIT
;
1077 strbuf_addstr(&buf
, refname
);
1079 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
1080 while (*p
&& *p
!= '/')
1082 /* tolerate duplicate slashes; see check_refname_format() */
1086 q
= buf
.buf
+ buf
.len
;
1087 while (flags
& (REMOVE_EMPTY_PARENTS_REF
| REMOVE_EMPTY_PARENTS_REFLOG
)) {
1088 while (q
> p
&& *q
!= '/')
1090 while (q
> p
&& *(q
-1) == '/')
1094 strbuf_setlen(&buf
, q
- buf
.buf
);
1097 files_ref_path(refs
, &sb
, buf
.buf
);
1098 if ((flags
& REMOVE_EMPTY_PARENTS_REF
) && rmdir(sb
.buf
))
1099 flags
&= ~REMOVE_EMPTY_PARENTS_REF
;
1102 files_reflog_path(refs
, &sb
, buf
.buf
);
1103 if ((flags
& REMOVE_EMPTY_PARENTS_REFLOG
) && rmdir(sb
.buf
))
1104 flags
&= ~REMOVE_EMPTY_PARENTS_REFLOG
;
1106 strbuf_release(&buf
);
1107 strbuf_release(&sb
);
1110 /* make sure nobody touched the ref, and unlink */
1111 static void prune_ref(struct files_ref_store
*refs
, struct ref_to_prune
*r
)
1113 struct ref_transaction
*transaction
;
1114 struct strbuf err
= STRBUF_INIT
;
1117 if (check_refname_format(r
->name
, 0))
1120 transaction
= ref_store_transaction_begin(&refs
->base
, &err
);
1123 ref_transaction_add_update(
1124 transaction
, r
->name
,
1125 REF_NO_DEREF
| REF_HAVE_NEW
| REF_HAVE_OLD
| REF_IS_PRUNING
,
1126 null_oid(), &r
->oid
, NULL
);
1127 if (ref_transaction_commit(transaction
, &err
))
1134 error("%s", err
.buf
);
1135 strbuf_release(&err
);
1136 ref_transaction_free(transaction
);
1141 * Prune the loose versions of the references in the linked list
1142 * `*refs_to_prune`, freeing the entries in the list as we go.
1144 static void prune_refs(struct files_ref_store
*refs
, struct ref_to_prune
**refs_to_prune
)
1146 while (*refs_to_prune
) {
1147 struct ref_to_prune
*r
= *refs_to_prune
;
1148 *refs_to_prune
= r
->next
;
1155 * Return true if the specified reference should be packed.
1157 static int should_pack_ref(const char *refname
,
1158 const struct object_id
*oid
, unsigned int ref_flags
,
1159 unsigned int pack_flags
)
1161 /* Do not pack per-worktree refs: */
1162 if (ref_type(refname
) != REF_TYPE_NORMAL
)
1165 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1166 if (!(pack_flags
& PACK_REFS_ALL
) && !starts_with(refname
, "refs/tags/"))
1169 /* Do not pack symbolic refs: */
1170 if (ref_flags
& REF_ISSYMREF
)
1173 /* Do not pack broken refs: */
1174 if (!ref_resolves_to_object(refname
, oid
, ref_flags
))
1180 static int files_pack_refs(struct ref_store
*ref_store
, unsigned int flags
)
1182 struct files_ref_store
*refs
=
1183 files_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_ODB
,
1185 struct ref_iterator
*iter
;
1187 struct ref_to_prune
*refs_to_prune
= NULL
;
1188 struct strbuf err
= STRBUF_INIT
;
1189 struct ref_transaction
*transaction
;
1191 transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, &err
);
1195 packed_refs_lock(refs
->packed_ref_store
, LOCK_DIE_ON_ERROR
, &err
);
1197 iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
), NULL
, 0);
1198 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
1200 * If the loose reference can be packed, add an entry
1201 * in the packed ref cache. If the reference should be
1202 * pruned, also add it to refs_to_prune.
1204 if (!should_pack_ref(iter
->refname
, iter
->oid
, iter
->flags
,
1209 * Add a reference creation for this reference to the
1210 * packed-refs transaction:
1212 if (ref_transaction_update(transaction
, iter
->refname
,
1214 REF_NO_DEREF
, NULL
, &err
))
1215 die("failure preparing to create packed reference %s: %s",
1216 iter
->refname
, err
.buf
);
1218 /* Schedule the loose reference for pruning if requested. */
1219 if ((flags
& PACK_REFS_PRUNE
)) {
1220 struct ref_to_prune
*n
;
1221 FLEX_ALLOC_STR(n
, name
, iter
->refname
);
1222 oidcpy(&n
->oid
, iter
->oid
);
1223 n
->next
= refs_to_prune
;
1227 if (ok
!= ITER_DONE
)
1228 die("error while iterating over references");
1230 if (ref_transaction_commit(transaction
, &err
))
1231 die("unable to write new packed-refs: %s", err
.buf
);
1233 ref_transaction_free(transaction
);
1235 packed_refs_unlock(refs
->packed_ref_store
);
1237 prune_refs(refs
, &refs_to_prune
);
1238 strbuf_release(&err
);
1242 static int files_delete_refs(struct ref_store
*ref_store
, const char *msg
,
1243 struct string_list
*refnames
, unsigned int flags
)
1245 struct files_ref_store
*refs
=
1246 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_refs");
1247 struct strbuf err
= STRBUF_INIT
;
1253 if (packed_refs_lock(refs
->packed_ref_store
, 0, &err
))
1256 if (refs_delete_refs(refs
->packed_ref_store
, msg
, refnames
, flags
)) {
1257 packed_refs_unlock(refs
->packed_ref_store
);
1261 packed_refs_unlock(refs
->packed_ref_store
);
1263 for (i
= 0; i
< refnames
->nr
; i
++) {
1264 const char *refname
= refnames
->items
[i
].string
;
1266 if (refs_delete_ref(&refs
->base
, msg
, refname
, NULL
, flags
))
1267 result
|= error(_("could not remove reference %s"), refname
);
1270 strbuf_release(&err
);
1275 * If we failed to rewrite the packed-refs file, then it is
1276 * unsafe to try to remove loose refs, because doing so might
1277 * expose an obsolete packed value for a reference that might
1278 * even point at an object that has been garbage collected.
1280 if (refnames
->nr
== 1)
1281 error(_("could not delete reference %s: %s"),
1282 refnames
->items
[0].string
, err
.buf
);
1284 error(_("could not delete references: %s"), err
.buf
);
1286 strbuf_release(&err
);
1291 * People using contrib's git-new-workdir have .git/logs/refs ->
1292 * /some/other/path/.git/logs/refs, and that may live on another device.
1294 * IOW, to avoid cross device rename errors, the temporary renamed log must
1295 * live into logs/refs.
1297 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1300 const char *tmp_renamed_log
;
1304 static int rename_tmp_log_callback(const char *path
, void *cb_data
)
1306 struct rename_cb
*cb
= cb_data
;
1308 if (rename(cb
->tmp_renamed_log
, path
)) {
1310 * rename(a, b) when b is an existing directory ought
1311 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1312 * Sheesh. Record the true errno for error reporting,
1313 * but report EISDIR to raceproof_create_file() so
1314 * that it knows to retry.
1316 cb
->true_errno
= errno
;
1317 if (errno
== ENOTDIR
)
1325 static int rename_tmp_log(struct files_ref_store
*refs
, const char *newrefname
)
1327 struct strbuf path
= STRBUF_INIT
;
1328 struct strbuf tmp
= STRBUF_INIT
;
1329 struct rename_cb cb
;
1332 files_reflog_path(refs
, &path
, newrefname
);
1333 files_reflog_path(refs
, &tmp
, TMP_RENAMED_LOG
);
1334 cb
.tmp_renamed_log
= tmp
.buf
;
1335 ret
= raceproof_create_file(path
.buf
, rename_tmp_log_callback
, &cb
);
1337 if (errno
== EISDIR
)
1338 error("directory not empty: %s", path
.buf
);
1340 error("unable to move logfile %s to %s: %s",
1342 strerror(cb
.true_errno
));
1345 strbuf_release(&path
);
1346 strbuf_release(&tmp
);
1350 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1351 const struct object_id
*oid
, struct strbuf
*err
);
1352 static int commit_ref_update(struct files_ref_store
*refs
,
1353 struct ref_lock
*lock
,
1354 const struct object_id
*oid
, const char *logmsg
,
1355 struct strbuf
*err
);
1357 static int files_copy_or_rename_ref(struct ref_store
*ref_store
,
1358 const char *oldrefname
, const char *newrefname
,
1359 const char *logmsg
, int copy
)
1361 struct files_ref_store
*refs
=
1362 files_downcast(ref_store
, REF_STORE_WRITE
, "rename_ref");
1363 struct object_id orig_oid
;
1364 int flag
= 0, logmoved
= 0;
1365 struct ref_lock
*lock
;
1366 struct stat loginfo
;
1367 struct strbuf sb_oldref
= STRBUF_INIT
;
1368 struct strbuf sb_newref
= STRBUF_INIT
;
1369 struct strbuf tmp_renamed_log
= STRBUF_INIT
;
1371 struct strbuf err
= STRBUF_INIT
;
1373 files_reflog_path(refs
, &sb_oldref
, oldrefname
);
1374 files_reflog_path(refs
, &sb_newref
, newrefname
);
1375 files_reflog_path(refs
, &tmp_renamed_log
, TMP_RENAMED_LOG
);
1377 log
= !lstat(sb_oldref
.buf
, &loginfo
);
1378 if (log
&& S_ISLNK(loginfo
.st_mode
)) {
1379 ret
= error("reflog for %s is a symlink", oldrefname
);
1383 if (!refs_resolve_ref_unsafe(&refs
->base
, oldrefname
,
1384 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1385 &orig_oid
, &flag
)) {
1386 ret
= error("refname %s not found", oldrefname
);
1390 if (flag
& REF_ISSYMREF
) {
1392 ret
= error("refname %s is a symbolic ref, copying it is not supported",
1395 ret
= error("refname %s is a symbolic ref, renaming it is not supported",
1399 if (!refs_rename_ref_available(&refs
->base
, oldrefname
, newrefname
)) {
1404 if (!copy
&& log
&& rename(sb_oldref
.buf
, tmp_renamed_log
.buf
)) {
1405 ret
= error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1406 oldrefname
, strerror(errno
));
1410 if (copy
&& log
&& copy_file(tmp_renamed_log
.buf
, sb_oldref
.buf
, 0644)) {
1411 ret
= error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1412 oldrefname
, strerror(errno
));
1416 if (!copy
&& refs_delete_ref(&refs
->base
, logmsg
, oldrefname
,
1417 &orig_oid
, REF_NO_DEREF
)) {
1418 error("unable to delete old %s", oldrefname
);
1423 * Since we are doing a shallow lookup, oid is not the
1424 * correct value to pass to delete_ref as old_oid. But that
1425 * doesn't matter, because an old_oid check wouldn't add to
1426 * the safety anyway; we want to delete the reference whatever
1427 * its current value.
1429 if (!copy
&& !refs_read_ref_full(&refs
->base
, newrefname
,
1430 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1432 refs_delete_ref(&refs
->base
, NULL
, newrefname
,
1433 NULL
, REF_NO_DEREF
)) {
1434 if (errno
== EISDIR
) {
1435 struct strbuf path
= STRBUF_INIT
;
1438 files_ref_path(refs
, &path
, newrefname
);
1439 result
= remove_empty_directories(&path
);
1440 strbuf_release(&path
);
1443 error("Directory not empty: %s", newrefname
);
1447 error("unable to delete existing %s", newrefname
);
1452 if (log
&& rename_tmp_log(refs
, newrefname
))
1457 lock
= lock_ref_oid_basic(refs
, newrefname
, NULL
, &err
);
1460 error("unable to copy '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1462 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1463 strbuf_release(&err
);
1466 oidcpy(&lock
->old_oid
, &orig_oid
);
1468 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1469 commit_ref_update(refs
, lock
, &orig_oid
, logmsg
, &err
)) {
1470 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
1471 strbuf_release(&err
);
1479 lock
= lock_ref_oid_basic(refs
, oldrefname
, NULL
, &err
);
1481 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
1482 strbuf_release(&err
);
1486 flag
= log_all_ref_updates
;
1487 log_all_ref_updates
= LOG_REFS_NONE
;
1488 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1489 commit_ref_update(refs
, lock
, &orig_oid
, NULL
, &err
)) {
1490 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
1491 strbuf_release(&err
);
1493 log_all_ref_updates
= flag
;
1496 if (logmoved
&& rename(sb_newref
.buf
, sb_oldref
.buf
))
1497 error("unable to restore logfile %s from %s: %s",
1498 oldrefname
, newrefname
, strerror(errno
));
1499 if (!logmoved
&& log
&&
1500 rename(tmp_renamed_log
.buf
, sb_oldref
.buf
))
1501 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG
": %s",
1502 oldrefname
, strerror(errno
));
1505 strbuf_release(&sb_newref
);
1506 strbuf_release(&sb_oldref
);
1507 strbuf_release(&tmp_renamed_log
);
1512 static int files_rename_ref(struct ref_store
*ref_store
,
1513 const char *oldrefname
, const char *newrefname
,
1516 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1517 newrefname
, logmsg
, 0);
1520 static int files_copy_ref(struct ref_store
*ref_store
,
1521 const char *oldrefname
, const char *newrefname
,
1524 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1525 newrefname
, logmsg
, 1);
1528 static int close_ref_gently(struct ref_lock
*lock
)
1530 if (close_lock_file_gently(&lock
->lk
))
1535 static int commit_ref(struct ref_lock
*lock
)
1537 char *path
= get_locked_file_path(&lock
->lk
);
1540 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
1542 * There is a directory at the path we want to rename
1543 * the lockfile to. Hopefully it is empty; try to
1546 size_t len
= strlen(path
);
1547 struct strbuf sb_path
= STRBUF_INIT
;
1549 strbuf_attach(&sb_path
, path
, len
, len
);
1552 * If this fails, commit_lock_file() will also fail
1553 * and will report the problem.
1555 remove_empty_directories(&sb_path
);
1556 strbuf_release(&sb_path
);
1561 if (commit_lock_file(&lock
->lk
))
1566 static int open_or_create_logfile(const char *path
, void *cb
)
1570 *fd
= open(path
, O_APPEND
| O_WRONLY
| O_CREAT
, 0666);
1571 return (*fd
< 0) ? -1 : 0;
1575 * Create a reflog for a ref. If force_create = 0, only create the
1576 * reflog for certain refs (those for which should_autocreate_reflog
1577 * returns non-zero). Otherwise, create it regardless of the reference
1578 * name. If the logfile already existed or was created, return 0 and
1579 * set *logfd to the file descriptor opened for appending to the file.
1580 * If no logfile exists and we decided not to create one, return 0 and
1581 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1584 static int log_ref_setup(struct files_ref_store
*refs
,
1585 const char *refname
, int force_create
,
1586 int *logfd
, struct strbuf
*err
)
1588 struct strbuf logfile_sb
= STRBUF_INIT
;
1591 files_reflog_path(refs
, &logfile_sb
, refname
);
1592 logfile
= strbuf_detach(&logfile_sb
, NULL
);
1594 if (force_create
|| should_autocreate_reflog(refname
)) {
1595 if (raceproof_create_file(logfile
, open_or_create_logfile
, logfd
)) {
1596 if (errno
== ENOENT
)
1597 strbuf_addf(err
, "unable to create directory for '%s': "
1598 "%s", logfile
, strerror(errno
));
1599 else if (errno
== EISDIR
)
1600 strbuf_addf(err
, "there are still logs under '%s'",
1603 strbuf_addf(err
, "unable to append to '%s': %s",
1604 logfile
, strerror(errno
));
1609 *logfd
= open(logfile
, O_APPEND
| O_WRONLY
);
1611 if (errno
== ENOENT
|| errno
== EISDIR
) {
1613 * The logfile doesn't already exist,
1614 * but that is not an error; it only
1615 * means that we won't write log
1620 strbuf_addf(err
, "unable to append to '%s': %s",
1621 logfile
, strerror(errno
));
1628 adjust_shared_perm(logfile
);
1638 static int files_create_reflog(struct ref_store
*ref_store
,
1639 const char *refname
, int force_create
,
1642 struct files_ref_store
*refs
=
1643 files_downcast(ref_store
, REF_STORE_WRITE
, "create_reflog");
1646 if (log_ref_setup(refs
, refname
, force_create
, &fd
, err
))
1655 static int log_ref_write_fd(int fd
, const struct object_id
*old_oid
,
1656 const struct object_id
*new_oid
,
1657 const char *committer
, const char *msg
)
1659 struct strbuf sb
= STRBUF_INIT
;
1662 strbuf_addf(&sb
, "%s %s %s", oid_to_hex(old_oid
), oid_to_hex(new_oid
), committer
);
1664 strbuf_addch(&sb
, '\t');
1665 strbuf_addstr(&sb
, msg
);
1667 strbuf_addch(&sb
, '\n');
1668 if (write_in_full(fd
, sb
.buf
, sb
.len
) < 0)
1670 strbuf_release(&sb
);
1674 static int files_log_ref_write(struct files_ref_store
*refs
,
1675 const char *refname
, const struct object_id
*old_oid
,
1676 const struct object_id
*new_oid
, const char *msg
,
1677 int flags
, struct strbuf
*err
)
1681 if (log_all_ref_updates
== LOG_REFS_UNSET
)
1682 log_all_ref_updates
= is_bare_repository() ? LOG_REFS_NONE
: LOG_REFS_NORMAL
;
1684 result
= log_ref_setup(refs
, refname
,
1685 flags
& REF_FORCE_CREATE_REFLOG
,
1693 result
= log_ref_write_fd(logfd
, old_oid
, new_oid
,
1694 git_committer_info(0), msg
);
1696 struct strbuf sb
= STRBUF_INIT
;
1697 int save_errno
= errno
;
1699 files_reflog_path(refs
, &sb
, refname
);
1700 strbuf_addf(err
, "unable to append to '%s': %s",
1701 sb
.buf
, strerror(save_errno
));
1702 strbuf_release(&sb
);
1707 struct strbuf sb
= STRBUF_INIT
;
1708 int save_errno
= errno
;
1710 files_reflog_path(refs
, &sb
, refname
);
1711 strbuf_addf(err
, "unable to append to '%s': %s",
1712 sb
.buf
, strerror(save_errno
));
1713 strbuf_release(&sb
);
1720 * Write oid into the open lockfile, then close the lockfile. On
1721 * errors, rollback the lockfile, fill in *err and return -1.
1723 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1724 const struct object_id
*oid
, struct strbuf
*err
)
1726 static char term
= '\n';
1730 o
= parse_object(the_repository
, oid
);
1733 "trying to write ref '%s' with nonexistent object %s",
1734 lock
->ref_name
, oid_to_hex(oid
));
1738 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
1740 "trying to write non-commit object %s to branch '%s'",
1741 oid_to_hex(oid
), lock
->ref_name
);
1745 fd
= get_lock_file_fd(&lock
->lk
);
1746 if (write_in_full(fd
, oid_to_hex(oid
), the_hash_algo
->hexsz
) < 0 ||
1747 write_in_full(fd
, &term
, 1) < 0 ||
1748 close_ref_gently(lock
) < 0) {
1750 "couldn't write '%s'", get_lock_file_path(&lock
->lk
));
1758 * Commit a change to a loose reference that has already been written
1759 * to the loose reference lockfile. Also update the reflogs if
1760 * necessary, using the specified lockmsg (which can be NULL).
1762 static int commit_ref_update(struct files_ref_store
*refs
,
1763 struct ref_lock
*lock
,
1764 const struct object_id
*oid
, const char *logmsg
,
1767 files_assert_main_repository(refs
, "commit_ref_update");
1769 clear_loose_ref_cache(refs
);
1770 if (files_log_ref_write(refs
, lock
->ref_name
,
1771 &lock
->old_oid
, oid
,
1773 char *old_msg
= strbuf_detach(err
, NULL
);
1774 strbuf_addf(err
, "cannot update the ref '%s': %s",
1775 lock
->ref_name
, old_msg
);
1781 if (strcmp(lock
->ref_name
, "HEAD") != 0) {
1783 * Special hack: If a branch is updated directly and HEAD
1784 * points to it (may happen on the remote side of a push
1785 * for example) then logically the HEAD reflog should be
1787 * A generic solution implies reverse symref information,
1788 * but finding all symrefs pointing to the given branch
1789 * would be rather costly for this rare event (the direct
1790 * update of a branch) to be worth it. So let's cheat and
1791 * check with HEAD only which should cover 99% of all usage
1792 * scenarios (even 100% of the default ones).
1795 const char *head_ref
;
1797 head_ref
= refs_resolve_ref_unsafe(&refs
->base
, "HEAD",
1798 RESOLVE_REF_READING
,
1800 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
1801 !strcmp(head_ref
, lock
->ref_name
)) {
1802 struct strbuf log_err
= STRBUF_INIT
;
1803 if (files_log_ref_write(refs
, "HEAD",
1804 &lock
->old_oid
, oid
,
1805 logmsg
, 0, &log_err
)) {
1806 error("%s", log_err
.buf
);
1807 strbuf_release(&log_err
);
1812 if (commit_ref(lock
)) {
1813 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
1822 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
1825 #ifndef NO_SYMLINK_HEAD
1826 char *ref_path
= get_locked_file_path(&lock
->lk
);
1828 ret
= symlink(target
, ref_path
);
1832 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
1837 static void update_symref_reflog(struct files_ref_store
*refs
,
1838 struct ref_lock
*lock
, const char *refname
,
1839 const char *target
, const char *logmsg
)
1841 struct strbuf err
= STRBUF_INIT
;
1842 struct object_id new_oid
;
1844 !refs_read_ref_full(&refs
->base
, target
,
1845 RESOLVE_REF_READING
, &new_oid
, NULL
) &&
1846 files_log_ref_write(refs
, refname
, &lock
->old_oid
,
1847 &new_oid
, logmsg
, 0, &err
)) {
1848 error("%s", err
.buf
);
1849 strbuf_release(&err
);
1853 static int create_symref_locked(struct files_ref_store
*refs
,
1854 struct ref_lock
*lock
, const char *refname
,
1855 const char *target
, const char *logmsg
)
1857 if (prefer_symlink_refs
&& !create_ref_symlink(lock
, target
)) {
1858 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1862 if (!fdopen_lock_file(&lock
->lk
, "w"))
1863 return error("unable to fdopen %s: %s",
1864 get_lock_file_path(&lock
->lk
), strerror(errno
));
1866 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1868 /* no error check; commit_ref will check ferror */
1869 fprintf(get_lock_file_fp(&lock
->lk
), "ref: %s\n", target
);
1870 if (commit_ref(lock
) < 0)
1871 return error("unable to write symref for %s: %s", refname
,
1876 static int files_create_symref(struct ref_store
*ref_store
,
1877 const char *refname
, const char *target
,
1880 struct files_ref_store
*refs
=
1881 files_downcast(ref_store
, REF_STORE_WRITE
, "create_symref");
1882 struct strbuf err
= STRBUF_INIT
;
1883 struct ref_lock
*lock
;
1886 lock
= lock_ref_oid_basic(refs
, refname
, NULL
, &err
);
1888 error("%s", err
.buf
);
1889 strbuf_release(&err
);
1893 ret
= create_symref_locked(refs
, lock
, refname
, target
, logmsg
);
1898 static int files_reflog_exists(struct ref_store
*ref_store
,
1899 const char *refname
)
1901 struct files_ref_store
*refs
=
1902 files_downcast(ref_store
, REF_STORE_READ
, "reflog_exists");
1903 struct strbuf sb
= STRBUF_INIT
;
1907 files_reflog_path(refs
, &sb
, refname
);
1908 ret
= !lstat(sb
.buf
, &st
) && S_ISREG(st
.st_mode
);
1909 strbuf_release(&sb
);
1913 static int files_delete_reflog(struct ref_store
*ref_store
,
1914 const char *refname
)
1916 struct files_ref_store
*refs
=
1917 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_reflog");
1918 struct strbuf sb
= STRBUF_INIT
;
1921 files_reflog_path(refs
, &sb
, refname
);
1922 ret
= remove_path(sb
.buf
);
1923 strbuf_release(&sb
);
1927 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
1929 struct object_id ooid
, noid
;
1930 char *email_end
, *message
;
1931 timestamp_t timestamp
;
1933 const char *p
= sb
->buf
;
1935 /* old SP new SP name <email> SP time TAB msg LF */
1936 if (!sb
->len
|| sb
->buf
[sb
->len
- 1] != '\n' ||
1937 parse_oid_hex(p
, &ooid
, &p
) || *p
++ != ' ' ||
1938 parse_oid_hex(p
, &noid
, &p
) || *p
++ != ' ' ||
1939 !(email_end
= strchr(p
, '>')) ||
1940 email_end
[1] != ' ' ||
1941 !(timestamp
= parse_timestamp(email_end
+ 2, &message
, 10)) ||
1942 !message
|| message
[0] != ' ' ||
1943 (message
[1] != '+' && message
[1] != '-') ||
1944 !isdigit(message
[2]) || !isdigit(message
[3]) ||
1945 !isdigit(message
[4]) || !isdigit(message
[5]))
1946 return 0; /* corrupt? */
1947 email_end
[1] = '\0';
1948 tz
= strtol(message
+ 1, NULL
, 10);
1949 if (message
[6] != '\t')
1953 return fn(&ooid
, &noid
, p
, timestamp
, tz
, message
, cb_data
);
1956 static char *find_beginning_of_line(char *bob
, char *scan
)
1958 while (bob
< scan
&& *(--scan
) != '\n')
1959 ; /* keep scanning backwards */
1961 * Return either beginning of the buffer, or LF at the end of
1962 * the previous line.
1967 static int files_for_each_reflog_ent_reverse(struct ref_store
*ref_store
,
1968 const char *refname
,
1969 each_reflog_ent_fn fn
,
1972 struct files_ref_store
*refs
=
1973 files_downcast(ref_store
, REF_STORE_READ
,
1974 "for_each_reflog_ent_reverse");
1975 struct strbuf sb
= STRBUF_INIT
;
1978 int ret
= 0, at_tail
= 1;
1980 files_reflog_path(refs
, &sb
, refname
);
1981 logfp
= fopen(sb
.buf
, "r");
1982 strbuf_release(&sb
);
1986 /* Jump to the end */
1987 if (fseek(logfp
, 0, SEEK_END
) < 0)
1988 ret
= error("cannot seek back reflog for %s: %s",
1989 refname
, strerror(errno
));
1991 while (!ret
&& 0 < pos
) {
1997 /* Fill next block from the end */
1998 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
1999 if (fseek(logfp
, pos
- cnt
, SEEK_SET
)) {
2000 ret
= error("cannot seek back reflog for %s: %s",
2001 refname
, strerror(errno
));
2004 nread
= fread(buf
, cnt
, 1, logfp
);
2006 ret
= error("cannot read %d bytes from reflog for %s: %s",
2007 cnt
, refname
, strerror(errno
));
2012 scanp
= endp
= buf
+ cnt
;
2013 if (at_tail
&& scanp
[-1] == '\n')
2014 /* Looking at the final LF at the end of the file */
2018 while (buf
< scanp
) {
2020 * terminating LF of the previous line, or the beginning
2025 bp
= find_beginning_of_line(buf
, scanp
);
2029 * The newline is the end of the previous line,
2030 * so we know we have complete line starting
2031 * at (bp + 1). Prefix it onto any prior data
2032 * we collected for the line and process it.
2034 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
2037 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2043 * We are at the start of the buffer, and the
2044 * start of the file; there is no previous
2045 * line, and we have everything for this one.
2046 * Process it, and we can end the loop.
2048 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2049 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2056 * We are at the start of the buffer, and there
2057 * is more file to read backwards. Which means
2058 * we are in the middle of a line. Note that we
2059 * may get here even if *bp was a newline; that
2060 * just means we are at the exact end of the
2061 * previous line, rather than some spot in the
2064 * Save away what we have to be combined with
2065 * the data from the next read.
2067 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2074 BUG("reverse reflog parser had leftover data");
2077 strbuf_release(&sb
);
2081 static int files_for_each_reflog_ent(struct ref_store
*ref_store
,
2082 const char *refname
,
2083 each_reflog_ent_fn fn
, void *cb_data
)
2085 struct files_ref_store
*refs
=
2086 files_downcast(ref_store
, REF_STORE_READ
,
2087 "for_each_reflog_ent");
2089 struct strbuf sb
= STRBUF_INIT
;
2092 files_reflog_path(refs
, &sb
, refname
);
2093 logfp
= fopen(sb
.buf
, "r");
2094 strbuf_release(&sb
);
2098 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
2099 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2101 strbuf_release(&sb
);
2105 struct files_reflog_iterator
{
2106 struct ref_iterator base
;
2108 struct ref_store
*ref_store
;
2109 struct dir_iterator
*dir_iterator
;
2110 struct object_id oid
;
2113 static int files_reflog_iterator_advance(struct ref_iterator
*ref_iterator
)
2115 struct files_reflog_iterator
*iter
=
2116 (struct files_reflog_iterator
*)ref_iterator
;
2117 struct dir_iterator
*diter
= iter
->dir_iterator
;
2120 while ((ok
= dir_iterator_advance(diter
)) == ITER_OK
) {
2123 if (!S_ISREG(diter
->st
.st_mode
))
2125 if (diter
->basename
[0] == '.')
2127 if (ends_with(diter
->basename
, ".lock"))
2130 if (refs_read_ref_full(iter
->ref_store
,
2131 diter
->relative_path
, 0,
2132 &iter
->oid
, &flags
)) {
2133 error("bad ref for %s", diter
->path
.buf
);
2137 iter
->base
.refname
= diter
->relative_path
;
2138 iter
->base
.oid
= &iter
->oid
;
2139 iter
->base
.flags
= flags
;
2143 iter
->dir_iterator
= NULL
;
2144 if (ref_iterator_abort(ref_iterator
) == ITER_ERROR
)
2149 static int files_reflog_iterator_peel(struct ref_iterator
*ref_iterator
,
2150 struct object_id
*peeled
)
2152 BUG("ref_iterator_peel() called for reflog_iterator");
2155 static int files_reflog_iterator_abort(struct ref_iterator
*ref_iterator
)
2157 struct files_reflog_iterator
*iter
=
2158 (struct files_reflog_iterator
*)ref_iterator
;
2161 if (iter
->dir_iterator
)
2162 ok
= dir_iterator_abort(iter
->dir_iterator
);
2164 base_ref_iterator_free(ref_iterator
);
2168 static struct ref_iterator_vtable files_reflog_iterator_vtable
= {
2169 files_reflog_iterator_advance
,
2170 files_reflog_iterator_peel
,
2171 files_reflog_iterator_abort
2174 static struct ref_iterator
*reflog_iterator_begin(struct ref_store
*ref_store
,
2177 struct dir_iterator
*diter
;
2178 struct files_reflog_iterator
*iter
;
2179 struct ref_iterator
*ref_iterator
;
2180 struct strbuf sb
= STRBUF_INIT
;
2182 strbuf_addf(&sb
, "%s/logs", gitdir
);
2184 diter
= dir_iterator_begin(sb
.buf
, 0);
2186 strbuf_release(&sb
);
2187 return empty_ref_iterator_begin();
2190 CALLOC_ARRAY(iter
, 1);
2191 ref_iterator
= &iter
->base
;
2193 base_ref_iterator_init(ref_iterator
, &files_reflog_iterator_vtable
, 0);
2194 iter
->dir_iterator
= diter
;
2195 iter
->ref_store
= ref_store
;
2196 strbuf_release(&sb
);
2198 return ref_iterator
;
2201 static enum iterator_selection
reflog_iterator_select(
2202 struct ref_iterator
*iter_worktree
,
2203 struct ref_iterator
*iter_common
,
2206 if (iter_worktree
) {
2208 * We're a bit loose here. We probably should ignore
2209 * common refs if they are accidentally added as
2210 * per-worktree refs.
2212 return ITER_SELECT_0
;
2213 } else if (iter_common
) {
2214 if (ref_type(iter_common
->refname
) == REF_TYPE_NORMAL
)
2215 return ITER_SELECT_1
;
2218 * The main ref store may contain main worktree's
2219 * per-worktree refs, which should be ignored
2226 static struct ref_iterator
*files_reflog_iterator_begin(struct ref_store
*ref_store
)
2228 struct files_ref_store
*refs
=
2229 files_downcast(ref_store
, REF_STORE_READ
,
2230 "reflog_iterator_begin");
2232 if (!strcmp(refs
->base
.gitdir
, refs
->gitcommondir
)) {
2233 return reflog_iterator_begin(ref_store
, refs
->gitcommondir
);
2235 return merge_ref_iterator_begin(
2236 0, reflog_iterator_begin(ref_store
, refs
->base
.gitdir
),
2237 reflog_iterator_begin(ref_store
, refs
->gitcommondir
),
2238 reflog_iterator_select
, refs
);
2243 * If update is a direct update of head_ref (the reference pointed to
2244 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2246 static int split_head_update(struct ref_update
*update
,
2247 struct ref_transaction
*transaction
,
2248 const char *head_ref
,
2249 struct string_list
*affected_refnames
,
2252 struct string_list_item
*item
;
2253 struct ref_update
*new_update
;
2255 if ((update
->flags
& REF_LOG_ONLY
) ||
2256 (update
->flags
& REF_IS_PRUNING
) ||
2257 (update
->flags
& REF_UPDATE_VIA_HEAD
))
2260 if (strcmp(update
->refname
, head_ref
))
2264 * First make sure that HEAD is not already in the
2265 * transaction. This check is O(lg N) in the transaction
2266 * size, but it happens at most once per transaction.
2268 if (string_list_has_string(affected_refnames
, "HEAD")) {
2269 /* An entry already existed */
2271 "multiple updates for 'HEAD' (including one "
2272 "via its referent '%s') are not allowed",
2274 return TRANSACTION_NAME_CONFLICT
;
2277 new_update
= ref_transaction_add_update(
2278 transaction
, "HEAD",
2279 update
->flags
| REF_LOG_ONLY
| REF_NO_DEREF
,
2280 &update
->new_oid
, &update
->old_oid
,
2284 * Add "HEAD". This insertion is O(N) in the transaction
2285 * size, but it happens at most once per transaction.
2286 * Add new_update->refname instead of a literal "HEAD".
2288 if (strcmp(new_update
->refname
, "HEAD"))
2289 BUG("%s unexpectedly not 'HEAD'", new_update
->refname
);
2290 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2291 item
->util
= new_update
;
2297 * update is for a symref that points at referent and doesn't have
2298 * REF_NO_DEREF set. Split it into two updates:
2299 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2300 * - A new, separate update for the referent reference
2301 * Note that the new update will itself be subject to splitting when
2302 * the iteration gets to it.
2304 static int split_symref_update(struct ref_update
*update
,
2305 const char *referent
,
2306 struct ref_transaction
*transaction
,
2307 struct string_list
*affected_refnames
,
2310 struct string_list_item
*item
;
2311 struct ref_update
*new_update
;
2312 unsigned int new_flags
;
2315 * First make sure that referent is not already in the
2316 * transaction. This check is O(lg N) in the transaction
2317 * size, but it happens at most once per symref in a
2320 if (string_list_has_string(affected_refnames
, referent
)) {
2321 /* An entry already exists */
2323 "multiple updates for '%s' (including one "
2324 "via symref '%s') are not allowed",
2325 referent
, update
->refname
);
2326 return TRANSACTION_NAME_CONFLICT
;
2329 new_flags
= update
->flags
;
2330 if (!strcmp(update
->refname
, "HEAD")) {
2332 * Record that the new update came via HEAD, so that
2333 * when we process it, split_head_update() doesn't try
2334 * to add another reflog update for HEAD. Note that
2335 * this bit will be propagated if the new_update
2336 * itself needs to be split.
2338 new_flags
|= REF_UPDATE_VIA_HEAD
;
2341 new_update
= ref_transaction_add_update(
2342 transaction
, referent
, new_flags
,
2343 &update
->new_oid
, &update
->old_oid
,
2346 new_update
->parent_update
= update
;
2349 * Change the symbolic ref update to log only. Also, it
2350 * doesn't need to check its old OID value, as that will be
2351 * done when new_update is processed.
2353 update
->flags
|= REF_LOG_ONLY
| REF_NO_DEREF
;
2354 update
->flags
&= ~REF_HAVE_OLD
;
2357 * Add the referent. This insertion is O(N) in the transaction
2358 * size, but it happens at most once per symref in a
2359 * transaction. Make sure to add new_update->refname, which will
2360 * be valid as long as affected_refnames is in use, and NOT
2361 * referent, which might soon be freed by our caller.
2363 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2365 BUG("%s unexpectedly found in affected_refnames",
2366 new_update
->refname
);
2367 item
->util
= new_update
;
2373 * Return the refname under which update was originally requested.
2375 static const char *original_update_refname(struct ref_update
*update
)
2377 while (update
->parent_update
)
2378 update
= update
->parent_update
;
2380 return update
->refname
;
2384 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2385 * are consistent with oid, which is the reference's current value. If
2386 * everything is OK, return 0; otherwise, write an error message to
2387 * err and return -1.
2389 static int check_old_oid(struct ref_update
*update
, struct object_id
*oid
,
2392 if (!(update
->flags
& REF_HAVE_OLD
) ||
2393 oideq(oid
, &update
->old_oid
))
2396 if (is_null_oid(&update
->old_oid
))
2397 strbuf_addf(err
, "cannot lock ref '%s': "
2398 "reference already exists",
2399 original_update_refname(update
));
2400 else if (is_null_oid(oid
))
2401 strbuf_addf(err
, "cannot lock ref '%s': "
2402 "reference is missing but expected %s",
2403 original_update_refname(update
),
2404 oid_to_hex(&update
->old_oid
));
2406 strbuf_addf(err
, "cannot lock ref '%s': "
2407 "is at %s but expected %s",
2408 original_update_refname(update
),
2410 oid_to_hex(&update
->old_oid
));
2416 * Prepare for carrying out update:
2417 * - Lock the reference referred to by update.
2418 * - Read the reference under lock.
2419 * - Check that its old OID value (if specified) is correct, and in
2420 * any case record it in update->lock->old_oid for later use when
2421 * writing the reflog.
2422 * - If it is a symref update without REF_NO_DEREF, split it up into a
2423 * REF_LOG_ONLY update of the symref and add a separate update for
2424 * the referent to transaction.
2425 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2428 static int lock_ref_for_update(struct files_ref_store
*refs
,
2429 struct ref_update
*update
,
2430 struct ref_transaction
*transaction
,
2431 const char *head_ref
,
2432 struct string_list
*affected_refnames
,
2435 struct strbuf referent
= STRBUF_INIT
;
2436 int mustexist
= (update
->flags
& REF_HAVE_OLD
) &&
2437 !is_null_oid(&update
->old_oid
);
2439 struct ref_lock
*lock
;
2441 files_assert_main_repository(refs
, "lock_ref_for_update");
2443 if ((update
->flags
& REF_HAVE_NEW
) && is_null_oid(&update
->new_oid
))
2444 update
->flags
|= REF_DELETING
;
2447 ret
= split_head_update(update
, transaction
, head_ref
,
2448 affected_refnames
, err
);
2453 ret
= lock_raw_ref(refs
, update
->refname
, mustexist
,
2456 &update
->type
, err
);
2460 reason
= strbuf_detach(err
, NULL
);
2461 strbuf_addf(err
, "cannot lock ref '%s': %s",
2462 original_update_refname(update
), reason
);
2467 update
->backend_data
= lock
;
2469 if (update
->type
& REF_ISSYMREF
) {
2470 if (update
->flags
& REF_NO_DEREF
) {
2472 * We won't be reading the referent as part of
2473 * the transaction, so we have to read it here
2474 * to record and possibly check old_oid:
2476 if (refs_read_ref_full(&refs
->base
,
2478 &lock
->old_oid
, NULL
)) {
2479 if (update
->flags
& REF_HAVE_OLD
) {
2480 strbuf_addf(err
, "cannot lock ref '%s': "
2481 "error reading reference",
2482 original_update_refname(update
));
2483 ret
= TRANSACTION_GENERIC_ERROR
;
2486 } else if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2487 ret
= TRANSACTION_GENERIC_ERROR
;
2492 * Create a new update for the reference this
2493 * symref is pointing at. Also, we will record
2494 * and verify old_oid for this update as part
2495 * of processing the split-off update, so we
2496 * don't have to do it here.
2498 ret
= split_symref_update(update
,
2499 referent
.buf
, transaction
,
2500 affected_refnames
, err
);
2505 struct ref_update
*parent_update
;
2507 if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2508 ret
= TRANSACTION_GENERIC_ERROR
;
2513 * If this update is happening indirectly because of a
2514 * symref update, record the old OID in the parent
2517 for (parent_update
= update
->parent_update
;
2519 parent_update
= parent_update
->parent_update
) {
2520 struct ref_lock
*parent_lock
= parent_update
->backend_data
;
2521 oidcpy(&parent_lock
->old_oid
, &lock
->old_oid
);
2525 if ((update
->flags
& REF_HAVE_NEW
) &&
2526 !(update
->flags
& REF_DELETING
) &&
2527 !(update
->flags
& REF_LOG_ONLY
)) {
2528 if (!(update
->type
& REF_ISSYMREF
) &&
2529 oideq(&lock
->old_oid
, &update
->new_oid
)) {
2531 * The reference already has the desired
2532 * value, so we don't need to write it.
2534 } else if (write_ref_to_lockfile(lock
, &update
->new_oid
,
2536 char *write_err
= strbuf_detach(err
, NULL
);
2539 * The lock was freed upon failure of
2540 * write_ref_to_lockfile():
2542 update
->backend_data
= NULL
;
2544 "cannot update ref '%s': %s",
2545 update
->refname
, write_err
);
2547 ret
= TRANSACTION_GENERIC_ERROR
;
2550 update
->flags
|= REF_NEEDS_COMMIT
;
2553 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
2555 * We didn't call write_ref_to_lockfile(), so
2556 * the lockfile is still open. Close it to
2557 * free up the file descriptor:
2559 if (close_ref_gently(lock
)) {
2560 strbuf_addf(err
, "couldn't close '%s.lock'",
2562 ret
= TRANSACTION_GENERIC_ERROR
;
2568 strbuf_release(&referent
);
2572 struct files_transaction_backend_data
{
2573 struct ref_transaction
*packed_transaction
;
2574 int packed_refs_locked
;
2578 * Unlock any references in `transaction` that are still locked, and
2579 * mark the transaction closed.
2581 static void files_transaction_cleanup(struct files_ref_store
*refs
,
2582 struct ref_transaction
*transaction
)
2585 struct files_transaction_backend_data
*backend_data
=
2586 transaction
->backend_data
;
2587 struct strbuf err
= STRBUF_INIT
;
2589 for (i
= 0; i
< transaction
->nr
; i
++) {
2590 struct ref_update
*update
= transaction
->updates
[i
];
2591 struct ref_lock
*lock
= update
->backend_data
;
2595 update
->backend_data
= NULL
;
2600 if (backend_data
->packed_transaction
&&
2601 ref_transaction_abort(backend_data
->packed_transaction
, &err
)) {
2602 error("error aborting transaction: %s", err
.buf
);
2603 strbuf_release(&err
);
2606 if (backend_data
->packed_refs_locked
)
2607 packed_refs_unlock(refs
->packed_ref_store
);
2612 transaction
->state
= REF_TRANSACTION_CLOSED
;
2615 static int files_transaction_prepare(struct ref_store
*ref_store
,
2616 struct ref_transaction
*transaction
,
2619 struct files_ref_store
*refs
=
2620 files_downcast(ref_store
, REF_STORE_WRITE
,
2621 "ref_transaction_prepare");
2624 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2625 char *head_ref
= NULL
;
2627 struct files_transaction_backend_data
*backend_data
;
2628 struct ref_transaction
*packed_transaction
= NULL
;
2632 if (!transaction
->nr
)
2635 CALLOC_ARRAY(backend_data
, 1);
2636 transaction
->backend_data
= backend_data
;
2639 * Fail if a refname appears more than once in the
2640 * transaction. (If we end up splitting up any updates using
2641 * split_symref_update() or split_head_update(), those
2642 * functions will check that the new updates don't have the
2643 * same refname as any existing ones.) Also fail if any of the
2644 * updates use REF_IS_PRUNING without REF_NO_DEREF.
2646 for (i
= 0; i
< transaction
->nr
; i
++) {
2647 struct ref_update
*update
= transaction
->updates
[i
];
2648 struct string_list_item
*item
=
2649 string_list_append(&affected_refnames
, update
->refname
);
2651 if ((update
->flags
& REF_IS_PRUNING
) &&
2652 !(update
->flags
& REF_NO_DEREF
))
2653 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2656 * We store a pointer to update in item->util, but at
2657 * the moment we never use the value of this field
2658 * except to check whether it is non-NULL.
2660 item
->util
= update
;
2662 string_list_sort(&affected_refnames
);
2663 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2664 ret
= TRANSACTION_GENERIC_ERROR
;
2669 * Special hack: If a branch is updated directly and HEAD
2670 * points to it (may happen on the remote side of a push
2671 * for example) then logically the HEAD reflog should be
2674 * A generic solution would require reverse symref lookups,
2675 * but finding all symrefs pointing to a given branch would be
2676 * rather costly for this rare event (the direct update of a
2677 * branch) to be worth it. So let's cheat and check with HEAD
2678 * only, which should cover 99% of all usage scenarios (even
2679 * 100% of the default ones).
2681 * So if HEAD is a symbolic reference, then record the name of
2682 * the reference that it points to. If we see an update of
2683 * head_ref within the transaction, then split_head_update()
2684 * arranges for the reflog of HEAD to be updated, too.
2686 head_ref
= refs_resolve_refdup(ref_store
, "HEAD",
2687 RESOLVE_REF_NO_RECURSE
,
2690 if (head_ref
&& !(head_type
& REF_ISSYMREF
)) {
2691 FREE_AND_NULL(head_ref
);
2695 * Acquire all locks, verify old values if provided, check
2696 * that new values are valid, and write new values to the
2697 * lockfiles, ready to be activated. Only keep one lockfile
2698 * open at a time to avoid running out of file descriptors.
2699 * Note that lock_ref_for_update() might append more updates
2700 * to the transaction.
2702 for (i
= 0; i
< transaction
->nr
; i
++) {
2703 struct ref_update
*update
= transaction
->updates
[i
];
2705 ret
= lock_ref_for_update(refs
, update
, transaction
,
2706 head_ref
, &affected_refnames
, err
);
2710 if (update
->flags
& REF_DELETING
&&
2711 !(update
->flags
& REF_LOG_ONLY
) &&
2712 !(update
->flags
& REF_IS_PRUNING
)) {
2714 * This reference has to be deleted from
2715 * packed-refs if it exists there.
2717 if (!packed_transaction
) {
2718 packed_transaction
= ref_store_transaction_begin(
2719 refs
->packed_ref_store
, err
);
2720 if (!packed_transaction
) {
2721 ret
= TRANSACTION_GENERIC_ERROR
;
2725 backend_data
->packed_transaction
=
2729 ref_transaction_add_update(
2730 packed_transaction
, update
->refname
,
2731 REF_HAVE_NEW
| REF_NO_DEREF
,
2732 &update
->new_oid
, NULL
,
2737 if (packed_transaction
) {
2738 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2739 ret
= TRANSACTION_GENERIC_ERROR
;
2742 backend_data
->packed_refs_locked
= 1;
2744 if (is_packed_transaction_needed(refs
->packed_ref_store
,
2745 packed_transaction
)) {
2746 ret
= ref_transaction_prepare(packed_transaction
, err
);
2748 * A failure during the prepare step will abort
2749 * itself, but not free. Do that now, and disconnect
2750 * from the files_transaction so it does not try to
2751 * abort us when we hit the cleanup code below.
2754 ref_transaction_free(packed_transaction
);
2755 backend_data
->packed_transaction
= NULL
;
2759 * We can skip rewriting the `packed-refs`
2760 * file. But we do need to leave it locked, so
2761 * that somebody else doesn't pack a reference
2762 * that we are trying to delete.
2764 * We need to disconnect our transaction from
2765 * backend_data, since the abort (whether successful or
2766 * not) will free it.
2768 backend_data
->packed_transaction
= NULL
;
2769 if (ref_transaction_abort(packed_transaction
, err
)) {
2770 ret
= TRANSACTION_GENERIC_ERROR
;
2778 string_list_clear(&affected_refnames
, 0);
2781 files_transaction_cleanup(refs
, transaction
);
2783 transaction
->state
= REF_TRANSACTION_PREPARED
;
2788 static int files_transaction_finish(struct ref_store
*ref_store
,
2789 struct ref_transaction
*transaction
,
2792 struct files_ref_store
*refs
=
2793 files_downcast(ref_store
, 0, "ref_transaction_finish");
2796 struct strbuf sb
= STRBUF_INIT
;
2797 struct files_transaction_backend_data
*backend_data
;
2798 struct ref_transaction
*packed_transaction
;
2803 if (!transaction
->nr
) {
2804 transaction
->state
= REF_TRANSACTION_CLOSED
;
2808 backend_data
= transaction
->backend_data
;
2809 packed_transaction
= backend_data
->packed_transaction
;
2811 /* Perform updates first so live commits remain referenced */
2812 for (i
= 0; i
< transaction
->nr
; i
++) {
2813 struct ref_update
*update
= transaction
->updates
[i
];
2814 struct ref_lock
*lock
= update
->backend_data
;
2816 if (update
->flags
& REF_NEEDS_COMMIT
||
2817 update
->flags
& REF_LOG_ONLY
) {
2818 if (files_log_ref_write(refs
,
2822 update
->msg
, update
->flags
,
2824 char *old_msg
= strbuf_detach(err
, NULL
);
2826 strbuf_addf(err
, "cannot update the ref '%s': %s",
2827 lock
->ref_name
, old_msg
);
2830 update
->backend_data
= NULL
;
2831 ret
= TRANSACTION_GENERIC_ERROR
;
2835 if (update
->flags
& REF_NEEDS_COMMIT
) {
2836 clear_loose_ref_cache(refs
);
2837 if (commit_ref(lock
)) {
2838 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
2840 update
->backend_data
= NULL
;
2841 ret
= TRANSACTION_GENERIC_ERROR
;
2848 * Now that updates are safely completed, we can perform
2849 * deletes. First delete the reflogs of any references that
2850 * will be deleted, since (in the unexpected event of an
2851 * error) leaving a reference without a reflog is less bad
2852 * than leaving a reflog without a reference (the latter is a
2853 * mildly invalid repository state):
2855 for (i
= 0; i
< transaction
->nr
; i
++) {
2856 struct ref_update
*update
= transaction
->updates
[i
];
2857 if (update
->flags
& REF_DELETING
&&
2858 !(update
->flags
& REF_LOG_ONLY
) &&
2859 !(update
->flags
& REF_IS_PRUNING
)) {
2861 files_reflog_path(refs
, &sb
, update
->refname
);
2862 if (!unlink_or_warn(sb
.buf
))
2863 try_remove_empty_parents(refs
, update
->refname
,
2864 REMOVE_EMPTY_PARENTS_REFLOG
);
2869 * Perform deletes now that updates are safely completed.
2871 * First delete any packed versions of the references, while
2872 * retaining the packed-refs lock:
2874 if (packed_transaction
) {
2875 ret
= ref_transaction_commit(packed_transaction
, err
);
2876 ref_transaction_free(packed_transaction
);
2877 packed_transaction
= NULL
;
2878 backend_data
->packed_transaction
= NULL
;
2883 /* Now delete the loose versions of the references: */
2884 for (i
= 0; i
< transaction
->nr
; i
++) {
2885 struct ref_update
*update
= transaction
->updates
[i
];
2886 struct ref_lock
*lock
= update
->backend_data
;
2888 if (update
->flags
& REF_DELETING
&&
2889 !(update
->flags
& REF_LOG_ONLY
)) {
2890 update
->flags
|= REF_DELETED_RMDIR
;
2891 if (!(update
->type
& REF_ISPACKED
) ||
2892 update
->type
& REF_ISSYMREF
) {
2893 /* It is a loose reference. */
2895 files_ref_path(refs
, &sb
, lock
->ref_name
);
2896 if (unlink_or_msg(sb
.buf
, err
)) {
2897 ret
= TRANSACTION_GENERIC_ERROR
;
2904 clear_loose_ref_cache(refs
);
2907 files_transaction_cleanup(refs
, transaction
);
2909 for (i
= 0; i
< transaction
->nr
; i
++) {
2910 struct ref_update
*update
= transaction
->updates
[i
];
2912 if (update
->flags
& REF_DELETED_RMDIR
) {
2914 * The reference was deleted. Delete any
2915 * empty parent directories. (Note that this
2916 * can only work because we have already
2917 * removed the lockfile.)
2919 try_remove_empty_parents(refs
, update
->refname
,
2920 REMOVE_EMPTY_PARENTS_REF
);
2924 strbuf_release(&sb
);
2928 static int files_transaction_abort(struct ref_store
*ref_store
,
2929 struct ref_transaction
*transaction
,
2932 struct files_ref_store
*refs
=
2933 files_downcast(ref_store
, 0, "ref_transaction_abort");
2935 files_transaction_cleanup(refs
, transaction
);
2939 static int ref_present(const char *refname
,
2940 const struct object_id
*oid
, int flags
, void *cb_data
)
2942 struct string_list
*affected_refnames
= cb_data
;
2944 return string_list_has_string(affected_refnames
, refname
);
2947 static int files_initial_transaction_commit(struct ref_store
*ref_store
,
2948 struct ref_transaction
*transaction
,
2951 struct files_ref_store
*refs
=
2952 files_downcast(ref_store
, REF_STORE_WRITE
,
2953 "initial_ref_transaction_commit");
2956 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2957 struct ref_transaction
*packed_transaction
= NULL
;
2961 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
2962 BUG("commit called for transaction that is not open");
2964 /* Fail if a refname appears more than once in the transaction: */
2965 for (i
= 0; i
< transaction
->nr
; i
++)
2966 string_list_append(&affected_refnames
,
2967 transaction
->updates
[i
]->refname
);
2968 string_list_sort(&affected_refnames
);
2969 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2970 ret
= TRANSACTION_GENERIC_ERROR
;
2975 * It's really undefined to call this function in an active
2976 * repository or when there are existing references: we are
2977 * only locking and changing packed-refs, so (1) any
2978 * simultaneous processes might try to change a reference at
2979 * the same time we do, and (2) any existing loose versions of
2980 * the references that we are setting would have precedence
2981 * over our values. But some remote helpers create the remote
2982 * "HEAD" and "master" branches before calling this function,
2983 * so here we really only check that none of the references
2984 * that we are creating already exists.
2986 if (refs_for_each_rawref(&refs
->base
, ref_present
,
2987 &affected_refnames
))
2988 BUG("initial ref transaction called with existing refs");
2990 packed_transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, err
);
2991 if (!packed_transaction
) {
2992 ret
= TRANSACTION_GENERIC_ERROR
;
2996 for (i
= 0; i
< transaction
->nr
; i
++) {
2997 struct ref_update
*update
= transaction
->updates
[i
];
2999 if ((update
->flags
& REF_HAVE_OLD
) &&
3000 !is_null_oid(&update
->old_oid
))
3001 BUG("initial ref transaction with old_sha1 set");
3002 if (refs_verify_refname_available(&refs
->base
, update
->refname
,
3003 &affected_refnames
, NULL
,
3005 ret
= TRANSACTION_NAME_CONFLICT
;
3010 * Add a reference creation for this reference to the
3011 * packed-refs transaction:
3013 ref_transaction_add_update(packed_transaction
, update
->refname
,
3014 update
->flags
& ~REF_HAVE_OLD
,
3015 &update
->new_oid
, &update
->old_oid
,
3019 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
3020 ret
= TRANSACTION_GENERIC_ERROR
;
3024 if (initial_ref_transaction_commit(packed_transaction
, err
)) {
3025 ret
= TRANSACTION_GENERIC_ERROR
;
3028 packed_refs_unlock(refs
->packed_ref_store
);
3030 if (packed_transaction
)
3031 ref_transaction_free(packed_transaction
);
3032 transaction
->state
= REF_TRANSACTION_CLOSED
;
3033 string_list_clear(&affected_refnames
, 0);
3037 struct expire_reflog_cb
{
3039 reflog_expiry_should_prune_fn
*should_prune_fn
;
3042 struct object_id last_kept_oid
;
3045 static int expire_reflog_ent(struct object_id
*ooid
, struct object_id
*noid
,
3046 const char *email
, timestamp_t timestamp
, int tz
,
3047 const char *message
, void *cb_data
)
3049 struct expire_reflog_cb
*cb
= cb_data
;
3050 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
3052 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
3053 ooid
= &cb
->last_kept_oid
;
3055 if ((*cb
->should_prune_fn
)(ooid
, noid
, email
, timestamp
, tz
,
3056 message
, policy_cb
)) {
3058 printf("would prune %s", message
);
3059 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3060 printf("prune %s", message
);
3063 fprintf(cb
->newlog
, "%s %s %s %"PRItime
" %+05d\t%s",
3064 oid_to_hex(ooid
), oid_to_hex(noid
),
3065 email
, timestamp
, tz
, message
);
3066 oidcpy(&cb
->last_kept_oid
, noid
);
3068 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3069 printf("keep %s", message
);
3074 static int files_reflog_expire(struct ref_store
*ref_store
,
3075 const char *refname
,
3077 reflog_expiry_prepare_fn prepare_fn
,
3078 reflog_expiry_should_prune_fn should_prune_fn
,
3079 reflog_expiry_cleanup_fn cleanup_fn
,
3080 void *policy_cb_data
)
3082 struct files_ref_store
*refs
=
3083 files_downcast(ref_store
, REF_STORE_WRITE
, "reflog_expire");
3084 struct lock_file reflog_lock
= LOCK_INIT
;
3085 struct expire_reflog_cb cb
;
3086 struct ref_lock
*lock
;
3087 struct strbuf log_file_sb
= STRBUF_INIT
;
3091 struct strbuf err
= STRBUF_INIT
;
3092 const struct object_id
*oid
;
3094 memset(&cb
, 0, sizeof(cb
));
3096 cb
.policy_cb
= policy_cb_data
;
3097 cb
.should_prune_fn
= should_prune_fn
;
3100 * The reflog file is locked by holding the lock on the
3101 * reference itself, plus we might need to update the
3102 * reference if --updateref was specified:
3104 lock
= lock_ref_oid_basic(refs
, refname
, &type
, &err
);
3106 error("cannot lock ref '%s': %s", refname
, err
.buf
);
3107 strbuf_release(&err
);
3110 oid
= &lock
->old_oid
;
3113 * When refs are deleted, their reflog is deleted before the
3114 * ref itself is deleted. This is because there is no separate
3115 * lock for reflog; instead we take a lock on the ref with
3116 * lock_ref_oid_basic().
3118 * If a race happens and the reflog doesn't exist after we've
3119 * acquired the lock that's OK. We've got nothing more to do;
3120 * We were asked to delete the reflog, but someone else
3121 * deleted it! The caller doesn't care that we deleted it,
3122 * just that it is deleted. So we can return successfully.
3124 if (!refs_reflog_exists(ref_store
, refname
)) {
3129 files_reflog_path(refs
, &log_file_sb
, refname
);
3130 log_file
= strbuf_detach(&log_file_sb
, NULL
);
3131 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3133 * Even though holding $GIT_DIR/logs/$reflog.lock has
3134 * no locking implications, we use the lock_file
3135 * machinery here anyway because it does a lot of the
3136 * work we need, including cleaning up if the program
3137 * exits unexpectedly.
3139 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
3140 struct strbuf err
= STRBUF_INIT
;
3141 unable_to_lock_message(log_file
, errno
, &err
);
3142 error("%s", err
.buf
);
3143 strbuf_release(&err
);
3146 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
3148 error("cannot fdopen %s (%s)",
3149 get_lock_file_path(&reflog_lock
), strerror(errno
));
3154 (*prepare_fn
)(refname
, oid
, cb
.policy_cb
);
3155 refs_for_each_reflog_ent(ref_store
, refname
, expire_reflog_ent
, &cb
);
3156 (*cleanup_fn
)(cb
.policy_cb
);
3158 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3160 * It doesn't make sense to adjust a reference pointed
3161 * to by a symbolic ref based on expiring entries in
3162 * the symbolic reference's reflog. Nor can we update
3163 * a reference if there are no remaining reflog
3166 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
3167 !(type
& REF_ISSYMREF
) &&
3168 !is_null_oid(&cb
.last_kept_oid
);
3170 if (close_lock_file_gently(&reflog_lock
)) {
3171 status
|= error("couldn't write %s: %s", log_file
,
3173 rollback_lock_file(&reflog_lock
);
3174 } else if (update
&&
3175 (write_in_full(get_lock_file_fd(&lock
->lk
),
3176 oid_to_hex(&cb
.last_kept_oid
), the_hash_algo
->hexsz
) < 0 ||
3177 write_str_in_full(get_lock_file_fd(&lock
->lk
), "\n") < 0 ||
3178 close_ref_gently(lock
) < 0)) {
3179 status
|= error("couldn't write %s",
3180 get_lock_file_path(&lock
->lk
));
3181 rollback_lock_file(&reflog_lock
);
3182 } else if (commit_lock_file(&reflog_lock
)) {
3183 status
|= error("unable to write reflog '%s' (%s)",
3184 log_file
, strerror(errno
));
3185 } else if (update
&& commit_ref(lock
)) {
3186 status
|= error("couldn't set %s", lock
->ref_name
);
3194 rollback_lock_file(&reflog_lock
);
3200 static int files_init_db(struct ref_store
*ref_store
, struct strbuf
*err
)
3202 struct files_ref_store
*refs
=
3203 files_downcast(ref_store
, REF_STORE_WRITE
, "init_db");
3204 struct strbuf sb
= STRBUF_INIT
;
3207 * Create .git/refs/{heads,tags}
3209 files_ref_path(refs
, &sb
, "refs/heads");
3210 safe_create_dir(sb
.buf
, 1);
3213 files_ref_path(refs
, &sb
, "refs/tags");
3214 safe_create_dir(sb
.buf
, 1);
3216 strbuf_release(&sb
);
3220 struct ref_storage_be refs_be_files
= {
3223 files_ref_store_create
,
3225 files_transaction_prepare
,
3226 files_transaction_finish
,
3227 files_transaction_abort
,
3228 files_initial_transaction_commit
,
3231 files_create_symref
,
3236 files_ref_iterator_begin
,
3239 files_reflog_iterator_begin
,
3240 files_for_each_reflog_ent
,
3241 files_for_each_reflog_ent_reverse
,
3242 files_reflog_exists
,
3243 files_create_reflog
,
3244 files_delete_reflog
,