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"
16 struct object_id old_oid
;
20 * Future: need to be in "struct repository"
21 * when doing a full libification.
23 struct files_ref_store
{
24 struct ref_store base
;
25 unsigned int store_flags
;
30 struct ref_cache
*loose
;
32 struct ref_store
*packed_ref_store
;
35 static void clear_loose_ref_cache(struct files_ref_store
*refs
)
38 free_ref_cache(refs
->loose
);
44 * Create a new submodule ref cache and add it to the internal
47 static struct ref_store
*files_ref_store_create(const char *gitdir
,
50 struct files_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
51 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
52 struct strbuf sb
= STRBUF_INIT
;
54 base_ref_store_init(ref_store
, &refs_be_files
);
55 refs
->store_flags
= flags
;
57 refs
->gitdir
= xstrdup(gitdir
);
58 get_common_dir_noenv(&sb
, gitdir
);
59 refs
->gitcommondir
= strbuf_detach(&sb
, NULL
);
60 strbuf_addf(&sb
, "%s/packed-refs", refs
->gitcommondir
);
61 refs
->packed_ref_store
= packed_ref_store_create(sb
.buf
, flags
);
68 * Die if refs is not the main ref store. caller is used in any
69 * necessary error messages.
71 static void files_assert_main_repository(struct files_ref_store
*refs
,
74 if (refs
->store_flags
& REF_STORE_MAIN
)
77 die("BUG: operation %s only allowed for main ref store", caller
);
81 * Downcast ref_store to files_ref_store. Die if ref_store is not a
82 * files_ref_store. required_flags is compared with ref_store's
83 * store_flags to ensure the ref_store has all required capabilities.
84 * "caller" is used in any necessary error messages.
86 static struct files_ref_store
*files_downcast(struct ref_store
*ref_store
,
87 unsigned int required_flags
,
90 struct files_ref_store
*refs
;
92 if (ref_store
->be
!= &refs_be_files
)
93 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
94 ref_store
->be
->name
, caller
);
96 refs
= (struct files_ref_store
*)ref_store
;
98 if ((refs
->store_flags
& required_flags
) != required_flags
)
99 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
100 caller
, required_flags
, refs
->store_flags
);
105 static void files_reflog_path(struct files_ref_store
*refs
,
109 switch (ref_type(refname
)) {
110 case REF_TYPE_PER_WORKTREE
:
111 case REF_TYPE_PSEUDOREF
:
112 strbuf_addf(sb
, "%s/logs/%s", refs
->gitdir
, refname
);
114 case REF_TYPE_NORMAL
:
115 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
, refname
);
118 die("BUG: unknown ref type %d of ref %s",
119 ref_type(refname
), refname
);
123 static void files_ref_path(struct files_ref_store
*refs
,
127 switch (ref_type(refname
)) {
128 case REF_TYPE_PER_WORKTREE
:
129 case REF_TYPE_PSEUDOREF
:
130 strbuf_addf(sb
, "%s/%s", refs
->gitdir
, refname
);
132 case REF_TYPE_NORMAL
:
133 strbuf_addf(sb
, "%s/%s", refs
->gitcommondir
, refname
);
136 die("BUG: unknown ref type %d of ref %s",
137 ref_type(refname
), refname
);
142 * Read the loose references from the namespace dirname into dir
143 * (without recursing). dirname must end with '/'. dir must be the
144 * directory entry corresponding to dirname.
146 static void loose_fill_ref_dir(struct ref_store
*ref_store
,
147 struct ref_dir
*dir
, const char *dirname
)
149 struct files_ref_store
*refs
=
150 files_downcast(ref_store
, REF_STORE_READ
, "fill_ref_dir");
153 int dirnamelen
= strlen(dirname
);
154 struct strbuf refname
;
155 struct strbuf path
= STRBUF_INIT
;
158 files_ref_path(refs
, &path
, dirname
);
159 path_baselen
= path
.len
;
161 d
= opendir(path
.buf
);
163 strbuf_release(&path
);
167 strbuf_init(&refname
, dirnamelen
+ 257);
168 strbuf_add(&refname
, dirname
, dirnamelen
);
170 while ((de
= readdir(d
)) != NULL
) {
171 struct object_id oid
;
175 if (de
->d_name
[0] == '.')
177 if (ends_with(de
->d_name
, ".lock"))
179 strbuf_addstr(&refname
, de
->d_name
);
180 strbuf_addstr(&path
, de
->d_name
);
181 if (stat(path
.buf
, &st
) < 0) {
182 ; /* silently ignore */
183 } else if (S_ISDIR(st
.st_mode
)) {
184 strbuf_addch(&refname
, '/');
185 add_entry_to_dir(dir
,
186 create_dir_entry(dir
->cache
, refname
.buf
,
189 if (!refs_resolve_ref_unsafe(&refs
->base
,
194 flag
|= REF_ISBROKEN
;
195 } else if (is_null_oid(&oid
)) {
197 * It is so astronomically unlikely
198 * that NULL_SHA1 is the SHA-1 of an
199 * actual object that we consider its
200 * appearance in a loose reference
201 * file to be repo corruption
202 * (probably due to a software bug).
204 flag
|= REF_ISBROKEN
;
207 if (check_refname_format(refname
.buf
,
208 REFNAME_ALLOW_ONELEVEL
)) {
209 if (!refname_is_safe(refname
.buf
))
210 die("loose refname is dangerous: %s", refname
.buf
);
212 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
214 add_entry_to_dir(dir
,
215 create_ref_entry(refname
.buf
, &oid
, flag
));
217 strbuf_setlen(&refname
, dirnamelen
);
218 strbuf_setlen(&path
, path_baselen
);
220 strbuf_release(&refname
);
221 strbuf_release(&path
);
225 * Manually add refs/bisect, which, being per-worktree, might
226 * not appear in the directory listing for refs/ in the main
229 if (!strcmp(dirname
, "refs/")) {
230 int pos
= search_ref_dir(dir
, "refs/bisect/", 12);
233 struct ref_entry
*child_entry
= create_dir_entry(
234 dir
->cache
, "refs/bisect/", 12, 1);
235 add_entry_to_dir(dir
, child_entry
);
240 static struct ref_cache
*get_loose_ref_cache(struct files_ref_store
*refs
)
244 * Mark the top-level directory complete because we
245 * are about to read the only subdirectory that can
248 refs
->loose
= create_ref_cache(&refs
->base
, loose_fill_ref_dir
);
250 /* We're going to fill the top level ourselves: */
251 refs
->loose
->root
->flag
&= ~REF_INCOMPLETE
;
254 * Add an incomplete entry for "refs/" (to be filled
257 add_entry_to_dir(get_ref_dir(refs
->loose
->root
),
258 create_dir_entry(refs
->loose
, "refs/", 5, 1));
263 static int files_read_raw_ref(struct ref_store
*ref_store
,
264 const char *refname
, unsigned char *sha1
,
265 struct strbuf
*referent
, unsigned int *type
)
267 struct files_ref_store
*refs
=
268 files_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
269 struct strbuf sb_contents
= STRBUF_INIT
;
270 struct strbuf sb_path
= STRBUF_INIT
;
277 int remaining_retries
= 3;
280 strbuf_reset(&sb_path
);
282 files_ref_path(refs
, &sb_path
, refname
);
288 * We might have to loop back here to avoid a race
289 * condition: first we lstat() the file, then we try
290 * to read it as a link or as a file. But if somebody
291 * changes the type of the file (file <-> directory
292 * <-> symlink) between the lstat() and reading, then
293 * we don't want to report that as an error but rather
294 * try again starting with the lstat().
296 * We'll keep a count of the retries, though, just to avoid
297 * any confusing situation sending us into an infinite loop.
300 if (remaining_retries
-- <= 0)
303 if (lstat(path
, &st
) < 0) {
306 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
,
307 sha1
, referent
, type
)) {
315 /* Follow "normalized" - ie "refs/.." symlinks by hand */
316 if (S_ISLNK(st
.st_mode
)) {
317 strbuf_reset(&sb_contents
);
318 if (strbuf_readlink(&sb_contents
, path
, 0) < 0) {
319 if (errno
== ENOENT
|| errno
== EINVAL
)
320 /* inconsistent with lstat; retry */
325 if (starts_with(sb_contents
.buf
, "refs/") &&
326 !check_refname_format(sb_contents
.buf
, 0)) {
327 strbuf_swap(&sb_contents
, referent
);
328 *type
|= REF_ISSYMREF
;
333 * It doesn't look like a refname; fall through to just
334 * treating it like a non-symlink, and reading whatever it
339 /* Is it a directory? */
340 if (S_ISDIR(st
.st_mode
)) {
342 * Even though there is a directory where the loose
343 * ref is supposed to be, there could still be a
346 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
,
347 sha1
, referent
, type
)) {
356 * Anything else, just open it and try to use it as
359 fd
= open(path
, O_RDONLY
);
361 if (errno
== ENOENT
&& !S_ISLNK(st
.st_mode
))
362 /* inconsistent with lstat; retry */
367 strbuf_reset(&sb_contents
);
368 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
369 int save_errno
= errno
;
375 strbuf_rtrim(&sb_contents
);
376 buf
= sb_contents
.buf
;
377 if (starts_with(buf
, "ref:")) {
379 while (isspace(*buf
))
382 strbuf_reset(referent
);
383 strbuf_addstr(referent
, buf
);
384 *type
|= REF_ISSYMREF
;
390 * Please note that FETCH_HEAD has additional
391 * data after the sha.
393 if (get_sha1_hex(buf
, sha1
) ||
394 (buf
[40] != '\0' && !isspace(buf
[40]))) {
395 *type
|= REF_ISBROKEN
;
404 strbuf_release(&sb_path
);
405 strbuf_release(&sb_contents
);
410 static void unlock_ref(struct ref_lock
*lock
)
412 rollback_lock_file(&lock
->lk
);
413 free(lock
->ref_name
);
418 * Lock refname, without following symrefs, and set *lock_p to point
419 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
420 * and type similarly to read_raw_ref().
422 * The caller must verify that refname is a "safe" reference name (in
423 * the sense of refname_is_safe()) before calling this function.
425 * If the reference doesn't already exist, verify that refname doesn't
426 * have a D/F conflict with any existing references. extras and skip
427 * are passed to refs_verify_refname_available() for this check.
429 * If mustexist is not set and the reference is not found or is
430 * broken, lock the reference anyway but clear sha1.
432 * Return 0 on success. On failure, write an error message to err and
433 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
435 * Implementation note: This function is basically
440 * but it includes a lot more code to
441 * - Deal with possible races with other processes
442 * - Avoid calling refs_verify_refname_available() when it can be
443 * avoided, namely if we were successfully able to read the ref
444 * - Generate informative error messages in the case of failure
446 static int lock_raw_ref(struct files_ref_store
*refs
,
447 const char *refname
, int mustexist
,
448 const struct string_list
*extras
,
449 const struct string_list
*skip
,
450 struct ref_lock
**lock_p
,
451 struct strbuf
*referent
,
455 struct ref_lock
*lock
;
456 struct strbuf ref_file
= STRBUF_INIT
;
457 int attempts_remaining
= 3;
458 int ret
= TRANSACTION_GENERIC_ERROR
;
461 files_assert_main_repository(refs
, "lock_raw_ref");
465 /* First lock the file so it can't change out from under us. */
467 *lock_p
= lock
= xcalloc(1, sizeof(*lock
));
469 lock
->ref_name
= xstrdup(refname
);
470 files_ref_path(refs
, &ref_file
, refname
);
473 switch (safe_create_leading_directories(ref_file
.buf
)) {
478 * Suppose refname is "refs/foo/bar". We just failed
479 * to create the containing directory, "refs/foo",
480 * because there was a non-directory in the way. This
481 * indicates a D/F conflict, probably because of
482 * another reference such as "refs/foo". There is no
483 * reason to expect this error to be transitory.
485 if (refs_verify_refname_available(&refs
->base
, refname
,
486 extras
, skip
, err
)) {
489 * To the user the relevant error is
490 * that the "mustexist" reference is
494 strbuf_addf(err
, "unable to resolve reference '%s'",
498 * The error message set by
499 * refs_verify_refname_available() is
502 ret
= TRANSACTION_NAME_CONFLICT
;
506 * The file that is in the way isn't a loose
507 * reference. Report it as a low-level
510 strbuf_addf(err
, "unable to create lock file %s.lock; "
511 "non-directory in the way",
516 /* Maybe another process was tidying up. Try again. */
517 if (--attempts_remaining
> 0)
521 strbuf_addf(err
, "unable to create directory for %s",
526 if (hold_lock_file_for_update_timeout(
527 &lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
,
528 get_files_ref_lock_timeout_ms()) < 0) {
529 if (errno
== ENOENT
&& --attempts_remaining
> 0) {
531 * Maybe somebody just deleted one of the
532 * directories leading to ref_file. Try
537 unable_to_lock_message(ref_file
.buf
, errno
, err
);
543 * Now we hold the lock and can read the reference without
544 * fear that its value will change.
547 if (files_read_raw_ref(&refs
->base
, refname
,
548 lock
->old_oid
.hash
, referent
, type
)) {
549 if (errno
== ENOENT
) {
551 /* Garden variety missing reference. */
552 strbuf_addf(err
, "unable to resolve reference '%s'",
557 * Reference is missing, but that's OK. We
558 * know that there is not a conflict with
559 * another loose reference because
560 * (supposing that we are trying to lock
561 * reference "refs/foo/bar"):
563 * - We were successfully able to create
564 * the lockfile refs/foo/bar.lock, so we
565 * know there cannot be a loose reference
568 * - We got ENOENT and not EISDIR, so we
569 * know that there cannot be a loose
570 * reference named "refs/foo/bar/baz".
573 } else if (errno
== EISDIR
) {
575 * There is a directory in the way. It might have
576 * contained references that have been deleted. If
577 * we don't require that the reference already
578 * exists, try to remove the directory so that it
579 * doesn't cause trouble when we want to rename the
580 * lockfile into place later.
583 /* Garden variety missing reference. */
584 strbuf_addf(err
, "unable to resolve reference '%s'",
587 } else if (remove_dir_recursively(&ref_file
,
588 REMOVE_DIR_EMPTY_ONLY
)) {
589 if (refs_verify_refname_available(
590 &refs
->base
, refname
,
591 extras
, skip
, err
)) {
593 * The error message set by
594 * verify_refname_available() is OK.
596 ret
= TRANSACTION_NAME_CONFLICT
;
600 * We can't delete the directory,
601 * but we also don't know of any
602 * references that it should
605 strbuf_addf(err
, "there is a non-empty directory '%s' "
606 "blocking reference '%s'",
607 ref_file
.buf
, refname
);
611 } else if (errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
612 strbuf_addf(err
, "unable to resolve reference '%s': "
613 "reference broken", refname
);
616 strbuf_addf(err
, "unable to resolve reference '%s': %s",
617 refname
, strerror(errno
));
622 * If the ref did not exist and we are creating it,
623 * make sure there is no existing packed ref that
624 * conflicts with refname:
626 if (refs_verify_refname_available(
627 refs
->packed_ref_store
, refname
,
640 strbuf_release(&ref_file
);
644 struct files_ref_iterator
{
645 struct ref_iterator base
;
647 struct ref_iterator
*iter0
;
651 static int files_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
653 struct files_ref_iterator
*iter
=
654 (struct files_ref_iterator
*)ref_iterator
;
657 while ((ok
= ref_iterator_advance(iter
->iter0
)) == ITER_OK
) {
658 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
659 ref_type(iter
->iter0
->refname
) != REF_TYPE_PER_WORKTREE
)
662 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
663 !ref_resolves_to_object(iter
->iter0
->refname
,
668 iter
->base
.refname
= iter
->iter0
->refname
;
669 iter
->base
.oid
= iter
->iter0
->oid
;
670 iter
->base
.flags
= iter
->iter0
->flags
;
675 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
681 static int files_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
682 struct object_id
*peeled
)
684 struct files_ref_iterator
*iter
=
685 (struct files_ref_iterator
*)ref_iterator
;
687 return ref_iterator_peel(iter
->iter0
, peeled
);
690 static int files_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
692 struct files_ref_iterator
*iter
=
693 (struct files_ref_iterator
*)ref_iterator
;
697 ok
= ref_iterator_abort(iter
->iter0
);
699 base_ref_iterator_free(ref_iterator
);
703 static struct ref_iterator_vtable files_ref_iterator_vtable
= {
704 files_ref_iterator_advance
,
705 files_ref_iterator_peel
,
706 files_ref_iterator_abort
709 static struct ref_iterator
*files_ref_iterator_begin(
710 struct ref_store
*ref_store
,
711 const char *prefix
, unsigned int flags
)
713 struct files_ref_store
*refs
;
714 struct ref_iterator
*loose_iter
, *packed_iter
, *overlay_iter
;
715 struct files_ref_iterator
*iter
;
716 struct ref_iterator
*ref_iterator
;
717 unsigned int required_flags
= REF_STORE_READ
;
719 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
720 required_flags
|= REF_STORE_ODB
;
722 refs
= files_downcast(ref_store
, required_flags
, "ref_iterator_begin");
725 * We must make sure that all loose refs are read before
726 * accessing the packed-refs file; this avoids a race
727 * condition if loose refs are migrated to the packed-refs
728 * file by a simultaneous process, but our in-memory view is
729 * from before the migration. We ensure this as follows:
730 * First, we call start the loose refs iteration with its
731 * `prime_ref` argument set to true. This causes the loose
732 * references in the subtree to be pre-read into the cache.
733 * (If they've already been read, that's OK; we only need to
734 * guarantee that they're read before the packed refs, not
735 * *how much* before.) After that, we call
736 * packed_ref_iterator_begin(), which internally checks
737 * whether the packed-ref cache is up to date with what is on
738 * disk, and re-reads it if not.
741 loose_iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
),
745 * The packed-refs file might contain broken references, for
746 * example an old version of a reference that points at an
747 * object that has since been garbage-collected. This is OK as
748 * long as there is a corresponding loose reference that
749 * overrides it, and we don't want to emit an error message in
750 * this case. So ask the packed_ref_store for all of its
751 * references, and (if needed) do our own check for broken
752 * ones in files_ref_iterator_advance(), after we have merged
753 * the packed and loose references.
755 packed_iter
= refs_ref_iterator_begin(
756 refs
->packed_ref_store
, prefix
, 0,
757 DO_FOR_EACH_INCLUDE_BROKEN
);
759 overlay_iter
= overlay_ref_iterator_begin(loose_iter
, packed_iter
);
761 iter
= xcalloc(1, sizeof(*iter
));
762 ref_iterator
= &iter
->base
;
763 base_ref_iterator_init(ref_iterator
, &files_ref_iterator_vtable
,
764 overlay_iter
->ordered
);
765 iter
->iter0
= overlay_iter
;
772 * Verify that the reference locked by lock has the value old_sha1.
773 * Fail if the reference doesn't exist and mustexist is set. Return 0
774 * on success. On error, write an error message to err, set errno, and
775 * return a negative value.
777 static int verify_lock(struct ref_store
*ref_store
, struct ref_lock
*lock
,
778 const unsigned char *old_sha1
, int mustexist
,
783 if (refs_read_ref_full(ref_store
, lock
->ref_name
,
784 mustexist
? RESOLVE_REF_READING
: 0,
785 &lock
->old_oid
, NULL
)) {
787 int save_errno
= errno
;
788 strbuf_addf(err
, "can't verify ref '%s'", lock
->ref_name
);
792 oidclr(&lock
->old_oid
);
796 if (old_sha1
&& hashcmp(lock
->old_oid
.hash
, old_sha1
)) {
797 strbuf_addf(err
, "ref '%s' is at %s but expected %s",
799 oid_to_hex(&lock
->old_oid
),
800 sha1_to_hex(old_sha1
));
807 static int remove_empty_directories(struct strbuf
*path
)
810 * we want to create a file but there is a directory there;
811 * if that is an empty directory (or a directory that contains
812 * only empty directories), remove them.
814 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
817 static int create_reflock(const char *path
, void *cb
)
819 struct lock_file
*lk
= cb
;
821 return hold_lock_file_for_update_timeout(
822 lk
, path
, LOCK_NO_DEREF
,
823 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
827 * Locks a ref returning the lock on success and NULL on failure.
828 * On failure errno is set to something meaningful.
830 static struct ref_lock
*lock_ref_sha1_basic(struct files_ref_store
*refs
,
832 const unsigned char *old_sha1
,
833 const struct string_list
*extras
,
834 const struct string_list
*skip
,
835 unsigned int flags
, int *type
,
838 struct strbuf ref_file
= STRBUF_INIT
;
839 struct ref_lock
*lock
;
841 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
842 int resolve_flags
= RESOLVE_REF_NO_RECURSE
;
845 files_assert_main_repository(refs
, "lock_ref_sha1_basic");
848 lock
= xcalloc(1, sizeof(struct ref_lock
));
851 resolve_flags
|= RESOLVE_REF_READING
;
852 if (flags
& REF_DELETING
)
853 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
855 files_ref_path(refs
, &ref_file
, refname
);
856 resolved
= !!refs_resolve_ref_unsafe(&refs
->base
,
857 refname
, resolve_flags
,
858 lock
->old_oid
.hash
, type
);
859 if (!resolved
&& errno
== EISDIR
) {
861 * we are trying to lock foo but we used to
862 * have foo/bar which now does not exist;
863 * it is normal for the empty directory 'foo'
866 if (remove_empty_directories(&ref_file
)) {
868 if (!refs_verify_refname_available(
870 refname
, extras
, skip
, err
))
871 strbuf_addf(err
, "there are still refs under '%s'",
875 resolved
= !!refs_resolve_ref_unsafe(&refs
->base
,
876 refname
, resolve_flags
,
877 lock
->old_oid
.hash
, type
);
881 if (last_errno
!= ENOTDIR
||
882 !refs_verify_refname_available(&refs
->base
, refname
,
884 strbuf_addf(err
, "unable to resolve reference '%s': %s",
885 refname
, strerror(last_errno
));
891 * If the ref did not exist and we are creating it, make sure
892 * there is no existing packed ref whose name begins with our
893 * refname, nor a packed ref whose name is a proper prefix of
896 if (is_null_oid(&lock
->old_oid
) &&
897 refs_verify_refname_available(refs
->packed_ref_store
, refname
,
898 extras
, skip
, err
)) {
899 last_errno
= ENOTDIR
;
903 lock
->ref_name
= xstrdup(refname
);
905 if (raceproof_create_file(ref_file
.buf
, create_reflock
, &lock
->lk
)) {
907 unable_to_lock_message(ref_file
.buf
, errno
, err
);
911 if (verify_lock(&refs
->base
, lock
, old_sha1
, mustexist
, err
)) {
922 strbuf_release(&ref_file
);
927 struct ref_to_prune
{
928 struct ref_to_prune
*next
;
929 struct object_id oid
;
930 char name
[FLEX_ARRAY
];
934 REMOVE_EMPTY_PARENTS_REF
= 0x01,
935 REMOVE_EMPTY_PARENTS_REFLOG
= 0x02
939 * Remove empty parent directories associated with the specified
940 * reference and/or its reflog, but spare [logs/]refs/ and immediate
941 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
942 * REMOVE_EMPTY_PARENTS_REFLOG.
944 static void try_remove_empty_parents(struct files_ref_store
*refs
,
948 struct strbuf buf
= STRBUF_INIT
;
949 struct strbuf sb
= STRBUF_INIT
;
953 strbuf_addstr(&buf
, refname
);
955 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
956 while (*p
&& *p
!= '/')
958 /* tolerate duplicate slashes; see check_refname_format() */
962 q
= buf
.buf
+ buf
.len
;
963 while (flags
& (REMOVE_EMPTY_PARENTS_REF
| REMOVE_EMPTY_PARENTS_REFLOG
)) {
964 while (q
> p
&& *q
!= '/')
966 while (q
> p
&& *(q
-1) == '/')
970 strbuf_setlen(&buf
, q
- buf
.buf
);
973 files_ref_path(refs
, &sb
, buf
.buf
);
974 if ((flags
& REMOVE_EMPTY_PARENTS_REF
) && rmdir(sb
.buf
))
975 flags
&= ~REMOVE_EMPTY_PARENTS_REF
;
978 files_reflog_path(refs
, &sb
, buf
.buf
);
979 if ((flags
& REMOVE_EMPTY_PARENTS_REFLOG
) && rmdir(sb
.buf
))
980 flags
&= ~REMOVE_EMPTY_PARENTS_REFLOG
;
982 strbuf_release(&buf
);
986 /* make sure nobody touched the ref, and unlink */
987 static void prune_ref(struct files_ref_store
*refs
, struct ref_to_prune
*r
)
989 struct ref_transaction
*transaction
;
990 struct strbuf err
= STRBUF_INIT
;
992 if (check_refname_format(r
->name
, 0))
995 transaction
= ref_store_transaction_begin(&refs
->base
, &err
);
997 ref_transaction_delete(transaction
, r
->name
, &r
->oid
,
998 REF_ISPRUNING
| REF_NODEREF
, NULL
, &err
) ||
999 ref_transaction_commit(transaction
, &err
)) {
1000 ref_transaction_free(transaction
);
1001 error("%s", err
.buf
);
1002 strbuf_release(&err
);
1005 ref_transaction_free(transaction
);
1006 strbuf_release(&err
);
1010 * Prune the loose versions of the references in the linked list
1011 * `*refs_to_prune`, freeing the entries in the list as we go.
1013 static void prune_refs(struct files_ref_store
*refs
, struct ref_to_prune
**refs_to_prune
)
1015 while (*refs_to_prune
) {
1016 struct ref_to_prune
*r
= *refs_to_prune
;
1017 *refs_to_prune
= r
->next
;
1024 * Return true if the specified reference should be packed.
1026 static int should_pack_ref(const char *refname
,
1027 const struct object_id
*oid
, unsigned int ref_flags
,
1028 unsigned int pack_flags
)
1030 /* Do not pack per-worktree refs: */
1031 if (ref_type(refname
) != REF_TYPE_NORMAL
)
1034 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1035 if (!(pack_flags
& PACK_REFS_ALL
) && !starts_with(refname
, "refs/tags/"))
1038 /* Do not pack symbolic refs: */
1039 if (ref_flags
& REF_ISSYMREF
)
1042 /* Do not pack broken refs: */
1043 if (!ref_resolves_to_object(refname
, oid
, ref_flags
))
1049 static int files_pack_refs(struct ref_store
*ref_store
, unsigned int flags
)
1051 struct files_ref_store
*refs
=
1052 files_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_ODB
,
1054 struct ref_iterator
*iter
;
1056 struct ref_to_prune
*refs_to_prune
= NULL
;
1057 struct strbuf err
= STRBUF_INIT
;
1058 struct ref_transaction
*transaction
;
1060 transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, &err
);
1064 packed_refs_lock(refs
->packed_ref_store
, LOCK_DIE_ON_ERROR
, &err
);
1066 iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
), NULL
, 0);
1067 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
1069 * If the loose reference can be packed, add an entry
1070 * in the packed ref cache. If the reference should be
1071 * pruned, also add it to refs_to_prune.
1073 if (!should_pack_ref(iter
->refname
, iter
->oid
, iter
->flags
,
1078 * Add a reference creation for this reference to the
1079 * packed-refs transaction:
1081 if (ref_transaction_update(transaction
, iter
->refname
,
1083 REF_NODEREF
, NULL
, &err
))
1084 die("failure preparing to create packed reference %s: %s",
1085 iter
->refname
, err
.buf
);
1087 /* Schedule the loose reference for pruning if requested. */
1088 if ((flags
& PACK_REFS_PRUNE
)) {
1089 struct ref_to_prune
*n
;
1090 FLEX_ALLOC_STR(n
, name
, iter
->refname
);
1091 oidcpy(&n
->oid
, iter
->oid
);
1092 n
->next
= refs_to_prune
;
1096 if (ok
!= ITER_DONE
)
1097 die("error while iterating over references");
1099 if (ref_transaction_commit(transaction
, &err
))
1100 die("unable to write new packed-refs: %s", err
.buf
);
1102 ref_transaction_free(transaction
);
1104 packed_refs_unlock(refs
->packed_ref_store
);
1106 prune_refs(refs
, &refs_to_prune
);
1107 strbuf_release(&err
);
1111 static int files_delete_refs(struct ref_store
*ref_store
, const char *msg
,
1112 struct string_list
*refnames
, unsigned int flags
)
1114 struct files_ref_store
*refs
=
1115 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_refs");
1116 struct strbuf err
= STRBUF_INIT
;
1122 if (packed_refs_lock(refs
->packed_ref_store
, 0, &err
))
1125 if (refs_delete_refs(refs
->packed_ref_store
, msg
, refnames
, flags
)) {
1126 packed_refs_unlock(refs
->packed_ref_store
);
1130 packed_refs_unlock(refs
->packed_ref_store
);
1132 for (i
= 0; i
< refnames
->nr
; i
++) {
1133 const char *refname
= refnames
->items
[i
].string
;
1135 if (refs_delete_ref(&refs
->base
, msg
, refname
, NULL
, flags
))
1136 result
|= error(_("could not remove reference %s"), refname
);
1139 strbuf_release(&err
);
1144 * If we failed to rewrite the packed-refs file, then it is
1145 * unsafe to try to remove loose refs, because doing so might
1146 * expose an obsolete packed value for a reference that might
1147 * even point at an object that has been garbage collected.
1149 if (refnames
->nr
== 1)
1150 error(_("could not delete reference %s: %s"),
1151 refnames
->items
[0].string
, err
.buf
);
1153 error(_("could not delete references: %s"), err
.buf
);
1155 strbuf_release(&err
);
1160 * People using contrib's git-new-workdir have .git/logs/refs ->
1161 * /some/other/path/.git/logs/refs, and that may live on another device.
1163 * IOW, to avoid cross device rename errors, the temporary renamed log must
1164 * live into logs/refs.
1166 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1169 const char *tmp_renamed_log
;
1173 static int rename_tmp_log_callback(const char *path
, void *cb_data
)
1175 struct rename_cb
*cb
= cb_data
;
1177 if (rename(cb
->tmp_renamed_log
, path
)) {
1179 * rename(a, b) when b is an existing directory ought
1180 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1181 * Sheesh. Record the true errno for error reporting,
1182 * but report EISDIR to raceproof_create_file() so
1183 * that it knows to retry.
1185 cb
->true_errno
= errno
;
1186 if (errno
== ENOTDIR
)
1194 static int rename_tmp_log(struct files_ref_store
*refs
, const char *newrefname
)
1196 struct strbuf path
= STRBUF_INIT
;
1197 struct strbuf tmp
= STRBUF_INIT
;
1198 struct rename_cb cb
;
1201 files_reflog_path(refs
, &path
, newrefname
);
1202 files_reflog_path(refs
, &tmp
, TMP_RENAMED_LOG
);
1203 cb
.tmp_renamed_log
= tmp
.buf
;
1204 ret
= raceproof_create_file(path
.buf
, rename_tmp_log_callback
, &cb
);
1206 if (errno
== EISDIR
)
1207 error("directory not empty: %s", path
.buf
);
1209 error("unable to move logfile %s to %s: %s",
1211 strerror(cb
.true_errno
));
1214 strbuf_release(&path
);
1215 strbuf_release(&tmp
);
1219 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1220 const struct object_id
*oid
, struct strbuf
*err
);
1221 static int commit_ref_update(struct files_ref_store
*refs
,
1222 struct ref_lock
*lock
,
1223 const struct object_id
*oid
, const char *logmsg
,
1224 struct strbuf
*err
);
1226 static int files_copy_or_rename_ref(struct ref_store
*ref_store
,
1227 const char *oldrefname
, const char *newrefname
,
1228 const char *logmsg
, int copy
)
1230 struct files_ref_store
*refs
=
1231 files_downcast(ref_store
, REF_STORE_WRITE
, "rename_ref");
1232 struct object_id oid
, orig_oid
;
1233 int flag
= 0, logmoved
= 0;
1234 struct ref_lock
*lock
;
1235 struct stat loginfo
;
1236 struct strbuf sb_oldref
= STRBUF_INIT
;
1237 struct strbuf sb_newref
= STRBUF_INIT
;
1238 struct strbuf tmp_renamed_log
= STRBUF_INIT
;
1240 struct strbuf err
= STRBUF_INIT
;
1242 files_reflog_path(refs
, &sb_oldref
, oldrefname
);
1243 files_reflog_path(refs
, &sb_newref
, newrefname
);
1244 files_reflog_path(refs
, &tmp_renamed_log
, TMP_RENAMED_LOG
);
1246 log
= !lstat(sb_oldref
.buf
, &loginfo
);
1247 if (log
&& S_ISLNK(loginfo
.st_mode
)) {
1248 ret
= error("reflog for %s is a symlink", oldrefname
);
1252 if (!refs_resolve_ref_unsafe(&refs
->base
, oldrefname
,
1253 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1254 orig_oid
.hash
, &flag
)) {
1255 ret
= error("refname %s not found", oldrefname
);
1259 if (flag
& REF_ISSYMREF
) {
1261 ret
= error("refname %s is a symbolic ref, copying it is not supported",
1264 ret
= error("refname %s is a symbolic ref, renaming it is not supported",
1268 if (!refs_rename_ref_available(&refs
->base
, oldrefname
, newrefname
)) {
1273 if (!copy
&& log
&& rename(sb_oldref
.buf
, tmp_renamed_log
.buf
)) {
1274 ret
= error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1275 oldrefname
, strerror(errno
));
1279 if (copy
&& log
&& copy_file(tmp_renamed_log
.buf
, sb_oldref
.buf
, 0644)) {
1280 ret
= error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1281 oldrefname
, strerror(errno
));
1285 if (!copy
&& refs_delete_ref(&refs
->base
, logmsg
, oldrefname
,
1286 &orig_oid
, REF_NODEREF
)) {
1287 error("unable to delete old %s", oldrefname
);
1292 * Since we are doing a shallow lookup, oid is not the
1293 * correct value to pass to delete_ref as old_oid. But that
1294 * doesn't matter, because an old_oid check wouldn't add to
1295 * the safety anyway; we want to delete the reference whatever
1296 * its current value.
1298 if (!copy
&& !refs_read_ref_full(&refs
->base
, newrefname
,
1299 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1301 refs_delete_ref(&refs
->base
, NULL
, newrefname
,
1302 NULL
, REF_NODEREF
)) {
1303 if (errno
== EISDIR
) {
1304 struct strbuf path
= STRBUF_INIT
;
1307 files_ref_path(refs
, &path
, newrefname
);
1308 result
= remove_empty_directories(&path
);
1309 strbuf_release(&path
);
1312 error("Directory not empty: %s", newrefname
);
1316 error("unable to delete existing %s", newrefname
);
1321 if (log
&& rename_tmp_log(refs
, newrefname
))
1326 lock
= lock_ref_sha1_basic(refs
, newrefname
, NULL
, NULL
, NULL
,
1327 REF_NODEREF
, NULL
, &err
);
1330 error("unable to copy '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1332 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1333 strbuf_release(&err
);
1336 oidcpy(&lock
->old_oid
, &orig_oid
);
1338 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1339 commit_ref_update(refs
, lock
, &orig_oid
, logmsg
, &err
)) {
1340 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
1341 strbuf_release(&err
);
1349 lock
= lock_ref_sha1_basic(refs
, oldrefname
, NULL
, NULL
, NULL
,
1350 REF_NODEREF
, NULL
, &err
);
1352 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
1353 strbuf_release(&err
);
1357 flag
= log_all_ref_updates
;
1358 log_all_ref_updates
= LOG_REFS_NONE
;
1359 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1360 commit_ref_update(refs
, lock
, &orig_oid
, NULL
, &err
)) {
1361 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
1362 strbuf_release(&err
);
1364 log_all_ref_updates
= flag
;
1367 if (logmoved
&& rename(sb_newref
.buf
, sb_oldref
.buf
))
1368 error("unable to restore logfile %s from %s: %s",
1369 oldrefname
, newrefname
, strerror(errno
));
1370 if (!logmoved
&& log
&&
1371 rename(tmp_renamed_log
.buf
, sb_oldref
.buf
))
1372 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG
": %s",
1373 oldrefname
, strerror(errno
));
1376 strbuf_release(&sb_newref
);
1377 strbuf_release(&sb_oldref
);
1378 strbuf_release(&tmp_renamed_log
);
1383 static int files_rename_ref(struct ref_store
*ref_store
,
1384 const char *oldrefname
, const char *newrefname
,
1387 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1388 newrefname
, logmsg
, 0);
1391 static int files_copy_ref(struct ref_store
*ref_store
,
1392 const char *oldrefname
, const char *newrefname
,
1395 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1396 newrefname
, logmsg
, 1);
1399 static int close_ref_gently(struct ref_lock
*lock
)
1401 if (close_lock_file_gently(&lock
->lk
))
1406 static int commit_ref(struct ref_lock
*lock
)
1408 char *path
= get_locked_file_path(&lock
->lk
);
1411 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
1413 * There is a directory at the path we want to rename
1414 * the lockfile to. Hopefully it is empty; try to
1417 size_t len
= strlen(path
);
1418 struct strbuf sb_path
= STRBUF_INIT
;
1420 strbuf_attach(&sb_path
, path
, len
, len
);
1423 * If this fails, commit_lock_file() will also fail
1424 * and will report the problem.
1426 remove_empty_directories(&sb_path
);
1427 strbuf_release(&sb_path
);
1432 if (commit_lock_file(&lock
->lk
))
1437 static int open_or_create_logfile(const char *path
, void *cb
)
1441 *fd
= open(path
, O_APPEND
| O_WRONLY
| O_CREAT
, 0666);
1442 return (*fd
< 0) ? -1 : 0;
1446 * Create a reflog for a ref. If force_create = 0, only create the
1447 * reflog for certain refs (those for which should_autocreate_reflog
1448 * returns non-zero). Otherwise, create it regardless of the reference
1449 * name. If the logfile already existed or was created, return 0 and
1450 * set *logfd to the file descriptor opened for appending to the file.
1451 * If no logfile exists and we decided not to create one, return 0 and
1452 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1455 static int log_ref_setup(struct files_ref_store
*refs
,
1456 const char *refname
, int force_create
,
1457 int *logfd
, struct strbuf
*err
)
1459 struct strbuf logfile_sb
= STRBUF_INIT
;
1462 files_reflog_path(refs
, &logfile_sb
, refname
);
1463 logfile
= strbuf_detach(&logfile_sb
, NULL
);
1465 if (force_create
|| should_autocreate_reflog(refname
)) {
1466 if (raceproof_create_file(logfile
, open_or_create_logfile
, logfd
)) {
1467 if (errno
== ENOENT
)
1468 strbuf_addf(err
, "unable to create directory for '%s': "
1469 "%s", logfile
, strerror(errno
));
1470 else if (errno
== EISDIR
)
1471 strbuf_addf(err
, "there are still logs under '%s'",
1474 strbuf_addf(err
, "unable to append to '%s': %s",
1475 logfile
, strerror(errno
));
1480 *logfd
= open(logfile
, O_APPEND
| O_WRONLY
, 0666);
1482 if (errno
== ENOENT
|| errno
== EISDIR
) {
1484 * The logfile doesn't already exist,
1485 * but that is not an error; it only
1486 * means that we won't write log
1491 strbuf_addf(err
, "unable to append to '%s': %s",
1492 logfile
, strerror(errno
));
1499 adjust_shared_perm(logfile
);
1509 static int files_create_reflog(struct ref_store
*ref_store
,
1510 const char *refname
, int force_create
,
1513 struct files_ref_store
*refs
=
1514 files_downcast(ref_store
, REF_STORE_WRITE
, "create_reflog");
1517 if (log_ref_setup(refs
, refname
, force_create
, &fd
, err
))
1526 static int log_ref_write_fd(int fd
, const struct object_id
*old_oid
,
1527 const struct object_id
*new_oid
,
1528 const char *committer
, const char *msg
)
1530 int msglen
, written
;
1531 unsigned maxlen
, len
;
1534 msglen
= msg
? strlen(msg
) : 0;
1535 maxlen
= strlen(committer
) + msglen
+ 100;
1536 logrec
= xmalloc(maxlen
);
1537 len
= xsnprintf(logrec
, maxlen
, "%s %s %s\n",
1538 oid_to_hex(old_oid
),
1539 oid_to_hex(new_oid
),
1542 len
+= copy_reflog_msg(logrec
+ len
- 1, msg
) - 1;
1544 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
1552 static int files_log_ref_write(struct files_ref_store
*refs
,
1553 const char *refname
, const struct object_id
*old_oid
,
1554 const struct object_id
*new_oid
, const char *msg
,
1555 int flags
, struct strbuf
*err
)
1559 if (log_all_ref_updates
== LOG_REFS_UNSET
)
1560 log_all_ref_updates
= is_bare_repository() ? LOG_REFS_NONE
: LOG_REFS_NORMAL
;
1562 result
= log_ref_setup(refs
, refname
,
1563 flags
& REF_FORCE_CREATE_REFLOG
,
1571 result
= log_ref_write_fd(logfd
, old_oid
, new_oid
,
1572 git_committer_info(0), msg
);
1574 struct strbuf sb
= STRBUF_INIT
;
1575 int save_errno
= errno
;
1577 files_reflog_path(refs
, &sb
, refname
);
1578 strbuf_addf(err
, "unable to append to '%s': %s",
1579 sb
.buf
, strerror(save_errno
));
1580 strbuf_release(&sb
);
1585 struct strbuf sb
= STRBUF_INIT
;
1586 int save_errno
= errno
;
1588 files_reflog_path(refs
, &sb
, refname
);
1589 strbuf_addf(err
, "unable to append to '%s': %s",
1590 sb
.buf
, strerror(save_errno
));
1591 strbuf_release(&sb
);
1598 * Write sha1 into the open lockfile, then close the lockfile. On
1599 * errors, rollback the lockfile, fill in *err and
1602 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1603 const struct object_id
*oid
, struct strbuf
*err
)
1605 static char term
= '\n';
1609 o
= parse_object(oid
);
1612 "trying to write ref '%s' with nonexistent object %s",
1613 lock
->ref_name
, oid_to_hex(oid
));
1617 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
1619 "trying to write non-commit object %s to branch '%s'",
1620 oid_to_hex(oid
), lock
->ref_name
);
1624 fd
= get_lock_file_fd(&lock
->lk
);
1625 if (write_in_full(fd
, oid_to_hex(oid
), GIT_SHA1_HEXSZ
) < 0 ||
1626 write_in_full(fd
, &term
, 1) < 0 ||
1627 close_ref_gently(lock
) < 0) {
1629 "couldn't write '%s'", get_lock_file_path(&lock
->lk
));
1637 * Commit a change to a loose reference that has already been written
1638 * to the loose reference lockfile. Also update the reflogs if
1639 * necessary, using the specified lockmsg (which can be NULL).
1641 static int commit_ref_update(struct files_ref_store
*refs
,
1642 struct ref_lock
*lock
,
1643 const struct object_id
*oid
, const char *logmsg
,
1646 files_assert_main_repository(refs
, "commit_ref_update");
1648 clear_loose_ref_cache(refs
);
1649 if (files_log_ref_write(refs
, lock
->ref_name
,
1650 &lock
->old_oid
, oid
,
1652 char *old_msg
= strbuf_detach(err
, NULL
);
1653 strbuf_addf(err
, "cannot update the ref '%s': %s",
1654 lock
->ref_name
, old_msg
);
1660 if (strcmp(lock
->ref_name
, "HEAD") != 0) {
1662 * Special hack: If a branch is updated directly and HEAD
1663 * points to it (may happen on the remote side of a push
1664 * for example) then logically the HEAD reflog should be
1666 * A generic solution implies reverse symref information,
1667 * but finding all symrefs pointing to the given branch
1668 * would be rather costly for this rare event (the direct
1669 * update of a branch) to be worth it. So let's cheat and
1670 * check with HEAD only which should cover 99% of all usage
1671 * scenarios (even 100% of the default ones).
1674 const char *head_ref
;
1676 head_ref
= refs_resolve_ref_unsafe(&refs
->base
, "HEAD",
1677 RESOLVE_REF_READING
,
1679 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
1680 !strcmp(head_ref
, lock
->ref_name
)) {
1681 struct strbuf log_err
= STRBUF_INIT
;
1682 if (files_log_ref_write(refs
, "HEAD",
1683 &lock
->old_oid
, oid
,
1684 logmsg
, 0, &log_err
)) {
1685 error("%s", log_err
.buf
);
1686 strbuf_release(&log_err
);
1691 if (commit_ref(lock
)) {
1692 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
1701 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
1704 #ifndef NO_SYMLINK_HEAD
1705 char *ref_path
= get_locked_file_path(&lock
->lk
);
1707 ret
= symlink(target
, ref_path
);
1711 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
1716 static void update_symref_reflog(struct files_ref_store
*refs
,
1717 struct ref_lock
*lock
, const char *refname
,
1718 const char *target
, const char *logmsg
)
1720 struct strbuf err
= STRBUF_INIT
;
1721 struct object_id new_oid
;
1723 !refs_read_ref_full(&refs
->base
, target
,
1724 RESOLVE_REF_READING
, &new_oid
, NULL
) &&
1725 files_log_ref_write(refs
, refname
, &lock
->old_oid
,
1726 &new_oid
, logmsg
, 0, &err
)) {
1727 error("%s", err
.buf
);
1728 strbuf_release(&err
);
1732 static int create_symref_locked(struct files_ref_store
*refs
,
1733 struct ref_lock
*lock
, const char *refname
,
1734 const char *target
, const char *logmsg
)
1736 if (prefer_symlink_refs
&& !create_ref_symlink(lock
, target
)) {
1737 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1741 if (!fdopen_lock_file(&lock
->lk
, "w"))
1742 return error("unable to fdopen %s: %s",
1743 lock
->lk
.tempfile
->filename
.buf
, strerror(errno
));
1745 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1747 /* no error check; commit_ref will check ferror */
1748 fprintf(lock
->lk
.tempfile
->fp
, "ref: %s\n", target
);
1749 if (commit_ref(lock
) < 0)
1750 return error("unable to write symref for %s: %s", refname
,
1755 static int files_create_symref(struct ref_store
*ref_store
,
1756 const char *refname
, const char *target
,
1759 struct files_ref_store
*refs
=
1760 files_downcast(ref_store
, REF_STORE_WRITE
, "create_symref");
1761 struct strbuf err
= STRBUF_INIT
;
1762 struct ref_lock
*lock
;
1765 lock
= lock_ref_sha1_basic(refs
, refname
, NULL
,
1766 NULL
, NULL
, REF_NODEREF
, NULL
,
1769 error("%s", err
.buf
);
1770 strbuf_release(&err
);
1774 ret
= create_symref_locked(refs
, lock
, refname
, target
, logmsg
);
1779 static int files_reflog_exists(struct ref_store
*ref_store
,
1780 const char *refname
)
1782 struct files_ref_store
*refs
=
1783 files_downcast(ref_store
, REF_STORE_READ
, "reflog_exists");
1784 struct strbuf sb
= STRBUF_INIT
;
1788 files_reflog_path(refs
, &sb
, refname
);
1789 ret
= !lstat(sb
.buf
, &st
) && S_ISREG(st
.st_mode
);
1790 strbuf_release(&sb
);
1794 static int files_delete_reflog(struct ref_store
*ref_store
,
1795 const char *refname
)
1797 struct files_ref_store
*refs
=
1798 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_reflog");
1799 struct strbuf sb
= STRBUF_INIT
;
1802 files_reflog_path(refs
, &sb
, refname
);
1803 ret
= remove_path(sb
.buf
);
1804 strbuf_release(&sb
);
1808 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
1810 struct object_id ooid
, noid
;
1811 char *email_end
, *message
;
1812 timestamp_t timestamp
;
1814 const char *p
= sb
->buf
;
1816 /* old SP new SP name <email> SP time TAB msg LF */
1817 if (!sb
->len
|| sb
->buf
[sb
->len
- 1] != '\n' ||
1818 parse_oid_hex(p
, &ooid
, &p
) || *p
++ != ' ' ||
1819 parse_oid_hex(p
, &noid
, &p
) || *p
++ != ' ' ||
1820 !(email_end
= strchr(p
, '>')) ||
1821 email_end
[1] != ' ' ||
1822 !(timestamp
= parse_timestamp(email_end
+ 2, &message
, 10)) ||
1823 !message
|| message
[0] != ' ' ||
1824 (message
[1] != '+' && message
[1] != '-') ||
1825 !isdigit(message
[2]) || !isdigit(message
[3]) ||
1826 !isdigit(message
[4]) || !isdigit(message
[5]))
1827 return 0; /* corrupt? */
1828 email_end
[1] = '\0';
1829 tz
= strtol(message
+ 1, NULL
, 10);
1830 if (message
[6] != '\t')
1834 return fn(&ooid
, &noid
, p
, timestamp
, tz
, message
, cb_data
);
1837 static char *find_beginning_of_line(char *bob
, char *scan
)
1839 while (bob
< scan
&& *(--scan
) != '\n')
1840 ; /* keep scanning backwards */
1842 * Return either beginning of the buffer, or LF at the end of
1843 * the previous line.
1848 static int files_for_each_reflog_ent_reverse(struct ref_store
*ref_store
,
1849 const char *refname
,
1850 each_reflog_ent_fn fn
,
1853 struct files_ref_store
*refs
=
1854 files_downcast(ref_store
, REF_STORE_READ
,
1855 "for_each_reflog_ent_reverse");
1856 struct strbuf sb
= STRBUF_INIT
;
1859 int ret
= 0, at_tail
= 1;
1861 files_reflog_path(refs
, &sb
, refname
);
1862 logfp
= fopen(sb
.buf
, "r");
1863 strbuf_release(&sb
);
1867 /* Jump to the end */
1868 if (fseek(logfp
, 0, SEEK_END
) < 0)
1869 ret
= error("cannot seek back reflog for %s: %s",
1870 refname
, strerror(errno
));
1872 while (!ret
&& 0 < pos
) {
1878 /* Fill next block from the end */
1879 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
1880 if (fseek(logfp
, pos
- cnt
, SEEK_SET
)) {
1881 ret
= error("cannot seek back reflog for %s: %s",
1882 refname
, strerror(errno
));
1885 nread
= fread(buf
, cnt
, 1, logfp
);
1887 ret
= error("cannot read %d bytes from reflog for %s: %s",
1888 cnt
, refname
, strerror(errno
));
1893 scanp
= endp
= buf
+ cnt
;
1894 if (at_tail
&& scanp
[-1] == '\n')
1895 /* Looking at the final LF at the end of the file */
1899 while (buf
< scanp
) {
1901 * terminating LF of the previous line, or the beginning
1906 bp
= find_beginning_of_line(buf
, scanp
);
1910 * The newline is the end of the previous line,
1911 * so we know we have complete line starting
1912 * at (bp + 1). Prefix it onto any prior data
1913 * we collected for the line and process it.
1915 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
1918 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
1924 * We are at the start of the buffer, and the
1925 * start of the file; there is no previous
1926 * line, and we have everything for this one.
1927 * Process it, and we can end the loop.
1929 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
1930 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
1937 * We are at the start of the buffer, and there
1938 * is more file to read backwards. Which means
1939 * we are in the middle of a line. Note that we
1940 * may get here even if *bp was a newline; that
1941 * just means we are at the exact end of the
1942 * previous line, rather than some spot in the
1945 * Save away what we have to be combined with
1946 * the data from the next read.
1948 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
1955 die("BUG: reverse reflog parser had leftover data");
1958 strbuf_release(&sb
);
1962 static int files_for_each_reflog_ent(struct ref_store
*ref_store
,
1963 const char *refname
,
1964 each_reflog_ent_fn fn
, void *cb_data
)
1966 struct files_ref_store
*refs
=
1967 files_downcast(ref_store
, REF_STORE_READ
,
1968 "for_each_reflog_ent");
1970 struct strbuf sb
= STRBUF_INIT
;
1973 files_reflog_path(refs
, &sb
, refname
);
1974 logfp
= fopen(sb
.buf
, "r");
1975 strbuf_release(&sb
);
1979 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
1980 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
1982 strbuf_release(&sb
);
1986 struct files_reflog_iterator
{
1987 struct ref_iterator base
;
1989 struct ref_store
*ref_store
;
1990 struct dir_iterator
*dir_iterator
;
1991 struct object_id oid
;
1994 static int files_reflog_iterator_advance(struct ref_iterator
*ref_iterator
)
1996 struct files_reflog_iterator
*iter
=
1997 (struct files_reflog_iterator
*)ref_iterator
;
1998 struct dir_iterator
*diter
= iter
->dir_iterator
;
2001 while ((ok
= dir_iterator_advance(diter
)) == ITER_OK
) {
2004 if (!S_ISREG(diter
->st
.st_mode
))
2006 if (diter
->basename
[0] == '.')
2008 if (ends_with(diter
->basename
, ".lock"))
2011 if (refs_read_ref_full(iter
->ref_store
,
2012 diter
->relative_path
, 0,
2013 &iter
->oid
, &flags
)) {
2014 error("bad ref for %s", diter
->path
.buf
);
2018 iter
->base
.refname
= diter
->relative_path
;
2019 iter
->base
.oid
= &iter
->oid
;
2020 iter
->base
.flags
= flags
;
2024 iter
->dir_iterator
= NULL
;
2025 if (ref_iterator_abort(ref_iterator
) == ITER_ERROR
)
2030 static int files_reflog_iterator_peel(struct ref_iterator
*ref_iterator
,
2031 struct object_id
*peeled
)
2033 die("BUG: ref_iterator_peel() called for reflog_iterator");
2036 static int files_reflog_iterator_abort(struct ref_iterator
*ref_iterator
)
2038 struct files_reflog_iterator
*iter
=
2039 (struct files_reflog_iterator
*)ref_iterator
;
2042 if (iter
->dir_iterator
)
2043 ok
= dir_iterator_abort(iter
->dir_iterator
);
2045 base_ref_iterator_free(ref_iterator
);
2049 static struct ref_iterator_vtable files_reflog_iterator_vtable
= {
2050 files_reflog_iterator_advance
,
2051 files_reflog_iterator_peel
,
2052 files_reflog_iterator_abort
2055 static struct ref_iterator
*reflog_iterator_begin(struct ref_store
*ref_store
,
2058 struct files_reflog_iterator
*iter
= xcalloc(1, sizeof(*iter
));
2059 struct ref_iterator
*ref_iterator
= &iter
->base
;
2060 struct strbuf sb
= STRBUF_INIT
;
2062 base_ref_iterator_init(ref_iterator
, &files_reflog_iterator_vtable
, 0);
2063 strbuf_addf(&sb
, "%s/logs", gitdir
);
2064 iter
->dir_iterator
= dir_iterator_begin(sb
.buf
);
2065 iter
->ref_store
= ref_store
;
2066 strbuf_release(&sb
);
2068 return ref_iterator
;
2071 static enum iterator_selection
reflog_iterator_select(
2072 struct ref_iterator
*iter_worktree
,
2073 struct ref_iterator
*iter_common
,
2076 if (iter_worktree
) {
2078 * We're a bit loose here. We probably should ignore
2079 * common refs if they are accidentally added as
2080 * per-worktree refs.
2082 return ITER_SELECT_0
;
2083 } else if (iter_common
) {
2084 if (ref_type(iter_common
->refname
) == REF_TYPE_NORMAL
)
2085 return ITER_SELECT_1
;
2088 * The main ref store may contain main worktree's
2089 * per-worktree refs, which should be ignored
2096 static struct ref_iterator
*files_reflog_iterator_begin(struct ref_store
*ref_store
)
2098 struct files_ref_store
*refs
=
2099 files_downcast(ref_store
, REF_STORE_READ
,
2100 "reflog_iterator_begin");
2102 if (!strcmp(refs
->gitdir
, refs
->gitcommondir
)) {
2103 return reflog_iterator_begin(ref_store
, refs
->gitcommondir
);
2105 return merge_ref_iterator_begin(
2107 reflog_iterator_begin(ref_store
, refs
->gitdir
),
2108 reflog_iterator_begin(ref_store
, refs
->gitcommondir
),
2109 reflog_iterator_select
, refs
);
2114 * If update is a direct update of head_ref (the reference pointed to
2115 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2117 static int split_head_update(struct ref_update
*update
,
2118 struct ref_transaction
*transaction
,
2119 const char *head_ref
,
2120 struct string_list
*affected_refnames
,
2123 struct string_list_item
*item
;
2124 struct ref_update
*new_update
;
2126 if ((update
->flags
& REF_LOG_ONLY
) ||
2127 (update
->flags
& REF_ISPRUNING
) ||
2128 (update
->flags
& REF_UPDATE_VIA_HEAD
))
2131 if (strcmp(update
->refname
, head_ref
))
2135 * First make sure that HEAD is not already in the
2136 * transaction. This check is O(lg N) in the transaction
2137 * size, but it happens at most once per transaction.
2139 if (string_list_has_string(affected_refnames
, "HEAD")) {
2140 /* An entry already existed */
2142 "multiple updates for 'HEAD' (including one "
2143 "via its referent '%s') are not allowed",
2145 return TRANSACTION_NAME_CONFLICT
;
2148 new_update
= ref_transaction_add_update(
2149 transaction
, "HEAD",
2150 update
->flags
| REF_LOG_ONLY
| REF_NODEREF
,
2151 &update
->new_oid
, &update
->old_oid
,
2155 * Add "HEAD". This insertion is O(N) in the transaction
2156 * size, but it happens at most once per transaction.
2157 * Add new_update->refname instead of a literal "HEAD".
2159 if (strcmp(new_update
->refname
, "HEAD"))
2160 BUG("%s unexpectedly not 'HEAD'", new_update
->refname
);
2161 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2162 item
->util
= new_update
;
2168 * update is for a symref that points at referent and doesn't have
2169 * REF_NODEREF set. Split it into two updates:
2170 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2171 * - A new, separate update for the referent reference
2172 * Note that the new update will itself be subject to splitting when
2173 * the iteration gets to it.
2175 static int split_symref_update(struct files_ref_store
*refs
,
2176 struct ref_update
*update
,
2177 const char *referent
,
2178 struct ref_transaction
*transaction
,
2179 struct string_list
*affected_refnames
,
2182 struct string_list_item
*item
;
2183 struct ref_update
*new_update
;
2184 unsigned int new_flags
;
2187 * First make sure that referent is not already in the
2188 * transaction. This check is O(lg N) in the transaction
2189 * size, but it happens at most once per symref in a
2192 if (string_list_has_string(affected_refnames
, referent
)) {
2193 /* An entry already exists */
2195 "multiple updates for '%s' (including one "
2196 "via symref '%s') are not allowed",
2197 referent
, update
->refname
);
2198 return TRANSACTION_NAME_CONFLICT
;
2201 new_flags
= update
->flags
;
2202 if (!strcmp(update
->refname
, "HEAD")) {
2204 * Record that the new update came via HEAD, so that
2205 * when we process it, split_head_update() doesn't try
2206 * to add another reflog update for HEAD. Note that
2207 * this bit will be propagated if the new_update
2208 * itself needs to be split.
2210 new_flags
|= REF_UPDATE_VIA_HEAD
;
2213 new_update
= ref_transaction_add_update(
2214 transaction
, referent
, new_flags
,
2215 &update
->new_oid
, &update
->old_oid
,
2218 new_update
->parent_update
= update
;
2221 * Change the symbolic ref update to log only. Also, it
2222 * doesn't need to check its old SHA-1 value, as that will be
2223 * done when new_update is processed.
2225 update
->flags
|= REF_LOG_ONLY
| REF_NODEREF
;
2226 update
->flags
&= ~REF_HAVE_OLD
;
2229 * Add the referent. This insertion is O(N) in the transaction
2230 * size, but it happens at most once per symref in a
2231 * transaction. Make sure to add new_update->refname, which will
2232 * be valid as long as affected_refnames is in use, and NOT
2233 * referent, which might soon be freed by our caller.
2235 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2237 BUG("%s unexpectedly found in affected_refnames",
2238 new_update
->refname
);
2239 item
->util
= new_update
;
2245 * Return the refname under which update was originally requested.
2247 static const char *original_update_refname(struct ref_update
*update
)
2249 while (update
->parent_update
)
2250 update
= update
->parent_update
;
2252 return update
->refname
;
2256 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2257 * are consistent with oid, which is the reference's current value. If
2258 * everything is OK, return 0; otherwise, write an error message to
2259 * err and return -1.
2261 static int check_old_oid(struct ref_update
*update
, struct object_id
*oid
,
2264 if (!(update
->flags
& REF_HAVE_OLD
) ||
2265 !oidcmp(oid
, &update
->old_oid
))
2268 if (is_null_oid(&update
->old_oid
))
2269 strbuf_addf(err
, "cannot lock ref '%s': "
2270 "reference already exists",
2271 original_update_refname(update
));
2272 else if (is_null_oid(oid
))
2273 strbuf_addf(err
, "cannot lock ref '%s': "
2274 "reference is missing but expected %s",
2275 original_update_refname(update
),
2276 oid_to_hex(&update
->old_oid
));
2278 strbuf_addf(err
, "cannot lock ref '%s': "
2279 "is at %s but expected %s",
2280 original_update_refname(update
),
2282 oid_to_hex(&update
->old_oid
));
2288 * Prepare for carrying out update:
2289 * - Lock the reference referred to by update.
2290 * - Read the reference under lock.
2291 * - Check that its old SHA-1 value (if specified) is correct, and in
2292 * any case record it in update->lock->old_oid for later use when
2293 * writing the reflog.
2294 * - If it is a symref update without REF_NODEREF, split it up into a
2295 * REF_LOG_ONLY update of the symref and add a separate update for
2296 * the referent to transaction.
2297 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2300 static int lock_ref_for_update(struct files_ref_store
*refs
,
2301 struct ref_update
*update
,
2302 struct ref_transaction
*transaction
,
2303 const char *head_ref
,
2304 struct string_list
*affected_refnames
,
2307 struct strbuf referent
= STRBUF_INIT
;
2308 int mustexist
= (update
->flags
& REF_HAVE_OLD
) &&
2309 !is_null_oid(&update
->old_oid
);
2311 struct ref_lock
*lock
;
2313 files_assert_main_repository(refs
, "lock_ref_for_update");
2315 if ((update
->flags
& REF_HAVE_NEW
) && is_null_oid(&update
->new_oid
))
2316 update
->flags
|= REF_DELETING
;
2319 ret
= split_head_update(update
, transaction
, head_ref
,
2320 affected_refnames
, err
);
2325 ret
= lock_raw_ref(refs
, update
->refname
, mustexist
,
2326 affected_refnames
, NULL
,
2328 &update
->type
, err
);
2332 reason
= strbuf_detach(err
, NULL
);
2333 strbuf_addf(err
, "cannot lock ref '%s': %s",
2334 original_update_refname(update
), reason
);
2339 update
->backend_data
= lock
;
2341 if (update
->type
& REF_ISSYMREF
) {
2342 if (update
->flags
& REF_NODEREF
) {
2344 * We won't be reading the referent as part of
2345 * the transaction, so we have to read it here
2346 * to record and possibly check old_sha1:
2348 if (refs_read_ref_full(&refs
->base
,
2350 &lock
->old_oid
, NULL
)) {
2351 if (update
->flags
& REF_HAVE_OLD
) {
2352 strbuf_addf(err
, "cannot lock ref '%s': "
2353 "error reading reference",
2354 original_update_refname(update
));
2355 ret
= TRANSACTION_GENERIC_ERROR
;
2358 } else if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2359 ret
= TRANSACTION_GENERIC_ERROR
;
2364 * Create a new update for the reference this
2365 * symref is pointing at. Also, we will record
2366 * and verify old_sha1 for this update as part
2367 * of processing the split-off update, so we
2368 * don't have to do it here.
2370 ret
= split_symref_update(refs
, update
,
2371 referent
.buf
, transaction
,
2372 affected_refnames
, err
);
2377 struct ref_update
*parent_update
;
2379 if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2380 ret
= TRANSACTION_GENERIC_ERROR
;
2385 * If this update is happening indirectly because of a
2386 * symref update, record the old SHA-1 in the parent
2389 for (parent_update
= update
->parent_update
;
2391 parent_update
= parent_update
->parent_update
) {
2392 struct ref_lock
*parent_lock
= parent_update
->backend_data
;
2393 oidcpy(&parent_lock
->old_oid
, &lock
->old_oid
);
2397 if ((update
->flags
& REF_HAVE_NEW
) &&
2398 !(update
->flags
& REF_DELETING
) &&
2399 !(update
->flags
& REF_LOG_ONLY
)) {
2400 if (!(update
->type
& REF_ISSYMREF
) &&
2401 !oidcmp(&lock
->old_oid
, &update
->new_oid
)) {
2403 * The reference already has the desired
2404 * value, so we don't need to write it.
2406 } else if (write_ref_to_lockfile(lock
, &update
->new_oid
,
2408 char *write_err
= strbuf_detach(err
, NULL
);
2411 * The lock was freed upon failure of
2412 * write_ref_to_lockfile():
2414 update
->backend_data
= NULL
;
2416 "cannot update ref '%s': %s",
2417 update
->refname
, write_err
);
2419 ret
= TRANSACTION_GENERIC_ERROR
;
2422 update
->flags
|= REF_NEEDS_COMMIT
;
2425 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
2427 * We didn't call write_ref_to_lockfile(), so
2428 * the lockfile is still open. Close it to
2429 * free up the file descriptor:
2431 if (close_ref_gently(lock
)) {
2432 strbuf_addf(err
, "couldn't close '%s.lock'",
2434 ret
= TRANSACTION_GENERIC_ERROR
;
2440 strbuf_release(&referent
);
2444 struct files_transaction_backend_data
{
2445 struct ref_transaction
*packed_transaction
;
2446 int packed_refs_locked
;
2450 * Unlock any references in `transaction` that are still locked, and
2451 * mark the transaction closed.
2453 static void files_transaction_cleanup(struct files_ref_store
*refs
,
2454 struct ref_transaction
*transaction
)
2457 struct files_transaction_backend_data
*backend_data
=
2458 transaction
->backend_data
;
2459 struct strbuf err
= STRBUF_INIT
;
2461 for (i
= 0; i
< transaction
->nr
; i
++) {
2462 struct ref_update
*update
= transaction
->updates
[i
];
2463 struct ref_lock
*lock
= update
->backend_data
;
2467 update
->backend_data
= NULL
;
2471 if (backend_data
->packed_transaction
&&
2472 ref_transaction_abort(backend_data
->packed_transaction
, &err
)) {
2473 error("error aborting transaction: %s", err
.buf
);
2474 strbuf_release(&err
);
2477 if (backend_data
->packed_refs_locked
)
2478 packed_refs_unlock(refs
->packed_ref_store
);
2482 transaction
->state
= REF_TRANSACTION_CLOSED
;
2485 static int files_transaction_prepare(struct ref_store
*ref_store
,
2486 struct ref_transaction
*transaction
,
2489 struct files_ref_store
*refs
=
2490 files_downcast(ref_store
, REF_STORE_WRITE
,
2491 "ref_transaction_prepare");
2494 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2495 char *head_ref
= NULL
;
2497 struct files_transaction_backend_data
*backend_data
;
2498 struct ref_transaction
*packed_transaction
= NULL
;
2502 if (!transaction
->nr
)
2505 backend_data
= xcalloc(1, sizeof(*backend_data
));
2506 transaction
->backend_data
= backend_data
;
2509 * Fail if a refname appears more than once in the
2510 * transaction. (If we end up splitting up any updates using
2511 * split_symref_update() or split_head_update(), those
2512 * functions will check that the new updates don't have the
2513 * same refname as any existing ones.)
2515 for (i
= 0; i
< transaction
->nr
; i
++) {
2516 struct ref_update
*update
= transaction
->updates
[i
];
2517 struct string_list_item
*item
=
2518 string_list_append(&affected_refnames
, update
->refname
);
2521 * We store a pointer to update in item->util, but at
2522 * the moment we never use the value of this field
2523 * except to check whether it is non-NULL.
2525 item
->util
= update
;
2527 string_list_sort(&affected_refnames
);
2528 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2529 ret
= TRANSACTION_GENERIC_ERROR
;
2534 * Special hack: If a branch is updated directly and HEAD
2535 * points to it (may happen on the remote side of a push
2536 * for example) then logically the HEAD reflog should be
2539 * A generic solution would require reverse symref lookups,
2540 * but finding all symrefs pointing to a given branch would be
2541 * rather costly for this rare event (the direct update of a
2542 * branch) to be worth it. So let's cheat and check with HEAD
2543 * only, which should cover 99% of all usage scenarios (even
2544 * 100% of the default ones).
2546 * So if HEAD is a symbolic reference, then record the name of
2547 * the reference that it points to. If we see an update of
2548 * head_ref within the transaction, then split_head_update()
2549 * arranges for the reflog of HEAD to be updated, too.
2551 head_ref
= refs_resolve_refdup(ref_store
, "HEAD",
2552 RESOLVE_REF_NO_RECURSE
,
2555 if (head_ref
&& !(head_type
& REF_ISSYMREF
)) {
2556 FREE_AND_NULL(head_ref
);
2560 * Acquire all locks, verify old values if provided, check
2561 * that new values are valid, and write new values to the
2562 * lockfiles, ready to be activated. Only keep one lockfile
2563 * open at a time to avoid running out of file descriptors.
2564 * Note that lock_ref_for_update() might append more updates
2565 * to the transaction.
2567 for (i
= 0; i
< transaction
->nr
; i
++) {
2568 struct ref_update
*update
= transaction
->updates
[i
];
2570 ret
= lock_ref_for_update(refs
, update
, transaction
,
2571 head_ref
, &affected_refnames
, err
);
2575 if (update
->flags
& REF_DELETING
&&
2576 !(update
->flags
& REF_LOG_ONLY
) &&
2577 !(update
->flags
& REF_ISPRUNING
)) {
2579 * This reference has to be deleted from
2580 * packed-refs if it exists there.
2582 if (!packed_transaction
) {
2583 packed_transaction
= ref_store_transaction_begin(
2584 refs
->packed_ref_store
, err
);
2585 if (!packed_transaction
) {
2586 ret
= TRANSACTION_GENERIC_ERROR
;
2590 backend_data
->packed_transaction
=
2594 ref_transaction_add_update(
2595 packed_transaction
, update
->refname
,
2596 update
->flags
& ~REF_HAVE_OLD
,
2597 &update
->new_oid
, &update
->old_oid
,
2602 if (packed_transaction
) {
2603 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2604 ret
= TRANSACTION_GENERIC_ERROR
;
2607 backend_data
->packed_refs_locked
= 1;
2608 ret
= ref_transaction_prepare(packed_transaction
, err
);
2613 string_list_clear(&affected_refnames
, 0);
2616 files_transaction_cleanup(refs
, transaction
);
2618 transaction
->state
= REF_TRANSACTION_PREPARED
;
2623 static int files_transaction_finish(struct ref_store
*ref_store
,
2624 struct ref_transaction
*transaction
,
2627 struct files_ref_store
*refs
=
2628 files_downcast(ref_store
, 0, "ref_transaction_finish");
2631 struct strbuf sb
= STRBUF_INIT
;
2632 struct files_transaction_backend_data
*backend_data
;
2633 struct ref_transaction
*packed_transaction
;
2638 if (!transaction
->nr
) {
2639 transaction
->state
= REF_TRANSACTION_CLOSED
;
2643 backend_data
= transaction
->backend_data
;
2644 packed_transaction
= backend_data
->packed_transaction
;
2646 /* Perform updates first so live commits remain referenced */
2647 for (i
= 0; i
< transaction
->nr
; i
++) {
2648 struct ref_update
*update
= transaction
->updates
[i
];
2649 struct ref_lock
*lock
= update
->backend_data
;
2651 if (update
->flags
& REF_NEEDS_COMMIT
||
2652 update
->flags
& REF_LOG_ONLY
) {
2653 if (files_log_ref_write(refs
,
2657 update
->msg
, update
->flags
,
2659 char *old_msg
= strbuf_detach(err
, NULL
);
2661 strbuf_addf(err
, "cannot update the ref '%s': %s",
2662 lock
->ref_name
, old_msg
);
2665 update
->backend_data
= NULL
;
2666 ret
= TRANSACTION_GENERIC_ERROR
;
2670 if (update
->flags
& REF_NEEDS_COMMIT
) {
2671 clear_loose_ref_cache(refs
);
2672 if (commit_ref(lock
)) {
2673 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
2675 update
->backend_data
= NULL
;
2676 ret
= TRANSACTION_GENERIC_ERROR
;
2683 * Now that updates are safely completed, we can perform
2684 * deletes. First delete the reflogs of any references that
2685 * will be deleted, since (in the unexpected event of an
2686 * error) leaving a reference without a reflog is less bad
2687 * than leaving a reflog without a reference (the latter is a
2688 * mildly invalid repository state):
2690 for (i
= 0; i
< transaction
->nr
; i
++) {
2691 struct ref_update
*update
= transaction
->updates
[i
];
2692 if (update
->flags
& REF_DELETING
&&
2693 !(update
->flags
& REF_LOG_ONLY
) &&
2694 !(update
->flags
& REF_ISPRUNING
)) {
2696 files_reflog_path(refs
, &sb
, update
->refname
);
2697 if (!unlink_or_warn(sb
.buf
))
2698 try_remove_empty_parents(refs
, update
->refname
,
2699 REMOVE_EMPTY_PARENTS_REFLOG
);
2704 * Perform deletes now that updates are safely completed.
2706 * First delete any packed versions of the references, while
2707 * retaining the packed-refs lock:
2709 if (packed_transaction
) {
2710 ret
= ref_transaction_commit(packed_transaction
, err
);
2711 ref_transaction_free(packed_transaction
);
2712 packed_transaction
= NULL
;
2713 backend_data
->packed_transaction
= NULL
;
2718 /* Now delete the loose versions of the references: */
2719 for (i
= 0; i
< transaction
->nr
; i
++) {
2720 struct ref_update
*update
= transaction
->updates
[i
];
2721 struct ref_lock
*lock
= update
->backend_data
;
2723 if (update
->flags
& REF_DELETING
&&
2724 !(update
->flags
& REF_LOG_ONLY
)) {
2725 if (!(update
->type
& REF_ISPACKED
) ||
2726 update
->type
& REF_ISSYMREF
) {
2727 /* It is a loose reference. */
2729 files_ref_path(refs
, &sb
, lock
->ref_name
);
2730 if (unlink_or_msg(sb
.buf
, err
)) {
2731 ret
= TRANSACTION_GENERIC_ERROR
;
2734 update
->flags
|= REF_DELETED_LOOSE
;
2739 clear_loose_ref_cache(refs
);
2742 files_transaction_cleanup(refs
, transaction
);
2744 for (i
= 0; i
< transaction
->nr
; i
++) {
2745 struct ref_update
*update
= transaction
->updates
[i
];
2747 if (update
->flags
& REF_DELETED_LOOSE
) {
2749 * The loose reference was deleted. Delete any
2750 * empty parent directories. (Note that this
2751 * can only work because we have already
2752 * removed the lockfile.)
2754 try_remove_empty_parents(refs
, update
->refname
,
2755 REMOVE_EMPTY_PARENTS_REF
);
2759 strbuf_release(&sb
);
2763 static int files_transaction_abort(struct ref_store
*ref_store
,
2764 struct ref_transaction
*transaction
,
2767 struct files_ref_store
*refs
=
2768 files_downcast(ref_store
, 0, "ref_transaction_abort");
2770 files_transaction_cleanup(refs
, transaction
);
2774 static int ref_present(const char *refname
,
2775 const struct object_id
*oid
, int flags
, void *cb_data
)
2777 struct string_list
*affected_refnames
= cb_data
;
2779 return string_list_has_string(affected_refnames
, refname
);
2782 static int files_initial_transaction_commit(struct ref_store
*ref_store
,
2783 struct ref_transaction
*transaction
,
2786 struct files_ref_store
*refs
=
2787 files_downcast(ref_store
, REF_STORE_WRITE
,
2788 "initial_ref_transaction_commit");
2791 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2792 struct ref_transaction
*packed_transaction
= NULL
;
2796 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
2797 die("BUG: commit called for transaction that is not open");
2799 /* Fail if a refname appears more than once in the transaction: */
2800 for (i
= 0; i
< transaction
->nr
; i
++)
2801 string_list_append(&affected_refnames
,
2802 transaction
->updates
[i
]->refname
);
2803 string_list_sort(&affected_refnames
);
2804 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2805 ret
= TRANSACTION_GENERIC_ERROR
;
2810 * It's really undefined to call this function in an active
2811 * repository or when there are existing references: we are
2812 * only locking and changing packed-refs, so (1) any
2813 * simultaneous processes might try to change a reference at
2814 * the same time we do, and (2) any existing loose versions of
2815 * the references that we are setting would have precedence
2816 * over our values. But some remote helpers create the remote
2817 * "HEAD" and "master" branches before calling this function,
2818 * so here we really only check that none of the references
2819 * that we are creating already exists.
2821 if (refs_for_each_rawref(&refs
->base
, ref_present
,
2822 &affected_refnames
))
2823 die("BUG: initial ref transaction called with existing refs");
2825 packed_transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, err
);
2826 if (!packed_transaction
) {
2827 ret
= TRANSACTION_GENERIC_ERROR
;
2831 for (i
= 0; i
< transaction
->nr
; i
++) {
2832 struct ref_update
*update
= transaction
->updates
[i
];
2834 if ((update
->flags
& REF_HAVE_OLD
) &&
2835 !is_null_oid(&update
->old_oid
))
2836 die("BUG: initial ref transaction with old_sha1 set");
2837 if (refs_verify_refname_available(&refs
->base
, update
->refname
,
2838 &affected_refnames
, NULL
,
2840 ret
= TRANSACTION_NAME_CONFLICT
;
2845 * Add a reference creation for this reference to the
2846 * packed-refs transaction:
2848 ref_transaction_add_update(packed_transaction
, update
->refname
,
2849 update
->flags
& ~REF_HAVE_OLD
,
2850 &update
->new_oid
, &update
->old_oid
,
2854 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2855 ret
= TRANSACTION_GENERIC_ERROR
;
2859 if (initial_ref_transaction_commit(packed_transaction
, err
)) {
2860 ret
= TRANSACTION_GENERIC_ERROR
;
2865 if (packed_transaction
)
2866 ref_transaction_free(packed_transaction
);
2867 packed_refs_unlock(refs
->packed_ref_store
);
2868 transaction
->state
= REF_TRANSACTION_CLOSED
;
2869 string_list_clear(&affected_refnames
, 0);
2873 struct expire_reflog_cb
{
2875 reflog_expiry_should_prune_fn
*should_prune_fn
;
2878 struct object_id last_kept_oid
;
2881 static int expire_reflog_ent(struct object_id
*ooid
, struct object_id
*noid
,
2882 const char *email
, timestamp_t timestamp
, int tz
,
2883 const char *message
, void *cb_data
)
2885 struct expire_reflog_cb
*cb
= cb_data
;
2886 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
2888 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
2889 ooid
= &cb
->last_kept_oid
;
2891 if ((*cb
->should_prune_fn
)(ooid
, noid
, email
, timestamp
, tz
,
2892 message
, policy_cb
)) {
2894 printf("would prune %s", message
);
2895 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
2896 printf("prune %s", message
);
2899 fprintf(cb
->newlog
, "%s %s %s %"PRItime
" %+05d\t%s",
2900 oid_to_hex(ooid
), oid_to_hex(noid
),
2901 email
, timestamp
, tz
, message
);
2902 oidcpy(&cb
->last_kept_oid
, noid
);
2904 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
2905 printf("keep %s", message
);
2910 static int files_reflog_expire(struct ref_store
*ref_store
,
2911 const char *refname
, const struct object_id
*oid
,
2913 reflog_expiry_prepare_fn prepare_fn
,
2914 reflog_expiry_should_prune_fn should_prune_fn
,
2915 reflog_expiry_cleanup_fn cleanup_fn
,
2916 void *policy_cb_data
)
2918 struct files_ref_store
*refs
=
2919 files_downcast(ref_store
, REF_STORE_WRITE
, "reflog_expire");
2920 static struct lock_file reflog_lock
;
2921 struct expire_reflog_cb cb
;
2922 struct ref_lock
*lock
;
2923 struct strbuf log_file_sb
= STRBUF_INIT
;
2927 struct strbuf err
= STRBUF_INIT
;
2929 memset(&cb
, 0, sizeof(cb
));
2931 cb
.policy_cb
= policy_cb_data
;
2932 cb
.should_prune_fn
= should_prune_fn
;
2935 * The reflog file is locked by holding the lock on the
2936 * reference itself, plus we might need to update the
2937 * reference if --updateref was specified:
2939 lock
= lock_ref_sha1_basic(refs
, refname
, oid
->hash
,
2940 NULL
, NULL
, REF_NODEREF
,
2943 error("cannot lock ref '%s': %s", refname
, err
.buf
);
2944 strbuf_release(&err
);
2947 if (!refs_reflog_exists(ref_store
, refname
)) {
2952 files_reflog_path(refs
, &log_file_sb
, refname
);
2953 log_file
= strbuf_detach(&log_file_sb
, NULL
);
2954 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
2956 * Even though holding $GIT_DIR/logs/$reflog.lock has
2957 * no locking implications, we use the lock_file
2958 * machinery here anyway because it does a lot of the
2959 * work we need, including cleaning up if the program
2960 * exits unexpectedly.
2962 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
2963 struct strbuf err
= STRBUF_INIT
;
2964 unable_to_lock_message(log_file
, errno
, &err
);
2965 error("%s", err
.buf
);
2966 strbuf_release(&err
);
2969 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
2971 error("cannot fdopen %s (%s)",
2972 get_lock_file_path(&reflog_lock
), strerror(errno
));
2977 (*prepare_fn
)(refname
, oid
, cb
.policy_cb
);
2978 refs_for_each_reflog_ent(ref_store
, refname
, expire_reflog_ent
, &cb
);
2979 (*cleanup_fn
)(cb
.policy_cb
);
2981 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
2983 * It doesn't make sense to adjust a reference pointed
2984 * to by a symbolic ref based on expiring entries in
2985 * the symbolic reference's reflog. Nor can we update
2986 * a reference if there are no remaining reflog
2989 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
2990 !(type
& REF_ISSYMREF
) &&
2991 !is_null_oid(&cb
.last_kept_oid
);
2993 if (close_lock_file_gently(&reflog_lock
)) {
2994 status
|= error("couldn't write %s: %s", log_file
,
2996 rollback_lock_file(&reflog_lock
);
2997 } else if (update
&&
2998 (write_in_full(get_lock_file_fd(&lock
->lk
),
2999 oid_to_hex(&cb
.last_kept_oid
), GIT_SHA1_HEXSZ
) < 0 ||
3000 write_str_in_full(get_lock_file_fd(&lock
->lk
), "\n") < 0 ||
3001 close_ref_gently(lock
) < 0)) {
3002 status
|= error("couldn't write %s",
3003 get_lock_file_path(&lock
->lk
));
3004 rollback_lock_file(&reflog_lock
);
3005 } else if (commit_lock_file(&reflog_lock
)) {
3006 status
|= error("unable to write reflog '%s' (%s)",
3007 log_file
, strerror(errno
));
3008 } else if (update
&& commit_ref(lock
)) {
3009 status
|= error("couldn't set %s", lock
->ref_name
);
3017 rollback_lock_file(&reflog_lock
);
3023 static int files_init_db(struct ref_store
*ref_store
, struct strbuf
*err
)
3025 struct files_ref_store
*refs
=
3026 files_downcast(ref_store
, REF_STORE_WRITE
, "init_db");
3027 struct strbuf sb
= STRBUF_INIT
;
3030 * Create .git/refs/{heads,tags}
3032 files_ref_path(refs
, &sb
, "refs/heads");
3033 safe_create_dir(sb
.buf
, 1);
3036 files_ref_path(refs
, &sb
, "refs/tags");
3037 safe_create_dir(sb
.buf
, 1);
3039 strbuf_release(&sb
);
3043 struct ref_storage_be refs_be_files
= {
3046 files_ref_store_create
,
3048 files_transaction_prepare
,
3049 files_transaction_finish
,
3050 files_transaction_abort
,
3051 files_initial_transaction_commit
,
3054 files_create_symref
,
3059 files_ref_iterator_begin
,
3062 files_reflog_iterator_begin
,
3063 files_for_each_reflog_ent
,
3064 files_for_each_reflog_ent_reverse
,
3065 files_reflog_exists
,
3066 files_create_reflog
,
3067 files_delete_reflog
,