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 we want to log a ref
43 * update but not actually perform it. This is used when a symbolic
44 * ref update is split up.
46 #define REF_LOG_ONLY (1 << 7)
49 * Used as a flag in ref_update::flags when the ref_update was via an
52 #define REF_UPDATE_VIA_HEAD (1 << 8)
55 * Used as a flag in ref_update::flags when the loose reference has
58 #define REF_DELETED_LOOSE (1 << 9)
63 struct object_id old_oid
;
66 struct files_ref_store
{
67 struct ref_store base
;
68 unsigned int store_flags
;
73 struct ref_cache
*loose
;
75 struct ref_store
*packed_ref_store
;
78 static void clear_loose_ref_cache(struct files_ref_store
*refs
)
81 free_ref_cache(refs
->loose
);
87 * Create a new submodule ref cache and add it to the internal
90 static struct ref_store
*files_ref_store_create(const char *gitdir
,
93 struct files_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
94 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
95 struct strbuf sb
= STRBUF_INIT
;
97 base_ref_store_init(ref_store
, &refs_be_files
);
98 refs
->store_flags
= flags
;
100 refs
->gitdir
= xstrdup(gitdir
);
101 get_common_dir_noenv(&sb
, gitdir
);
102 refs
->gitcommondir
= strbuf_detach(&sb
, NULL
);
103 strbuf_addf(&sb
, "%s/packed-refs", refs
->gitcommondir
);
104 refs
->packed_ref_store
= packed_ref_store_create(sb
.buf
, flags
);
107 chdir_notify_reparent("files-backend $GIT_DIR",
109 chdir_notify_reparent("files-backend $GIT_COMMONDIR",
110 &refs
->gitcommondir
);
116 * Die if refs is not the main ref store. caller is used in any
117 * necessary error messages.
119 static void files_assert_main_repository(struct files_ref_store
*refs
,
122 if (refs
->store_flags
& REF_STORE_MAIN
)
125 BUG("operation %s only allowed for main ref store", caller
);
129 * Downcast ref_store to files_ref_store. Die if ref_store is not a
130 * files_ref_store. required_flags is compared with ref_store's
131 * store_flags to ensure the ref_store has all required capabilities.
132 * "caller" is used in any necessary error messages.
134 static struct files_ref_store
*files_downcast(struct ref_store
*ref_store
,
135 unsigned int required_flags
,
138 struct files_ref_store
*refs
;
140 if (ref_store
->be
!= &refs_be_files
)
141 BUG("ref_store is type \"%s\" not \"files\" in %s",
142 ref_store
->be
->name
, caller
);
144 refs
= (struct files_ref_store
*)ref_store
;
146 if ((refs
->store_flags
& required_flags
) != required_flags
)
147 BUG("operation %s requires abilities 0x%x, but only have 0x%x",
148 caller
, required_flags
, refs
->store_flags
);
153 static void files_reflog_path_other_worktrees(struct files_ref_store
*refs
,
157 const char *real_ref
;
158 const char *worktree_name
;
161 if (parse_worktree_ref(refname
, &worktree_name
, &length
, &real_ref
))
162 BUG("refname %s is not a other-worktree ref", refname
);
165 strbuf_addf(sb
, "%s/worktrees/%.*s/logs/%s", refs
->gitcommondir
,
166 length
, worktree_name
, real_ref
);
168 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
,
172 static void files_reflog_path(struct files_ref_store
*refs
,
176 switch (ref_type(refname
)) {
177 case REF_TYPE_PER_WORKTREE
:
178 case REF_TYPE_PSEUDOREF
:
179 strbuf_addf(sb
, "%s/logs/%s", refs
->gitdir
, refname
);
181 case REF_TYPE_OTHER_PSEUDOREF
:
182 case REF_TYPE_MAIN_PSEUDOREF
:
183 files_reflog_path_other_worktrees(refs
, sb
, refname
);
185 case REF_TYPE_NORMAL
:
186 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
, refname
);
189 BUG("unknown ref type %d of ref %s",
190 ref_type(refname
), refname
);
194 static void files_ref_path(struct files_ref_store
*refs
,
198 switch (ref_type(refname
)) {
199 case REF_TYPE_PER_WORKTREE
:
200 case REF_TYPE_PSEUDOREF
:
201 strbuf_addf(sb
, "%s/%s", refs
->gitdir
, refname
);
203 case REF_TYPE_MAIN_PSEUDOREF
:
204 if (!skip_prefix(refname
, "main-worktree/", &refname
))
205 BUG("ref %s is not a main pseudoref", refname
);
207 case REF_TYPE_OTHER_PSEUDOREF
:
208 case REF_TYPE_NORMAL
:
209 strbuf_addf(sb
, "%s/%s", refs
->gitcommondir
, refname
);
212 BUG("unknown ref type %d of ref %s",
213 ref_type(refname
), refname
);
218 * Manually add refs/bisect, refs/rewritten and refs/worktree, which, being
219 * per-worktree, might not appear in the directory listing for
220 * refs/ in the main repo.
222 static void add_per_worktree_entries_to_dir(struct ref_dir
*dir
, const char *dirname
)
224 const char *prefixes
[] = { "refs/bisect/", "refs/worktree/", "refs/rewritten/" };
227 if (strcmp(dirname
, "refs/"))
230 for (ip
= 0; ip
< ARRAY_SIZE(prefixes
); ip
++) {
231 const char *prefix
= prefixes
[ip
];
232 int prefix_len
= strlen(prefix
);
233 struct ref_entry
*child_entry
;
236 pos
= search_ref_dir(dir
, prefix
, prefix_len
);
239 child_entry
= create_dir_entry(dir
->cache
, prefix
, prefix_len
, 1);
240 add_entry_to_dir(dir
, child_entry
);
245 * Read the loose references from the namespace dirname into dir
246 * (without recursing). dirname must end with '/'. dir must be the
247 * directory entry corresponding to dirname.
249 static void loose_fill_ref_dir(struct ref_store
*ref_store
,
250 struct ref_dir
*dir
, const char *dirname
)
252 struct files_ref_store
*refs
=
253 files_downcast(ref_store
, REF_STORE_READ
, "fill_ref_dir");
256 int dirnamelen
= strlen(dirname
);
257 struct strbuf refname
;
258 struct strbuf path
= STRBUF_INIT
;
261 files_ref_path(refs
, &path
, dirname
);
262 path_baselen
= path
.len
;
264 d
= opendir(path
.buf
);
266 strbuf_release(&path
);
270 strbuf_init(&refname
, dirnamelen
+ 257);
271 strbuf_add(&refname
, dirname
, dirnamelen
);
273 while ((de
= readdir(d
)) != NULL
) {
274 struct object_id oid
;
278 if (de
->d_name
[0] == '.')
280 if (ends_with(de
->d_name
, ".lock"))
282 strbuf_addstr(&refname
, de
->d_name
);
283 strbuf_addstr(&path
, de
->d_name
);
284 if (stat(path
.buf
, &st
) < 0) {
285 ; /* silently ignore */
286 } else if (S_ISDIR(st
.st_mode
)) {
287 strbuf_addch(&refname
, '/');
288 add_entry_to_dir(dir
,
289 create_dir_entry(dir
->cache
, refname
.buf
,
292 if (!refs_resolve_ref_unsafe(&refs
->base
,
297 flag
|= REF_ISBROKEN
;
298 } else if (is_null_oid(&oid
)) {
300 * It is so astronomically unlikely
301 * that null_oid is the OID of an
302 * actual object that we consider its
303 * appearance in a loose reference
304 * file to be repo corruption
305 * (probably due to a software bug).
307 flag
|= REF_ISBROKEN
;
310 if (check_refname_format(refname
.buf
,
311 REFNAME_ALLOW_ONELEVEL
)) {
312 if (!refname_is_safe(refname
.buf
))
313 die("loose refname is dangerous: %s", refname
.buf
);
315 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
317 add_entry_to_dir(dir
,
318 create_ref_entry(refname
.buf
, &oid
, flag
));
320 strbuf_setlen(&refname
, dirnamelen
);
321 strbuf_setlen(&path
, path_baselen
);
323 strbuf_release(&refname
);
324 strbuf_release(&path
);
327 add_per_worktree_entries_to_dir(dir
, dirname
);
330 static struct ref_cache
*get_loose_ref_cache(struct files_ref_store
*refs
)
334 * Mark the top-level directory complete because we
335 * are about to read the only subdirectory that can
338 refs
->loose
= create_ref_cache(&refs
->base
, loose_fill_ref_dir
);
340 /* We're going to fill the top level ourselves: */
341 refs
->loose
->root
->flag
&= ~REF_INCOMPLETE
;
344 * Add an incomplete entry for "refs/" (to be filled
347 add_entry_to_dir(get_ref_dir(refs
->loose
->root
),
348 create_dir_entry(refs
->loose
, "refs/", 5, 1));
353 static int files_read_raw_ref(struct ref_store
*ref_store
,
354 const char *refname
, struct object_id
*oid
,
355 struct strbuf
*referent
, unsigned int *type
)
357 struct files_ref_store
*refs
=
358 files_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
359 struct strbuf sb_contents
= STRBUF_INIT
;
360 struct strbuf sb_path
= STRBUF_INIT
;
368 int remaining_retries
= 3;
371 strbuf_reset(&sb_path
);
373 files_ref_path(refs
, &sb_path
, refname
);
379 * We might have to loop back here to avoid a race
380 * condition: first we lstat() the file, then we try
381 * to read it as a link or as a file. But if somebody
382 * changes the type of the file (file <-> directory
383 * <-> symlink) between the lstat() and reading, then
384 * we don't want to report that as an error but rather
385 * try again starting with the lstat().
387 * We'll keep a count of the retries, though, just to avoid
388 * any confusing situation sending us into an infinite loop.
391 if (remaining_retries
-- <= 0)
394 if (lstat(path
, &st
) < 0) {
397 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
,
398 oid
, referent
, type
)) {
406 /* Follow "normalized" - ie "refs/.." symlinks by hand */
407 if (S_ISLNK(st
.st_mode
)) {
408 strbuf_reset(&sb_contents
);
409 if (strbuf_readlink(&sb_contents
, path
, st
.st_size
) < 0) {
410 if (errno
== ENOENT
|| errno
== EINVAL
)
411 /* inconsistent with lstat; retry */
416 if (starts_with(sb_contents
.buf
, "refs/") &&
417 !check_refname_format(sb_contents
.buf
, 0)) {
418 strbuf_swap(&sb_contents
, referent
);
419 *type
|= REF_ISSYMREF
;
424 * It doesn't look like a refname; fall through to just
425 * treating it like a non-symlink, and reading whatever it
430 /* Is it a directory? */
431 if (S_ISDIR(st
.st_mode
)) {
433 * Even though there is a directory where the loose
434 * ref is supposed to be, there could still be a
437 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
,
438 oid
, referent
, type
)) {
447 * Anything else, just open it and try to use it as
450 fd
= open(path
, O_RDONLY
);
452 if (errno
== ENOENT
&& !S_ISLNK(st
.st_mode
))
453 /* inconsistent with lstat; retry */
458 strbuf_reset(&sb_contents
);
459 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
460 int save_errno
= errno
;
466 strbuf_rtrim(&sb_contents
);
467 buf
= sb_contents
.buf
;
468 if (skip_prefix(buf
, "ref:", &buf
)) {
469 while (isspace(*buf
))
472 strbuf_reset(referent
);
473 strbuf_addstr(referent
, buf
);
474 *type
|= REF_ISSYMREF
;
480 * Please note that FETCH_HEAD has additional
481 * data after the sha.
483 if (parse_oid_hex(buf
, oid
, &p
) ||
484 (*p
!= '\0' && !isspace(*p
))) {
485 *type
|= REF_ISBROKEN
;
494 strbuf_release(&sb_path
);
495 strbuf_release(&sb_contents
);
500 static void unlock_ref(struct ref_lock
*lock
)
502 rollback_lock_file(&lock
->lk
);
503 free(lock
->ref_name
);
508 * Lock refname, without following symrefs, and set *lock_p to point
509 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
510 * and type similarly to read_raw_ref().
512 * The caller must verify that refname is a "safe" reference name (in
513 * the sense of refname_is_safe()) before calling this function.
515 * If the reference doesn't already exist, verify that refname doesn't
516 * have a D/F conflict with any existing references. extras and skip
517 * are passed to refs_verify_refname_available() for this check.
519 * If mustexist is not set and the reference is not found or is
520 * broken, lock the reference anyway but clear old_oid.
522 * Return 0 on success. On failure, write an error message to err and
523 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
525 * Implementation note: This function is basically
530 * but it includes a lot more code to
531 * - Deal with possible races with other processes
532 * - Avoid calling refs_verify_refname_available() when it can be
533 * avoided, namely if we were successfully able to read the ref
534 * - Generate informative error messages in the case of failure
536 static int lock_raw_ref(struct files_ref_store
*refs
,
537 const char *refname
, int mustexist
,
538 const struct string_list
*extras
,
539 const struct string_list
*skip
,
540 struct ref_lock
**lock_p
,
541 struct strbuf
*referent
,
545 struct ref_lock
*lock
;
546 struct strbuf ref_file
= STRBUF_INIT
;
547 int attempts_remaining
= 3;
548 int ret
= TRANSACTION_GENERIC_ERROR
;
551 files_assert_main_repository(refs
, "lock_raw_ref");
555 /* First lock the file so it can't change out from under us. */
557 *lock_p
= lock
= xcalloc(1, sizeof(*lock
));
559 lock
->ref_name
= xstrdup(refname
);
560 files_ref_path(refs
, &ref_file
, refname
);
563 switch (safe_create_leading_directories(ref_file
.buf
)) {
568 * Suppose refname is "refs/foo/bar". We just failed
569 * to create the containing directory, "refs/foo",
570 * because there was a non-directory in the way. This
571 * indicates a D/F conflict, probably because of
572 * another reference such as "refs/foo". There is no
573 * reason to expect this error to be transitory.
575 if (refs_verify_refname_available(&refs
->base
, refname
,
576 extras
, skip
, err
)) {
579 * To the user the relevant error is
580 * that the "mustexist" reference is
584 strbuf_addf(err
, "unable to resolve reference '%s'",
588 * The error message set by
589 * refs_verify_refname_available() is
592 ret
= TRANSACTION_NAME_CONFLICT
;
596 * The file that is in the way isn't a loose
597 * reference. Report it as a low-level
600 strbuf_addf(err
, "unable to create lock file %s.lock; "
601 "non-directory in the way",
606 /* Maybe another process was tidying up. Try again. */
607 if (--attempts_remaining
> 0)
611 strbuf_addf(err
, "unable to create directory for %s",
616 if (hold_lock_file_for_update_timeout(
617 &lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
,
618 get_files_ref_lock_timeout_ms()) < 0) {
619 if (errno
== ENOENT
&& --attempts_remaining
> 0) {
621 * Maybe somebody just deleted one of the
622 * directories leading to ref_file. Try
627 unable_to_lock_message(ref_file
.buf
, errno
, err
);
633 * Now we hold the lock and can read the reference without
634 * fear that its value will change.
637 if (files_read_raw_ref(&refs
->base
, refname
,
638 &lock
->old_oid
, referent
, type
)) {
639 if (errno
== ENOENT
) {
641 /* Garden variety missing reference. */
642 strbuf_addf(err
, "unable to resolve reference '%s'",
647 * Reference is missing, but that's OK. We
648 * know that there is not a conflict with
649 * another loose reference because
650 * (supposing that we are trying to lock
651 * reference "refs/foo/bar"):
653 * - We were successfully able to create
654 * the lockfile refs/foo/bar.lock, so we
655 * know there cannot be a loose reference
658 * - We got ENOENT and not EISDIR, so we
659 * know that there cannot be a loose
660 * reference named "refs/foo/bar/baz".
663 } else if (errno
== EISDIR
) {
665 * There is a directory in the way. It might have
666 * contained references that have been deleted. If
667 * we don't require that the reference already
668 * exists, try to remove the directory so that it
669 * doesn't cause trouble when we want to rename the
670 * lockfile into place later.
673 /* Garden variety missing reference. */
674 strbuf_addf(err
, "unable to resolve reference '%s'",
677 } else if (remove_dir_recursively(&ref_file
,
678 REMOVE_DIR_EMPTY_ONLY
)) {
679 if (refs_verify_refname_available(
680 &refs
->base
, refname
,
681 extras
, skip
, err
)) {
683 * The error message set by
684 * verify_refname_available() is OK.
686 ret
= TRANSACTION_NAME_CONFLICT
;
690 * We can't delete the directory,
691 * but we also don't know of any
692 * references that it should
695 strbuf_addf(err
, "there is a non-empty directory '%s' "
696 "blocking reference '%s'",
697 ref_file
.buf
, refname
);
701 } else if (errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
702 strbuf_addf(err
, "unable to resolve reference '%s': "
703 "reference broken", refname
);
706 strbuf_addf(err
, "unable to resolve reference '%s': %s",
707 refname
, strerror(errno
));
712 * If the ref did not exist and we are creating it,
713 * make sure there is no existing packed ref that
714 * conflicts with refname:
716 if (refs_verify_refname_available(
717 refs
->packed_ref_store
, refname
,
730 strbuf_release(&ref_file
);
734 struct files_ref_iterator
{
735 struct ref_iterator base
;
737 struct ref_iterator
*iter0
;
741 static int files_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
743 struct files_ref_iterator
*iter
=
744 (struct files_ref_iterator
*)ref_iterator
;
747 while ((ok
= ref_iterator_advance(iter
->iter0
)) == ITER_OK
) {
748 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
749 ref_type(iter
->iter0
->refname
) != REF_TYPE_PER_WORKTREE
)
752 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
753 !ref_resolves_to_object(iter
->iter0
->refname
,
758 iter
->base
.refname
= iter
->iter0
->refname
;
759 iter
->base
.oid
= iter
->iter0
->oid
;
760 iter
->base
.flags
= iter
->iter0
->flags
;
765 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
771 static int files_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
772 struct object_id
*peeled
)
774 struct files_ref_iterator
*iter
=
775 (struct files_ref_iterator
*)ref_iterator
;
777 return ref_iterator_peel(iter
->iter0
, peeled
);
780 static int files_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
782 struct files_ref_iterator
*iter
=
783 (struct files_ref_iterator
*)ref_iterator
;
787 ok
= ref_iterator_abort(iter
->iter0
);
789 base_ref_iterator_free(ref_iterator
);
793 static struct ref_iterator_vtable files_ref_iterator_vtable
= {
794 files_ref_iterator_advance
,
795 files_ref_iterator_peel
,
796 files_ref_iterator_abort
799 static struct ref_iterator
*files_ref_iterator_begin(
800 struct ref_store
*ref_store
,
801 const char *prefix
, unsigned int flags
)
803 struct files_ref_store
*refs
;
804 struct ref_iterator
*loose_iter
, *packed_iter
, *overlay_iter
;
805 struct files_ref_iterator
*iter
;
806 struct ref_iterator
*ref_iterator
;
807 unsigned int required_flags
= REF_STORE_READ
;
809 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
810 required_flags
|= REF_STORE_ODB
;
812 refs
= files_downcast(ref_store
, required_flags
, "ref_iterator_begin");
815 * We must make sure that all loose refs are read before
816 * accessing the packed-refs file; this avoids a race
817 * condition if loose refs are migrated to the packed-refs
818 * file by a simultaneous process, but our in-memory view is
819 * from before the migration. We ensure this as follows:
820 * First, we call start the loose refs iteration with its
821 * `prime_ref` argument set to true. This causes the loose
822 * references in the subtree to be pre-read into the cache.
823 * (If they've already been read, that's OK; we only need to
824 * guarantee that they're read before the packed refs, not
825 * *how much* before.) After that, we call
826 * packed_ref_iterator_begin(), which internally checks
827 * whether the packed-ref cache is up to date with what is on
828 * disk, and re-reads it if not.
831 loose_iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
),
835 * The packed-refs file might contain broken references, for
836 * example an old version of a reference that points at an
837 * object that has since been garbage-collected. This is OK as
838 * long as there is a corresponding loose reference that
839 * overrides it, and we don't want to emit an error message in
840 * this case. So ask the packed_ref_store for all of its
841 * references, and (if needed) do our own check for broken
842 * ones in files_ref_iterator_advance(), after we have merged
843 * the packed and loose references.
845 packed_iter
= refs_ref_iterator_begin(
846 refs
->packed_ref_store
, prefix
, 0,
847 DO_FOR_EACH_INCLUDE_BROKEN
);
849 overlay_iter
= overlay_ref_iterator_begin(loose_iter
, packed_iter
);
851 iter
= xcalloc(1, sizeof(*iter
));
852 ref_iterator
= &iter
->base
;
853 base_ref_iterator_init(ref_iterator
, &files_ref_iterator_vtable
,
854 overlay_iter
->ordered
);
855 iter
->iter0
= overlay_iter
;
862 * Verify that the reference locked by lock has the value old_oid
863 * (unless it is NULL). Fail if the reference doesn't exist and
864 * mustexist is set. Return 0 on success. On error, write an error
865 * message to err, set errno, and return a negative value.
867 static int verify_lock(struct ref_store
*ref_store
, struct ref_lock
*lock
,
868 const struct object_id
*old_oid
, int mustexist
,
873 if (refs_read_ref_full(ref_store
, lock
->ref_name
,
874 mustexist
? RESOLVE_REF_READING
: 0,
875 &lock
->old_oid
, NULL
)) {
877 int save_errno
= errno
;
878 strbuf_addf(err
, "can't verify ref '%s'", lock
->ref_name
);
882 oidclr(&lock
->old_oid
);
886 if (old_oid
&& !oideq(&lock
->old_oid
, old_oid
)) {
887 strbuf_addf(err
, "ref '%s' is at %s but expected %s",
889 oid_to_hex(&lock
->old_oid
),
890 oid_to_hex(old_oid
));
897 static int remove_empty_directories(struct strbuf
*path
)
900 * we want to create a file but there is a directory there;
901 * if that is an empty directory (or a directory that contains
902 * only empty directories), remove them.
904 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
907 static int create_reflock(const char *path
, void *cb
)
909 struct lock_file
*lk
= cb
;
911 return hold_lock_file_for_update_timeout(
912 lk
, path
, LOCK_NO_DEREF
,
913 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
917 * Locks a ref returning the lock on success and NULL on failure.
918 * On failure errno is set to something meaningful.
920 static struct ref_lock
*lock_ref_oid_basic(struct files_ref_store
*refs
,
922 const struct object_id
*old_oid
,
923 const struct string_list
*extras
,
924 const struct string_list
*skip
,
925 unsigned int flags
, int *type
,
928 struct strbuf ref_file
= STRBUF_INIT
;
929 struct ref_lock
*lock
;
931 int mustexist
= (old_oid
&& !is_null_oid(old_oid
));
932 int resolve_flags
= RESOLVE_REF_NO_RECURSE
;
935 files_assert_main_repository(refs
, "lock_ref_oid_basic");
938 lock
= xcalloc(1, sizeof(struct ref_lock
));
941 resolve_flags
|= RESOLVE_REF_READING
;
942 if (flags
& REF_DELETING
)
943 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
945 files_ref_path(refs
, &ref_file
, refname
);
946 resolved
= !!refs_resolve_ref_unsafe(&refs
->base
,
947 refname
, resolve_flags
,
948 &lock
->old_oid
, type
);
949 if (!resolved
&& errno
== EISDIR
) {
951 * we are trying to lock foo but we used to
952 * have foo/bar which now does not exist;
953 * it is normal for the empty directory 'foo'
956 if (remove_empty_directories(&ref_file
)) {
958 if (!refs_verify_refname_available(
960 refname
, extras
, skip
, err
))
961 strbuf_addf(err
, "there are still refs under '%s'",
965 resolved
= !!refs_resolve_ref_unsafe(&refs
->base
,
966 refname
, resolve_flags
,
967 &lock
->old_oid
, type
);
971 if (last_errno
!= ENOTDIR
||
972 !refs_verify_refname_available(&refs
->base
, refname
,
974 strbuf_addf(err
, "unable to resolve reference '%s': %s",
975 refname
, strerror(last_errno
));
981 * If the ref did not exist and we are creating it, make sure
982 * there is no existing packed ref whose name begins with our
983 * refname, nor a packed ref whose name is a proper prefix of
986 if (is_null_oid(&lock
->old_oid
) &&
987 refs_verify_refname_available(refs
->packed_ref_store
, refname
,
988 extras
, skip
, err
)) {
989 last_errno
= ENOTDIR
;
993 lock
->ref_name
= xstrdup(refname
);
995 if (raceproof_create_file(ref_file
.buf
, create_reflock
, &lock
->lk
)) {
997 unable_to_lock_message(ref_file
.buf
, errno
, err
);
1001 if (verify_lock(&refs
->base
, lock
, old_oid
, mustexist
, err
)) {
1012 strbuf_release(&ref_file
);
1017 struct ref_to_prune
{
1018 struct ref_to_prune
*next
;
1019 struct object_id oid
;
1020 char name
[FLEX_ARRAY
];
1024 REMOVE_EMPTY_PARENTS_REF
= 0x01,
1025 REMOVE_EMPTY_PARENTS_REFLOG
= 0x02
1029 * Remove empty parent directories associated with the specified
1030 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1031 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1032 * REMOVE_EMPTY_PARENTS_REFLOG.
1034 static void try_remove_empty_parents(struct files_ref_store
*refs
,
1035 const char *refname
,
1038 struct strbuf buf
= STRBUF_INIT
;
1039 struct strbuf sb
= STRBUF_INIT
;
1043 strbuf_addstr(&buf
, refname
);
1045 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
1046 while (*p
&& *p
!= '/')
1048 /* tolerate duplicate slashes; see check_refname_format() */
1052 q
= buf
.buf
+ buf
.len
;
1053 while (flags
& (REMOVE_EMPTY_PARENTS_REF
| REMOVE_EMPTY_PARENTS_REFLOG
)) {
1054 while (q
> p
&& *q
!= '/')
1056 while (q
> p
&& *(q
-1) == '/')
1060 strbuf_setlen(&buf
, q
- buf
.buf
);
1063 files_ref_path(refs
, &sb
, buf
.buf
);
1064 if ((flags
& REMOVE_EMPTY_PARENTS_REF
) && rmdir(sb
.buf
))
1065 flags
&= ~REMOVE_EMPTY_PARENTS_REF
;
1068 files_reflog_path(refs
, &sb
, buf
.buf
);
1069 if ((flags
& REMOVE_EMPTY_PARENTS_REFLOG
) && rmdir(sb
.buf
))
1070 flags
&= ~REMOVE_EMPTY_PARENTS_REFLOG
;
1072 strbuf_release(&buf
);
1073 strbuf_release(&sb
);
1076 /* make sure nobody touched the ref, and unlink */
1077 static void prune_ref(struct files_ref_store
*refs
, struct ref_to_prune
*r
)
1079 struct ref_transaction
*transaction
;
1080 struct strbuf err
= STRBUF_INIT
;
1083 if (check_refname_format(r
->name
, 0))
1086 transaction
= ref_store_transaction_begin(&refs
->base
, &err
);
1089 ref_transaction_add_update(
1090 transaction
, r
->name
,
1091 REF_NO_DEREF
| REF_HAVE_NEW
| REF_HAVE_OLD
| REF_IS_PRUNING
,
1092 &null_oid
, &r
->oid
, NULL
);
1093 if (ref_transaction_commit(transaction
, &err
))
1100 error("%s", err
.buf
);
1101 strbuf_release(&err
);
1102 ref_transaction_free(transaction
);
1107 * Prune the loose versions of the references in the linked list
1108 * `*refs_to_prune`, freeing the entries in the list as we go.
1110 static void prune_refs(struct files_ref_store
*refs
, struct ref_to_prune
**refs_to_prune
)
1112 while (*refs_to_prune
) {
1113 struct ref_to_prune
*r
= *refs_to_prune
;
1114 *refs_to_prune
= r
->next
;
1121 * Return true if the specified reference should be packed.
1123 static int should_pack_ref(const char *refname
,
1124 const struct object_id
*oid
, unsigned int ref_flags
,
1125 unsigned int pack_flags
)
1127 /* Do not pack per-worktree refs: */
1128 if (ref_type(refname
) != REF_TYPE_NORMAL
)
1131 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1132 if (!(pack_flags
& PACK_REFS_ALL
) && !starts_with(refname
, "refs/tags/"))
1135 /* Do not pack symbolic refs: */
1136 if (ref_flags
& REF_ISSYMREF
)
1139 /* Do not pack broken refs: */
1140 if (!ref_resolves_to_object(refname
, oid
, ref_flags
))
1146 static int files_pack_refs(struct ref_store
*ref_store
, unsigned int flags
)
1148 struct files_ref_store
*refs
=
1149 files_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_ODB
,
1151 struct ref_iterator
*iter
;
1153 struct ref_to_prune
*refs_to_prune
= NULL
;
1154 struct strbuf err
= STRBUF_INIT
;
1155 struct ref_transaction
*transaction
;
1157 transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, &err
);
1161 packed_refs_lock(refs
->packed_ref_store
, LOCK_DIE_ON_ERROR
, &err
);
1163 iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
), NULL
, 0);
1164 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
1166 * If the loose reference can be packed, add an entry
1167 * in the packed ref cache. If the reference should be
1168 * pruned, also add it to refs_to_prune.
1170 if (!should_pack_ref(iter
->refname
, iter
->oid
, iter
->flags
,
1175 * Add a reference creation for this reference to the
1176 * packed-refs transaction:
1178 if (ref_transaction_update(transaction
, iter
->refname
,
1180 REF_NO_DEREF
, NULL
, &err
))
1181 die("failure preparing to create packed reference %s: %s",
1182 iter
->refname
, err
.buf
);
1184 /* Schedule the loose reference for pruning if requested. */
1185 if ((flags
& PACK_REFS_PRUNE
)) {
1186 struct ref_to_prune
*n
;
1187 FLEX_ALLOC_STR(n
, name
, iter
->refname
);
1188 oidcpy(&n
->oid
, iter
->oid
);
1189 n
->next
= refs_to_prune
;
1193 if (ok
!= ITER_DONE
)
1194 die("error while iterating over references");
1196 if (ref_transaction_commit(transaction
, &err
))
1197 die("unable to write new packed-refs: %s", err
.buf
);
1199 ref_transaction_free(transaction
);
1201 packed_refs_unlock(refs
->packed_ref_store
);
1203 prune_refs(refs
, &refs_to_prune
);
1204 strbuf_release(&err
);
1208 static int files_delete_refs(struct ref_store
*ref_store
, const char *msg
,
1209 struct string_list
*refnames
, unsigned int flags
)
1211 struct files_ref_store
*refs
=
1212 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_refs");
1213 struct strbuf err
= STRBUF_INIT
;
1219 if (packed_refs_lock(refs
->packed_ref_store
, 0, &err
))
1222 if (refs_delete_refs(refs
->packed_ref_store
, msg
, refnames
, flags
)) {
1223 packed_refs_unlock(refs
->packed_ref_store
);
1227 packed_refs_unlock(refs
->packed_ref_store
);
1229 for (i
= 0; i
< refnames
->nr
; i
++) {
1230 const char *refname
= refnames
->items
[i
].string
;
1232 if (refs_delete_ref(&refs
->base
, msg
, refname
, NULL
, flags
))
1233 result
|= error(_("could not remove reference %s"), refname
);
1236 strbuf_release(&err
);
1241 * If we failed to rewrite the packed-refs file, then it is
1242 * unsafe to try to remove loose refs, because doing so might
1243 * expose an obsolete packed value for a reference that might
1244 * even point at an object that has been garbage collected.
1246 if (refnames
->nr
== 1)
1247 error(_("could not delete reference %s: %s"),
1248 refnames
->items
[0].string
, err
.buf
);
1250 error(_("could not delete references: %s"), err
.buf
);
1252 strbuf_release(&err
);
1257 * People using contrib's git-new-workdir have .git/logs/refs ->
1258 * /some/other/path/.git/logs/refs, and that may live on another device.
1260 * IOW, to avoid cross device rename errors, the temporary renamed log must
1261 * live into logs/refs.
1263 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1266 const char *tmp_renamed_log
;
1270 static int rename_tmp_log_callback(const char *path
, void *cb_data
)
1272 struct rename_cb
*cb
= cb_data
;
1274 if (rename(cb
->tmp_renamed_log
, path
)) {
1276 * rename(a, b) when b is an existing directory ought
1277 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1278 * Sheesh. Record the true errno for error reporting,
1279 * but report EISDIR to raceproof_create_file() so
1280 * that it knows to retry.
1282 cb
->true_errno
= errno
;
1283 if (errno
== ENOTDIR
)
1291 static int rename_tmp_log(struct files_ref_store
*refs
, const char *newrefname
)
1293 struct strbuf path
= STRBUF_INIT
;
1294 struct strbuf tmp
= STRBUF_INIT
;
1295 struct rename_cb cb
;
1298 files_reflog_path(refs
, &path
, newrefname
);
1299 files_reflog_path(refs
, &tmp
, TMP_RENAMED_LOG
);
1300 cb
.tmp_renamed_log
= tmp
.buf
;
1301 ret
= raceproof_create_file(path
.buf
, rename_tmp_log_callback
, &cb
);
1303 if (errno
== EISDIR
)
1304 error("directory not empty: %s", path
.buf
);
1306 error("unable to move logfile %s to %s: %s",
1308 strerror(cb
.true_errno
));
1311 strbuf_release(&path
);
1312 strbuf_release(&tmp
);
1316 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1317 const struct object_id
*oid
, struct strbuf
*err
);
1318 static int commit_ref_update(struct files_ref_store
*refs
,
1319 struct ref_lock
*lock
,
1320 const struct object_id
*oid
, const char *logmsg
,
1321 struct strbuf
*err
);
1323 static int files_copy_or_rename_ref(struct ref_store
*ref_store
,
1324 const char *oldrefname
, const char *newrefname
,
1325 const char *logmsg
, int copy
)
1327 struct files_ref_store
*refs
=
1328 files_downcast(ref_store
, REF_STORE_WRITE
, "rename_ref");
1329 struct object_id orig_oid
;
1330 int flag
= 0, logmoved
= 0;
1331 struct ref_lock
*lock
;
1332 struct stat loginfo
;
1333 struct strbuf sb_oldref
= STRBUF_INIT
;
1334 struct strbuf sb_newref
= STRBUF_INIT
;
1335 struct strbuf tmp_renamed_log
= STRBUF_INIT
;
1337 struct strbuf err
= STRBUF_INIT
;
1339 files_reflog_path(refs
, &sb_oldref
, oldrefname
);
1340 files_reflog_path(refs
, &sb_newref
, newrefname
);
1341 files_reflog_path(refs
, &tmp_renamed_log
, TMP_RENAMED_LOG
);
1343 log
= !lstat(sb_oldref
.buf
, &loginfo
);
1344 if (log
&& S_ISLNK(loginfo
.st_mode
)) {
1345 ret
= error("reflog for %s is a symlink", oldrefname
);
1349 if (!refs_resolve_ref_unsafe(&refs
->base
, oldrefname
,
1350 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1351 &orig_oid
, &flag
)) {
1352 ret
= error("refname %s not found", oldrefname
);
1356 if (flag
& REF_ISSYMREF
) {
1358 ret
= error("refname %s is a symbolic ref, copying it is not supported",
1361 ret
= error("refname %s is a symbolic ref, renaming it is not supported",
1365 if (!refs_rename_ref_available(&refs
->base
, oldrefname
, newrefname
)) {
1370 if (!copy
&& log
&& rename(sb_oldref
.buf
, tmp_renamed_log
.buf
)) {
1371 ret
= error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1372 oldrefname
, strerror(errno
));
1376 if (copy
&& log
&& copy_file(tmp_renamed_log
.buf
, sb_oldref
.buf
, 0644)) {
1377 ret
= error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1378 oldrefname
, strerror(errno
));
1382 if (!copy
&& refs_delete_ref(&refs
->base
, logmsg
, oldrefname
,
1383 &orig_oid
, REF_NO_DEREF
)) {
1384 error("unable to delete old %s", oldrefname
);
1389 * Since we are doing a shallow lookup, oid is not the
1390 * correct value to pass to delete_ref as old_oid. But that
1391 * doesn't matter, because an old_oid check wouldn't add to
1392 * the safety anyway; we want to delete the reference whatever
1393 * its current value.
1395 if (!copy
&& !refs_read_ref_full(&refs
->base
, newrefname
,
1396 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1398 refs_delete_ref(&refs
->base
, NULL
, newrefname
,
1399 NULL
, REF_NO_DEREF
)) {
1400 if (errno
== EISDIR
) {
1401 struct strbuf path
= STRBUF_INIT
;
1404 files_ref_path(refs
, &path
, newrefname
);
1405 result
= remove_empty_directories(&path
);
1406 strbuf_release(&path
);
1409 error("Directory not empty: %s", newrefname
);
1413 error("unable to delete existing %s", newrefname
);
1418 if (log
&& rename_tmp_log(refs
, newrefname
))
1423 lock
= lock_ref_oid_basic(refs
, newrefname
, NULL
, NULL
, NULL
,
1424 REF_NO_DEREF
, NULL
, &err
);
1427 error("unable to copy '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1429 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1430 strbuf_release(&err
);
1433 oidcpy(&lock
->old_oid
, &orig_oid
);
1435 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1436 commit_ref_update(refs
, lock
, &orig_oid
, logmsg
, &err
)) {
1437 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
1438 strbuf_release(&err
);
1446 lock
= lock_ref_oid_basic(refs
, oldrefname
, NULL
, NULL
, NULL
,
1447 REF_NO_DEREF
, NULL
, &err
);
1449 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
1450 strbuf_release(&err
);
1454 flag
= log_all_ref_updates
;
1455 log_all_ref_updates
= LOG_REFS_NONE
;
1456 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1457 commit_ref_update(refs
, lock
, &orig_oid
, NULL
, &err
)) {
1458 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
1459 strbuf_release(&err
);
1461 log_all_ref_updates
= flag
;
1464 if (logmoved
&& rename(sb_newref
.buf
, sb_oldref
.buf
))
1465 error("unable to restore logfile %s from %s: %s",
1466 oldrefname
, newrefname
, strerror(errno
));
1467 if (!logmoved
&& log
&&
1468 rename(tmp_renamed_log
.buf
, sb_oldref
.buf
))
1469 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG
": %s",
1470 oldrefname
, strerror(errno
));
1473 strbuf_release(&sb_newref
);
1474 strbuf_release(&sb_oldref
);
1475 strbuf_release(&tmp_renamed_log
);
1480 static int files_rename_ref(struct ref_store
*ref_store
,
1481 const char *oldrefname
, const char *newrefname
,
1484 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1485 newrefname
, logmsg
, 0);
1488 static int files_copy_ref(struct ref_store
*ref_store
,
1489 const char *oldrefname
, const char *newrefname
,
1492 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1493 newrefname
, logmsg
, 1);
1496 static int close_ref_gently(struct ref_lock
*lock
)
1498 if (close_lock_file_gently(&lock
->lk
))
1503 static int commit_ref(struct ref_lock
*lock
)
1505 char *path
= get_locked_file_path(&lock
->lk
);
1508 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
1510 * There is a directory at the path we want to rename
1511 * the lockfile to. Hopefully it is empty; try to
1514 size_t len
= strlen(path
);
1515 struct strbuf sb_path
= STRBUF_INIT
;
1517 strbuf_attach(&sb_path
, path
, len
, len
);
1520 * If this fails, commit_lock_file() will also fail
1521 * and will report the problem.
1523 remove_empty_directories(&sb_path
);
1524 strbuf_release(&sb_path
);
1529 if (commit_lock_file(&lock
->lk
))
1534 static int open_or_create_logfile(const char *path
, void *cb
)
1538 *fd
= open(path
, O_APPEND
| O_WRONLY
| O_CREAT
, 0666);
1539 return (*fd
< 0) ? -1 : 0;
1543 * Create a reflog for a ref. If force_create = 0, only create the
1544 * reflog for certain refs (those for which should_autocreate_reflog
1545 * returns non-zero). Otherwise, create it regardless of the reference
1546 * name. If the logfile already existed or was created, return 0 and
1547 * set *logfd to the file descriptor opened for appending to the file.
1548 * If no logfile exists and we decided not to create one, return 0 and
1549 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1552 static int log_ref_setup(struct files_ref_store
*refs
,
1553 const char *refname
, int force_create
,
1554 int *logfd
, struct strbuf
*err
)
1556 struct strbuf logfile_sb
= STRBUF_INIT
;
1559 files_reflog_path(refs
, &logfile_sb
, refname
);
1560 logfile
= strbuf_detach(&logfile_sb
, NULL
);
1562 if (force_create
|| should_autocreate_reflog(refname
)) {
1563 if (raceproof_create_file(logfile
, open_or_create_logfile
, logfd
)) {
1564 if (errno
== ENOENT
)
1565 strbuf_addf(err
, "unable to create directory for '%s': "
1566 "%s", logfile
, strerror(errno
));
1567 else if (errno
== EISDIR
)
1568 strbuf_addf(err
, "there are still logs under '%s'",
1571 strbuf_addf(err
, "unable to append to '%s': %s",
1572 logfile
, strerror(errno
));
1577 *logfd
= open(logfile
, O_APPEND
| O_WRONLY
, 0666);
1579 if (errno
== ENOENT
|| errno
== EISDIR
) {
1581 * The logfile doesn't already exist,
1582 * but that is not an error; it only
1583 * means that we won't write log
1588 strbuf_addf(err
, "unable to append to '%s': %s",
1589 logfile
, strerror(errno
));
1596 adjust_shared_perm(logfile
);
1606 static int files_create_reflog(struct ref_store
*ref_store
,
1607 const char *refname
, int force_create
,
1610 struct files_ref_store
*refs
=
1611 files_downcast(ref_store
, REF_STORE_WRITE
, "create_reflog");
1614 if (log_ref_setup(refs
, refname
, force_create
, &fd
, err
))
1623 static int log_ref_write_fd(int fd
, const struct object_id
*old_oid
,
1624 const struct object_id
*new_oid
,
1625 const char *committer
, const char *msg
)
1627 struct strbuf sb
= STRBUF_INIT
;
1630 strbuf_addf(&sb
, "%s %s %s", oid_to_hex(old_oid
), oid_to_hex(new_oid
), committer
);
1632 copy_reflog_msg(&sb
, msg
);
1633 strbuf_addch(&sb
, '\n');
1634 if (write_in_full(fd
, sb
.buf
, sb
.len
) < 0)
1636 strbuf_release(&sb
);
1640 static int files_log_ref_write(struct files_ref_store
*refs
,
1641 const char *refname
, const struct object_id
*old_oid
,
1642 const struct object_id
*new_oid
, const char *msg
,
1643 int flags
, struct strbuf
*err
)
1647 if (log_all_ref_updates
== LOG_REFS_UNSET
)
1648 log_all_ref_updates
= is_bare_repository() ? LOG_REFS_NONE
: LOG_REFS_NORMAL
;
1650 result
= log_ref_setup(refs
, refname
,
1651 flags
& REF_FORCE_CREATE_REFLOG
,
1659 result
= log_ref_write_fd(logfd
, old_oid
, new_oid
,
1660 git_committer_info(0), msg
);
1662 struct strbuf sb
= STRBUF_INIT
;
1663 int save_errno
= errno
;
1665 files_reflog_path(refs
, &sb
, refname
);
1666 strbuf_addf(err
, "unable to append to '%s': %s",
1667 sb
.buf
, strerror(save_errno
));
1668 strbuf_release(&sb
);
1673 struct strbuf sb
= STRBUF_INIT
;
1674 int save_errno
= errno
;
1676 files_reflog_path(refs
, &sb
, refname
);
1677 strbuf_addf(err
, "unable to append to '%s': %s",
1678 sb
.buf
, strerror(save_errno
));
1679 strbuf_release(&sb
);
1686 * Write oid into the open lockfile, then close the lockfile. On
1687 * errors, rollback the lockfile, fill in *err and return -1.
1689 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1690 const struct object_id
*oid
, struct strbuf
*err
)
1692 static char term
= '\n';
1696 o
= parse_object(the_repository
, oid
);
1699 "trying to write ref '%s' with nonexistent object %s",
1700 lock
->ref_name
, oid_to_hex(oid
));
1704 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
1706 "trying to write non-commit object %s to branch '%s'",
1707 oid_to_hex(oid
), lock
->ref_name
);
1711 fd
= get_lock_file_fd(&lock
->lk
);
1712 if (write_in_full(fd
, oid_to_hex(oid
), the_hash_algo
->hexsz
) < 0 ||
1713 write_in_full(fd
, &term
, 1) < 0 ||
1714 close_ref_gently(lock
) < 0) {
1716 "couldn't write '%s'", get_lock_file_path(&lock
->lk
));
1724 * Commit a change to a loose reference that has already been written
1725 * to the loose reference lockfile. Also update the reflogs if
1726 * necessary, using the specified lockmsg (which can be NULL).
1728 static int commit_ref_update(struct files_ref_store
*refs
,
1729 struct ref_lock
*lock
,
1730 const struct object_id
*oid
, const char *logmsg
,
1733 files_assert_main_repository(refs
, "commit_ref_update");
1735 clear_loose_ref_cache(refs
);
1736 if (files_log_ref_write(refs
, lock
->ref_name
,
1737 &lock
->old_oid
, oid
,
1739 char *old_msg
= strbuf_detach(err
, NULL
);
1740 strbuf_addf(err
, "cannot update the ref '%s': %s",
1741 lock
->ref_name
, old_msg
);
1747 if (strcmp(lock
->ref_name
, "HEAD") != 0) {
1749 * Special hack: If a branch is updated directly and HEAD
1750 * points to it (may happen on the remote side of a push
1751 * for example) then logically the HEAD reflog should be
1753 * A generic solution implies reverse symref information,
1754 * but finding all symrefs pointing to the given branch
1755 * would be rather costly for this rare event (the direct
1756 * update of a branch) to be worth it. So let's cheat and
1757 * check with HEAD only which should cover 99% of all usage
1758 * scenarios (even 100% of the default ones).
1761 const char *head_ref
;
1763 head_ref
= refs_resolve_ref_unsafe(&refs
->base
, "HEAD",
1764 RESOLVE_REF_READING
,
1766 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
1767 !strcmp(head_ref
, lock
->ref_name
)) {
1768 struct strbuf log_err
= STRBUF_INIT
;
1769 if (files_log_ref_write(refs
, "HEAD",
1770 &lock
->old_oid
, oid
,
1771 logmsg
, 0, &log_err
)) {
1772 error("%s", log_err
.buf
);
1773 strbuf_release(&log_err
);
1778 if (commit_ref(lock
)) {
1779 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
1788 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
1791 #ifndef NO_SYMLINK_HEAD
1792 char *ref_path
= get_locked_file_path(&lock
->lk
);
1794 ret
= symlink(target
, ref_path
);
1798 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
1803 static void update_symref_reflog(struct files_ref_store
*refs
,
1804 struct ref_lock
*lock
, const char *refname
,
1805 const char *target
, const char *logmsg
)
1807 struct strbuf err
= STRBUF_INIT
;
1808 struct object_id new_oid
;
1810 !refs_read_ref_full(&refs
->base
, target
,
1811 RESOLVE_REF_READING
, &new_oid
, NULL
) &&
1812 files_log_ref_write(refs
, refname
, &lock
->old_oid
,
1813 &new_oid
, logmsg
, 0, &err
)) {
1814 error("%s", err
.buf
);
1815 strbuf_release(&err
);
1819 static int create_symref_locked(struct files_ref_store
*refs
,
1820 struct ref_lock
*lock
, const char *refname
,
1821 const char *target
, const char *logmsg
)
1823 if (prefer_symlink_refs
&& !create_ref_symlink(lock
, target
)) {
1824 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1828 if (!fdopen_lock_file(&lock
->lk
, "w"))
1829 return error("unable to fdopen %s: %s",
1830 lock
->lk
.tempfile
->filename
.buf
, strerror(errno
));
1832 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1834 /* no error check; commit_ref will check ferror */
1835 fprintf(lock
->lk
.tempfile
->fp
, "ref: %s\n", target
);
1836 if (commit_ref(lock
) < 0)
1837 return error("unable to write symref for %s: %s", refname
,
1842 static int files_create_symref(struct ref_store
*ref_store
,
1843 const char *refname
, const char *target
,
1846 struct files_ref_store
*refs
=
1847 files_downcast(ref_store
, REF_STORE_WRITE
, "create_symref");
1848 struct strbuf err
= STRBUF_INIT
;
1849 struct ref_lock
*lock
;
1852 lock
= lock_ref_oid_basic(refs
, refname
, NULL
,
1853 NULL
, NULL
, REF_NO_DEREF
, NULL
,
1856 error("%s", err
.buf
);
1857 strbuf_release(&err
);
1861 ret
= create_symref_locked(refs
, lock
, refname
, target
, logmsg
);
1866 static int files_reflog_exists(struct ref_store
*ref_store
,
1867 const char *refname
)
1869 struct files_ref_store
*refs
=
1870 files_downcast(ref_store
, REF_STORE_READ
, "reflog_exists");
1871 struct strbuf sb
= STRBUF_INIT
;
1875 files_reflog_path(refs
, &sb
, refname
);
1876 ret
= !lstat(sb
.buf
, &st
) && S_ISREG(st
.st_mode
);
1877 strbuf_release(&sb
);
1881 static int files_delete_reflog(struct ref_store
*ref_store
,
1882 const char *refname
)
1884 struct files_ref_store
*refs
=
1885 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_reflog");
1886 struct strbuf sb
= STRBUF_INIT
;
1889 files_reflog_path(refs
, &sb
, refname
);
1890 ret
= remove_path(sb
.buf
);
1891 strbuf_release(&sb
);
1895 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
1897 struct object_id ooid
, noid
;
1898 char *email_end
, *message
;
1899 timestamp_t timestamp
;
1901 const char *p
= sb
->buf
;
1903 /* old SP new SP name <email> SP time TAB msg LF */
1904 if (!sb
->len
|| sb
->buf
[sb
->len
- 1] != '\n' ||
1905 parse_oid_hex(p
, &ooid
, &p
) || *p
++ != ' ' ||
1906 parse_oid_hex(p
, &noid
, &p
) || *p
++ != ' ' ||
1907 !(email_end
= strchr(p
, '>')) ||
1908 email_end
[1] != ' ' ||
1909 !(timestamp
= parse_timestamp(email_end
+ 2, &message
, 10)) ||
1910 !message
|| message
[0] != ' ' ||
1911 (message
[1] != '+' && message
[1] != '-') ||
1912 !isdigit(message
[2]) || !isdigit(message
[3]) ||
1913 !isdigit(message
[4]) || !isdigit(message
[5]))
1914 return 0; /* corrupt? */
1915 email_end
[1] = '\0';
1916 tz
= strtol(message
+ 1, NULL
, 10);
1917 if (message
[6] != '\t')
1921 return fn(&ooid
, &noid
, p
, timestamp
, tz
, message
, cb_data
);
1924 static char *find_beginning_of_line(char *bob
, char *scan
)
1926 while (bob
< scan
&& *(--scan
) != '\n')
1927 ; /* keep scanning backwards */
1929 * Return either beginning of the buffer, or LF at the end of
1930 * the previous line.
1935 static int files_for_each_reflog_ent_reverse(struct ref_store
*ref_store
,
1936 const char *refname
,
1937 each_reflog_ent_fn fn
,
1940 struct files_ref_store
*refs
=
1941 files_downcast(ref_store
, REF_STORE_READ
,
1942 "for_each_reflog_ent_reverse");
1943 struct strbuf sb
= STRBUF_INIT
;
1946 int ret
= 0, at_tail
= 1;
1948 files_reflog_path(refs
, &sb
, refname
);
1949 logfp
= fopen(sb
.buf
, "r");
1950 strbuf_release(&sb
);
1954 /* Jump to the end */
1955 if (fseek(logfp
, 0, SEEK_END
) < 0)
1956 ret
= error("cannot seek back reflog for %s: %s",
1957 refname
, strerror(errno
));
1959 while (!ret
&& 0 < pos
) {
1965 /* Fill next block from the end */
1966 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
1967 if (fseek(logfp
, pos
- cnt
, SEEK_SET
)) {
1968 ret
= error("cannot seek back reflog for %s: %s",
1969 refname
, strerror(errno
));
1972 nread
= fread(buf
, cnt
, 1, logfp
);
1974 ret
= error("cannot read %d bytes from reflog for %s: %s",
1975 cnt
, refname
, strerror(errno
));
1980 scanp
= endp
= buf
+ cnt
;
1981 if (at_tail
&& scanp
[-1] == '\n')
1982 /* Looking at the final LF at the end of the file */
1986 while (buf
< scanp
) {
1988 * terminating LF of the previous line, or the beginning
1993 bp
= find_beginning_of_line(buf
, scanp
);
1997 * The newline is the end of the previous line,
1998 * so we know we have complete line starting
1999 * at (bp + 1). Prefix it onto any prior data
2000 * we collected for the line and process it.
2002 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
2005 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2011 * We are at the start of the buffer, and the
2012 * start of the file; there is no previous
2013 * line, and we have everything for this one.
2014 * Process it, and we can end the loop.
2016 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2017 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2024 * We are at the start of the buffer, and there
2025 * is more file to read backwards. Which means
2026 * we are in the middle of a line. Note that we
2027 * may get here even if *bp was a newline; that
2028 * just means we are at the exact end of the
2029 * previous line, rather than some spot in the
2032 * Save away what we have to be combined with
2033 * the data from the next read.
2035 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2042 BUG("reverse reflog parser had leftover data");
2045 strbuf_release(&sb
);
2049 static int files_for_each_reflog_ent(struct ref_store
*ref_store
,
2050 const char *refname
,
2051 each_reflog_ent_fn fn
, void *cb_data
)
2053 struct files_ref_store
*refs
=
2054 files_downcast(ref_store
, REF_STORE_READ
,
2055 "for_each_reflog_ent");
2057 struct strbuf sb
= STRBUF_INIT
;
2060 files_reflog_path(refs
, &sb
, refname
);
2061 logfp
= fopen(sb
.buf
, "r");
2062 strbuf_release(&sb
);
2066 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
2067 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2069 strbuf_release(&sb
);
2073 struct files_reflog_iterator
{
2074 struct ref_iterator base
;
2076 struct ref_store
*ref_store
;
2077 struct dir_iterator
*dir_iterator
;
2078 struct object_id oid
;
2081 static int files_reflog_iterator_advance(struct ref_iterator
*ref_iterator
)
2083 struct files_reflog_iterator
*iter
=
2084 (struct files_reflog_iterator
*)ref_iterator
;
2085 struct dir_iterator
*diter
= iter
->dir_iterator
;
2088 while ((ok
= dir_iterator_advance(diter
)) == ITER_OK
) {
2091 if (!S_ISREG(diter
->st
.st_mode
))
2093 if (diter
->basename
[0] == '.')
2095 if (ends_with(diter
->basename
, ".lock"))
2098 if (refs_read_ref_full(iter
->ref_store
,
2099 diter
->relative_path
, 0,
2100 &iter
->oid
, &flags
)) {
2101 error("bad ref for %s", diter
->path
.buf
);
2105 iter
->base
.refname
= diter
->relative_path
;
2106 iter
->base
.oid
= &iter
->oid
;
2107 iter
->base
.flags
= flags
;
2111 iter
->dir_iterator
= NULL
;
2112 if (ref_iterator_abort(ref_iterator
) == ITER_ERROR
)
2117 static int files_reflog_iterator_peel(struct ref_iterator
*ref_iterator
,
2118 struct object_id
*peeled
)
2120 BUG("ref_iterator_peel() called for reflog_iterator");
2123 static int files_reflog_iterator_abort(struct ref_iterator
*ref_iterator
)
2125 struct files_reflog_iterator
*iter
=
2126 (struct files_reflog_iterator
*)ref_iterator
;
2129 if (iter
->dir_iterator
)
2130 ok
= dir_iterator_abort(iter
->dir_iterator
);
2132 base_ref_iterator_free(ref_iterator
);
2136 static struct ref_iterator_vtable files_reflog_iterator_vtable
= {
2137 files_reflog_iterator_advance
,
2138 files_reflog_iterator_peel
,
2139 files_reflog_iterator_abort
2142 static struct ref_iterator
*reflog_iterator_begin(struct ref_store
*ref_store
,
2145 struct dir_iterator
*diter
;
2146 struct files_reflog_iterator
*iter
;
2147 struct ref_iterator
*ref_iterator
;
2148 struct strbuf sb
= STRBUF_INIT
;
2150 strbuf_addf(&sb
, "%s/logs", gitdir
);
2152 diter
= dir_iterator_begin(sb
.buf
, 0);
2154 strbuf_release(&sb
);
2155 return empty_ref_iterator_begin();
2158 iter
= xcalloc(1, sizeof(*iter
));
2159 ref_iterator
= &iter
->base
;
2161 base_ref_iterator_init(ref_iterator
, &files_reflog_iterator_vtable
, 0);
2162 iter
->dir_iterator
= diter
;
2163 iter
->ref_store
= ref_store
;
2164 strbuf_release(&sb
);
2166 return ref_iterator
;
2169 static enum iterator_selection
reflog_iterator_select(
2170 struct ref_iterator
*iter_worktree
,
2171 struct ref_iterator
*iter_common
,
2174 if (iter_worktree
) {
2176 * We're a bit loose here. We probably should ignore
2177 * common refs if they are accidentally added as
2178 * per-worktree refs.
2180 return ITER_SELECT_0
;
2181 } else if (iter_common
) {
2182 if (ref_type(iter_common
->refname
) == REF_TYPE_NORMAL
)
2183 return ITER_SELECT_1
;
2186 * The main ref store may contain main worktree's
2187 * per-worktree refs, which should be ignored
2194 static struct ref_iterator
*files_reflog_iterator_begin(struct ref_store
*ref_store
)
2196 struct files_ref_store
*refs
=
2197 files_downcast(ref_store
, REF_STORE_READ
,
2198 "reflog_iterator_begin");
2200 if (!strcmp(refs
->gitdir
, refs
->gitcommondir
)) {
2201 return reflog_iterator_begin(ref_store
, refs
->gitcommondir
);
2203 return merge_ref_iterator_begin(
2205 reflog_iterator_begin(ref_store
, refs
->gitdir
),
2206 reflog_iterator_begin(ref_store
, refs
->gitcommondir
),
2207 reflog_iterator_select
, refs
);
2212 * If update is a direct update of head_ref (the reference pointed to
2213 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2215 static int split_head_update(struct ref_update
*update
,
2216 struct ref_transaction
*transaction
,
2217 const char *head_ref
,
2218 struct string_list
*affected_refnames
,
2221 struct string_list_item
*item
;
2222 struct ref_update
*new_update
;
2224 if ((update
->flags
& REF_LOG_ONLY
) ||
2225 (update
->flags
& REF_IS_PRUNING
) ||
2226 (update
->flags
& REF_UPDATE_VIA_HEAD
))
2229 if (strcmp(update
->refname
, head_ref
))
2233 * First make sure that HEAD is not already in the
2234 * transaction. This check is O(lg N) in the transaction
2235 * size, but it happens at most once per transaction.
2237 if (string_list_has_string(affected_refnames
, "HEAD")) {
2238 /* An entry already existed */
2240 "multiple updates for 'HEAD' (including one "
2241 "via its referent '%s') are not allowed",
2243 return TRANSACTION_NAME_CONFLICT
;
2246 new_update
= ref_transaction_add_update(
2247 transaction
, "HEAD",
2248 update
->flags
| REF_LOG_ONLY
| REF_NO_DEREF
,
2249 &update
->new_oid
, &update
->old_oid
,
2253 * Add "HEAD". This insertion is O(N) in the transaction
2254 * size, but it happens at most once per transaction.
2255 * Add new_update->refname instead of a literal "HEAD".
2257 if (strcmp(new_update
->refname
, "HEAD"))
2258 BUG("%s unexpectedly not 'HEAD'", new_update
->refname
);
2259 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2260 item
->util
= new_update
;
2266 * update is for a symref that points at referent and doesn't have
2267 * REF_NO_DEREF set. Split it into two updates:
2268 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2269 * - A new, separate update for the referent reference
2270 * Note that the new update will itself be subject to splitting when
2271 * the iteration gets to it.
2273 static int split_symref_update(struct ref_update
*update
,
2274 const char *referent
,
2275 struct ref_transaction
*transaction
,
2276 struct string_list
*affected_refnames
,
2279 struct string_list_item
*item
;
2280 struct ref_update
*new_update
;
2281 unsigned int new_flags
;
2284 * First make sure that referent is not already in the
2285 * transaction. This check is O(lg N) in the transaction
2286 * size, but it happens at most once per symref in a
2289 if (string_list_has_string(affected_refnames
, referent
)) {
2290 /* An entry already exists */
2292 "multiple updates for '%s' (including one "
2293 "via symref '%s') are not allowed",
2294 referent
, update
->refname
);
2295 return TRANSACTION_NAME_CONFLICT
;
2298 new_flags
= update
->flags
;
2299 if (!strcmp(update
->refname
, "HEAD")) {
2301 * Record that the new update came via HEAD, so that
2302 * when we process it, split_head_update() doesn't try
2303 * to add another reflog update for HEAD. Note that
2304 * this bit will be propagated if the new_update
2305 * itself needs to be split.
2307 new_flags
|= REF_UPDATE_VIA_HEAD
;
2310 new_update
= ref_transaction_add_update(
2311 transaction
, referent
, new_flags
,
2312 &update
->new_oid
, &update
->old_oid
,
2315 new_update
->parent_update
= update
;
2318 * Change the symbolic ref update to log only. Also, it
2319 * doesn't need to check its old OID value, as that will be
2320 * done when new_update is processed.
2322 update
->flags
|= REF_LOG_ONLY
| REF_NO_DEREF
;
2323 update
->flags
&= ~REF_HAVE_OLD
;
2326 * Add the referent. This insertion is O(N) in the transaction
2327 * size, but it happens at most once per symref in a
2328 * transaction. Make sure to add new_update->refname, which will
2329 * be valid as long as affected_refnames is in use, and NOT
2330 * referent, which might soon be freed by our caller.
2332 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2334 BUG("%s unexpectedly found in affected_refnames",
2335 new_update
->refname
);
2336 item
->util
= new_update
;
2342 * Return the refname under which update was originally requested.
2344 static const char *original_update_refname(struct ref_update
*update
)
2346 while (update
->parent_update
)
2347 update
= update
->parent_update
;
2349 return update
->refname
;
2353 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2354 * are consistent with oid, which is the reference's current value. If
2355 * everything is OK, return 0; otherwise, write an error message to
2356 * err and return -1.
2358 static int check_old_oid(struct ref_update
*update
, struct object_id
*oid
,
2361 if (!(update
->flags
& REF_HAVE_OLD
) ||
2362 oideq(oid
, &update
->old_oid
))
2365 if (is_null_oid(&update
->old_oid
))
2366 strbuf_addf(err
, "cannot lock ref '%s': "
2367 "reference already exists",
2368 original_update_refname(update
));
2369 else if (is_null_oid(oid
))
2370 strbuf_addf(err
, "cannot lock ref '%s': "
2371 "reference is missing but expected %s",
2372 original_update_refname(update
),
2373 oid_to_hex(&update
->old_oid
));
2375 strbuf_addf(err
, "cannot lock ref '%s': "
2376 "is at %s but expected %s",
2377 original_update_refname(update
),
2379 oid_to_hex(&update
->old_oid
));
2385 * Prepare for carrying out update:
2386 * - Lock the reference referred to by update.
2387 * - Read the reference under lock.
2388 * - Check that its old OID value (if specified) is correct, and in
2389 * any case record it in update->lock->old_oid for later use when
2390 * writing the reflog.
2391 * - If it is a symref update without REF_NO_DEREF, split it up into a
2392 * REF_LOG_ONLY update of the symref and add a separate update for
2393 * the referent to transaction.
2394 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2397 static int lock_ref_for_update(struct files_ref_store
*refs
,
2398 struct ref_update
*update
,
2399 struct ref_transaction
*transaction
,
2400 const char *head_ref
,
2401 struct string_list
*affected_refnames
,
2404 struct strbuf referent
= STRBUF_INIT
;
2405 int mustexist
= (update
->flags
& REF_HAVE_OLD
) &&
2406 !is_null_oid(&update
->old_oid
);
2408 struct ref_lock
*lock
;
2410 files_assert_main_repository(refs
, "lock_ref_for_update");
2412 if ((update
->flags
& REF_HAVE_NEW
) && is_null_oid(&update
->new_oid
))
2413 update
->flags
|= REF_DELETING
;
2416 ret
= split_head_update(update
, transaction
, head_ref
,
2417 affected_refnames
, err
);
2422 ret
= lock_raw_ref(refs
, update
->refname
, mustexist
,
2423 affected_refnames
, NULL
,
2425 &update
->type
, err
);
2429 reason
= strbuf_detach(err
, NULL
);
2430 strbuf_addf(err
, "cannot lock ref '%s': %s",
2431 original_update_refname(update
), reason
);
2436 update
->backend_data
= lock
;
2438 if (update
->type
& REF_ISSYMREF
) {
2439 if (update
->flags
& REF_NO_DEREF
) {
2441 * We won't be reading the referent as part of
2442 * the transaction, so we have to read it here
2443 * to record and possibly check old_oid:
2445 if (refs_read_ref_full(&refs
->base
,
2447 &lock
->old_oid
, NULL
)) {
2448 if (update
->flags
& REF_HAVE_OLD
) {
2449 strbuf_addf(err
, "cannot lock ref '%s': "
2450 "error reading reference",
2451 original_update_refname(update
));
2452 ret
= TRANSACTION_GENERIC_ERROR
;
2455 } else if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2456 ret
= TRANSACTION_GENERIC_ERROR
;
2461 * Create a new update for the reference this
2462 * symref is pointing at. Also, we will record
2463 * and verify old_oid for this update as part
2464 * of processing the split-off update, so we
2465 * don't have to do it here.
2467 ret
= split_symref_update(update
,
2468 referent
.buf
, transaction
,
2469 affected_refnames
, err
);
2474 struct ref_update
*parent_update
;
2476 if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2477 ret
= TRANSACTION_GENERIC_ERROR
;
2482 * If this update is happening indirectly because of a
2483 * symref update, record the old OID in the parent
2486 for (parent_update
= update
->parent_update
;
2488 parent_update
= parent_update
->parent_update
) {
2489 struct ref_lock
*parent_lock
= parent_update
->backend_data
;
2490 oidcpy(&parent_lock
->old_oid
, &lock
->old_oid
);
2494 if ((update
->flags
& REF_HAVE_NEW
) &&
2495 !(update
->flags
& REF_DELETING
) &&
2496 !(update
->flags
& REF_LOG_ONLY
)) {
2497 if (!(update
->type
& REF_ISSYMREF
) &&
2498 oideq(&lock
->old_oid
, &update
->new_oid
)) {
2500 * The reference already has the desired
2501 * value, so we don't need to write it.
2503 } else if (write_ref_to_lockfile(lock
, &update
->new_oid
,
2505 char *write_err
= strbuf_detach(err
, NULL
);
2508 * The lock was freed upon failure of
2509 * write_ref_to_lockfile():
2511 update
->backend_data
= NULL
;
2513 "cannot update ref '%s': %s",
2514 update
->refname
, write_err
);
2516 ret
= TRANSACTION_GENERIC_ERROR
;
2519 update
->flags
|= REF_NEEDS_COMMIT
;
2522 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
2524 * We didn't call write_ref_to_lockfile(), so
2525 * the lockfile is still open. Close it to
2526 * free up the file descriptor:
2528 if (close_ref_gently(lock
)) {
2529 strbuf_addf(err
, "couldn't close '%s.lock'",
2531 ret
= TRANSACTION_GENERIC_ERROR
;
2537 strbuf_release(&referent
);
2541 struct files_transaction_backend_data
{
2542 struct ref_transaction
*packed_transaction
;
2543 int packed_refs_locked
;
2547 * Unlock any references in `transaction` that are still locked, and
2548 * mark the transaction closed.
2550 static void files_transaction_cleanup(struct files_ref_store
*refs
,
2551 struct ref_transaction
*transaction
)
2554 struct files_transaction_backend_data
*backend_data
=
2555 transaction
->backend_data
;
2556 struct strbuf err
= STRBUF_INIT
;
2558 for (i
= 0; i
< transaction
->nr
; i
++) {
2559 struct ref_update
*update
= transaction
->updates
[i
];
2560 struct ref_lock
*lock
= update
->backend_data
;
2564 update
->backend_data
= NULL
;
2568 if (backend_data
->packed_transaction
&&
2569 ref_transaction_abort(backend_data
->packed_transaction
, &err
)) {
2570 error("error aborting transaction: %s", err
.buf
);
2571 strbuf_release(&err
);
2574 if (backend_data
->packed_refs_locked
)
2575 packed_refs_unlock(refs
->packed_ref_store
);
2579 transaction
->state
= REF_TRANSACTION_CLOSED
;
2582 static int files_transaction_prepare(struct ref_store
*ref_store
,
2583 struct ref_transaction
*transaction
,
2586 struct files_ref_store
*refs
=
2587 files_downcast(ref_store
, REF_STORE_WRITE
,
2588 "ref_transaction_prepare");
2591 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2592 char *head_ref
= NULL
;
2594 struct files_transaction_backend_data
*backend_data
;
2595 struct ref_transaction
*packed_transaction
= NULL
;
2599 if (!transaction
->nr
)
2602 backend_data
= xcalloc(1, sizeof(*backend_data
));
2603 transaction
->backend_data
= backend_data
;
2606 * Fail if a refname appears more than once in the
2607 * transaction. (If we end up splitting up any updates using
2608 * split_symref_update() or split_head_update(), those
2609 * functions will check that the new updates don't have the
2610 * same refname as any existing ones.) Also fail if any of the
2611 * updates use REF_IS_PRUNING without REF_NO_DEREF.
2613 for (i
= 0; i
< transaction
->nr
; i
++) {
2614 struct ref_update
*update
= transaction
->updates
[i
];
2615 struct string_list_item
*item
=
2616 string_list_append(&affected_refnames
, update
->refname
);
2618 if ((update
->flags
& REF_IS_PRUNING
) &&
2619 !(update
->flags
& REF_NO_DEREF
))
2620 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2623 * We store a pointer to update in item->util, but at
2624 * the moment we never use the value of this field
2625 * except to check whether it is non-NULL.
2627 item
->util
= update
;
2629 string_list_sort(&affected_refnames
);
2630 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2631 ret
= TRANSACTION_GENERIC_ERROR
;
2636 * Special hack: If a branch is updated directly and HEAD
2637 * points to it (may happen on the remote side of a push
2638 * for example) then logically the HEAD reflog should be
2641 * A generic solution would require reverse symref lookups,
2642 * but finding all symrefs pointing to a given branch would be
2643 * rather costly for this rare event (the direct update of a
2644 * branch) to be worth it. So let's cheat and check with HEAD
2645 * only, which should cover 99% of all usage scenarios (even
2646 * 100% of the default ones).
2648 * So if HEAD is a symbolic reference, then record the name of
2649 * the reference that it points to. If we see an update of
2650 * head_ref within the transaction, then split_head_update()
2651 * arranges for the reflog of HEAD to be updated, too.
2653 head_ref
= refs_resolve_refdup(ref_store
, "HEAD",
2654 RESOLVE_REF_NO_RECURSE
,
2657 if (head_ref
&& !(head_type
& REF_ISSYMREF
)) {
2658 FREE_AND_NULL(head_ref
);
2662 * Acquire all locks, verify old values if provided, check
2663 * that new values are valid, and write new values to the
2664 * lockfiles, ready to be activated. Only keep one lockfile
2665 * open at a time to avoid running out of file descriptors.
2666 * Note that lock_ref_for_update() might append more updates
2667 * to the transaction.
2669 for (i
= 0; i
< transaction
->nr
; i
++) {
2670 struct ref_update
*update
= transaction
->updates
[i
];
2672 ret
= lock_ref_for_update(refs
, update
, transaction
,
2673 head_ref
, &affected_refnames
, err
);
2677 if (update
->flags
& REF_DELETING
&&
2678 !(update
->flags
& REF_LOG_ONLY
) &&
2679 !(update
->flags
& REF_IS_PRUNING
)) {
2681 * This reference has to be deleted from
2682 * packed-refs if it exists there.
2684 if (!packed_transaction
) {
2685 packed_transaction
= ref_store_transaction_begin(
2686 refs
->packed_ref_store
, err
);
2687 if (!packed_transaction
) {
2688 ret
= TRANSACTION_GENERIC_ERROR
;
2692 backend_data
->packed_transaction
=
2696 ref_transaction_add_update(
2697 packed_transaction
, update
->refname
,
2698 REF_HAVE_NEW
| REF_NO_DEREF
,
2699 &update
->new_oid
, NULL
,
2704 if (packed_transaction
) {
2705 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2706 ret
= TRANSACTION_GENERIC_ERROR
;
2709 backend_data
->packed_refs_locked
= 1;
2711 if (is_packed_transaction_needed(refs
->packed_ref_store
,
2712 packed_transaction
)) {
2713 ret
= ref_transaction_prepare(packed_transaction
, err
);
2715 * A failure during the prepare step will abort
2716 * itself, but not free. Do that now, and disconnect
2717 * from the files_transaction so it does not try to
2718 * abort us when we hit the cleanup code below.
2721 ref_transaction_free(packed_transaction
);
2722 backend_data
->packed_transaction
= NULL
;
2726 * We can skip rewriting the `packed-refs`
2727 * file. But we do need to leave it locked, so
2728 * that somebody else doesn't pack a reference
2729 * that we are trying to delete.
2731 * We need to disconnect our transaction from
2732 * backend_data, since the abort (whether successful or
2733 * not) will free it.
2735 backend_data
->packed_transaction
= NULL
;
2736 if (ref_transaction_abort(packed_transaction
, err
)) {
2737 ret
= TRANSACTION_GENERIC_ERROR
;
2745 string_list_clear(&affected_refnames
, 0);
2748 files_transaction_cleanup(refs
, transaction
);
2750 transaction
->state
= REF_TRANSACTION_PREPARED
;
2755 static int files_transaction_finish(struct ref_store
*ref_store
,
2756 struct ref_transaction
*transaction
,
2759 struct files_ref_store
*refs
=
2760 files_downcast(ref_store
, 0, "ref_transaction_finish");
2763 struct strbuf sb
= STRBUF_INIT
;
2764 struct files_transaction_backend_data
*backend_data
;
2765 struct ref_transaction
*packed_transaction
;
2770 if (!transaction
->nr
) {
2771 transaction
->state
= REF_TRANSACTION_CLOSED
;
2775 backend_data
= transaction
->backend_data
;
2776 packed_transaction
= backend_data
->packed_transaction
;
2778 /* Perform updates first so live commits remain referenced */
2779 for (i
= 0; i
< transaction
->nr
; i
++) {
2780 struct ref_update
*update
= transaction
->updates
[i
];
2781 struct ref_lock
*lock
= update
->backend_data
;
2783 if (update
->flags
& REF_NEEDS_COMMIT
||
2784 update
->flags
& REF_LOG_ONLY
) {
2785 if (files_log_ref_write(refs
,
2789 update
->msg
, update
->flags
,
2791 char *old_msg
= strbuf_detach(err
, NULL
);
2793 strbuf_addf(err
, "cannot update the ref '%s': %s",
2794 lock
->ref_name
, old_msg
);
2797 update
->backend_data
= NULL
;
2798 ret
= TRANSACTION_GENERIC_ERROR
;
2802 if (update
->flags
& REF_NEEDS_COMMIT
) {
2803 clear_loose_ref_cache(refs
);
2804 if (commit_ref(lock
)) {
2805 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
2807 update
->backend_data
= NULL
;
2808 ret
= TRANSACTION_GENERIC_ERROR
;
2815 * Now that updates are safely completed, we can perform
2816 * deletes. First delete the reflogs of any references that
2817 * will be deleted, since (in the unexpected event of an
2818 * error) leaving a reference without a reflog is less bad
2819 * than leaving a reflog without a reference (the latter is a
2820 * mildly invalid repository state):
2822 for (i
= 0; i
< transaction
->nr
; i
++) {
2823 struct ref_update
*update
= transaction
->updates
[i
];
2824 if (update
->flags
& REF_DELETING
&&
2825 !(update
->flags
& REF_LOG_ONLY
) &&
2826 !(update
->flags
& REF_IS_PRUNING
)) {
2828 files_reflog_path(refs
, &sb
, update
->refname
);
2829 if (!unlink_or_warn(sb
.buf
))
2830 try_remove_empty_parents(refs
, update
->refname
,
2831 REMOVE_EMPTY_PARENTS_REFLOG
);
2836 * Perform deletes now that updates are safely completed.
2838 * First delete any packed versions of the references, while
2839 * retaining the packed-refs lock:
2841 if (packed_transaction
) {
2842 ret
= ref_transaction_commit(packed_transaction
, err
);
2843 ref_transaction_free(packed_transaction
);
2844 packed_transaction
= NULL
;
2845 backend_data
->packed_transaction
= NULL
;
2850 /* Now delete the loose versions of the references: */
2851 for (i
= 0; i
< transaction
->nr
; i
++) {
2852 struct ref_update
*update
= transaction
->updates
[i
];
2853 struct ref_lock
*lock
= update
->backend_data
;
2855 if (update
->flags
& REF_DELETING
&&
2856 !(update
->flags
& REF_LOG_ONLY
)) {
2857 if (!(update
->type
& REF_ISPACKED
) ||
2858 update
->type
& REF_ISSYMREF
) {
2859 /* It is a loose reference. */
2861 files_ref_path(refs
, &sb
, lock
->ref_name
);
2862 if (unlink_or_msg(sb
.buf
, err
)) {
2863 ret
= TRANSACTION_GENERIC_ERROR
;
2866 update
->flags
|= REF_DELETED_LOOSE
;
2871 clear_loose_ref_cache(refs
);
2874 files_transaction_cleanup(refs
, transaction
);
2876 for (i
= 0; i
< transaction
->nr
; i
++) {
2877 struct ref_update
*update
= transaction
->updates
[i
];
2879 if (update
->flags
& REF_DELETED_LOOSE
) {
2881 * The loose reference was deleted. Delete any
2882 * empty parent directories. (Note that this
2883 * can only work because we have already
2884 * removed the lockfile.)
2886 try_remove_empty_parents(refs
, update
->refname
,
2887 REMOVE_EMPTY_PARENTS_REF
);
2891 strbuf_release(&sb
);
2895 static int files_transaction_abort(struct ref_store
*ref_store
,
2896 struct ref_transaction
*transaction
,
2899 struct files_ref_store
*refs
=
2900 files_downcast(ref_store
, 0, "ref_transaction_abort");
2902 files_transaction_cleanup(refs
, transaction
);
2906 static int ref_present(const char *refname
,
2907 const struct object_id
*oid
, int flags
, void *cb_data
)
2909 struct string_list
*affected_refnames
= cb_data
;
2911 return string_list_has_string(affected_refnames
, refname
);
2914 static int files_initial_transaction_commit(struct ref_store
*ref_store
,
2915 struct ref_transaction
*transaction
,
2918 struct files_ref_store
*refs
=
2919 files_downcast(ref_store
, REF_STORE_WRITE
,
2920 "initial_ref_transaction_commit");
2923 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2924 struct ref_transaction
*packed_transaction
= NULL
;
2928 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
2929 BUG("commit called for transaction that is not open");
2931 /* Fail if a refname appears more than once in the transaction: */
2932 for (i
= 0; i
< transaction
->nr
; i
++)
2933 string_list_append(&affected_refnames
,
2934 transaction
->updates
[i
]->refname
);
2935 string_list_sort(&affected_refnames
);
2936 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2937 ret
= TRANSACTION_GENERIC_ERROR
;
2942 * It's really undefined to call this function in an active
2943 * repository or when there are existing references: we are
2944 * only locking and changing packed-refs, so (1) any
2945 * simultaneous processes might try to change a reference at
2946 * the same time we do, and (2) any existing loose versions of
2947 * the references that we are setting would have precedence
2948 * over our values. But some remote helpers create the remote
2949 * "HEAD" and "master" branches before calling this function,
2950 * so here we really only check that none of the references
2951 * that we are creating already exists.
2953 if (refs_for_each_rawref(&refs
->base
, ref_present
,
2954 &affected_refnames
))
2955 BUG("initial ref transaction called with existing refs");
2957 packed_transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, err
);
2958 if (!packed_transaction
) {
2959 ret
= TRANSACTION_GENERIC_ERROR
;
2963 for (i
= 0; i
< transaction
->nr
; i
++) {
2964 struct ref_update
*update
= transaction
->updates
[i
];
2966 if ((update
->flags
& REF_HAVE_OLD
) &&
2967 !is_null_oid(&update
->old_oid
))
2968 BUG("initial ref transaction with old_sha1 set");
2969 if (refs_verify_refname_available(&refs
->base
, update
->refname
,
2970 &affected_refnames
, NULL
,
2972 ret
= TRANSACTION_NAME_CONFLICT
;
2977 * Add a reference creation for this reference to the
2978 * packed-refs transaction:
2980 ref_transaction_add_update(packed_transaction
, update
->refname
,
2981 update
->flags
& ~REF_HAVE_OLD
,
2982 &update
->new_oid
, &update
->old_oid
,
2986 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2987 ret
= TRANSACTION_GENERIC_ERROR
;
2991 if (initial_ref_transaction_commit(packed_transaction
, err
)) {
2992 ret
= TRANSACTION_GENERIC_ERROR
;
2995 packed_refs_unlock(refs
->packed_ref_store
);
2997 if (packed_transaction
)
2998 ref_transaction_free(packed_transaction
);
2999 transaction
->state
= REF_TRANSACTION_CLOSED
;
3000 string_list_clear(&affected_refnames
, 0);
3004 struct expire_reflog_cb
{
3006 reflog_expiry_should_prune_fn
*should_prune_fn
;
3009 struct object_id last_kept_oid
;
3012 static int expire_reflog_ent(struct object_id
*ooid
, struct object_id
*noid
,
3013 const char *email
, timestamp_t timestamp
, int tz
,
3014 const char *message
, void *cb_data
)
3016 struct expire_reflog_cb
*cb
= cb_data
;
3017 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
3019 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
3020 ooid
= &cb
->last_kept_oid
;
3022 if ((*cb
->should_prune_fn
)(ooid
, noid
, email
, timestamp
, tz
,
3023 message
, policy_cb
)) {
3025 printf("would prune %s", message
);
3026 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3027 printf("prune %s", message
);
3030 fprintf(cb
->newlog
, "%s %s %s %"PRItime
" %+05d\t%s",
3031 oid_to_hex(ooid
), oid_to_hex(noid
),
3032 email
, timestamp
, tz
, message
);
3033 oidcpy(&cb
->last_kept_oid
, noid
);
3035 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3036 printf("keep %s", message
);
3041 static int files_reflog_expire(struct ref_store
*ref_store
,
3042 const char *refname
, const struct object_id
*oid
,
3044 reflog_expiry_prepare_fn prepare_fn
,
3045 reflog_expiry_should_prune_fn should_prune_fn
,
3046 reflog_expiry_cleanup_fn cleanup_fn
,
3047 void *policy_cb_data
)
3049 struct files_ref_store
*refs
=
3050 files_downcast(ref_store
, REF_STORE_WRITE
, "reflog_expire");
3051 struct lock_file reflog_lock
= LOCK_INIT
;
3052 struct expire_reflog_cb cb
;
3053 struct ref_lock
*lock
;
3054 struct strbuf log_file_sb
= STRBUF_INIT
;
3058 struct strbuf err
= STRBUF_INIT
;
3060 memset(&cb
, 0, sizeof(cb
));
3062 cb
.policy_cb
= policy_cb_data
;
3063 cb
.should_prune_fn
= should_prune_fn
;
3066 * The reflog file is locked by holding the lock on the
3067 * reference itself, plus we might need to update the
3068 * reference if --updateref was specified:
3070 lock
= lock_ref_oid_basic(refs
, refname
, oid
,
3071 NULL
, NULL
, REF_NO_DEREF
,
3074 error("cannot lock ref '%s': %s", refname
, err
.buf
);
3075 strbuf_release(&err
);
3078 if (!refs_reflog_exists(ref_store
, refname
)) {
3083 files_reflog_path(refs
, &log_file_sb
, refname
);
3084 log_file
= strbuf_detach(&log_file_sb
, NULL
);
3085 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3087 * Even though holding $GIT_DIR/logs/$reflog.lock has
3088 * no locking implications, we use the lock_file
3089 * machinery here anyway because it does a lot of the
3090 * work we need, including cleaning up if the program
3091 * exits unexpectedly.
3093 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
3094 struct strbuf err
= STRBUF_INIT
;
3095 unable_to_lock_message(log_file
, errno
, &err
);
3096 error("%s", err
.buf
);
3097 strbuf_release(&err
);
3100 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
3102 error("cannot fdopen %s (%s)",
3103 get_lock_file_path(&reflog_lock
), strerror(errno
));
3108 (*prepare_fn
)(refname
, oid
, cb
.policy_cb
);
3109 refs_for_each_reflog_ent(ref_store
, refname
, expire_reflog_ent
, &cb
);
3110 (*cleanup_fn
)(cb
.policy_cb
);
3112 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3114 * It doesn't make sense to adjust a reference pointed
3115 * to by a symbolic ref based on expiring entries in
3116 * the symbolic reference's reflog. Nor can we update
3117 * a reference if there are no remaining reflog
3120 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
3121 !(type
& REF_ISSYMREF
) &&
3122 !is_null_oid(&cb
.last_kept_oid
);
3124 if (close_lock_file_gently(&reflog_lock
)) {
3125 status
|= error("couldn't write %s: %s", log_file
,
3127 rollback_lock_file(&reflog_lock
);
3128 } else if (update
&&
3129 (write_in_full(get_lock_file_fd(&lock
->lk
),
3130 oid_to_hex(&cb
.last_kept_oid
), the_hash_algo
->hexsz
) < 0 ||
3131 write_str_in_full(get_lock_file_fd(&lock
->lk
), "\n") < 0 ||
3132 close_ref_gently(lock
) < 0)) {
3133 status
|= error("couldn't write %s",
3134 get_lock_file_path(&lock
->lk
));
3135 rollback_lock_file(&reflog_lock
);
3136 } else if (commit_lock_file(&reflog_lock
)) {
3137 status
|= error("unable to write reflog '%s' (%s)",
3138 log_file
, strerror(errno
));
3139 } else if (update
&& commit_ref(lock
)) {
3140 status
|= error("couldn't set %s", lock
->ref_name
);
3148 rollback_lock_file(&reflog_lock
);
3154 static int files_init_db(struct ref_store
*ref_store
, struct strbuf
*err
)
3156 struct files_ref_store
*refs
=
3157 files_downcast(ref_store
, REF_STORE_WRITE
, "init_db");
3158 struct strbuf sb
= STRBUF_INIT
;
3161 * Create .git/refs/{heads,tags}
3163 files_ref_path(refs
, &sb
, "refs/heads");
3164 safe_create_dir(sb
.buf
, 1);
3167 files_ref_path(refs
, &sb
, "refs/tags");
3168 safe_create_dir(sb
.buf
, 1);
3170 strbuf_release(&sb
);
3174 struct ref_storage_be refs_be_files
= {
3177 files_ref_store_create
,
3179 files_transaction_prepare
,
3180 files_transaction_finish
,
3181 files_transaction_abort
,
3182 files_initial_transaction_commit
,
3185 files_create_symref
,
3190 files_ref_iterator_begin
,
3193 files_reflog_iterator_begin
,
3194 files_for_each_reflog_ent
,
3195 files_for_each_reflog_ent_reverse
,
3196 files_reflog_exists
,
3197 files_create_reflog
,
3198 files_delete_reflog
,