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
;
72 struct ref_cache
*loose
;
74 struct ref_store
*packed_ref_store
;
77 static void clear_loose_ref_cache(struct files_ref_store
*refs
)
80 free_ref_cache(refs
->loose
);
86 * Create a new submodule ref cache and add it to the internal
89 static struct ref_store
*files_ref_store_create(const char *gitdir
,
92 struct files_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
93 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
94 struct strbuf sb
= STRBUF_INIT
;
96 ref_store
->gitdir
= xstrdup(gitdir
);
97 base_ref_store_init(ref_store
, &refs_be_files
);
98 refs
->store_flags
= flags
;
100 get_common_dir_noenv(&sb
, gitdir
);
101 refs
->gitcommondir
= strbuf_detach(&sb
, NULL
);
102 strbuf_addf(&sb
, "%s/packed-refs", refs
->gitcommondir
);
103 refs
->packed_ref_store
= packed_ref_store_create(sb
.buf
, flags
);
106 chdir_notify_reparent("files-backend $GIT_DIR", &refs
->base
.gitdir
);
107 chdir_notify_reparent("files-backend $GIT_COMMONDIR",
108 &refs
->gitcommondir
);
114 * Die if refs is not the main ref store. caller is used in any
115 * necessary error messages.
117 static void files_assert_main_repository(struct files_ref_store
*refs
,
120 if (refs
->store_flags
& REF_STORE_MAIN
)
123 BUG("operation %s only allowed for main ref store", caller
);
127 * Downcast ref_store to files_ref_store. Die if ref_store is not a
128 * files_ref_store. required_flags is compared with ref_store's
129 * store_flags to ensure the ref_store has all required capabilities.
130 * "caller" is used in any necessary error messages.
132 static struct files_ref_store
*files_downcast(struct ref_store
*ref_store
,
133 unsigned int required_flags
,
136 struct files_ref_store
*refs
;
138 if (ref_store
->be
!= &refs_be_files
)
139 BUG("ref_store is type \"%s\" not \"files\" in %s",
140 ref_store
->be
->name
, caller
);
142 refs
= (struct files_ref_store
*)ref_store
;
144 if ((refs
->store_flags
& required_flags
) != required_flags
)
145 BUG("operation %s requires abilities 0x%x, but only have 0x%x",
146 caller
, required_flags
, refs
->store_flags
);
151 static void files_reflog_path_other_worktrees(struct files_ref_store
*refs
,
155 const char *real_ref
;
156 const char *worktree_name
;
159 if (parse_worktree_ref(refname
, &worktree_name
, &length
, &real_ref
))
160 BUG("refname %s is not a other-worktree ref", refname
);
163 strbuf_addf(sb
, "%s/worktrees/%.*s/logs/%s", refs
->gitcommondir
,
164 length
, worktree_name
, real_ref
);
166 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
,
170 static void files_reflog_path(struct files_ref_store
*refs
,
174 switch (ref_type(refname
)) {
175 case REF_TYPE_PER_WORKTREE
:
176 case REF_TYPE_PSEUDOREF
:
177 strbuf_addf(sb
, "%s/logs/%s", refs
->base
.gitdir
, refname
);
179 case REF_TYPE_OTHER_PSEUDOREF
:
180 case REF_TYPE_MAIN_PSEUDOREF
:
181 files_reflog_path_other_worktrees(refs
, sb
, refname
);
183 case REF_TYPE_NORMAL
:
184 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
, refname
);
187 BUG("unknown ref type %d of ref %s",
188 ref_type(refname
), refname
);
192 static void files_ref_path(struct files_ref_store
*refs
,
196 switch (ref_type(refname
)) {
197 case REF_TYPE_PER_WORKTREE
:
198 case REF_TYPE_PSEUDOREF
:
199 strbuf_addf(sb
, "%s/%s", refs
->base
.gitdir
, refname
);
201 case REF_TYPE_MAIN_PSEUDOREF
:
202 if (!skip_prefix(refname
, "main-worktree/", &refname
))
203 BUG("ref %s is not a main pseudoref", refname
);
205 case REF_TYPE_OTHER_PSEUDOREF
:
206 case REF_TYPE_NORMAL
:
207 strbuf_addf(sb
, "%s/%s", refs
->gitcommondir
, refname
);
210 BUG("unknown ref type %d of ref %s",
211 ref_type(refname
), refname
);
216 * Manually add refs/bisect, refs/rewritten and refs/worktree, which, being
217 * per-worktree, might not appear in the directory listing for
218 * refs/ in the main repo.
220 static void add_per_worktree_entries_to_dir(struct ref_dir
*dir
, const char *dirname
)
222 const char *prefixes
[] = { "refs/bisect/", "refs/worktree/", "refs/rewritten/" };
225 if (strcmp(dirname
, "refs/"))
228 for (ip
= 0; ip
< ARRAY_SIZE(prefixes
); ip
++) {
229 const char *prefix
= prefixes
[ip
];
230 int prefix_len
= strlen(prefix
);
231 struct ref_entry
*child_entry
;
234 pos
= search_ref_dir(dir
, prefix
, prefix_len
);
237 child_entry
= create_dir_entry(dir
->cache
, prefix
, prefix_len
, 1);
238 add_entry_to_dir(dir
, child_entry
);
243 * Read the loose references from the namespace dirname into dir
244 * (without recursing). dirname must end with '/'. dir must be the
245 * directory entry corresponding to dirname.
247 static void loose_fill_ref_dir(struct ref_store
*ref_store
,
248 struct ref_dir
*dir
, const char *dirname
)
250 struct files_ref_store
*refs
=
251 files_downcast(ref_store
, REF_STORE_READ
, "fill_ref_dir");
254 int dirnamelen
= strlen(dirname
);
255 struct strbuf refname
;
256 struct strbuf path
= STRBUF_INIT
;
259 files_ref_path(refs
, &path
, dirname
);
260 path_baselen
= path
.len
;
262 d
= opendir(path
.buf
);
264 strbuf_release(&path
);
268 strbuf_init(&refname
, dirnamelen
+ 257);
269 strbuf_add(&refname
, dirname
, dirnamelen
);
271 while ((de
= readdir(d
)) != NULL
) {
272 struct object_id oid
;
276 if (de
->d_name
[0] == '.')
278 if (ends_with(de
->d_name
, ".lock"))
280 strbuf_addstr(&refname
, de
->d_name
);
281 strbuf_addstr(&path
, de
->d_name
);
282 if (stat(path
.buf
, &st
) < 0) {
283 ; /* silently ignore */
284 } else if (S_ISDIR(st
.st_mode
)) {
285 strbuf_addch(&refname
, '/');
286 add_entry_to_dir(dir
,
287 create_dir_entry(dir
->cache
, refname
.buf
,
290 if (!refs_resolve_ref_unsafe(&refs
->base
,
295 flag
|= REF_ISBROKEN
;
296 } else if (is_null_oid(&oid
)) {
298 * It is so astronomically unlikely
299 * that null_oid is the OID of an
300 * actual object that we consider its
301 * appearance in a loose reference
302 * file to be repo corruption
303 * (probably due to a software bug).
305 flag
|= REF_ISBROKEN
;
308 if (check_refname_format(refname
.buf
,
309 REFNAME_ALLOW_ONELEVEL
)) {
310 if (!refname_is_safe(refname
.buf
))
311 die("loose refname is dangerous: %s", refname
.buf
);
313 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
315 add_entry_to_dir(dir
,
316 create_ref_entry(refname
.buf
, &oid
, flag
));
318 strbuf_setlen(&refname
, dirnamelen
);
319 strbuf_setlen(&path
, path_baselen
);
321 strbuf_release(&refname
);
322 strbuf_release(&path
);
325 add_per_worktree_entries_to_dir(dir
, dirname
);
328 static struct ref_cache
*get_loose_ref_cache(struct files_ref_store
*refs
)
332 * Mark the top-level directory complete because we
333 * are about to read the only subdirectory that can
336 refs
->loose
= create_ref_cache(&refs
->base
, loose_fill_ref_dir
);
338 /* We're going to fill the top level ourselves: */
339 refs
->loose
->root
->flag
&= ~REF_INCOMPLETE
;
342 * Add an incomplete entry for "refs/" (to be filled
345 add_entry_to_dir(get_ref_dir(refs
->loose
->root
),
346 create_dir_entry(refs
->loose
, "refs/", 5, 1));
351 static int files_read_raw_ref(struct ref_store
*ref_store
,
352 const char *refname
, struct object_id
*oid
,
353 struct strbuf
*referent
, unsigned int *type
)
355 struct files_ref_store
*refs
=
356 files_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
357 struct strbuf sb_contents
= STRBUF_INIT
;
358 struct strbuf sb_path
= STRBUF_INIT
;
365 int remaining_retries
= 3;
368 strbuf_reset(&sb_path
);
370 files_ref_path(refs
, &sb_path
, refname
);
376 * We might have to loop back here to avoid a race
377 * condition: first we lstat() the file, then we try
378 * to read it as a link or as a file. But if somebody
379 * changes the type of the file (file <-> directory
380 * <-> symlink) between the lstat() and reading, then
381 * we don't want to report that as an error but rather
382 * try again starting with the lstat().
384 * We'll keep a count of the retries, though, just to avoid
385 * any confusing situation sending us into an infinite loop.
388 if (remaining_retries
-- <= 0)
391 if (lstat(path
, &st
) < 0) {
394 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
,
395 oid
, referent
, type
)) {
403 /* Follow "normalized" - ie "refs/.." symlinks by hand */
404 if (S_ISLNK(st
.st_mode
)) {
405 strbuf_reset(&sb_contents
);
406 if (strbuf_readlink(&sb_contents
, path
, st
.st_size
) < 0) {
407 if (errno
== ENOENT
|| errno
== EINVAL
)
408 /* inconsistent with lstat; retry */
413 if (starts_with(sb_contents
.buf
, "refs/") &&
414 !check_refname_format(sb_contents
.buf
, 0)) {
415 strbuf_swap(&sb_contents
, referent
);
416 *type
|= REF_ISSYMREF
;
421 * It doesn't look like a refname; fall through to just
422 * treating it like a non-symlink, and reading whatever it
427 /* Is it a directory? */
428 if (S_ISDIR(st
.st_mode
)) {
430 * Even though there is a directory where the loose
431 * ref is supposed to be, there could still be a
434 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
,
435 oid
, referent
, type
)) {
444 * Anything else, just open it and try to use it as
447 fd
= open(path
, O_RDONLY
);
449 if (errno
== ENOENT
&& !S_ISLNK(st
.st_mode
))
450 /* inconsistent with lstat; retry */
455 strbuf_reset(&sb_contents
);
456 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
457 int save_errno
= errno
;
463 strbuf_rtrim(&sb_contents
);
464 buf
= sb_contents
.buf
;
466 ret
= parse_loose_ref_contents(buf
, oid
, referent
, type
);
470 strbuf_release(&sb_path
);
471 strbuf_release(&sb_contents
);
476 int parse_loose_ref_contents(const char *buf
, struct object_id
*oid
,
477 struct strbuf
*referent
, unsigned int *type
)
480 if (skip_prefix(buf
, "ref:", &buf
)) {
481 while (isspace(*buf
))
484 strbuf_reset(referent
);
485 strbuf_addstr(referent
, buf
);
486 *type
|= REF_ISSYMREF
;
491 * FETCH_HEAD has additional data after the sha.
493 if (parse_oid_hex(buf
, oid
, &p
) ||
494 (*p
!= '\0' && !isspace(*p
))) {
495 *type
|= REF_ISBROKEN
;
502 static void unlock_ref(struct ref_lock
*lock
)
504 rollback_lock_file(&lock
->lk
);
505 free(lock
->ref_name
);
510 * Lock refname, without following symrefs, and set *lock_p to point
511 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
512 * and type similarly to read_raw_ref().
514 * The caller must verify that refname is a "safe" reference name (in
515 * the sense of refname_is_safe()) before calling this function.
517 * If the reference doesn't already exist, verify that refname doesn't
518 * have a D/F conflict with any existing references. extras and skip
519 * are passed to refs_verify_refname_available() for this check.
521 * If mustexist is not set and the reference is not found or is
522 * broken, lock the reference anyway but clear old_oid.
524 * Return 0 on success. On failure, write an error message to err and
525 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
527 * Implementation note: This function is basically
532 * but it includes a lot more code to
533 * - Deal with possible races with other processes
534 * - Avoid calling refs_verify_refname_available() when it can be
535 * avoided, namely if we were successfully able to read the ref
536 * - Generate informative error messages in the case of failure
538 static int lock_raw_ref(struct files_ref_store
*refs
,
539 const char *refname
, int mustexist
,
540 const struct string_list
*extras
,
541 const struct string_list
*skip
,
542 struct ref_lock
**lock_p
,
543 struct strbuf
*referent
,
547 struct ref_lock
*lock
;
548 struct strbuf ref_file
= STRBUF_INIT
;
549 int attempts_remaining
= 3;
550 int ret
= TRANSACTION_GENERIC_ERROR
;
553 files_assert_main_repository(refs
, "lock_raw_ref");
557 /* First lock the file so it can't change out from under us. */
559 *lock_p
= lock
= xcalloc(1, sizeof(*lock
));
561 lock
->ref_name
= xstrdup(refname
);
562 files_ref_path(refs
, &ref_file
, refname
);
565 switch (safe_create_leading_directories(ref_file
.buf
)) {
570 * Suppose refname is "refs/foo/bar". We just failed
571 * to create the containing directory, "refs/foo",
572 * because there was a non-directory in the way. This
573 * indicates a D/F conflict, probably because of
574 * another reference such as "refs/foo". There is no
575 * reason to expect this error to be transitory.
577 if (refs_verify_refname_available(&refs
->base
, refname
,
578 extras
, skip
, err
)) {
581 * To the user the relevant error is
582 * that the "mustexist" reference is
586 strbuf_addf(err
, "unable to resolve reference '%s'",
590 * The error message set by
591 * refs_verify_refname_available() is
594 ret
= TRANSACTION_NAME_CONFLICT
;
598 * The file that is in the way isn't a loose
599 * reference. Report it as a low-level
602 strbuf_addf(err
, "unable to create lock file %s.lock; "
603 "non-directory in the way",
608 /* Maybe another process was tidying up. Try again. */
609 if (--attempts_remaining
> 0)
613 strbuf_addf(err
, "unable to create directory for %s",
618 if (hold_lock_file_for_update_timeout(
619 &lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
,
620 get_files_ref_lock_timeout_ms()) < 0) {
621 if (errno
== ENOENT
&& --attempts_remaining
> 0) {
623 * Maybe somebody just deleted one of the
624 * directories leading to ref_file. Try
629 unable_to_lock_message(ref_file
.buf
, errno
, err
);
635 * Now we hold the lock and can read the reference without
636 * fear that its value will change.
639 if (files_read_raw_ref(&refs
->base
, refname
,
640 &lock
->old_oid
, referent
, type
)) {
641 if (errno
== ENOENT
) {
643 /* Garden variety missing reference. */
644 strbuf_addf(err
, "unable to resolve reference '%s'",
649 * Reference is missing, but that's OK. We
650 * know that there is not a conflict with
651 * another loose reference because
652 * (supposing that we are trying to lock
653 * reference "refs/foo/bar"):
655 * - We were successfully able to create
656 * the lockfile refs/foo/bar.lock, so we
657 * know there cannot be a loose reference
660 * - We got ENOENT and not EISDIR, so we
661 * know that there cannot be a loose
662 * reference named "refs/foo/bar/baz".
665 } else if (errno
== EISDIR
) {
667 * There is a directory in the way. It might have
668 * contained references that have been deleted. If
669 * we don't require that the reference already
670 * exists, try to remove the directory so that it
671 * doesn't cause trouble when we want to rename the
672 * lockfile into place later.
675 /* Garden variety missing reference. */
676 strbuf_addf(err
, "unable to resolve reference '%s'",
679 } else if (remove_dir_recursively(&ref_file
,
680 REMOVE_DIR_EMPTY_ONLY
)) {
681 if (refs_verify_refname_available(
682 &refs
->base
, refname
,
683 extras
, skip
, err
)) {
685 * The error message set by
686 * verify_refname_available() is OK.
688 ret
= TRANSACTION_NAME_CONFLICT
;
692 * We can't delete the directory,
693 * but we also don't know of any
694 * references that it should
697 strbuf_addf(err
, "there is a non-empty directory '%s' "
698 "blocking reference '%s'",
699 ref_file
.buf
, refname
);
703 } else if (errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
704 strbuf_addf(err
, "unable to resolve reference '%s': "
705 "reference broken", refname
);
708 strbuf_addf(err
, "unable to resolve reference '%s': %s",
709 refname
, strerror(errno
));
714 * If the ref did not exist and we are creating it,
715 * make sure there is no existing packed ref that
716 * conflicts with refname:
718 if (refs_verify_refname_available(
719 refs
->packed_ref_store
, refname
,
732 strbuf_release(&ref_file
);
736 struct files_ref_iterator
{
737 struct ref_iterator base
;
739 struct ref_iterator
*iter0
;
743 static int files_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
745 struct files_ref_iterator
*iter
=
746 (struct files_ref_iterator
*)ref_iterator
;
749 while ((ok
= ref_iterator_advance(iter
->iter0
)) == ITER_OK
) {
750 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
751 ref_type(iter
->iter0
->refname
) != REF_TYPE_PER_WORKTREE
)
754 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
755 !ref_resolves_to_object(iter
->iter0
->refname
,
760 iter
->base
.refname
= iter
->iter0
->refname
;
761 iter
->base
.oid
= iter
->iter0
->oid
;
762 iter
->base
.flags
= iter
->iter0
->flags
;
767 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
773 static int files_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
774 struct object_id
*peeled
)
776 struct files_ref_iterator
*iter
=
777 (struct files_ref_iterator
*)ref_iterator
;
779 return ref_iterator_peel(iter
->iter0
, peeled
);
782 static int files_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
784 struct files_ref_iterator
*iter
=
785 (struct files_ref_iterator
*)ref_iterator
;
789 ok
= ref_iterator_abort(iter
->iter0
);
791 base_ref_iterator_free(ref_iterator
);
795 static struct ref_iterator_vtable files_ref_iterator_vtable
= {
796 files_ref_iterator_advance
,
797 files_ref_iterator_peel
,
798 files_ref_iterator_abort
801 static struct ref_iterator
*files_ref_iterator_begin(
802 struct ref_store
*ref_store
,
803 const char *prefix
, unsigned int flags
)
805 struct files_ref_store
*refs
;
806 struct ref_iterator
*loose_iter
, *packed_iter
, *overlay_iter
;
807 struct files_ref_iterator
*iter
;
808 struct ref_iterator
*ref_iterator
;
809 unsigned int required_flags
= REF_STORE_READ
;
811 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
812 required_flags
|= REF_STORE_ODB
;
814 refs
= files_downcast(ref_store
, required_flags
, "ref_iterator_begin");
817 * We must make sure that all loose refs are read before
818 * accessing the packed-refs file; this avoids a race
819 * condition if loose refs are migrated to the packed-refs
820 * file by a simultaneous process, but our in-memory view is
821 * from before the migration. We ensure this as follows:
822 * First, we call start the loose refs iteration with its
823 * `prime_ref` argument set to true. This causes the loose
824 * references in the subtree to be pre-read into the cache.
825 * (If they've already been read, that's OK; we only need to
826 * guarantee that they're read before the packed refs, not
827 * *how much* before.) After that, we call
828 * packed_ref_iterator_begin(), which internally checks
829 * whether the packed-ref cache is up to date with what is on
830 * disk, and re-reads it if not.
833 loose_iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
),
837 * The packed-refs file might contain broken references, for
838 * example an old version of a reference that points at an
839 * object that has since been garbage-collected. This is OK as
840 * long as there is a corresponding loose reference that
841 * overrides it, and we don't want to emit an error message in
842 * this case. So ask the packed_ref_store for all of its
843 * references, and (if needed) do our own check for broken
844 * ones in files_ref_iterator_advance(), after we have merged
845 * the packed and loose references.
847 packed_iter
= refs_ref_iterator_begin(
848 refs
->packed_ref_store
, prefix
, 0,
849 DO_FOR_EACH_INCLUDE_BROKEN
);
851 overlay_iter
= overlay_ref_iterator_begin(loose_iter
, packed_iter
);
853 iter
= xcalloc(1, sizeof(*iter
));
854 ref_iterator
= &iter
->base
;
855 base_ref_iterator_init(ref_iterator
, &files_ref_iterator_vtable
,
856 overlay_iter
->ordered
);
857 iter
->iter0
= overlay_iter
;
864 * Verify that the reference locked by lock has the value old_oid
865 * (unless it is NULL). Fail if the reference doesn't exist and
866 * mustexist is set. Return 0 on success. On error, write an error
867 * message to err, set errno, and return a negative value.
869 static int verify_lock(struct ref_store
*ref_store
, struct ref_lock
*lock
,
870 const struct object_id
*old_oid
, int mustexist
,
875 if (refs_read_ref_full(ref_store
, lock
->ref_name
,
876 mustexist
? RESOLVE_REF_READING
: 0,
877 &lock
->old_oid
, NULL
)) {
879 int save_errno
= errno
;
880 strbuf_addf(err
, "can't verify ref '%s'", lock
->ref_name
);
884 oidclr(&lock
->old_oid
);
888 if (old_oid
&& !oideq(&lock
->old_oid
, old_oid
)) {
889 strbuf_addf(err
, "ref '%s' is at %s but expected %s",
891 oid_to_hex(&lock
->old_oid
),
892 oid_to_hex(old_oid
));
899 static int remove_empty_directories(struct strbuf
*path
)
902 * we want to create a file but there is a directory there;
903 * if that is an empty directory (or a directory that contains
904 * only empty directories), remove them.
906 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
909 static int create_reflock(const char *path
, void *cb
)
911 struct lock_file
*lk
= cb
;
913 return hold_lock_file_for_update_timeout(
914 lk
, path
, LOCK_NO_DEREF
,
915 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
919 * Locks a ref returning the lock on success and NULL on failure.
920 * On failure errno is set to something meaningful.
922 static struct ref_lock
*lock_ref_oid_basic(struct files_ref_store
*refs
,
924 const struct object_id
*old_oid
,
925 const struct string_list
*extras
,
926 const struct string_list
*skip
,
927 unsigned int flags
, int *type
,
930 struct strbuf ref_file
= STRBUF_INIT
;
931 struct ref_lock
*lock
;
933 int mustexist
= (old_oid
&& !is_null_oid(old_oid
));
934 int resolve_flags
= RESOLVE_REF_NO_RECURSE
;
937 files_assert_main_repository(refs
, "lock_ref_oid_basic");
940 lock
= xcalloc(1, sizeof(struct ref_lock
));
943 resolve_flags
|= RESOLVE_REF_READING
;
944 if (flags
& REF_DELETING
)
945 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
947 files_ref_path(refs
, &ref_file
, refname
);
948 resolved
= !!refs_resolve_ref_unsafe(&refs
->base
,
949 refname
, resolve_flags
,
950 &lock
->old_oid
, type
);
951 if (!resolved
&& errno
== EISDIR
) {
953 * we are trying to lock foo but we used to
954 * have foo/bar which now does not exist;
955 * it is normal for the empty directory 'foo'
958 if (remove_empty_directories(&ref_file
)) {
960 if (!refs_verify_refname_available(
962 refname
, extras
, skip
, err
))
963 strbuf_addf(err
, "there are still refs under '%s'",
967 resolved
= !!refs_resolve_ref_unsafe(&refs
->base
,
968 refname
, resolve_flags
,
969 &lock
->old_oid
, type
);
973 if (last_errno
!= ENOTDIR
||
974 !refs_verify_refname_available(&refs
->base
, refname
,
976 strbuf_addf(err
, "unable to resolve reference '%s': %s",
977 refname
, strerror(last_errno
));
983 * If the ref did not exist and we are creating it, make sure
984 * there is no existing packed ref whose name begins with our
985 * refname, nor a packed ref whose name is a proper prefix of
988 if (is_null_oid(&lock
->old_oid
) &&
989 refs_verify_refname_available(refs
->packed_ref_store
, refname
,
990 extras
, skip
, err
)) {
991 last_errno
= ENOTDIR
;
995 lock
->ref_name
= xstrdup(refname
);
997 if (raceproof_create_file(ref_file
.buf
, create_reflock
, &lock
->lk
)) {
999 unable_to_lock_message(ref_file
.buf
, errno
, err
);
1003 if (verify_lock(&refs
->base
, lock
, old_oid
, mustexist
, err
)) {
1014 strbuf_release(&ref_file
);
1019 struct ref_to_prune
{
1020 struct ref_to_prune
*next
;
1021 struct object_id oid
;
1022 char name
[FLEX_ARRAY
];
1026 REMOVE_EMPTY_PARENTS_REF
= 0x01,
1027 REMOVE_EMPTY_PARENTS_REFLOG
= 0x02
1031 * Remove empty parent directories associated with the specified
1032 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1033 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1034 * REMOVE_EMPTY_PARENTS_REFLOG.
1036 static void try_remove_empty_parents(struct files_ref_store
*refs
,
1037 const char *refname
,
1040 struct strbuf buf
= STRBUF_INIT
;
1041 struct strbuf sb
= STRBUF_INIT
;
1045 strbuf_addstr(&buf
, refname
);
1047 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
1048 while (*p
&& *p
!= '/')
1050 /* tolerate duplicate slashes; see check_refname_format() */
1054 q
= buf
.buf
+ buf
.len
;
1055 while (flags
& (REMOVE_EMPTY_PARENTS_REF
| REMOVE_EMPTY_PARENTS_REFLOG
)) {
1056 while (q
> p
&& *q
!= '/')
1058 while (q
> p
&& *(q
-1) == '/')
1062 strbuf_setlen(&buf
, q
- buf
.buf
);
1065 files_ref_path(refs
, &sb
, buf
.buf
);
1066 if ((flags
& REMOVE_EMPTY_PARENTS_REF
) && rmdir(sb
.buf
))
1067 flags
&= ~REMOVE_EMPTY_PARENTS_REF
;
1070 files_reflog_path(refs
, &sb
, buf
.buf
);
1071 if ((flags
& REMOVE_EMPTY_PARENTS_REFLOG
) && rmdir(sb
.buf
))
1072 flags
&= ~REMOVE_EMPTY_PARENTS_REFLOG
;
1074 strbuf_release(&buf
);
1075 strbuf_release(&sb
);
1078 /* make sure nobody touched the ref, and unlink */
1079 static void prune_ref(struct files_ref_store
*refs
, struct ref_to_prune
*r
)
1081 struct ref_transaction
*transaction
;
1082 struct strbuf err
= STRBUF_INIT
;
1085 if (check_refname_format(r
->name
, 0))
1088 transaction
= ref_store_transaction_begin(&refs
->base
, &err
);
1091 ref_transaction_add_update(
1092 transaction
, r
->name
,
1093 REF_NO_DEREF
| REF_HAVE_NEW
| REF_HAVE_OLD
| REF_IS_PRUNING
,
1094 &null_oid
, &r
->oid
, NULL
);
1095 if (ref_transaction_commit(transaction
, &err
))
1102 error("%s", err
.buf
);
1103 strbuf_release(&err
);
1104 ref_transaction_free(transaction
);
1109 * Prune the loose versions of the references in the linked list
1110 * `*refs_to_prune`, freeing the entries in the list as we go.
1112 static void prune_refs(struct files_ref_store
*refs
, struct ref_to_prune
**refs_to_prune
)
1114 while (*refs_to_prune
) {
1115 struct ref_to_prune
*r
= *refs_to_prune
;
1116 *refs_to_prune
= r
->next
;
1123 * Return true if the specified reference should be packed.
1125 static int should_pack_ref(const char *refname
,
1126 const struct object_id
*oid
, unsigned int ref_flags
,
1127 unsigned int pack_flags
)
1129 /* Do not pack per-worktree refs: */
1130 if (ref_type(refname
) != REF_TYPE_NORMAL
)
1133 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1134 if (!(pack_flags
& PACK_REFS_ALL
) && !starts_with(refname
, "refs/tags/"))
1137 /* Do not pack symbolic refs: */
1138 if (ref_flags
& REF_ISSYMREF
)
1141 /* Do not pack broken refs: */
1142 if (!ref_resolves_to_object(refname
, oid
, ref_flags
))
1148 static int files_pack_refs(struct ref_store
*ref_store
, unsigned int flags
)
1150 struct files_ref_store
*refs
=
1151 files_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_ODB
,
1153 struct ref_iterator
*iter
;
1155 struct ref_to_prune
*refs_to_prune
= NULL
;
1156 struct strbuf err
= STRBUF_INIT
;
1157 struct ref_transaction
*transaction
;
1159 transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, &err
);
1163 packed_refs_lock(refs
->packed_ref_store
, LOCK_DIE_ON_ERROR
, &err
);
1165 iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
), NULL
, 0);
1166 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
1168 * If the loose reference can be packed, add an entry
1169 * in the packed ref cache. If the reference should be
1170 * pruned, also add it to refs_to_prune.
1172 if (!should_pack_ref(iter
->refname
, iter
->oid
, iter
->flags
,
1177 * Add a reference creation for this reference to the
1178 * packed-refs transaction:
1180 if (ref_transaction_update(transaction
, iter
->refname
,
1182 REF_NO_DEREF
, NULL
, &err
))
1183 die("failure preparing to create packed reference %s: %s",
1184 iter
->refname
, err
.buf
);
1186 /* Schedule the loose reference for pruning if requested. */
1187 if ((flags
& PACK_REFS_PRUNE
)) {
1188 struct ref_to_prune
*n
;
1189 FLEX_ALLOC_STR(n
, name
, iter
->refname
);
1190 oidcpy(&n
->oid
, iter
->oid
);
1191 n
->next
= refs_to_prune
;
1195 if (ok
!= ITER_DONE
)
1196 die("error while iterating over references");
1198 if (ref_transaction_commit(transaction
, &err
))
1199 die("unable to write new packed-refs: %s", err
.buf
);
1201 ref_transaction_free(transaction
);
1203 packed_refs_unlock(refs
->packed_ref_store
);
1205 prune_refs(refs
, &refs_to_prune
);
1206 strbuf_release(&err
);
1210 static int files_delete_refs(struct ref_store
*ref_store
, const char *msg
,
1211 struct string_list
*refnames
, unsigned int flags
)
1213 struct files_ref_store
*refs
=
1214 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_refs");
1215 struct strbuf err
= STRBUF_INIT
;
1221 if (packed_refs_lock(refs
->packed_ref_store
, 0, &err
))
1224 if (refs_delete_refs(refs
->packed_ref_store
, msg
, refnames
, flags
)) {
1225 packed_refs_unlock(refs
->packed_ref_store
);
1229 packed_refs_unlock(refs
->packed_ref_store
);
1231 for (i
= 0; i
< refnames
->nr
; i
++) {
1232 const char *refname
= refnames
->items
[i
].string
;
1234 if (refs_delete_ref(&refs
->base
, msg
, refname
, NULL
, flags
))
1235 result
|= error(_("could not remove reference %s"), refname
);
1238 strbuf_release(&err
);
1243 * If we failed to rewrite the packed-refs file, then it is
1244 * unsafe to try to remove loose refs, because doing so might
1245 * expose an obsolete packed value for a reference that might
1246 * even point at an object that has been garbage collected.
1248 if (refnames
->nr
== 1)
1249 error(_("could not delete reference %s: %s"),
1250 refnames
->items
[0].string
, err
.buf
);
1252 error(_("could not delete references: %s"), err
.buf
);
1254 strbuf_release(&err
);
1259 * People using contrib's git-new-workdir have .git/logs/refs ->
1260 * /some/other/path/.git/logs/refs, and that may live on another device.
1262 * IOW, to avoid cross device rename errors, the temporary renamed log must
1263 * live into logs/refs.
1265 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1268 const char *tmp_renamed_log
;
1272 static int rename_tmp_log_callback(const char *path
, void *cb_data
)
1274 struct rename_cb
*cb
= cb_data
;
1276 if (rename(cb
->tmp_renamed_log
, path
)) {
1278 * rename(a, b) when b is an existing directory ought
1279 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1280 * Sheesh. Record the true errno for error reporting,
1281 * but report EISDIR to raceproof_create_file() so
1282 * that it knows to retry.
1284 cb
->true_errno
= errno
;
1285 if (errno
== ENOTDIR
)
1293 static int rename_tmp_log(struct files_ref_store
*refs
, const char *newrefname
)
1295 struct strbuf path
= STRBUF_INIT
;
1296 struct strbuf tmp
= STRBUF_INIT
;
1297 struct rename_cb cb
;
1300 files_reflog_path(refs
, &path
, newrefname
);
1301 files_reflog_path(refs
, &tmp
, TMP_RENAMED_LOG
);
1302 cb
.tmp_renamed_log
= tmp
.buf
;
1303 ret
= raceproof_create_file(path
.buf
, rename_tmp_log_callback
, &cb
);
1305 if (errno
== EISDIR
)
1306 error("directory not empty: %s", path
.buf
);
1308 error("unable to move logfile %s to %s: %s",
1310 strerror(cb
.true_errno
));
1313 strbuf_release(&path
);
1314 strbuf_release(&tmp
);
1318 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1319 const struct object_id
*oid
, struct strbuf
*err
);
1320 static int commit_ref_update(struct files_ref_store
*refs
,
1321 struct ref_lock
*lock
,
1322 const struct object_id
*oid
, const char *logmsg
,
1323 struct strbuf
*err
);
1325 static int files_copy_or_rename_ref(struct ref_store
*ref_store
,
1326 const char *oldrefname
, const char *newrefname
,
1327 const char *logmsg
, int copy
)
1329 struct files_ref_store
*refs
=
1330 files_downcast(ref_store
, REF_STORE_WRITE
, "rename_ref");
1331 struct object_id orig_oid
;
1332 int flag
= 0, logmoved
= 0;
1333 struct ref_lock
*lock
;
1334 struct stat loginfo
;
1335 struct strbuf sb_oldref
= STRBUF_INIT
;
1336 struct strbuf sb_newref
= STRBUF_INIT
;
1337 struct strbuf tmp_renamed_log
= STRBUF_INIT
;
1339 struct strbuf err
= STRBUF_INIT
;
1341 files_reflog_path(refs
, &sb_oldref
, oldrefname
);
1342 files_reflog_path(refs
, &sb_newref
, newrefname
);
1343 files_reflog_path(refs
, &tmp_renamed_log
, TMP_RENAMED_LOG
);
1345 log
= !lstat(sb_oldref
.buf
, &loginfo
);
1346 if (log
&& S_ISLNK(loginfo
.st_mode
)) {
1347 ret
= error("reflog for %s is a symlink", oldrefname
);
1351 if (!refs_resolve_ref_unsafe(&refs
->base
, oldrefname
,
1352 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1353 &orig_oid
, &flag
)) {
1354 ret
= error("refname %s not found", oldrefname
);
1358 if (flag
& REF_ISSYMREF
) {
1360 ret
= error("refname %s is a symbolic ref, copying it is not supported",
1363 ret
= error("refname %s is a symbolic ref, renaming it is not supported",
1367 if (!refs_rename_ref_available(&refs
->base
, oldrefname
, newrefname
)) {
1372 if (!copy
&& log
&& rename(sb_oldref
.buf
, tmp_renamed_log
.buf
)) {
1373 ret
= error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1374 oldrefname
, strerror(errno
));
1378 if (copy
&& log
&& copy_file(tmp_renamed_log
.buf
, sb_oldref
.buf
, 0644)) {
1379 ret
= error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1380 oldrefname
, strerror(errno
));
1384 if (!copy
&& refs_delete_ref(&refs
->base
, logmsg
, oldrefname
,
1385 &orig_oid
, REF_NO_DEREF
)) {
1386 error("unable to delete old %s", oldrefname
);
1391 * Since we are doing a shallow lookup, oid is not the
1392 * correct value to pass to delete_ref as old_oid. But that
1393 * doesn't matter, because an old_oid check wouldn't add to
1394 * the safety anyway; we want to delete the reference whatever
1395 * its current value.
1397 if (!copy
&& !refs_read_ref_full(&refs
->base
, newrefname
,
1398 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1400 refs_delete_ref(&refs
->base
, NULL
, newrefname
,
1401 NULL
, REF_NO_DEREF
)) {
1402 if (errno
== EISDIR
) {
1403 struct strbuf path
= STRBUF_INIT
;
1406 files_ref_path(refs
, &path
, newrefname
);
1407 result
= remove_empty_directories(&path
);
1408 strbuf_release(&path
);
1411 error("Directory not empty: %s", newrefname
);
1415 error("unable to delete existing %s", newrefname
);
1420 if (log
&& rename_tmp_log(refs
, newrefname
))
1425 lock
= lock_ref_oid_basic(refs
, newrefname
, NULL
, NULL
, NULL
,
1426 REF_NO_DEREF
, NULL
, &err
);
1429 error("unable to copy '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1431 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1432 strbuf_release(&err
);
1435 oidcpy(&lock
->old_oid
, &orig_oid
);
1437 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1438 commit_ref_update(refs
, lock
, &orig_oid
, logmsg
, &err
)) {
1439 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
1440 strbuf_release(&err
);
1448 lock
= lock_ref_oid_basic(refs
, oldrefname
, NULL
, NULL
, NULL
,
1449 REF_NO_DEREF
, NULL
, &err
);
1451 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
1452 strbuf_release(&err
);
1456 flag
= log_all_ref_updates
;
1457 log_all_ref_updates
= LOG_REFS_NONE
;
1458 if (write_ref_to_lockfile(lock
, &orig_oid
, &err
) ||
1459 commit_ref_update(refs
, lock
, &orig_oid
, NULL
, &err
)) {
1460 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
1461 strbuf_release(&err
);
1463 log_all_ref_updates
= flag
;
1466 if (logmoved
&& rename(sb_newref
.buf
, sb_oldref
.buf
))
1467 error("unable to restore logfile %s from %s: %s",
1468 oldrefname
, newrefname
, strerror(errno
));
1469 if (!logmoved
&& log
&&
1470 rename(tmp_renamed_log
.buf
, sb_oldref
.buf
))
1471 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG
": %s",
1472 oldrefname
, strerror(errno
));
1475 strbuf_release(&sb_newref
);
1476 strbuf_release(&sb_oldref
);
1477 strbuf_release(&tmp_renamed_log
);
1482 static int files_rename_ref(struct ref_store
*ref_store
,
1483 const char *oldrefname
, const char *newrefname
,
1486 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1487 newrefname
, logmsg
, 0);
1490 static int files_copy_ref(struct ref_store
*ref_store
,
1491 const char *oldrefname
, const char *newrefname
,
1494 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1495 newrefname
, logmsg
, 1);
1498 static int close_ref_gently(struct ref_lock
*lock
)
1500 if (close_lock_file_gently(&lock
->lk
))
1505 static int commit_ref(struct ref_lock
*lock
)
1507 char *path
= get_locked_file_path(&lock
->lk
);
1510 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
1512 * There is a directory at the path we want to rename
1513 * the lockfile to. Hopefully it is empty; try to
1516 size_t len
= strlen(path
);
1517 struct strbuf sb_path
= STRBUF_INIT
;
1519 strbuf_attach(&sb_path
, path
, len
, len
);
1522 * If this fails, commit_lock_file() will also fail
1523 * and will report the problem.
1525 remove_empty_directories(&sb_path
);
1526 strbuf_release(&sb_path
);
1531 if (commit_lock_file(&lock
->lk
))
1536 static int open_or_create_logfile(const char *path
, void *cb
)
1540 *fd
= open(path
, O_APPEND
| O_WRONLY
| O_CREAT
, 0666);
1541 return (*fd
< 0) ? -1 : 0;
1545 * Create a reflog for a ref. If force_create = 0, only create the
1546 * reflog for certain refs (those for which should_autocreate_reflog
1547 * returns non-zero). Otherwise, create it regardless of the reference
1548 * name. If the logfile already existed or was created, return 0 and
1549 * set *logfd to the file descriptor opened for appending to the file.
1550 * If no logfile exists and we decided not to create one, return 0 and
1551 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1554 static int log_ref_setup(struct files_ref_store
*refs
,
1555 const char *refname
, int force_create
,
1556 int *logfd
, struct strbuf
*err
)
1558 struct strbuf logfile_sb
= STRBUF_INIT
;
1561 files_reflog_path(refs
, &logfile_sb
, refname
);
1562 logfile
= strbuf_detach(&logfile_sb
, NULL
);
1564 if (force_create
|| should_autocreate_reflog(refname
)) {
1565 if (raceproof_create_file(logfile
, open_or_create_logfile
, logfd
)) {
1566 if (errno
== ENOENT
)
1567 strbuf_addf(err
, "unable to create directory for '%s': "
1568 "%s", logfile
, strerror(errno
));
1569 else if (errno
== EISDIR
)
1570 strbuf_addf(err
, "there are still logs under '%s'",
1573 strbuf_addf(err
, "unable to append to '%s': %s",
1574 logfile
, strerror(errno
));
1579 *logfd
= open(logfile
, O_APPEND
| O_WRONLY
, 0666);
1581 if (errno
== ENOENT
|| errno
== EISDIR
) {
1583 * The logfile doesn't already exist,
1584 * but that is not an error; it only
1585 * means that we won't write log
1590 strbuf_addf(err
, "unable to append to '%s': %s",
1591 logfile
, strerror(errno
));
1598 adjust_shared_perm(logfile
);
1608 static int files_create_reflog(struct ref_store
*ref_store
,
1609 const char *refname
, int force_create
,
1612 struct files_ref_store
*refs
=
1613 files_downcast(ref_store
, REF_STORE_WRITE
, "create_reflog");
1616 if (log_ref_setup(refs
, refname
, force_create
, &fd
, err
))
1625 static int log_ref_write_fd(int fd
, const struct object_id
*old_oid
,
1626 const struct object_id
*new_oid
,
1627 const char *committer
, const char *msg
)
1629 struct strbuf sb
= STRBUF_INIT
;
1632 strbuf_addf(&sb
, "%s %s %s", oid_to_hex(old_oid
), oid_to_hex(new_oid
), committer
);
1634 strbuf_addch(&sb
, '\t');
1635 strbuf_addstr(&sb
, msg
);
1637 strbuf_addch(&sb
, '\n');
1638 if (write_in_full(fd
, sb
.buf
, sb
.len
) < 0)
1640 strbuf_release(&sb
);
1644 static int files_log_ref_write(struct files_ref_store
*refs
,
1645 const char *refname
, const struct object_id
*old_oid
,
1646 const struct object_id
*new_oid
, const char *msg
,
1647 int flags
, struct strbuf
*err
)
1651 if (log_all_ref_updates
== LOG_REFS_UNSET
)
1652 log_all_ref_updates
= is_bare_repository() ? LOG_REFS_NONE
: LOG_REFS_NORMAL
;
1654 result
= log_ref_setup(refs
, refname
,
1655 flags
& REF_FORCE_CREATE_REFLOG
,
1663 result
= log_ref_write_fd(logfd
, old_oid
, new_oid
,
1664 git_committer_info(0), msg
);
1666 struct strbuf sb
= STRBUF_INIT
;
1667 int save_errno
= errno
;
1669 files_reflog_path(refs
, &sb
, refname
);
1670 strbuf_addf(err
, "unable to append to '%s': %s",
1671 sb
.buf
, strerror(save_errno
));
1672 strbuf_release(&sb
);
1677 struct strbuf sb
= STRBUF_INIT
;
1678 int save_errno
= errno
;
1680 files_reflog_path(refs
, &sb
, refname
);
1681 strbuf_addf(err
, "unable to append to '%s': %s",
1682 sb
.buf
, strerror(save_errno
));
1683 strbuf_release(&sb
);
1690 * Write oid into the open lockfile, then close the lockfile. On
1691 * errors, rollback the lockfile, fill in *err and return -1.
1693 static int write_ref_to_lockfile(struct ref_lock
*lock
,
1694 const struct object_id
*oid
, struct strbuf
*err
)
1696 static char term
= '\n';
1700 o
= parse_object(the_repository
, oid
);
1703 "trying to write ref '%s' with nonexistent object %s",
1704 lock
->ref_name
, oid_to_hex(oid
));
1708 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
1710 "trying to write non-commit object %s to branch '%s'",
1711 oid_to_hex(oid
), lock
->ref_name
);
1715 fd
= get_lock_file_fd(&lock
->lk
);
1716 if (write_in_full(fd
, oid_to_hex(oid
), the_hash_algo
->hexsz
) < 0 ||
1717 write_in_full(fd
, &term
, 1) < 0 ||
1718 close_ref_gently(lock
) < 0) {
1720 "couldn't write '%s'", get_lock_file_path(&lock
->lk
));
1728 * Commit a change to a loose reference that has already been written
1729 * to the loose reference lockfile. Also update the reflogs if
1730 * necessary, using the specified lockmsg (which can be NULL).
1732 static int commit_ref_update(struct files_ref_store
*refs
,
1733 struct ref_lock
*lock
,
1734 const struct object_id
*oid
, const char *logmsg
,
1737 files_assert_main_repository(refs
, "commit_ref_update");
1739 clear_loose_ref_cache(refs
);
1740 if (files_log_ref_write(refs
, lock
->ref_name
,
1741 &lock
->old_oid
, oid
,
1743 char *old_msg
= strbuf_detach(err
, NULL
);
1744 strbuf_addf(err
, "cannot update the ref '%s': %s",
1745 lock
->ref_name
, old_msg
);
1751 if (strcmp(lock
->ref_name
, "HEAD") != 0) {
1753 * Special hack: If a branch is updated directly and HEAD
1754 * points to it (may happen on the remote side of a push
1755 * for example) then logically the HEAD reflog should be
1757 * A generic solution implies reverse symref information,
1758 * but finding all symrefs pointing to the given branch
1759 * would be rather costly for this rare event (the direct
1760 * update of a branch) to be worth it. So let's cheat and
1761 * check with HEAD only which should cover 99% of all usage
1762 * scenarios (even 100% of the default ones).
1765 const char *head_ref
;
1767 head_ref
= refs_resolve_ref_unsafe(&refs
->base
, "HEAD",
1768 RESOLVE_REF_READING
,
1770 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
1771 !strcmp(head_ref
, lock
->ref_name
)) {
1772 struct strbuf log_err
= STRBUF_INIT
;
1773 if (files_log_ref_write(refs
, "HEAD",
1774 &lock
->old_oid
, oid
,
1775 logmsg
, 0, &log_err
)) {
1776 error("%s", log_err
.buf
);
1777 strbuf_release(&log_err
);
1782 if (commit_ref(lock
)) {
1783 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
1792 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
1795 #ifndef NO_SYMLINK_HEAD
1796 char *ref_path
= get_locked_file_path(&lock
->lk
);
1798 ret
= symlink(target
, ref_path
);
1802 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
1807 static void update_symref_reflog(struct files_ref_store
*refs
,
1808 struct ref_lock
*lock
, const char *refname
,
1809 const char *target
, const char *logmsg
)
1811 struct strbuf err
= STRBUF_INIT
;
1812 struct object_id new_oid
;
1814 !refs_read_ref_full(&refs
->base
, target
,
1815 RESOLVE_REF_READING
, &new_oid
, NULL
) &&
1816 files_log_ref_write(refs
, refname
, &lock
->old_oid
,
1817 &new_oid
, logmsg
, 0, &err
)) {
1818 error("%s", err
.buf
);
1819 strbuf_release(&err
);
1823 static int create_symref_locked(struct files_ref_store
*refs
,
1824 struct ref_lock
*lock
, const char *refname
,
1825 const char *target
, const char *logmsg
)
1827 if (prefer_symlink_refs
&& !create_ref_symlink(lock
, target
)) {
1828 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1832 if (!fdopen_lock_file(&lock
->lk
, "w"))
1833 return error("unable to fdopen %s: %s",
1834 lock
->lk
.tempfile
->filename
.buf
, strerror(errno
));
1836 update_symref_reflog(refs
, lock
, refname
, target
, logmsg
);
1838 /* no error check; commit_ref will check ferror */
1839 fprintf(lock
->lk
.tempfile
->fp
, "ref: %s\n", target
);
1840 if (commit_ref(lock
) < 0)
1841 return error("unable to write symref for %s: %s", refname
,
1846 static int files_create_symref(struct ref_store
*ref_store
,
1847 const char *refname
, const char *target
,
1850 struct files_ref_store
*refs
=
1851 files_downcast(ref_store
, REF_STORE_WRITE
, "create_symref");
1852 struct strbuf err
= STRBUF_INIT
;
1853 struct ref_lock
*lock
;
1856 lock
= lock_ref_oid_basic(refs
, refname
, NULL
,
1857 NULL
, NULL
, REF_NO_DEREF
, NULL
,
1860 error("%s", err
.buf
);
1861 strbuf_release(&err
);
1865 ret
= create_symref_locked(refs
, lock
, refname
, target
, logmsg
);
1870 static int files_reflog_exists(struct ref_store
*ref_store
,
1871 const char *refname
)
1873 struct files_ref_store
*refs
=
1874 files_downcast(ref_store
, REF_STORE_READ
, "reflog_exists");
1875 struct strbuf sb
= STRBUF_INIT
;
1879 files_reflog_path(refs
, &sb
, refname
);
1880 ret
= !lstat(sb
.buf
, &st
) && S_ISREG(st
.st_mode
);
1881 strbuf_release(&sb
);
1885 static int files_delete_reflog(struct ref_store
*ref_store
,
1886 const char *refname
)
1888 struct files_ref_store
*refs
=
1889 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_reflog");
1890 struct strbuf sb
= STRBUF_INIT
;
1893 files_reflog_path(refs
, &sb
, refname
);
1894 ret
= remove_path(sb
.buf
);
1895 strbuf_release(&sb
);
1899 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
1901 struct object_id ooid
, noid
;
1902 char *email_end
, *message
;
1903 timestamp_t timestamp
;
1905 const char *p
= sb
->buf
;
1907 /* old SP new SP name <email> SP time TAB msg LF */
1908 if (!sb
->len
|| sb
->buf
[sb
->len
- 1] != '\n' ||
1909 parse_oid_hex(p
, &ooid
, &p
) || *p
++ != ' ' ||
1910 parse_oid_hex(p
, &noid
, &p
) || *p
++ != ' ' ||
1911 !(email_end
= strchr(p
, '>')) ||
1912 email_end
[1] != ' ' ||
1913 !(timestamp
= parse_timestamp(email_end
+ 2, &message
, 10)) ||
1914 !message
|| message
[0] != ' ' ||
1915 (message
[1] != '+' && message
[1] != '-') ||
1916 !isdigit(message
[2]) || !isdigit(message
[3]) ||
1917 !isdigit(message
[4]) || !isdigit(message
[5]))
1918 return 0; /* corrupt? */
1919 email_end
[1] = '\0';
1920 tz
= strtol(message
+ 1, NULL
, 10);
1921 if (message
[6] != '\t')
1925 return fn(&ooid
, &noid
, p
, timestamp
, tz
, message
, cb_data
);
1928 static char *find_beginning_of_line(char *bob
, char *scan
)
1930 while (bob
< scan
&& *(--scan
) != '\n')
1931 ; /* keep scanning backwards */
1933 * Return either beginning of the buffer, or LF at the end of
1934 * the previous line.
1939 static int files_for_each_reflog_ent_reverse(struct ref_store
*ref_store
,
1940 const char *refname
,
1941 each_reflog_ent_fn fn
,
1944 struct files_ref_store
*refs
=
1945 files_downcast(ref_store
, REF_STORE_READ
,
1946 "for_each_reflog_ent_reverse");
1947 struct strbuf sb
= STRBUF_INIT
;
1950 int ret
= 0, at_tail
= 1;
1952 files_reflog_path(refs
, &sb
, refname
);
1953 logfp
= fopen(sb
.buf
, "r");
1954 strbuf_release(&sb
);
1958 /* Jump to the end */
1959 if (fseek(logfp
, 0, SEEK_END
) < 0)
1960 ret
= error("cannot seek back reflog for %s: %s",
1961 refname
, strerror(errno
));
1963 while (!ret
&& 0 < pos
) {
1969 /* Fill next block from the end */
1970 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
1971 if (fseek(logfp
, pos
- cnt
, SEEK_SET
)) {
1972 ret
= error("cannot seek back reflog for %s: %s",
1973 refname
, strerror(errno
));
1976 nread
= fread(buf
, cnt
, 1, logfp
);
1978 ret
= error("cannot read %d bytes from reflog for %s: %s",
1979 cnt
, refname
, strerror(errno
));
1984 scanp
= endp
= buf
+ cnt
;
1985 if (at_tail
&& scanp
[-1] == '\n')
1986 /* Looking at the final LF at the end of the file */
1990 while (buf
< scanp
) {
1992 * terminating LF of the previous line, or the beginning
1997 bp
= find_beginning_of_line(buf
, scanp
);
2001 * The newline is the end of the previous line,
2002 * so we know we have complete line starting
2003 * at (bp + 1). Prefix it onto any prior data
2004 * we collected for the line and process it.
2006 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
2009 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2015 * We are at the start of the buffer, and the
2016 * start of the file; there is no previous
2017 * line, and we have everything for this one.
2018 * Process it, and we can end the loop.
2020 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2021 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2028 * We are at the start of the buffer, and there
2029 * is more file to read backwards. Which means
2030 * we are in the middle of a line. Note that we
2031 * may get here even if *bp was a newline; that
2032 * just means we are at the exact end of the
2033 * previous line, rather than some spot in the
2036 * Save away what we have to be combined with
2037 * the data from the next read.
2039 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2046 BUG("reverse reflog parser had leftover data");
2049 strbuf_release(&sb
);
2053 static int files_for_each_reflog_ent(struct ref_store
*ref_store
,
2054 const char *refname
,
2055 each_reflog_ent_fn fn
, void *cb_data
)
2057 struct files_ref_store
*refs
=
2058 files_downcast(ref_store
, REF_STORE_READ
,
2059 "for_each_reflog_ent");
2061 struct strbuf sb
= STRBUF_INIT
;
2064 files_reflog_path(refs
, &sb
, refname
);
2065 logfp
= fopen(sb
.buf
, "r");
2066 strbuf_release(&sb
);
2070 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
2071 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
2073 strbuf_release(&sb
);
2077 struct files_reflog_iterator
{
2078 struct ref_iterator base
;
2080 struct ref_store
*ref_store
;
2081 struct dir_iterator
*dir_iterator
;
2082 struct object_id oid
;
2085 static int files_reflog_iterator_advance(struct ref_iterator
*ref_iterator
)
2087 struct files_reflog_iterator
*iter
=
2088 (struct files_reflog_iterator
*)ref_iterator
;
2089 struct dir_iterator
*diter
= iter
->dir_iterator
;
2092 while ((ok
= dir_iterator_advance(diter
)) == ITER_OK
) {
2095 if (!S_ISREG(diter
->st
.st_mode
))
2097 if (diter
->basename
[0] == '.')
2099 if (ends_with(diter
->basename
, ".lock"))
2102 if (refs_read_ref_full(iter
->ref_store
,
2103 diter
->relative_path
, 0,
2104 &iter
->oid
, &flags
)) {
2105 error("bad ref for %s", diter
->path
.buf
);
2109 iter
->base
.refname
= diter
->relative_path
;
2110 iter
->base
.oid
= &iter
->oid
;
2111 iter
->base
.flags
= flags
;
2115 iter
->dir_iterator
= NULL
;
2116 if (ref_iterator_abort(ref_iterator
) == ITER_ERROR
)
2121 static int files_reflog_iterator_peel(struct ref_iterator
*ref_iterator
,
2122 struct object_id
*peeled
)
2124 BUG("ref_iterator_peel() called for reflog_iterator");
2127 static int files_reflog_iterator_abort(struct ref_iterator
*ref_iterator
)
2129 struct files_reflog_iterator
*iter
=
2130 (struct files_reflog_iterator
*)ref_iterator
;
2133 if (iter
->dir_iterator
)
2134 ok
= dir_iterator_abort(iter
->dir_iterator
);
2136 base_ref_iterator_free(ref_iterator
);
2140 static struct ref_iterator_vtable files_reflog_iterator_vtable
= {
2141 files_reflog_iterator_advance
,
2142 files_reflog_iterator_peel
,
2143 files_reflog_iterator_abort
2146 static struct ref_iterator
*reflog_iterator_begin(struct ref_store
*ref_store
,
2149 struct dir_iterator
*diter
;
2150 struct files_reflog_iterator
*iter
;
2151 struct ref_iterator
*ref_iterator
;
2152 struct strbuf sb
= STRBUF_INIT
;
2154 strbuf_addf(&sb
, "%s/logs", gitdir
);
2156 diter
= dir_iterator_begin(sb
.buf
, 0);
2158 strbuf_release(&sb
);
2159 return empty_ref_iterator_begin();
2162 iter
= xcalloc(1, sizeof(*iter
));
2163 ref_iterator
= &iter
->base
;
2165 base_ref_iterator_init(ref_iterator
, &files_reflog_iterator_vtable
, 0);
2166 iter
->dir_iterator
= diter
;
2167 iter
->ref_store
= ref_store
;
2168 strbuf_release(&sb
);
2170 return ref_iterator
;
2173 static enum iterator_selection
reflog_iterator_select(
2174 struct ref_iterator
*iter_worktree
,
2175 struct ref_iterator
*iter_common
,
2178 if (iter_worktree
) {
2180 * We're a bit loose here. We probably should ignore
2181 * common refs if they are accidentally added as
2182 * per-worktree refs.
2184 return ITER_SELECT_0
;
2185 } else if (iter_common
) {
2186 if (ref_type(iter_common
->refname
) == REF_TYPE_NORMAL
)
2187 return ITER_SELECT_1
;
2190 * The main ref store may contain main worktree's
2191 * per-worktree refs, which should be ignored
2198 static struct ref_iterator
*files_reflog_iterator_begin(struct ref_store
*ref_store
)
2200 struct files_ref_store
*refs
=
2201 files_downcast(ref_store
, REF_STORE_READ
,
2202 "reflog_iterator_begin");
2204 if (!strcmp(refs
->base
.gitdir
, refs
->gitcommondir
)) {
2205 return reflog_iterator_begin(ref_store
, refs
->gitcommondir
);
2207 return merge_ref_iterator_begin(
2208 0, reflog_iterator_begin(ref_store
, refs
->base
.gitdir
),
2209 reflog_iterator_begin(ref_store
, refs
->gitcommondir
),
2210 reflog_iterator_select
, refs
);
2215 * If update is a direct update of head_ref (the reference pointed to
2216 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2218 static int split_head_update(struct ref_update
*update
,
2219 struct ref_transaction
*transaction
,
2220 const char *head_ref
,
2221 struct string_list
*affected_refnames
,
2224 struct string_list_item
*item
;
2225 struct ref_update
*new_update
;
2227 if ((update
->flags
& REF_LOG_ONLY
) ||
2228 (update
->flags
& REF_IS_PRUNING
) ||
2229 (update
->flags
& REF_UPDATE_VIA_HEAD
))
2232 if (strcmp(update
->refname
, head_ref
))
2236 * First make sure that HEAD is not already in the
2237 * transaction. This check is O(lg N) in the transaction
2238 * size, but it happens at most once per transaction.
2240 if (string_list_has_string(affected_refnames
, "HEAD")) {
2241 /* An entry already existed */
2243 "multiple updates for 'HEAD' (including one "
2244 "via its referent '%s') are not allowed",
2246 return TRANSACTION_NAME_CONFLICT
;
2249 new_update
= ref_transaction_add_update(
2250 transaction
, "HEAD",
2251 update
->flags
| REF_LOG_ONLY
| REF_NO_DEREF
,
2252 &update
->new_oid
, &update
->old_oid
,
2256 * Add "HEAD". This insertion is O(N) in the transaction
2257 * size, but it happens at most once per transaction.
2258 * Add new_update->refname instead of a literal "HEAD".
2260 if (strcmp(new_update
->refname
, "HEAD"))
2261 BUG("%s unexpectedly not 'HEAD'", new_update
->refname
);
2262 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2263 item
->util
= new_update
;
2269 * update is for a symref that points at referent and doesn't have
2270 * REF_NO_DEREF set. Split it into two updates:
2271 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2272 * - A new, separate update for the referent reference
2273 * Note that the new update will itself be subject to splitting when
2274 * the iteration gets to it.
2276 static int split_symref_update(struct ref_update
*update
,
2277 const char *referent
,
2278 struct ref_transaction
*transaction
,
2279 struct string_list
*affected_refnames
,
2282 struct string_list_item
*item
;
2283 struct ref_update
*new_update
;
2284 unsigned int new_flags
;
2287 * First make sure that referent is not already in the
2288 * transaction. This check is O(lg N) in the transaction
2289 * size, but it happens at most once per symref in a
2292 if (string_list_has_string(affected_refnames
, referent
)) {
2293 /* An entry already exists */
2295 "multiple updates for '%s' (including one "
2296 "via symref '%s') are not allowed",
2297 referent
, update
->refname
);
2298 return TRANSACTION_NAME_CONFLICT
;
2301 new_flags
= update
->flags
;
2302 if (!strcmp(update
->refname
, "HEAD")) {
2304 * Record that the new update came via HEAD, so that
2305 * when we process it, split_head_update() doesn't try
2306 * to add another reflog update for HEAD. Note that
2307 * this bit will be propagated if the new_update
2308 * itself needs to be split.
2310 new_flags
|= REF_UPDATE_VIA_HEAD
;
2313 new_update
= ref_transaction_add_update(
2314 transaction
, referent
, new_flags
,
2315 &update
->new_oid
, &update
->old_oid
,
2318 new_update
->parent_update
= update
;
2321 * Change the symbolic ref update to log only. Also, it
2322 * doesn't need to check its old OID value, as that will be
2323 * done when new_update is processed.
2325 update
->flags
|= REF_LOG_ONLY
| REF_NO_DEREF
;
2326 update
->flags
&= ~REF_HAVE_OLD
;
2329 * Add the referent. This insertion is O(N) in the transaction
2330 * size, but it happens at most once per symref in a
2331 * transaction. Make sure to add new_update->refname, which will
2332 * be valid as long as affected_refnames is in use, and NOT
2333 * referent, which might soon be freed by our caller.
2335 item
= string_list_insert(affected_refnames
, new_update
->refname
);
2337 BUG("%s unexpectedly found in affected_refnames",
2338 new_update
->refname
);
2339 item
->util
= new_update
;
2345 * Return the refname under which update was originally requested.
2347 static const char *original_update_refname(struct ref_update
*update
)
2349 while (update
->parent_update
)
2350 update
= update
->parent_update
;
2352 return update
->refname
;
2356 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2357 * are consistent with oid, which is the reference's current value. If
2358 * everything is OK, return 0; otherwise, write an error message to
2359 * err and return -1.
2361 static int check_old_oid(struct ref_update
*update
, struct object_id
*oid
,
2364 if (!(update
->flags
& REF_HAVE_OLD
) ||
2365 oideq(oid
, &update
->old_oid
))
2368 if (is_null_oid(&update
->old_oid
))
2369 strbuf_addf(err
, "cannot lock ref '%s': "
2370 "reference already exists",
2371 original_update_refname(update
));
2372 else if (is_null_oid(oid
))
2373 strbuf_addf(err
, "cannot lock ref '%s': "
2374 "reference is missing but expected %s",
2375 original_update_refname(update
),
2376 oid_to_hex(&update
->old_oid
));
2378 strbuf_addf(err
, "cannot lock ref '%s': "
2379 "is at %s but expected %s",
2380 original_update_refname(update
),
2382 oid_to_hex(&update
->old_oid
));
2388 * Prepare for carrying out update:
2389 * - Lock the reference referred to by update.
2390 * - Read the reference under lock.
2391 * - Check that its old OID value (if specified) is correct, and in
2392 * any case record it in update->lock->old_oid for later use when
2393 * writing the reflog.
2394 * - If it is a symref update without REF_NO_DEREF, split it up into a
2395 * REF_LOG_ONLY update of the symref and add a separate update for
2396 * the referent to transaction.
2397 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2400 static int lock_ref_for_update(struct files_ref_store
*refs
,
2401 struct ref_update
*update
,
2402 struct ref_transaction
*transaction
,
2403 const char *head_ref
,
2404 struct string_list
*affected_refnames
,
2407 struct strbuf referent
= STRBUF_INIT
;
2408 int mustexist
= (update
->flags
& REF_HAVE_OLD
) &&
2409 !is_null_oid(&update
->old_oid
);
2411 struct ref_lock
*lock
;
2413 files_assert_main_repository(refs
, "lock_ref_for_update");
2415 if ((update
->flags
& REF_HAVE_NEW
) && is_null_oid(&update
->new_oid
))
2416 update
->flags
|= REF_DELETING
;
2419 ret
= split_head_update(update
, transaction
, head_ref
,
2420 affected_refnames
, err
);
2425 ret
= lock_raw_ref(refs
, update
->refname
, mustexist
,
2426 affected_refnames
, NULL
,
2428 &update
->type
, err
);
2432 reason
= strbuf_detach(err
, NULL
);
2433 strbuf_addf(err
, "cannot lock ref '%s': %s",
2434 original_update_refname(update
), reason
);
2439 update
->backend_data
= lock
;
2441 if (update
->type
& REF_ISSYMREF
) {
2442 if (update
->flags
& REF_NO_DEREF
) {
2444 * We won't be reading the referent as part of
2445 * the transaction, so we have to read it here
2446 * to record and possibly check old_oid:
2448 if (refs_read_ref_full(&refs
->base
,
2450 &lock
->old_oid
, NULL
)) {
2451 if (update
->flags
& REF_HAVE_OLD
) {
2452 strbuf_addf(err
, "cannot lock ref '%s': "
2453 "error reading reference",
2454 original_update_refname(update
));
2455 ret
= TRANSACTION_GENERIC_ERROR
;
2458 } else if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2459 ret
= TRANSACTION_GENERIC_ERROR
;
2464 * Create a new update for the reference this
2465 * symref is pointing at. Also, we will record
2466 * and verify old_oid for this update as part
2467 * of processing the split-off update, so we
2468 * don't have to do it here.
2470 ret
= split_symref_update(update
,
2471 referent
.buf
, transaction
,
2472 affected_refnames
, err
);
2477 struct ref_update
*parent_update
;
2479 if (check_old_oid(update
, &lock
->old_oid
, err
)) {
2480 ret
= TRANSACTION_GENERIC_ERROR
;
2485 * If this update is happening indirectly because of a
2486 * symref update, record the old OID in the parent
2489 for (parent_update
= update
->parent_update
;
2491 parent_update
= parent_update
->parent_update
) {
2492 struct ref_lock
*parent_lock
= parent_update
->backend_data
;
2493 oidcpy(&parent_lock
->old_oid
, &lock
->old_oid
);
2497 if ((update
->flags
& REF_HAVE_NEW
) &&
2498 !(update
->flags
& REF_DELETING
) &&
2499 !(update
->flags
& REF_LOG_ONLY
)) {
2500 if (!(update
->type
& REF_ISSYMREF
) &&
2501 oideq(&lock
->old_oid
, &update
->new_oid
)) {
2503 * The reference already has the desired
2504 * value, so we don't need to write it.
2506 } else if (write_ref_to_lockfile(lock
, &update
->new_oid
,
2508 char *write_err
= strbuf_detach(err
, NULL
);
2511 * The lock was freed upon failure of
2512 * write_ref_to_lockfile():
2514 update
->backend_data
= NULL
;
2516 "cannot update ref '%s': %s",
2517 update
->refname
, write_err
);
2519 ret
= TRANSACTION_GENERIC_ERROR
;
2522 update
->flags
|= REF_NEEDS_COMMIT
;
2525 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
2527 * We didn't call write_ref_to_lockfile(), so
2528 * the lockfile is still open. Close it to
2529 * free up the file descriptor:
2531 if (close_ref_gently(lock
)) {
2532 strbuf_addf(err
, "couldn't close '%s.lock'",
2534 ret
= TRANSACTION_GENERIC_ERROR
;
2540 strbuf_release(&referent
);
2544 struct files_transaction_backend_data
{
2545 struct ref_transaction
*packed_transaction
;
2546 int packed_refs_locked
;
2550 * Unlock any references in `transaction` that are still locked, and
2551 * mark the transaction closed.
2553 static void files_transaction_cleanup(struct files_ref_store
*refs
,
2554 struct ref_transaction
*transaction
)
2557 struct files_transaction_backend_data
*backend_data
=
2558 transaction
->backend_data
;
2559 struct strbuf err
= STRBUF_INIT
;
2561 for (i
= 0; i
< transaction
->nr
; i
++) {
2562 struct ref_update
*update
= transaction
->updates
[i
];
2563 struct ref_lock
*lock
= update
->backend_data
;
2567 update
->backend_data
= NULL
;
2572 if (backend_data
->packed_transaction
&&
2573 ref_transaction_abort(backend_data
->packed_transaction
, &err
)) {
2574 error("error aborting transaction: %s", err
.buf
);
2575 strbuf_release(&err
);
2578 if (backend_data
->packed_refs_locked
)
2579 packed_refs_unlock(refs
->packed_ref_store
);
2584 transaction
->state
= REF_TRANSACTION_CLOSED
;
2587 static int files_transaction_prepare(struct ref_store
*ref_store
,
2588 struct ref_transaction
*transaction
,
2591 struct files_ref_store
*refs
=
2592 files_downcast(ref_store
, REF_STORE_WRITE
,
2593 "ref_transaction_prepare");
2596 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2597 char *head_ref
= NULL
;
2599 struct files_transaction_backend_data
*backend_data
;
2600 struct ref_transaction
*packed_transaction
= NULL
;
2604 if (!transaction
->nr
)
2607 backend_data
= xcalloc(1, sizeof(*backend_data
));
2608 transaction
->backend_data
= backend_data
;
2611 * Fail if a refname appears more than once in the
2612 * transaction. (If we end up splitting up any updates using
2613 * split_symref_update() or split_head_update(), those
2614 * functions will check that the new updates don't have the
2615 * same refname as any existing ones.) Also fail if any of the
2616 * updates use REF_IS_PRUNING without REF_NO_DEREF.
2618 for (i
= 0; i
< transaction
->nr
; i
++) {
2619 struct ref_update
*update
= transaction
->updates
[i
];
2620 struct string_list_item
*item
=
2621 string_list_append(&affected_refnames
, update
->refname
);
2623 if ((update
->flags
& REF_IS_PRUNING
) &&
2624 !(update
->flags
& REF_NO_DEREF
))
2625 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2628 * We store a pointer to update in item->util, but at
2629 * the moment we never use the value of this field
2630 * except to check whether it is non-NULL.
2632 item
->util
= update
;
2634 string_list_sort(&affected_refnames
);
2635 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2636 ret
= TRANSACTION_GENERIC_ERROR
;
2641 * Special hack: If a branch is updated directly and HEAD
2642 * points to it (may happen on the remote side of a push
2643 * for example) then logically the HEAD reflog should be
2646 * A generic solution would require reverse symref lookups,
2647 * but finding all symrefs pointing to a given branch would be
2648 * rather costly for this rare event (the direct update of a
2649 * branch) to be worth it. So let's cheat and check with HEAD
2650 * only, which should cover 99% of all usage scenarios (even
2651 * 100% of the default ones).
2653 * So if HEAD is a symbolic reference, then record the name of
2654 * the reference that it points to. If we see an update of
2655 * head_ref within the transaction, then split_head_update()
2656 * arranges for the reflog of HEAD to be updated, too.
2658 head_ref
= refs_resolve_refdup(ref_store
, "HEAD",
2659 RESOLVE_REF_NO_RECURSE
,
2662 if (head_ref
&& !(head_type
& REF_ISSYMREF
)) {
2663 FREE_AND_NULL(head_ref
);
2667 * Acquire all locks, verify old values if provided, check
2668 * that new values are valid, and write new values to the
2669 * lockfiles, ready to be activated. Only keep one lockfile
2670 * open at a time to avoid running out of file descriptors.
2671 * Note that lock_ref_for_update() might append more updates
2672 * to the transaction.
2674 for (i
= 0; i
< transaction
->nr
; i
++) {
2675 struct ref_update
*update
= transaction
->updates
[i
];
2677 ret
= lock_ref_for_update(refs
, update
, transaction
,
2678 head_ref
, &affected_refnames
, err
);
2682 if (update
->flags
& REF_DELETING
&&
2683 !(update
->flags
& REF_LOG_ONLY
) &&
2684 !(update
->flags
& REF_IS_PRUNING
)) {
2686 * This reference has to be deleted from
2687 * packed-refs if it exists there.
2689 if (!packed_transaction
) {
2690 packed_transaction
= ref_store_transaction_begin(
2691 refs
->packed_ref_store
, err
);
2692 if (!packed_transaction
) {
2693 ret
= TRANSACTION_GENERIC_ERROR
;
2697 backend_data
->packed_transaction
=
2701 ref_transaction_add_update(
2702 packed_transaction
, update
->refname
,
2703 REF_HAVE_NEW
| REF_NO_DEREF
,
2704 &update
->new_oid
, NULL
,
2709 if (packed_transaction
) {
2710 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2711 ret
= TRANSACTION_GENERIC_ERROR
;
2714 backend_data
->packed_refs_locked
= 1;
2716 if (is_packed_transaction_needed(refs
->packed_ref_store
,
2717 packed_transaction
)) {
2718 ret
= ref_transaction_prepare(packed_transaction
, err
);
2720 * A failure during the prepare step will abort
2721 * itself, but not free. Do that now, and disconnect
2722 * from the files_transaction so it does not try to
2723 * abort us when we hit the cleanup code below.
2726 ref_transaction_free(packed_transaction
);
2727 backend_data
->packed_transaction
= NULL
;
2731 * We can skip rewriting the `packed-refs`
2732 * file. But we do need to leave it locked, so
2733 * that somebody else doesn't pack a reference
2734 * that we are trying to delete.
2736 * We need to disconnect our transaction from
2737 * backend_data, since the abort (whether successful or
2738 * not) will free it.
2740 backend_data
->packed_transaction
= NULL
;
2741 if (ref_transaction_abort(packed_transaction
, err
)) {
2742 ret
= TRANSACTION_GENERIC_ERROR
;
2750 string_list_clear(&affected_refnames
, 0);
2753 files_transaction_cleanup(refs
, transaction
);
2755 transaction
->state
= REF_TRANSACTION_PREPARED
;
2760 static int files_transaction_finish(struct ref_store
*ref_store
,
2761 struct ref_transaction
*transaction
,
2764 struct files_ref_store
*refs
=
2765 files_downcast(ref_store
, 0, "ref_transaction_finish");
2768 struct strbuf sb
= STRBUF_INIT
;
2769 struct files_transaction_backend_data
*backend_data
;
2770 struct ref_transaction
*packed_transaction
;
2775 if (!transaction
->nr
) {
2776 transaction
->state
= REF_TRANSACTION_CLOSED
;
2780 backend_data
= transaction
->backend_data
;
2781 packed_transaction
= backend_data
->packed_transaction
;
2783 /* Perform updates first so live commits remain referenced */
2784 for (i
= 0; i
< transaction
->nr
; i
++) {
2785 struct ref_update
*update
= transaction
->updates
[i
];
2786 struct ref_lock
*lock
= update
->backend_data
;
2788 if (update
->flags
& REF_NEEDS_COMMIT
||
2789 update
->flags
& REF_LOG_ONLY
) {
2790 if (files_log_ref_write(refs
,
2794 update
->msg
, update
->flags
,
2796 char *old_msg
= strbuf_detach(err
, NULL
);
2798 strbuf_addf(err
, "cannot update the ref '%s': %s",
2799 lock
->ref_name
, old_msg
);
2802 update
->backend_data
= NULL
;
2803 ret
= TRANSACTION_GENERIC_ERROR
;
2807 if (update
->flags
& REF_NEEDS_COMMIT
) {
2808 clear_loose_ref_cache(refs
);
2809 if (commit_ref(lock
)) {
2810 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
2812 update
->backend_data
= NULL
;
2813 ret
= TRANSACTION_GENERIC_ERROR
;
2820 * Now that updates are safely completed, we can perform
2821 * deletes. First delete the reflogs of any references that
2822 * will be deleted, since (in the unexpected event of an
2823 * error) leaving a reference without a reflog is less bad
2824 * than leaving a reflog without a reference (the latter is a
2825 * mildly invalid repository state):
2827 for (i
= 0; i
< transaction
->nr
; i
++) {
2828 struct ref_update
*update
= transaction
->updates
[i
];
2829 if (update
->flags
& REF_DELETING
&&
2830 !(update
->flags
& REF_LOG_ONLY
) &&
2831 !(update
->flags
& REF_IS_PRUNING
)) {
2833 files_reflog_path(refs
, &sb
, update
->refname
);
2834 if (!unlink_or_warn(sb
.buf
))
2835 try_remove_empty_parents(refs
, update
->refname
,
2836 REMOVE_EMPTY_PARENTS_REFLOG
);
2841 * Perform deletes now that updates are safely completed.
2843 * First delete any packed versions of the references, while
2844 * retaining the packed-refs lock:
2846 if (packed_transaction
) {
2847 ret
= ref_transaction_commit(packed_transaction
, err
);
2848 ref_transaction_free(packed_transaction
);
2849 packed_transaction
= NULL
;
2850 backend_data
->packed_transaction
= NULL
;
2855 /* Now delete the loose versions of the references: */
2856 for (i
= 0; i
< transaction
->nr
; i
++) {
2857 struct ref_update
*update
= transaction
->updates
[i
];
2858 struct ref_lock
*lock
= update
->backend_data
;
2860 if (update
->flags
& REF_DELETING
&&
2861 !(update
->flags
& REF_LOG_ONLY
)) {
2862 if (!(update
->type
& REF_ISPACKED
) ||
2863 update
->type
& REF_ISSYMREF
) {
2864 /* It is a loose reference. */
2866 files_ref_path(refs
, &sb
, lock
->ref_name
);
2867 if (unlink_or_msg(sb
.buf
, err
)) {
2868 ret
= TRANSACTION_GENERIC_ERROR
;
2871 update
->flags
|= REF_DELETED_LOOSE
;
2876 clear_loose_ref_cache(refs
);
2879 files_transaction_cleanup(refs
, transaction
);
2881 for (i
= 0; i
< transaction
->nr
; i
++) {
2882 struct ref_update
*update
= transaction
->updates
[i
];
2884 if (update
->flags
& REF_DELETED_LOOSE
) {
2886 * The loose reference was deleted. Delete any
2887 * empty parent directories. (Note that this
2888 * can only work because we have already
2889 * removed the lockfile.)
2891 try_remove_empty_parents(refs
, update
->refname
,
2892 REMOVE_EMPTY_PARENTS_REF
);
2896 strbuf_release(&sb
);
2900 static int files_transaction_abort(struct ref_store
*ref_store
,
2901 struct ref_transaction
*transaction
,
2904 struct files_ref_store
*refs
=
2905 files_downcast(ref_store
, 0, "ref_transaction_abort");
2907 files_transaction_cleanup(refs
, transaction
);
2911 static int ref_present(const char *refname
,
2912 const struct object_id
*oid
, int flags
, void *cb_data
)
2914 struct string_list
*affected_refnames
= cb_data
;
2916 return string_list_has_string(affected_refnames
, refname
);
2919 static int files_initial_transaction_commit(struct ref_store
*ref_store
,
2920 struct ref_transaction
*transaction
,
2923 struct files_ref_store
*refs
=
2924 files_downcast(ref_store
, REF_STORE_WRITE
,
2925 "initial_ref_transaction_commit");
2928 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
2929 struct ref_transaction
*packed_transaction
= NULL
;
2933 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
2934 BUG("commit called for transaction that is not open");
2936 /* Fail if a refname appears more than once in the transaction: */
2937 for (i
= 0; i
< transaction
->nr
; i
++)
2938 string_list_append(&affected_refnames
,
2939 transaction
->updates
[i
]->refname
);
2940 string_list_sort(&affected_refnames
);
2941 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
2942 ret
= TRANSACTION_GENERIC_ERROR
;
2947 * It's really undefined to call this function in an active
2948 * repository or when there are existing references: we are
2949 * only locking and changing packed-refs, so (1) any
2950 * simultaneous processes might try to change a reference at
2951 * the same time we do, and (2) any existing loose versions of
2952 * the references that we are setting would have precedence
2953 * over our values. But some remote helpers create the remote
2954 * "HEAD" and "master" branches before calling this function,
2955 * so here we really only check that none of the references
2956 * that we are creating already exists.
2958 if (refs_for_each_rawref(&refs
->base
, ref_present
,
2959 &affected_refnames
))
2960 BUG("initial ref transaction called with existing refs");
2962 packed_transaction
= ref_store_transaction_begin(refs
->packed_ref_store
, err
);
2963 if (!packed_transaction
) {
2964 ret
= TRANSACTION_GENERIC_ERROR
;
2968 for (i
= 0; i
< transaction
->nr
; i
++) {
2969 struct ref_update
*update
= transaction
->updates
[i
];
2971 if ((update
->flags
& REF_HAVE_OLD
) &&
2972 !is_null_oid(&update
->old_oid
))
2973 BUG("initial ref transaction with old_sha1 set");
2974 if (refs_verify_refname_available(&refs
->base
, update
->refname
,
2975 &affected_refnames
, NULL
,
2977 ret
= TRANSACTION_NAME_CONFLICT
;
2982 * Add a reference creation for this reference to the
2983 * packed-refs transaction:
2985 ref_transaction_add_update(packed_transaction
, update
->refname
,
2986 update
->flags
& ~REF_HAVE_OLD
,
2987 &update
->new_oid
, &update
->old_oid
,
2991 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2992 ret
= TRANSACTION_GENERIC_ERROR
;
2996 if (initial_ref_transaction_commit(packed_transaction
, err
)) {
2997 ret
= TRANSACTION_GENERIC_ERROR
;
3000 packed_refs_unlock(refs
->packed_ref_store
);
3002 if (packed_transaction
)
3003 ref_transaction_free(packed_transaction
);
3004 transaction
->state
= REF_TRANSACTION_CLOSED
;
3005 string_list_clear(&affected_refnames
, 0);
3009 struct expire_reflog_cb
{
3011 reflog_expiry_should_prune_fn
*should_prune_fn
;
3014 struct object_id last_kept_oid
;
3017 static int expire_reflog_ent(struct object_id
*ooid
, struct object_id
*noid
,
3018 const char *email
, timestamp_t timestamp
, int tz
,
3019 const char *message
, void *cb_data
)
3021 struct expire_reflog_cb
*cb
= cb_data
;
3022 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
3024 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
3025 ooid
= &cb
->last_kept_oid
;
3027 if ((*cb
->should_prune_fn
)(ooid
, noid
, email
, timestamp
, tz
,
3028 message
, policy_cb
)) {
3030 printf("would prune %s", message
);
3031 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3032 printf("prune %s", message
);
3035 fprintf(cb
->newlog
, "%s %s %s %"PRItime
" %+05d\t%s",
3036 oid_to_hex(ooid
), oid_to_hex(noid
),
3037 email
, timestamp
, tz
, message
);
3038 oidcpy(&cb
->last_kept_oid
, noid
);
3040 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3041 printf("keep %s", message
);
3046 static int files_reflog_expire(struct ref_store
*ref_store
,
3047 const char *refname
, const struct object_id
*oid
,
3049 reflog_expiry_prepare_fn prepare_fn
,
3050 reflog_expiry_should_prune_fn should_prune_fn
,
3051 reflog_expiry_cleanup_fn cleanup_fn
,
3052 void *policy_cb_data
)
3054 struct files_ref_store
*refs
=
3055 files_downcast(ref_store
, REF_STORE_WRITE
, "reflog_expire");
3056 struct lock_file reflog_lock
= LOCK_INIT
;
3057 struct expire_reflog_cb cb
;
3058 struct ref_lock
*lock
;
3059 struct strbuf log_file_sb
= STRBUF_INIT
;
3063 struct strbuf err
= STRBUF_INIT
;
3065 memset(&cb
, 0, sizeof(cb
));
3067 cb
.policy_cb
= policy_cb_data
;
3068 cb
.should_prune_fn
= should_prune_fn
;
3071 * The reflog file is locked by holding the lock on the
3072 * reference itself, plus we might need to update the
3073 * reference if --updateref was specified:
3075 lock
= lock_ref_oid_basic(refs
, refname
, oid
,
3076 NULL
, NULL
, REF_NO_DEREF
,
3079 error("cannot lock ref '%s': %s", refname
, err
.buf
);
3080 strbuf_release(&err
);
3083 if (!refs_reflog_exists(ref_store
, refname
)) {
3088 files_reflog_path(refs
, &log_file_sb
, refname
);
3089 log_file
= strbuf_detach(&log_file_sb
, NULL
);
3090 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3092 * Even though holding $GIT_DIR/logs/$reflog.lock has
3093 * no locking implications, we use the lock_file
3094 * machinery here anyway because it does a lot of the
3095 * work we need, including cleaning up if the program
3096 * exits unexpectedly.
3098 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
3099 struct strbuf err
= STRBUF_INIT
;
3100 unable_to_lock_message(log_file
, errno
, &err
);
3101 error("%s", err
.buf
);
3102 strbuf_release(&err
);
3105 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
3107 error("cannot fdopen %s (%s)",
3108 get_lock_file_path(&reflog_lock
), strerror(errno
));
3113 (*prepare_fn
)(refname
, oid
, cb
.policy_cb
);
3114 refs_for_each_reflog_ent(ref_store
, refname
, expire_reflog_ent
, &cb
);
3115 (*cleanup_fn
)(cb
.policy_cb
);
3117 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3119 * It doesn't make sense to adjust a reference pointed
3120 * to by a symbolic ref based on expiring entries in
3121 * the symbolic reference's reflog. Nor can we update
3122 * a reference if there are no remaining reflog
3125 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
3126 !(type
& REF_ISSYMREF
) &&
3127 !is_null_oid(&cb
.last_kept_oid
);
3129 if (close_lock_file_gently(&reflog_lock
)) {
3130 status
|= error("couldn't write %s: %s", log_file
,
3132 rollback_lock_file(&reflog_lock
);
3133 } else if (update
&&
3134 (write_in_full(get_lock_file_fd(&lock
->lk
),
3135 oid_to_hex(&cb
.last_kept_oid
), the_hash_algo
->hexsz
) < 0 ||
3136 write_str_in_full(get_lock_file_fd(&lock
->lk
), "\n") < 0 ||
3137 close_ref_gently(lock
) < 0)) {
3138 status
|= error("couldn't write %s",
3139 get_lock_file_path(&lock
->lk
));
3140 rollback_lock_file(&reflog_lock
);
3141 } else if (commit_lock_file(&reflog_lock
)) {
3142 status
|= error("unable to write reflog '%s' (%s)",
3143 log_file
, strerror(errno
));
3144 } else if (update
&& commit_ref(lock
)) {
3145 status
|= error("couldn't set %s", lock
->ref_name
);
3153 rollback_lock_file(&reflog_lock
);
3159 static int files_init_db(struct ref_store
*ref_store
, struct strbuf
*err
)
3161 struct files_ref_store
*refs
=
3162 files_downcast(ref_store
, REF_STORE_WRITE
, "init_db");
3163 struct strbuf sb
= STRBUF_INIT
;
3166 * Create .git/refs/{heads,tags}
3168 files_ref_path(refs
, &sb
, "refs/heads");
3169 safe_create_dir(sb
.buf
, 1);
3172 files_ref_path(refs
, &sb
, "refs/tags");
3173 safe_create_dir(sb
.buf
, 1);
3175 strbuf_release(&sb
);
3179 struct ref_storage_be refs_be_files
= {
3182 files_ref_store_create
,
3184 files_transaction_prepare
,
3185 files_transaction_finish
,
3186 files_transaction_abort
,
3187 files_initial_transaction_commit
,
3190 files_create_symref
,
3195 files_ref_iterator_begin
,
3198 files_reflog_iterator_begin
,
3199 files_for_each_reflog_ent
,
3200 files_for_each_reflog_ent_reverse
,
3201 files_reflog_exists
,
3202 files_create_reflog
,
3203 files_delete_reflog
,