1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "../git-compat-util.h"
5 #include "../abspath.h"
8 #include "../environment.h"
9 #include "../gettext.h"
14 #include "../repo-settings.h"
15 #include "refs-internal.h"
16 #include "ref-cache.h"
17 #include "packed-backend.h"
19 #include "../iterator.h"
20 #include "../dir-iterator.h"
21 #include "../lockfile.h"
22 #include "../object.h"
23 #include "../object-file.h"
26 #include "../chdir-notify.h"
28 #include "../worktree.h"
29 #include "../wrapper.h"
30 #include "../write-or-die.h"
31 #include "../revision.h"
32 #include <wildmatch.h>
35 * This backend uses the following flags in `ref_update::flags` for
36 * internal bookkeeping purposes. Their numerical values must not
37 * conflict with REF_NO_DEREF, REF_FORCE_CREATE_REFLOG, REF_HAVE_NEW,
38 * or REF_HAVE_OLD, which are also stored in `ref_update::flags`.
42 * Used as a flag in ref_update::flags when a loose ref is being
43 * pruned. This flag must only be used when REF_NO_DEREF is set.
45 #define REF_IS_PRUNING (1 << 4)
48 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
49 * refs (i.e., because the reference is about to be deleted anyway).
51 #define REF_DELETING (1 << 5)
54 * Used as a flag in ref_update::flags when the lockfile needs to be
57 #define REF_NEEDS_COMMIT (1 << 6)
60 * Used as a flag in ref_update::flags when the ref_update was via an
63 #define REF_UPDATE_VIA_HEAD (1 << 8)
66 * Used as a flag in ref_update::flags when a reference has been
67 * deleted and the ref's parent directories may need cleanup.
69 #define REF_DELETED_RMDIR (1 << 9)
74 struct object_id old_oid
;
75 unsigned int count
; /* track users of the lock (ref update + reflog updates) */
78 struct files_ref_store
{
79 struct ref_store base
;
80 unsigned int store_flags
;
83 enum log_refs_config log_all_ref_updates
;
84 int prefer_symlink_refs
;
86 struct ref_cache
*loose
;
88 struct ref_store
*packed_ref_store
;
91 static void clear_loose_ref_cache(struct files_ref_store
*refs
)
94 free_ref_cache(refs
->loose
);
100 * Create a new submodule ref cache and add it to the internal
103 static struct ref_store
*files_ref_store_init(struct repository
*repo
,
107 struct files_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
108 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
109 struct strbuf sb
= STRBUF_INIT
;
111 base_ref_store_init(ref_store
, repo
, gitdir
, &refs_be_files
);
112 refs
->store_flags
= flags
;
113 get_common_dir_noenv(&sb
, gitdir
);
114 refs
->gitcommondir
= strbuf_detach(&sb
, NULL
);
115 refs
->packed_ref_store
=
116 packed_ref_store_init(repo
, refs
->gitcommondir
, flags
);
117 refs
->log_all_ref_updates
= repo_settings_get_log_all_ref_updates(repo
);
118 repo_config_get_bool(repo
, "core.prefersymlinkrefs", &refs
->prefer_symlink_refs
);
120 chdir_notify_reparent("files-backend $GIT_DIR", &refs
->base
.gitdir
);
121 chdir_notify_reparent("files-backend $GIT_COMMONDIR",
122 &refs
->gitcommondir
);
128 * Die if refs is not the main ref store. caller is used in any
129 * necessary error messages.
131 static void files_assert_main_repository(struct files_ref_store
*refs
,
134 if (refs
->store_flags
& REF_STORE_MAIN
)
137 BUG("operation %s only allowed for main ref store", caller
);
141 * Downcast ref_store to files_ref_store. Die if ref_store is not a
142 * files_ref_store. required_flags is compared with ref_store's
143 * store_flags to ensure the ref_store has all required capabilities.
144 * "caller" is used in any necessary error messages.
146 static struct files_ref_store
*files_downcast(struct ref_store
*ref_store
,
147 unsigned int required_flags
,
150 struct files_ref_store
*refs
;
152 if (ref_store
->be
!= &refs_be_files
)
153 BUG("ref_store is type \"%s\" not \"files\" in %s",
154 ref_store
->be
->name
, caller
);
156 refs
= (struct files_ref_store
*)ref_store
;
158 if ((refs
->store_flags
& required_flags
) != required_flags
)
159 BUG("operation %s requires abilities 0x%x, but only have 0x%x",
160 caller
, required_flags
, refs
->store_flags
);
165 static void files_ref_store_release(struct ref_store
*ref_store
)
167 struct files_ref_store
*refs
= files_downcast(ref_store
, 0, "release");
168 free_ref_cache(refs
->loose
);
169 free(refs
->gitcommondir
);
170 ref_store_release(refs
->packed_ref_store
);
171 free(refs
->packed_ref_store
);
174 static void files_reflog_path(struct files_ref_store
*refs
,
178 const char *bare_refname
;
181 enum ref_worktree_type wt_type
= parse_worktree_ref(
182 refname
, &wtname
, &wtname_len
, &bare_refname
);
185 case REF_WORKTREE_CURRENT
:
186 strbuf_addf(sb
, "%s/logs/%s", refs
->base
.gitdir
, refname
);
188 case REF_WORKTREE_SHARED
:
189 case REF_WORKTREE_MAIN
:
190 strbuf_addf(sb
, "%s/logs/%s", refs
->gitcommondir
, bare_refname
);
192 case REF_WORKTREE_OTHER
:
193 strbuf_addf(sb
, "%s/worktrees/%.*s/logs/%s", refs
->gitcommondir
,
194 wtname_len
, wtname
, bare_refname
);
197 BUG("unknown ref type %d of ref %s", wt_type
, refname
);
201 static void files_ref_path(struct files_ref_store
*refs
,
205 const char *bare_refname
;
208 enum ref_worktree_type wt_type
= parse_worktree_ref(
209 refname
, &wtname
, &wtname_len
, &bare_refname
);
211 case REF_WORKTREE_CURRENT
:
212 strbuf_addf(sb
, "%s/%s", refs
->base
.gitdir
, refname
);
214 case REF_WORKTREE_OTHER
:
215 strbuf_addf(sb
, "%s/worktrees/%.*s/%s", refs
->gitcommondir
,
216 wtname_len
, wtname
, bare_refname
);
218 case REF_WORKTREE_SHARED
:
219 case REF_WORKTREE_MAIN
:
220 strbuf_addf(sb
, "%s/%s", refs
->gitcommondir
, bare_refname
);
223 BUG("unknown ref type %d of ref %s", wt_type
, refname
);
228 * Manually add refs/bisect, refs/rewritten and refs/worktree, which, being
229 * per-worktree, might not appear in the directory listing for
230 * refs/ in the main repo.
232 static void add_per_worktree_entries_to_dir(struct ref_dir
*dir
, const char *dirname
)
234 const char *prefixes
[] = { "refs/bisect/", "refs/worktree/", "refs/rewritten/" };
237 if (strcmp(dirname
, "refs/"))
240 for (ip
= 0; ip
< ARRAY_SIZE(prefixes
); ip
++) {
241 const char *prefix
= prefixes
[ip
];
242 int prefix_len
= strlen(prefix
);
243 struct ref_entry
*child_entry
;
246 pos
= search_ref_dir(dir
, prefix
, prefix_len
);
249 child_entry
= create_dir_entry(dir
->cache
, prefix
, prefix_len
);
250 add_entry_to_dir(dir
, child_entry
);
254 static void loose_fill_ref_dir_regular_file(struct files_ref_store
*refs
,
258 struct object_id oid
;
260 const char *referent
= refs_resolve_ref_unsafe(&refs
->base
,
266 oidclr(&oid
, refs
->base
.repo
->hash_algo
);
267 flag
|= REF_ISBROKEN
;
268 } else if (is_null_oid(&oid
)) {
270 * It is so astronomically unlikely
271 * that null_oid is the OID of an
272 * actual object that we consider its
273 * appearance in a loose reference
274 * file to be repo corruption
275 * (probably due to a software bug).
277 flag
|= REF_ISBROKEN
;
280 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
281 if (!refname_is_safe(refname
))
282 die("loose refname is dangerous: %s", refname
);
283 oidclr(&oid
, refs
->base
.repo
->hash_algo
);
284 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
287 if (!(flag
& REF_ISSYMREF
))
290 add_entry_to_dir(dir
, create_ref_entry(refname
, referent
, &oid
, flag
));
294 * Read the loose references from the namespace dirname into dir
295 * (without recursing). dirname must end with '/'. dir must be the
296 * directory entry corresponding to dirname.
298 static void loose_fill_ref_dir(struct ref_store
*ref_store
,
299 struct ref_dir
*dir
, const char *dirname
)
301 struct files_ref_store
*refs
=
302 files_downcast(ref_store
, REF_STORE_READ
, "fill_ref_dir");
305 int dirnamelen
= strlen(dirname
);
306 struct strbuf refname
;
307 struct strbuf path
= STRBUF_INIT
;
309 files_ref_path(refs
, &path
, dirname
);
311 d
= opendir(path
.buf
);
313 strbuf_release(&path
);
317 strbuf_init(&refname
, dirnamelen
+ 257);
318 strbuf_add(&refname
, dirname
, dirnamelen
);
320 while ((de
= readdir(d
)) != NULL
) {
323 if (de
->d_name
[0] == '.')
325 if (ends_with(de
->d_name
, ".lock"))
327 strbuf_addstr(&refname
, de
->d_name
);
329 dtype
= get_dtype(de
, &path
, 1);
330 if (dtype
== DT_DIR
) {
331 strbuf_addch(&refname
, '/');
332 add_entry_to_dir(dir
,
333 create_dir_entry(dir
->cache
, refname
.buf
,
335 } else if (dtype
== DT_REG
) {
336 loose_fill_ref_dir_regular_file(refs
, refname
.buf
, dir
);
338 strbuf_setlen(&refname
, dirnamelen
);
340 strbuf_release(&refname
);
341 strbuf_release(&path
);
344 add_per_worktree_entries_to_dir(dir
, dirname
);
347 static int for_each_root_ref(struct files_ref_store
*refs
,
348 int (*cb
)(const char *refname
, void *cb_data
),
351 struct strbuf path
= STRBUF_INIT
, refname
= STRBUF_INIT
;
352 const char *dirname
= refs
->loose
->root
->name
;
358 files_ref_path(refs
, &path
, dirname
);
360 d
= opendir(path
.buf
);
362 strbuf_release(&path
);
366 strbuf_addstr(&refname
, dirname
);
367 dirnamelen
= refname
.len
;
369 while ((de
= readdir(d
)) != NULL
) {
372 if (de
->d_name
[0] == '.')
374 if (ends_with(de
->d_name
, ".lock"))
376 strbuf_addstr(&refname
, de
->d_name
);
378 dtype
= get_dtype(de
, &path
, 1);
379 if (dtype
== DT_REG
&& is_root_ref(de
->d_name
)) {
380 ret
= cb(refname
.buf
, cb_data
);
385 strbuf_setlen(&refname
, dirnamelen
);
391 strbuf_release(&refname
);
392 strbuf_release(&path
);
397 struct fill_root_ref_data
{
398 struct files_ref_store
*refs
;
402 static int fill_root_ref(const char *refname
, void *cb_data
)
404 struct fill_root_ref_data
*data
= cb_data
;
405 loose_fill_ref_dir_regular_file(data
->refs
, refname
, data
->dir
);
410 * Add root refs to the ref dir by parsing the directory for any files which
411 * follow the root ref syntax.
413 static void add_root_refs(struct files_ref_store
*refs
,
416 struct fill_root_ref_data data
= {
421 for_each_root_ref(refs
, fill_root_ref
, &data
);
424 static struct ref_cache
*get_loose_ref_cache(struct files_ref_store
*refs
,
431 * Mark the top-level directory complete because we
432 * are about to read the only subdirectory that can
435 refs
->loose
= create_ref_cache(&refs
->base
, loose_fill_ref_dir
);
437 /* We're going to fill the top level ourselves: */
438 refs
->loose
->root
->flag
&= ~REF_INCOMPLETE
;
440 dir
= get_ref_dir(refs
->loose
->root
);
442 if (flags
& DO_FOR_EACH_INCLUDE_ROOT_REFS
)
443 add_root_refs(refs
, dir
);
446 * Add an incomplete entry for "refs/" (to be filled
449 add_entry_to_dir(dir
, create_dir_entry(refs
->loose
, "refs/", 5));
454 static int read_ref_internal(struct ref_store
*ref_store
, const char *refname
,
455 struct object_id
*oid
, struct strbuf
*referent
,
456 unsigned int *type
, int *failure_errno
, int skip_packed_refs
)
458 struct files_ref_store
*refs
=
459 files_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
460 struct strbuf sb_contents
= STRBUF_INIT
;
461 struct strbuf sb_path
= STRBUF_INIT
;
467 int remaining_retries
= 3;
471 strbuf_reset(&sb_path
);
473 files_ref_path(refs
, &sb_path
, refname
);
479 * We might have to loop back here to avoid a race
480 * condition: first we lstat() the file, then we try
481 * to read it as a link or as a file. But if somebody
482 * changes the type of the file (file <-> directory
483 * <-> symlink) between the lstat() and reading, then
484 * we don't want to report that as an error but rather
485 * try again starting with the lstat().
487 * We'll keep a count of the retries, though, just to avoid
488 * any confusing situation sending us into an infinite loop.
491 if (remaining_retries
-- <= 0)
494 if (lstat(path
, &st
) < 0) {
497 if (myerr
!= ENOENT
|| skip_packed_refs
)
499 if (refs_read_raw_ref(refs
->packed_ref_store
, refname
, oid
,
500 referent
, type
, &ignore_errno
)) {
508 /* Follow "normalized" - ie "refs/.." symlinks by hand */
509 if (S_ISLNK(st
.st_mode
)) {
510 strbuf_reset(&sb_contents
);
511 if (strbuf_readlink(&sb_contents
, path
, st
.st_size
) < 0) {
513 if (myerr
== ENOENT
|| myerr
== EINVAL
)
514 /* inconsistent with lstat; retry */
519 if (starts_with(sb_contents
.buf
, "refs/") &&
520 !check_refname_format(sb_contents
.buf
, 0)) {
521 strbuf_swap(&sb_contents
, referent
);
522 *type
|= REF_ISSYMREF
;
527 * It doesn't look like a refname; fall through to just
528 * treating it like a non-symlink, and reading whatever it
533 /* Is it a directory? */
534 if (S_ISDIR(st
.st_mode
)) {
537 * Even though there is a directory where the loose
538 * ref is supposed to be, there could still be a
541 if (skip_packed_refs
||
542 refs_read_raw_ref(refs
->packed_ref_store
, refname
, oid
,
543 referent
, type
, &ignore_errno
)) {
552 * Anything else, just open it and try to use it as
555 fd
= open(path
, O_RDONLY
);
558 if (myerr
== ENOENT
&& !S_ISLNK(st
.st_mode
))
559 /* inconsistent with lstat; retry */
564 strbuf_reset(&sb_contents
);
565 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
571 strbuf_rtrim(&sb_contents
);
572 buf
= sb_contents
.buf
;
574 ret
= parse_loose_ref_contents(ref_store
->repo
->hash_algo
, buf
,
575 oid
, referent
, type
, NULL
, &myerr
);
579 BUG("returning non-zero %d, should have set myerr!", ret
);
580 *failure_errno
= myerr
;
582 strbuf_release(&sb_path
);
583 strbuf_release(&sb_contents
);
588 static int files_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
589 struct object_id
*oid
, struct strbuf
*referent
,
590 unsigned int *type
, int *failure_errno
)
592 return read_ref_internal(ref_store
, refname
, oid
, referent
, type
, failure_errno
, 0);
595 static int files_read_symbolic_ref(struct ref_store
*ref_store
, const char *refname
,
596 struct strbuf
*referent
)
598 struct object_id oid
;
599 int failure_errno
, ret
;
602 ret
= read_ref_internal(ref_store
, refname
, &oid
, referent
, &type
, &failure_errno
, 1);
603 if (!ret
&& !(type
& REF_ISSYMREF
))
608 int parse_loose_ref_contents(const struct git_hash_algo
*algop
,
609 const char *buf
, struct object_id
*oid
,
610 struct strbuf
*referent
, unsigned int *type
,
611 const char **trailing
, int *failure_errno
)
614 if (skip_prefix(buf
, "ref:", &buf
)) {
615 while (isspace(*buf
))
618 strbuf_reset(referent
);
619 strbuf_addstr(referent
, buf
);
620 *type
|= REF_ISSYMREF
;
625 * FETCH_HEAD has additional data after the sha.
627 if (parse_oid_hex_algop(buf
, oid
, &p
, algop
) ||
628 (*p
!= '\0' && !isspace(*p
))) {
629 *type
|= REF_ISBROKEN
;
630 *failure_errno
= EINVAL
;
640 static void unlock_ref(struct ref_lock
*lock
)
644 rollback_lock_file(&lock
->lk
);
645 free(lock
->ref_name
);
651 * Lock refname, without following symrefs, and set *lock_p to point
652 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
653 * and type similarly to read_raw_ref().
655 * The caller must verify that refname is a "safe" reference name (in
656 * the sense of refname_is_safe()) before calling this function.
658 * If the reference doesn't already exist, verify that refname doesn't
659 * have a D/F conflict with any existing references. extras and skip
660 * are passed to refs_verify_refname_available() for this check.
662 * If mustexist is not set and the reference is not found or is
663 * broken, lock the reference anyway but clear old_oid.
665 * Return 0 on success. On failure, write an error message to err and
666 * return REF_TRANSACTION_ERROR_NAME_CONFLICT or REF_TRANSACTION_ERROR_GENERIC.
668 * Implementation note: This function is basically
673 * but it includes a lot more code to
674 * - Deal with possible races with other processes
675 * - Avoid calling refs_verify_refname_available() when it can be
676 * avoided, namely if we were successfully able to read the ref
677 * - Generate informative error messages in the case of failure
679 static enum ref_transaction_error
lock_raw_ref(struct files_ref_store
*refs
,
680 struct ref_update
*update
,
683 struct string_list
*refnames_to_check
,
684 const struct string_list
*extras
,
685 struct ref_lock
**lock_p
,
686 struct strbuf
*referent
,
689 enum ref_transaction_error ret
= REF_TRANSACTION_ERROR_GENERIC
;
690 const char *refname
= update
->refname
;
691 unsigned int *type
= &update
->type
;
692 struct ref_lock
*lock
;
693 struct strbuf ref_file
= STRBUF_INIT
;
694 int attempts_remaining
= 3;
698 files_assert_main_repository(refs
, "lock_raw_ref");
702 /* First lock the file so it can't change out from under us. */
704 *lock_p
= CALLOC_ARRAY(lock
, 1);
706 lock
->ref_name
= xstrdup(refname
);
708 files_ref_path(refs
, &ref_file
, refname
);
711 switch (safe_create_leading_directories(the_repository
, ref_file
.buf
)) {
716 * Suppose refname is "refs/foo/bar". We just failed
717 * to create the containing directory, "refs/foo",
718 * because there was a non-directory in the way. This
719 * indicates a D/F conflict, probably because of
720 * another reference such as "refs/foo". There is no
721 * reason to expect this error to be transitory.
723 if (refs_verify_refname_available(&refs
->base
, refname
,
724 extras
, NULL
, 0, err
)) {
727 * To the user the relevant error is
728 * that the "mustexist" reference is
732 strbuf_addf(err
, "unable to resolve reference '%s'",
734 ret
= REF_TRANSACTION_ERROR_NONEXISTENT_REF
;
737 * The error message set by
738 * refs_verify_refname_available() is
741 ret
= REF_TRANSACTION_ERROR_NAME_CONFLICT
;
745 * The file that is in the way isn't a loose
746 * reference. Report it as a low-level
749 strbuf_addf(err
, "unable to create lock file %s.lock; "
750 "non-directory in the way",
755 /* Maybe another process was tidying up. Try again. */
756 if (--attempts_remaining
> 0)
760 strbuf_addf(err
, "unable to create directory for %s",
765 if (hold_lock_file_for_update_timeout(
766 &lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
,
767 get_files_ref_lock_timeout_ms()) < 0) {
770 if (myerr
== ENOENT
&& --attempts_remaining
> 0) {
772 * Maybe somebody just deleted one of the
773 * directories leading to ref_file. Try
778 unable_to_lock_message(ref_file
.buf
, myerr
, err
);
784 * Now we hold the lock and can read the reference without
785 * fear that its value will change.
788 if (files_read_raw_ref(&refs
->base
, refname
, &lock
->old_oid
, referent
,
789 type
, &failure_errno
)) {
790 struct string_list_item
*item
;
792 if (failure_errno
== ENOENT
) {
794 /* Garden variety missing reference. */
795 strbuf_addf(err
, "unable to resolve reference '%s'",
797 ret
= REF_TRANSACTION_ERROR_NONEXISTENT_REF
;
801 * Reference is missing, but that's OK. We
802 * know that there is not a conflict with
803 * another loose reference because
804 * (supposing that we are trying to lock
805 * reference "refs/foo/bar"):
807 * - We were successfully able to create
808 * the lockfile refs/foo/bar.lock, so we
809 * know there cannot be a loose reference
812 * - We got ENOENT and not EISDIR, so we
813 * know that there cannot be a loose
814 * reference named "refs/foo/bar/baz".
817 } else if (failure_errno
== EISDIR
) {
819 * There is a directory in the way. It might have
820 * contained references that have been deleted. If
821 * we don't require that the reference already
822 * exists, try to remove the directory so that it
823 * doesn't cause trouble when we want to rename the
824 * lockfile into place later.
827 /* Garden variety missing reference. */
828 strbuf_addf(err
, "unable to resolve reference '%s'",
830 ret
= REF_TRANSACTION_ERROR_NONEXISTENT_REF
;
832 } else if (remove_dir_recursively(&ref_file
,
833 REMOVE_DIR_EMPTY_ONLY
)) {
834 if (refs_verify_refname_available(
835 &refs
->base
, refname
,
836 extras
, NULL
, 0, err
)) {
838 * The error message set by
839 * verify_refname_available() is OK.
841 ret
= REF_TRANSACTION_ERROR_NAME_CONFLICT
;
845 * We can't delete the directory,
846 * but we also don't know of any
847 * references that it should
850 strbuf_addf(err
, "there is a non-empty directory '%s' "
851 "blocking reference '%s'",
852 ref_file
.buf
, refname
);
856 } else if (failure_errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
857 strbuf_addf(err
, "unable to resolve reference '%s': "
858 "reference broken", refname
);
861 strbuf_addf(err
, "unable to resolve reference '%s': %s",
862 refname
, strerror(failure_errno
));
867 * If the ref did not exist and we are creating it, we have to
868 * make sure there is no existing packed ref that conflicts
869 * with refname. This check is deferred so that we can batch it.
871 item
= string_list_append(refnames_to_check
, refname
);
872 item
->util
= xmalloc(sizeof(update_idx
));
873 memcpy(item
->util
, &update_idx
, sizeof(update_idx
));
884 strbuf_release(&ref_file
);
888 struct files_ref_iterator
{
889 struct ref_iterator base
;
891 struct ref_iterator
*iter0
;
892 struct repository
*repo
;
896 static int files_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
898 struct files_ref_iterator
*iter
=
899 (struct files_ref_iterator
*)ref_iterator
;
902 while ((ok
= ref_iterator_advance(iter
->iter0
)) == ITER_OK
) {
903 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
904 parse_worktree_ref(iter
->iter0
->refname
, NULL
, NULL
,
905 NULL
) != REF_WORKTREE_CURRENT
)
908 if ((iter
->flags
& DO_FOR_EACH_OMIT_DANGLING_SYMREFS
) &&
909 (iter
->iter0
->flags
& REF_ISSYMREF
) &&
910 (iter
->iter0
->flags
& REF_ISBROKEN
))
913 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
914 !ref_resolves_to_object(iter
->iter0
->refname
,
920 iter
->base
.refname
= iter
->iter0
->refname
;
921 iter
->base
.oid
= iter
->iter0
->oid
;
922 iter
->base
.flags
= iter
->iter0
->flags
;
923 iter
->base
.referent
= iter
->iter0
->referent
;
931 static int files_ref_iterator_seek(struct ref_iterator
*ref_iterator
,
934 struct files_ref_iterator
*iter
=
935 (struct files_ref_iterator
*)ref_iterator
;
936 return ref_iterator_seek(iter
->iter0
, prefix
);
939 static int files_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
940 struct object_id
*peeled
)
942 struct files_ref_iterator
*iter
=
943 (struct files_ref_iterator
*)ref_iterator
;
945 return ref_iterator_peel(iter
->iter0
, peeled
);
948 static void files_ref_iterator_release(struct ref_iterator
*ref_iterator
)
950 struct files_ref_iterator
*iter
=
951 (struct files_ref_iterator
*)ref_iterator
;
952 ref_iterator_free(iter
->iter0
);
955 static struct ref_iterator_vtable files_ref_iterator_vtable
= {
956 .advance
= files_ref_iterator_advance
,
957 .seek
= files_ref_iterator_seek
,
958 .peel
= files_ref_iterator_peel
,
959 .release
= files_ref_iterator_release
,
962 static struct ref_iterator
*files_ref_iterator_begin(
963 struct ref_store
*ref_store
,
964 const char *prefix
, const char **exclude_patterns
,
967 struct files_ref_store
*refs
;
968 struct ref_iterator
*loose_iter
, *packed_iter
, *overlay_iter
;
969 struct files_ref_iterator
*iter
;
970 struct ref_iterator
*ref_iterator
;
971 unsigned int required_flags
= REF_STORE_READ
;
973 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
974 required_flags
|= REF_STORE_ODB
;
976 refs
= files_downcast(ref_store
, required_flags
, "ref_iterator_begin");
979 * We must make sure that all loose refs are read before
980 * accessing the packed-refs file; this avoids a race
981 * condition if loose refs are migrated to the packed-refs
982 * file by a simultaneous process, but our in-memory view is
983 * from before the migration. We ensure this as follows:
984 * First, we call start the loose refs iteration with its
985 * `prime_ref` argument set to true. This causes the loose
986 * references in the subtree to be pre-read into the cache.
987 * (If they've already been read, that's OK; we only need to
988 * guarantee that they're read before the packed refs, not
989 * *how much* before.) After that, we call
990 * packed_ref_iterator_begin(), which internally checks
991 * whether the packed-ref cache is up to date with what is on
992 * disk, and re-reads it if not.
995 loose_iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
, flags
),
996 prefix
, ref_store
->repo
, 1);
999 * The packed-refs file might contain broken references, for
1000 * example an old version of a reference that points at an
1001 * object that has since been garbage-collected. This is OK as
1002 * long as there is a corresponding loose reference that
1003 * overrides it, and we don't want to emit an error message in
1004 * this case. So ask the packed_ref_store for all of its
1005 * references, and (if needed) do our own check for broken
1006 * ones in files_ref_iterator_advance(), after we have merged
1007 * the packed and loose references.
1009 packed_iter
= refs_ref_iterator_begin(
1010 refs
->packed_ref_store
, prefix
, exclude_patterns
, 0,
1011 DO_FOR_EACH_INCLUDE_BROKEN
);
1013 overlay_iter
= overlay_ref_iterator_begin(loose_iter
, packed_iter
);
1015 CALLOC_ARRAY(iter
, 1);
1016 ref_iterator
= &iter
->base
;
1017 base_ref_iterator_init(ref_iterator
, &files_ref_iterator_vtable
);
1018 iter
->iter0
= overlay_iter
;
1019 iter
->repo
= ref_store
->repo
;
1020 iter
->flags
= flags
;
1022 return ref_iterator
;
1026 * Callback function for raceproof_create_file(). This function is
1027 * expected to do something that makes dirname(path) permanent despite
1028 * the fact that other processes might be cleaning up empty
1029 * directories at the same time. Usually it will create a file named
1030 * path, but alternatively it could create another file in that
1031 * directory, or even chdir() into that directory. The function should
1032 * return 0 if the action was completed successfully. On error, it
1033 * should return a nonzero result and set errno.
1034 * raceproof_create_file() treats two errno values specially:
1036 * - ENOENT -- dirname(path) does not exist. In this case,
1037 * raceproof_create_file() tries creating dirname(path)
1038 * (and any parent directories, if necessary) and calls
1039 * the function again.
1041 * - EISDIR -- the file already exists and is a directory. In this
1042 * case, raceproof_create_file() removes the directory if
1043 * it is empty (and recursively any empty directories that
1044 * it contains) and calls the function again.
1046 * Any other errno causes raceproof_create_file() to fail with the
1047 * callback's return value and errno.
1049 * Obviously, this function should be OK with being called again if it
1050 * fails with ENOENT or EISDIR. In other scenarios it will not be
1053 typedef int create_file_fn(const char *path
, void *cb
);
1056 * Create a file in dirname(path) by calling fn, creating leading
1057 * directories if necessary. Retry a few times in case we are racing
1058 * with another process that is trying to clean up the directory that
1059 * contains path. See the documentation for create_file_fn for more
1062 * Return the value and set the errno that resulted from the most
1063 * recent call of fn. fn is always called at least once, and will be
1064 * called more than once if it returns ENOENT or EISDIR.
1066 static int raceproof_create_file(const char *path
, create_file_fn fn
, void *cb
)
1069 * The number of times we will try to remove empty directories
1070 * in the way of path. This is only 1 because if another
1071 * process is racily creating directories that conflict with
1072 * us, we don't want to fight against them.
1074 int remove_directories_remaining
= 1;
1077 * The number of times that we will try to create the
1078 * directories containing path. We are willing to attempt this
1079 * more than once, because another process could be trying to
1080 * clean up empty directories at the same time as we are
1081 * trying to create them.
1083 int create_directories_remaining
= 3;
1085 /* A scratch copy of path, filled lazily if we need it: */
1086 struct strbuf path_copy
= STRBUF_INIT
;
1088 int ret
, save_errno
;
1099 if (errno
== EISDIR
&& remove_directories_remaining
-- > 0) {
1101 * A directory is in the way. Maybe it is empty; try
1105 strbuf_addstr(&path_copy
, path
);
1107 if (!remove_dir_recursively(&path_copy
, REMOVE_DIR_EMPTY_ONLY
))
1109 } else if (errno
== ENOENT
&& create_directories_remaining
-- > 0) {
1111 * Maybe the containing directory didn't exist, or
1112 * maybe it was just deleted by a process that is
1113 * racing with us to clean up empty directories. Try
1116 enum scld_error scld_result
;
1119 strbuf_addstr(&path_copy
, path
);
1122 scld_result
= safe_create_leading_directories(the_repository
, path_copy
.buf
);
1123 if (scld_result
== SCLD_OK
)
1125 } while (scld_result
== SCLD_VANISHED
&& create_directories_remaining
-- > 0);
1129 strbuf_release(&path_copy
);
1134 static int remove_empty_directories(struct strbuf
*path
)
1137 * we want to create a file but there is a directory there;
1138 * if that is an empty directory (or a directory that contains
1139 * only empty directories), remove them.
1141 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
1144 static int create_reflock(const char *path
, void *cb
)
1146 struct lock_file
*lk
= cb
;
1148 return hold_lock_file_for_update_timeout(
1149 lk
, path
, LOCK_NO_DEREF
,
1150 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
1154 * Locks a ref returning the lock on success and NULL on failure.
1156 static struct ref_lock
*lock_ref_oid_basic(struct files_ref_store
*refs
,
1157 const char *refname
,
1160 struct strbuf ref_file
= STRBUF_INIT
;
1161 struct ref_lock
*lock
;
1163 files_assert_main_repository(refs
, "lock_ref_oid_basic");
1166 CALLOC_ARRAY(lock
, 1);
1168 files_ref_path(refs
, &ref_file
, refname
);
1171 * If the ref did not exist and we are creating it, make sure
1172 * there is no existing packed ref whose name begins with our
1173 * refname, nor a packed ref whose name is a proper prefix of
1176 if (is_null_oid(&lock
->old_oid
) &&
1177 refs_verify_refname_available(refs
->packed_ref_store
, refname
,
1178 NULL
, NULL
, 0, err
))
1181 lock
->ref_name
= xstrdup(refname
);
1184 if (raceproof_create_file(ref_file
.buf
, create_reflock
, &lock
->lk
)) {
1185 unable_to_lock_message(ref_file
.buf
, errno
, err
);
1189 if (!refs_resolve_ref_unsafe(&refs
->base
, lock
->ref_name
, 0,
1190 &lock
->old_oid
, NULL
))
1191 oidclr(&lock
->old_oid
, refs
->base
.repo
->hash_algo
);
1199 strbuf_release(&ref_file
);
1203 struct ref_to_prune
{
1204 struct ref_to_prune
*next
;
1205 struct object_id oid
;
1206 char name
[FLEX_ARRAY
];
1210 REMOVE_EMPTY_PARENTS_REF
= 0x01,
1211 REMOVE_EMPTY_PARENTS_REFLOG
= 0x02
1215 * Remove empty parent directories associated with the specified
1216 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1217 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1218 * REMOVE_EMPTY_PARENTS_REFLOG.
1220 static void try_remove_empty_parents(struct files_ref_store
*refs
,
1221 const char *refname
,
1224 struct strbuf buf
= STRBUF_INIT
;
1225 struct strbuf sb
= STRBUF_INIT
;
1229 strbuf_addstr(&buf
, refname
);
1231 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
1232 while (*p
&& *p
!= '/')
1234 /* tolerate duplicate slashes; see check_refname_format() */
1238 q
= buf
.buf
+ buf
.len
;
1239 while (flags
& (REMOVE_EMPTY_PARENTS_REF
| REMOVE_EMPTY_PARENTS_REFLOG
)) {
1240 while (q
> p
&& *q
!= '/')
1242 while (q
> p
&& *(q
-1) == '/')
1246 strbuf_setlen(&buf
, q
- buf
.buf
);
1249 files_ref_path(refs
, &sb
, buf
.buf
);
1250 if ((flags
& REMOVE_EMPTY_PARENTS_REF
) && rmdir(sb
.buf
))
1251 flags
&= ~REMOVE_EMPTY_PARENTS_REF
;
1254 files_reflog_path(refs
, &sb
, buf
.buf
);
1255 if ((flags
& REMOVE_EMPTY_PARENTS_REFLOG
) && rmdir(sb
.buf
))
1256 flags
&= ~REMOVE_EMPTY_PARENTS_REFLOG
;
1258 strbuf_release(&buf
);
1259 strbuf_release(&sb
);
1262 /* make sure nobody touched the ref, and unlink */
1263 static void prune_ref(struct files_ref_store
*refs
, struct ref_to_prune
*r
)
1265 struct ref_transaction
*transaction
;
1266 struct strbuf err
= STRBUF_INIT
;
1269 if (check_refname_format(r
->name
, 0))
1272 transaction
= ref_store_transaction_begin(&refs
->base
, 0, &err
);
1275 ref_transaction_add_update(
1276 transaction
, r
->name
,
1277 REF_NO_DEREF
| REF_HAVE_NEW
| REF_HAVE_OLD
| REF_IS_PRUNING
,
1278 null_oid(the_hash_algo
), &r
->oid
, NULL
, NULL
, NULL
, NULL
);
1279 if (ref_transaction_commit(transaction
, &err
))
1286 error("%s", err
.buf
);
1287 strbuf_release(&err
);
1288 ref_transaction_free(transaction
);
1293 * Prune the loose versions of the references in the linked list
1294 * `*refs_to_prune`, freeing the entries in the list as we go.
1296 static void prune_refs(struct files_ref_store
*refs
, struct ref_to_prune
**refs_to_prune
)
1298 while (*refs_to_prune
) {
1299 struct ref_to_prune
*r
= *refs_to_prune
;
1300 *refs_to_prune
= r
->next
;
1307 * Return true if the specified reference should be packed.
1309 static int should_pack_ref(struct files_ref_store
*refs
,
1310 const char *refname
,
1311 const struct object_id
*oid
, unsigned int ref_flags
,
1312 struct pack_refs_opts
*opts
)
1314 struct string_list_item
*item
;
1316 /* Do not pack per-worktree refs: */
1317 if (parse_worktree_ref(refname
, NULL
, NULL
, NULL
) !=
1318 REF_WORKTREE_SHARED
)
1321 /* Do not pack symbolic refs: */
1322 if (ref_flags
& REF_ISSYMREF
)
1325 /* Do not pack broken refs: */
1326 if (!ref_resolves_to_object(refname
, refs
->base
.repo
, oid
, ref_flags
))
1329 if (ref_excluded(opts
->exclusions
, refname
))
1332 for_each_string_list_item(item
, opts
->includes
)
1333 if (!wildmatch(item
->string
, refname
, 0))
1339 static int should_pack_refs(struct files_ref_store
*refs
,
1340 struct pack_refs_opts
*opts
)
1342 struct ref_iterator
*iter
;
1344 size_t refcount
= 0;
1348 if (!(opts
->flags
& PACK_REFS_AUTO
))
1351 ret
= packed_refs_size(refs
->packed_ref_store
, &packed_size
);
1353 die("cannot determine packed-refs size");
1356 * Packing loose references into the packed-refs file scales with the
1357 * number of references we're about to write. We thus decide whether we
1358 * repack refs by weighing the current size of the packed-refs file
1359 * against the number of loose references. This is done such that we do
1360 * not repack too often on repositories with a huge number of
1361 * references, where we can expect a lot of churn in the number of
1364 * As a heuristic, we repack if the number of loose references in the
1365 * repository exceeds `log2(nr_packed_refs) * 5`, where we estimate
1366 * `nr_packed_refs = packed_size / 100`, which scales as following:
1368 * - 1kB ~ 10 packed refs: 16 refs
1369 * - 10kB ~ 100 packed refs: 33 refs
1370 * - 100kB ~ 1k packed refs: 49 refs
1371 * - 1MB ~ 10k packed refs: 66 refs
1372 * - 10MB ~ 100k packed refs: 82 refs
1373 * - 100MB ~ 1m packed refs: 99 refs
1375 * We thus allow roughly 16 additional loose refs per factor of ten of
1376 * packed refs. This heuristic may be tweaked in the future, but should
1377 * serve as a sufficiently good first iteration.
1379 limit
= log2u(packed_size
/ 100) * 5;
1383 iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
, 0), NULL
,
1384 refs
->base
.repo
, 0);
1385 while ((ret
= ref_iterator_advance(iter
)) == ITER_OK
) {
1386 if (should_pack_ref(refs
, iter
->refname
, iter
->oid
,
1389 if (refcount
>= limit
) {
1390 ref_iterator_free(iter
);
1395 if (ret
!= ITER_DONE
)
1396 die("error while iterating over references");
1398 ref_iterator_free(iter
);
1402 static int files_pack_refs(struct ref_store
*ref_store
,
1403 struct pack_refs_opts
*opts
)
1405 struct files_ref_store
*refs
=
1406 files_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_ODB
,
1408 struct ref_iterator
*iter
;
1410 struct ref_to_prune
*refs_to_prune
= NULL
;
1411 struct strbuf err
= STRBUF_INIT
;
1412 struct ref_transaction
*transaction
;
1414 if (!should_pack_refs(refs
, opts
))
1417 transaction
= ref_store_transaction_begin(refs
->packed_ref_store
,
1422 packed_refs_lock(refs
->packed_ref_store
, LOCK_DIE_ON_ERROR
, &err
);
1424 iter
= cache_ref_iterator_begin(get_loose_ref_cache(refs
, 0), NULL
,
1425 refs
->base
.repo
, 0);
1426 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
1428 * If the loose reference can be packed, add an entry
1429 * in the packed ref cache. If the reference should be
1430 * pruned, also add it to refs_to_prune.
1432 if (!should_pack_ref(refs
, iter
->refname
, iter
->oid
, iter
->flags
, opts
))
1436 * Add a reference creation for this reference to the
1437 * packed-refs transaction:
1439 if (ref_transaction_update(transaction
, iter
->refname
,
1440 iter
->oid
, NULL
, NULL
, NULL
,
1441 REF_NO_DEREF
, NULL
, &err
))
1442 die("failure preparing to create packed reference %s: %s",
1443 iter
->refname
, err
.buf
);
1445 /* Schedule the loose reference for pruning if requested. */
1446 if ((opts
->flags
& PACK_REFS_PRUNE
)) {
1447 struct ref_to_prune
*n
;
1448 FLEX_ALLOC_STR(n
, name
, iter
->refname
);
1449 oidcpy(&n
->oid
, iter
->oid
);
1450 n
->next
= refs_to_prune
;
1454 if (ok
!= ITER_DONE
)
1455 die("error while iterating over references");
1457 if (ref_transaction_commit(transaction
, &err
))
1458 die("unable to write new packed-refs: %s", err
.buf
);
1460 ref_transaction_free(transaction
);
1462 packed_refs_unlock(refs
->packed_ref_store
);
1464 prune_refs(refs
, &refs_to_prune
);
1465 ref_iterator_free(iter
);
1466 strbuf_release(&err
);
1471 * People using contrib's git-new-workdir have .git/logs/refs ->
1472 * /some/other/path/.git/logs/refs, and that may live on another device.
1474 * IOW, to avoid cross device rename errors, the temporary renamed log must
1475 * live into logs/refs.
1477 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1480 const char *tmp_renamed_log
;
1484 static int rename_tmp_log_callback(const char *path
, void *cb_data
)
1486 struct rename_cb
*cb
= cb_data
;
1488 if (rename(cb
->tmp_renamed_log
, path
)) {
1490 * rename(a, b) when b is an existing directory ought
1491 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1492 * Sheesh. Record the true errno for error reporting,
1493 * but report EISDIR to raceproof_create_file() so
1494 * that it knows to retry.
1496 cb
->true_errno
= errno
;
1497 if (errno
== ENOTDIR
)
1505 static int rename_tmp_log(struct files_ref_store
*refs
, const char *newrefname
)
1507 struct strbuf path
= STRBUF_INIT
;
1508 struct strbuf tmp
= STRBUF_INIT
;
1509 struct rename_cb cb
;
1512 files_reflog_path(refs
, &path
, newrefname
);
1513 files_reflog_path(refs
, &tmp
, TMP_RENAMED_LOG
);
1514 cb
.tmp_renamed_log
= tmp
.buf
;
1515 ret
= raceproof_create_file(path
.buf
, rename_tmp_log_callback
, &cb
);
1517 if (errno
== EISDIR
)
1518 error("directory not empty: %s", path
.buf
);
1520 error("unable to move logfile %s to %s: %s",
1522 strerror(cb
.true_errno
));
1525 strbuf_release(&path
);
1526 strbuf_release(&tmp
);
1530 static enum ref_transaction_error
write_ref_to_lockfile(struct files_ref_store
*refs
,
1531 struct ref_lock
*lock
,
1532 const struct object_id
*oid
,
1533 int skip_oid_verification
,
1534 struct strbuf
*err
);
1535 static int commit_ref_update(struct files_ref_store
*refs
,
1536 struct ref_lock
*lock
,
1537 const struct object_id
*oid
, const char *logmsg
,
1539 struct strbuf
*err
);
1542 * Emit a better error message than lockfile.c's
1543 * unable_to_lock_message() would in case there is a D/F conflict with
1544 * another existing reference. If there would be a conflict, emit an error
1545 * message and return false; otherwise, return true.
1547 * Note that this function is not safe against all races with other
1548 * processes, and that's not its job. We'll emit a more verbose error on D/f
1549 * conflicts if we get past it into lock_ref_oid_basic().
1551 static int refs_rename_ref_available(struct ref_store
*refs
,
1552 const char *old_refname
,
1553 const char *new_refname
)
1555 struct string_list skip
= STRING_LIST_INIT_NODUP
;
1556 struct strbuf err
= STRBUF_INIT
;
1559 string_list_insert(&skip
, old_refname
);
1560 ok
= !refs_verify_refname_available(refs
, new_refname
,
1561 NULL
, &skip
, 0, &err
);
1563 error("%s", err
.buf
);
1565 string_list_clear(&skip
, 0);
1566 strbuf_release(&err
);
1570 static int files_copy_or_rename_ref(struct ref_store
*ref_store
,
1571 const char *oldrefname
, const char *newrefname
,
1572 const char *logmsg
, int copy
)
1574 struct files_ref_store
*refs
=
1575 files_downcast(ref_store
, REF_STORE_WRITE
, "rename_ref");
1576 struct object_id orig_oid
;
1577 int flag
= 0, logmoved
= 0;
1578 struct ref_lock
*lock
;
1579 struct stat loginfo
;
1580 struct strbuf sb_oldref
= STRBUF_INIT
;
1581 struct strbuf sb_newref
= STRBUF_INIT
;
1582 struct strbuf tmp_renamed_log
= STRBUF_INIT
;
1584 struct strbuf err
= STRBUF_INIT
;
1586 files_reflog_path(refs
, &sb_oldref
, oldrefname
);
1587 files_reflog_path(refs
, &sb_newref
, newrefname
);
1588 files_reflog_path(refs
, &tmp_renamed_log
, TMP_RENAMED_LOG
);
1590 log
= !lstat(sb_oldref
.buf
, &loginfo
);
1591 if (log
&& S_ISLNK(loginfo
.st_mode
)) {
1592 ret
= error("reflog for %s is a symlink", oldrefname
);
1596 if (!refs_resolve_ref_unsafe(&refs
->base
, oldrefname
,
1597 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1598 &orig_oid
, &flag
)) {
1599 ret
= error("refname %s not found", oldrefname
);
1603 if (flag
& REF_ISSYMREF
) {
1605 ret
= error("refname %s is a symbolic ref, copying it is not supported",
1608 ret
= error("refname %s is a symbolic ref, renaming it is not supported",
1612 if (!refs_rename_ref_available(&refs
->base
, oldrefname
, newrefname
)) {
1617 if (!copy
&& log
&& rename(sb_oldref
.buf
, tmp_renamed_log
.buf
)) {
1618 ret
= error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1619 oldrefname
, strerror(errno
));
1623 if (copy
&& log
&& copy_file(tmp_renamed_log
.buf
, sb_oldref
.buf
, 0644)) {
1624 ret
= error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG
": %s",
1625 oldrefname
, strerror(errno
));
1629 if (!copy
&& refs_delete_ref(&refs
->base
, logmsg
, oldrefname
,
1630 &orig_oid
, REF_NO_DEREF
)) {
1631 error("unable to delete old %s", oldrefname
);
1636 * Since we are doing a shallow lookup, oid is not the
1637 * correct value to pass to delete_ref as old_oid. But that
1638 * doesn't matter, because an old_oid check wouldn't add to
1639 * the safety anyway; we want to delete the reference whatever
1640 * its current value.
1642 if (!copy
&& refs_resolve_ref_unsafe(&refs
->base
, newrefname
,
1643 RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
1645 refs_delete_ref(&refs
->base
, NULL
, newrefname
,
1646 NULL
, REF_NO_DEREF
)) {
1647 if (errno
== EISDIR
) {
1648 struct strbuf path
= STRBUF_INIT
;
1651 files_ref_path(refs
, &path
, newrefname
);
1652 result
= remove_empty_directories(&path
);
1653 strbuf_release(&path
);
1656 error("Directory not empty: %s", newrefname
);
1660 error("unable to delete existing %s", newrefname
);
1665 if (log
&& rename_tmp_log(refs
, newrefname
))
1670 lock
= lock_ref_oid_basic(refs
, newrefname
, &err
);
1673 error("unable to copy '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1675 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
1676 strbuf_release(&err
);
1679 oidcpy(&lock
->old_oid
, &orig_oid
);
1681 if (write_ref_to_lockfile(refs
, lock
, &orig_oid
, 0, &err
) ||
1682 commit_ref_update(refs
, lock
, &orig_oid
, logmsg
, 0, &err
)) {
1683 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
1684 strbuf_release(&err
);
1692 lock
= lock_ref_oid_basic(refs
, oldrefname
, &err
);
1694 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
1695 strbuf_release(&err
);
1699 if (write_ref_to_lockfile(refs
, lock
, &orig_oid
, 0, &err
) ||
1700 commit_ref_update(refs
, lock
, &orig_oid
, NULL
, REF_SKIP_CREATE_REFLOG
, &err
)) {
1701 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
1702 strbuf_release(&err
);
1706 if (logmoved
&& rename(sb_newref
.buf
, sb_oldref
.buf
))
1707 error("unable to restore logfile %s from %s: %s",
1708 oldrefname
, newrefname
, strerror(errno
));
1709 if (!logmoved
&& log
&&
1710 rename(tmp_renamed_log
.buf
, sb_oldref
.buf
))
1711 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG
": %s",
1712 oldrefname
, strerror(errno
));
1715 strbuf_release(&sb_newref
);
1716 strbuf_release(&sb_oldref
);
1717 strbuf_release(&tmp_renamed_log
);
1722 static int files_rename_ref(struct ref_store
*ref_store
,
1723 const char *oldrefname
, const char *newrefname
,
1726 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1727 newrefname
, logmsg
, 0);
1730 static int files_copy_ref(struct ref_store
*ref_store
,
1731 const char *oldrefname
, const char *newrefname
,
1734 return files_copy_or_rename_ref(ref_store
, oldrefname
,
1735 newrefname
, logmsg
, 1);
1738 static int close_ref_gently(struct ref_lock
*lock
)
1740 if (close_lock_file_gently(&lock
->lk
))
1745 static int commit_ref(struct ref_lock
*lock
)
1747 char *path
= get_locked_file_path(&lock
->lk
);
1750 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
1752 * There is a directory at the path we want to rename
1753 * the lockfile to. Hopefully it is empty; try to
1756 size_t len
= strlen(path
);
1757 struct strbuf sb_path
= STRBUF_INIT
;
1759 strbuf_attach(&sb_path
, path
, len
, len
);
1762 * If this fails, commit_lock_file() will also fail
1763 * and will report the problem.
1765 remove_empty_directories(&sb_path
);
1766 strbuf_release(&sb_path
);
1771 if (commit_lock_file(&lock
->lk
))
1776 static int open_or_create_logfile(const char *path
, void *cb
)
1780 *fd
= open(path
, O_APPEND
| O_WRONLY
| O_CREAT
, 0666);
1781 return (*fd
< 0) ? -1 : 0;
1785 * Create a reflog for a ref. If force_create = 0, only create the
1786 * reflog for certain refs (those for which should_autocreate_reflog
1787 * returns non-zero). Otherwise, create it regardless of the reference
1788 * name. If the logfile already existed or was created, return 0 and
1789 * set *logfd to the file descriptor opened for appending to the file.
1790 * If no logfile exists and we decided not to create one, return 0 and
1791 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1794 static int log_ref_setup(struct files_ref_store
*refs
,
1795 const char *refname
, int force_create
,
1796 int *logfd
, struct strbuf
*err
)
1798 enum log_refs_config log_refs_cfg
= refs
->log_all_ref_updates
;
1799 struct strbuf logfile_sb
= STRBUF_INIT
;
1802 if (log_refs_cfg
== LOG_REFS_UNSET
)
1803 log_refs_cfg
= is_bare_repository() ? LOG_REFS_NONE
: LOG_REFS_NORMAL
;
1805 files_reflog_path(refs
, &logfile_sb
, refname
);
1806 logfile
= strbuf_detach(&logfile_sb
, NULL
);
1808 if (force_create
|| should_autocreate_reflog(log_refs_cfg
, refname
)) {
1809 if (raceproof_create_file(logfile
, open_or_create_logfile
, logfd
)) {
1810 if (errno
== ENOENT
)
1811 strbuf_addf(err
, "unable to create directory for '%s': "
1812 "%s", logfile
, strerror(errno
));
1813 else if (errno
== EISDIR
)
1814 strbuf_addf(err
, "there are still logs under '%s'",
1817 strbuf_addf(err
, "unable to append to '%s': %s",
1818 logfile
, strerror(errno
));
1823 *logfd
= open(logfile
, O_APPEND
| O_WRONLY
);
1825 if (errno
== ENOENT
|| errno
== EISDIR
) {
1827 * The logfile doesn't already exist,
1828 * but that is not an error; it only
1829 * means that we won't write log
1834 strbuf_addf(err
, "unable to append to '%s': %s",
1835 logfile
, strerror(errno
));
1842 adjust_shared_perm(the_repository
, logfile
);
1852 static int files_create_reflog(struct ref_store
*ref_store
, const char *refname
,
1855 struct files_ref_store
*refs
=
1856 files_downcast(ref_store
, REF_STORE_WRITE
, "create_reflog");
1859 if (log_ref_setup(refs
, refname
, 1, &fd
, err
))
1868 static int log_ref_write_fd(int fd
, const struct object_id
*old_oid
,
1869 const struct object_id
*new_oid
,
1870 const char *committer
, const char *msg
)
1872 struct strbuf sb
= STRBUF_INIT
;
1876 committer
= git_committer_info(0);
1878 strbuf_addf(&sb
, "%s %s %s", oid_to_hex(old_oid
), oid_to_hex(new_oid
), committer
);
1880 strbuf_addch(&sb
, '\t');
1881 strbuf_addstr(&sb
, msg
);
1883 strbuf_addch(&sb
, '\n');
1884 if (write_in_full(fd
, sb
.buf
, sb
.len
) < 0)
1886 strbuf_release(&sb
);
1890 static int files_log_ref_write(struct files_ref_store
*refs
,
1891 const char *refname
,
1892 const struct object_id
*old_oid
,
1893 const struct object_id
*new_oid
,
1894 const char *committer_info
, const char *msg
,
1895 int flags
, struct strbuf
*err
)
1899 if (flags
& REF_SKIP_CREATE_REFLOG
)
1902 result
= log_ref_setup(refs
, refname
,
1903 flags
& REF_FORCE_CREATE_REFLOG
,
1911 result
= log_ref_write_fd(logfd
, old_oid
, new_oid
, committer_info
, msg
);
1913 struct strbuf sb
= STRBUF_INIT
;
1914 int save_errno
= errno
;
1916 files_reflog_path(refs
, &sb
, refname
);
1917 strbuf_addf(err
, "unable to append to '%s': %s",
1918 sb
.buf
, strerror(save_errno
));
1919 strbuf_release(&sb
);
1924 struct strbuf sb
= STRBUF_INIT
;
1925 int save_errno
= errno
;
1927 files_reflog_path(refs
, &sb
, refname
);
1928 strbuf_addf(err
, "unable to append to '%s': %s",
1929 sb
.buf
, strerror(save_errno
));
1930 strbuf_release(&sb
);
1937 * Write oid into the open lockfile, then close the lockfile. On
1938 * errors, rollback the lockfile, fill in *err and return -1.
1940 static enum ref_transaction_error
write_ref_to_lockfile(struct files_ref_store
*refs
,
1941 struct ref_lock
*lock
,
1942 const struct object_id
*oid
,
1943 int skip_oid_verification
,
1946 static char term
= '\n';
1950 if (!skip_oid_verification
) {
1951 o
= parse_object(refs
->base
.repo
, oid
);
1955 "trying to write ref '%s' with nonexistent object %s",
1956 lock
->ref_name
, oid_to_hex(oid
));
1958 return REF_TRANSACTION_ERROR_INVALID_NEW_VALUE
;
1960 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
1963 "trying to write non-commit object %s to branch '%s'",
1964 oid_to_hex(oid
), lock
->ref_name
);
1966 return REF_TRANSACTION_ERROR_INVALID_NEW_VALUE
;
1969 fd
= get_lock_file_fd(&lock
->lk
);
1970 if (write_in_full(fd
, oid_to_hex(oid
), refs
->base
.repo
->hash_algo
->hexsz
) < 0 ||
1971 write_in_full(fd
, &term
, 1) < 0 ||
1972 fsync_component(FSYNC_COMPONENT_REFERENCE
, get_lock_file_fd(&lock
->lk
)) < 0 ||
1973 close_ref_gently(lock
) < 0) {
1975 "couldn't write '%s'", get_lock_file_path(&lock
->lk
));
1977 return REF_TRANSACTION_ERROR_GENERIC
;
1983 * Commit a change to a loose reference that has already been written
1984 * to the loose reference lockfile. Also update the reflogs if
1985 * necessary, using the specified lockmsg (which can be NULL).
1987 static int commit_ref_update(struct files_ref_store
*refs
,
1988 struct ref_lock
*lock
,
1989 const struct object_id
*oid
, const char *logmsg
,
1993 files_assert_main_repository(refs
, "commit_ref_update");
1995 clear_loose_ref_cache(refs
);
1996 if (files_log_ref_write(refs
, lock
->ref_name
, &lock
->old_oid
, oid
, NULL
,
1997 logmsg
, flags
, err
)) {
1998 char *old_msg
= strbuf_detach(err
, NULL
);
1999 strbuf_addf(err
, "cannot update the ref '%s': %s",
2000 lock
->ref_name
, old_msg
);
2006 if (strcmp(lock
->ref_name
, "HEAD") != 0) {
2008 * Special hack: If a branch is updated directly and HEAD
2009 * points to it (may happen on the remote side of a push
2010 * for example) then logically the HEAD reflog should be
2012 * A generic solution implies reverse symref information,
2013 * but finding all symrefs pointing to the given branch
2014 * would be rather costly for this rare event (the direct
2015 * update of a branch) to be worth it. So let's cheat and
2016 * check with HEAD only which should cover 99% of all usage
2017 * scenarios (even 100% of the default ones).
2020 const char *head_ref
;
2022 head_ref
= refs_resolve_ref_unsafe(&refs
->base
, "HEAD",
2023 RESOLVE_REF_READING
,
2025 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
2026 !strcmp(head_ref
, lock
->ref_name
)) {
2027 struct strbuf log_err
= STRBUF_INIT
;
2028 if (files_log_ref_write(refs
, "HEAD", &lock
->old_oid
,
2029 oid
, NULL
, logmsg
, flags
,
2031 error("%s", log_err
.buf
);
2032 strbuf_release(&log_err
);
2037 if (commit_ref(lock
)) {
2038 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
2047 #ifdef NO_SYMLINK_HEAD
2048 #define create_ref_symlink(a, b) (-1)
2050 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
2054 char *ref_path
= get_locked_file_path(&lock
->lk
);
2056 ret
= symlink(target
, ref_path
);
2060 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
2065 static int create_symref_lock(struct ref_lock
*lock
, const char *target
,
2068 if (!fdopen_lock_file(&lock
->lk
, "w")) {
2069 strbuf_addf(err
, "unable to fdopen %s: %s",
2070 get_lock_file_path(&lock
->lk
), strerror(errno
));
2074 if (fprintf(get_lock_file_fp(&lock
->lk
), "ref: %s\n", target
) < 0) {
2075 strbuf_addf(err
, "unable to write to %s: %s",
2076 get_lock_file_path(&lock
->lk
), strerror(errno
));
2083 static int files_reflog_exists(struct ref_store
*ref_store
,
2084 const char *refname
)
2086 struct files_ref_store
*refs
=
2087 files_downcast(ref_store
, REF_STORE_READ
, "reflog_exists");
2088 struct strbuf sb
= STRBUF_INIT
;
2092 files_reflog_path(refs
, &sb
, refname
);
2093 ret
= !lstat(sb
.buf
, &st
) && S_ISREG(st
.st_mode
);
2094 strbuf_release(&sb
);
2098 static int files_delete_reflog(struct ref_store
*ref_store
,
2099 const char *refname
)
2101 struct files_ref_store
*refs
=
2102 files_downcast(ref_store
, REF_STORE_WRITE
, "delete_reflog");
2103 struct strbuf sb
= STRBUF_INIT
;
2106 files_reflog_path(refs
, &sb
, refname
);
2107 ret
= remove_path(sb
.buf
);
2108 strbuf_release(&sb
);
2112 static int show_one_reflog_ent(struct files_ref_store
*refs
, struct strbuf
*sb
,
2113 each_reflog_ent_fn fn
, void *cb_data
)
2115 struct object_id ooid
, noid
;
2116 char *email_end
, *message
;
2117 timestamp_t timestamp
;
2119 const char *p
= sb
->buf
;
2121 /* old SP new SP name <email> SP time TAB msg LF */
2122 if (!sb
->len
|| sb
->buf
[sb
->len
- 1] != '\n' ||
2123 parse_oid_hex_algop(p
, &ooid
, &p
, refs
->base
.repo
->hash_algo
) || *p
++ != ' ' ||
2124 parse_oid_hex_algop(p
, &noid
, &p
, refs
->base
.repo
->hash_algo
) || *p
++ != ' ' ||
2125 !(email_end
= strchr(p
, '>')) ||
2126 email_end
[1] != ' ' ||
2127 !(timestamp
= parse_timestamp(email_end
+ 2, &message
, 10)) ||
2128 !message
|| message
[0] != ' ' ||
2129 (message
[1] != '+' && message
[1] != '-') ||
2130 !isdigit(message
[2]) || !isdigit(message
[3]) ||
2131 !isdigit(message
[4]) || !isdigit(message
[5]))
2132 return 0; /* corrupt? */
2133 email_end
[1] = '\0';
2134 tz
= strtol(message
+ 1, NULL
, 10);
2135 if (message
[6] != '\t')
2139 return fn(&ooid
, &noid
, p
, timestamp
, tz
, message
, cb_data
);
2142 static char *find_beginning_of_line(char *bob
, char *scan
)
2144 while (bob
< scan
&& *(--scan
) != '\n')
2145 ; /* keep scanning backwards */
2147 * Return either beginning of the buffer, or LF at the end of
2148 * the previous line.
2153 static int files_for_each_reflog_ent_reverse(struct ref_store
*ref_store
,
2154 const char *refname
,
2155 each_reflog_ent_fn fn
,
2158 struct files_ref_store
*refs
=
2159 files_downcast(ref_store
, REF_STORE_READ
,
2160 "for_each_reflog_ent_reverse");
2161 struct strbuf sb
= STRBUF_INIT
;
2164 int ret
= 0, at_tail
= 1;
2166 files_reflog_path(refs
, &sb
, refname
);
2167 logfp
= fopen(sb
.buf
, "r");
2168 strbuf_release(&sb
);
2172 /* Jump to the end */
2173 if (fseek(logfp
, 0, SEEK_END
) < 0)
2174 ret
= error("cannot seek back reflog for %s: %s",
2175 refname
, strerror(errno
));
2177 while (!ret
&& 0 < pos
) {
2183 /* Fill next block from the end */
2184 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
2185 if (fseek(logfp
, pos
- cnt
, SEEK_SET
)) {
2186 ret
= error("cannot seek back reflog for %s: %s",
2187 refname
, strerror(errno
));
2190 nread
= fread(buf
, cnt
, 1, logfp
);
2192 ret
= error("cannot read %d bytes from reflog for %s: %s",
2193 cnt
, refname
, strerror(errno
));
2198 scanp
= endp
= buf
+ cnt
;
2199 if (at_tail
&& scanp
[-1] == '\n')
2200 /* Looking at the final LF at the end of the file */
2204 while (buf
< scanp
) {
2206 * terminating LF of the previous line, or the beginning
2211 bp
= find_beginning_of_line(buf
, scanp
);
2215 * The newline is the end of the previous line,
2216 * so we know we have complete line starting
2217 * at (bp + 1). Prefix it onto any prior data
2218 * we collected for the line and process it.
2220 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
2223 ret
= show_one_reflog_ent(refs
, &sb
, fn
, cb_data
);
2229 * We are at the start of the buffer, and the
2230 * start of the file; there is no previous
2231 * line, and we have everything for this one.
2232 * Process it, and we can end the loop.
2234 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2235 ret
= show_one_reflog_ent(refs
, &sb
, fn
, cb_data
);
2242 * We are at the start of the buffer, and there
2243 * is more file to read backwards. Which means
2244 * we are in the middle of a line. Note that we
2245 * may get here even if *bp was a newline; that
2246 * just means we are at the exact end of the
2247 * previous line, rather than some spot in the
2250 * Save away what we have to be combined with
2251 * the data from the next read.
2253 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
2260 BUG("reverse reflog parser had leftover data");
2263 strbuf_release(&sb
);
2267 static int files_for_each_reflog_ent(struct ref_store
*ref_store
,
2268 const char *refname
,
2269 each_reflog_ent_fn fn
, void *cb_data
)
2271 struct files_ref_store
*refs
=
2272 files_downcast(ref_store
, REF_STORE_READ
,
2273 "for_each_reflog_ent");
2275 struct strbuf sb
= STRBUF_INIT
;
2278 files_reflog_path(refs
, &sb
, refname
);
2279 logfp
= fopen(sb
.buf
, "r");
2280 strbuf_release(&sb
);
2284 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
2285 ret
= show_one_reflog_ent(refs
, &sb
, fn
, cb_data
);
2287 strbuf_release(&sb
);
2291 struct files_reflog_iterator
{
2292 struct ref_iterator base
;
2293 struct ref_store
*ref_store
;
2294 struct dir_iterator
*dir_iterator
;
2297 static int files_reflog_iterator_advance(struct ref_iterator
*ref_iterator
)
2299 struct files_reflog_iterator
*iter
=
2300 (struct files_reflog_iterator
*)ref_iterator
;
2301 struct dir_iterator
*diter
= iter
->dir_iterator
;
2304 while ((ok
= dir_iterator_advance(diter
)) == ITER_OK
) {
2305 if (!S_ISREG(diter
->st
.st_mode
))
2307 if (check_refname_format(diter
->basename
,
2308 REFNAME_ALLOW_ONELEVEL
))
2311 iter
->base
.refname
= diter
->relative_path
;
2318 static int files_reflog_iterator_seek(struct ref_iterator
*ref_iterator UNUSED
,
2319 const char *prefix UNUSED
)
2321 BUG("ref_iterator_seek() called for reflog_iterator");
2324 static int files_reflog_iterator_peel(struct ref_iterator
*ref_iterator UNUSED
,
2325 struct object_id
*peeled UNUSED
)
2327 BUG("ref_iterator_peel() called for reflog_iterator");
2330 static void files_reflog_iterator_release(struct ref_iterator
*ref_iterator
)
2332 struct files_reflog_iterator
*iter
=
2333 (struct files_reflog_iterator
*)ref_iterator
;
2334 dir_iterator_free(iter
->dir_iterator
);
2337 static struct ref_iterator_vtable files_reflog_iterator_vtable
= {
2338 .advance
= files_reflog_iterator_advance
,
2339 .seek
= files_reflog_iterator_seek
,
2340 .peel
= files_reflog_iterator_peel
,
2341 .release
= files_reflog_iterator_release
,
2344 static struct ref_iterator
*reflog_iterator_begin(struct ref_store
*ref_store
,
2347 struct dir_iterator
*diter
;
2348 struct files_reflog_iterator
*iter
;
2349 struct ref_iterator
*ref_iterator
;
2350 struct strbuf sb
= STRBUF_INIT
;
2352 strbuf_addf(&sb
, "%s/logs", gitdir
);
2354 diter
= dir_iterator_begin(sb
.buf
, DIR_ITERATOR_SORTED
);
2356 strbuf_release(&sb
);
2357 return empty_ref_iterator_begin();
2360 CALLOC_ARRAY(iter
, 1);
2361 ref_iterator
= &iter
->base
;
2363 base_ref_iterator_init(ref_iterator
, &files_reflog_iterator_vtable
);
2364 iter
->dir_iterator
= diter
;
2365 iter
->ref_store
= ref_store
;
2366 strbuf_release(&sb
);
2368 return ref_iterator
;
2371 static struct ref_iterator
*files_reflog_iterator_begin(struct ref_store
*ref_store
)
2373 struct files_ref_store
*refs
=
2374 files_downcast(ref_store
, REF_STORE_READ
,
2375 "reflog_iterator_begin");
2377 if (!strcmp(refs
->base
.gitdir
, refs
->gitcommondir
)) {
2378 return reflog_iterator_begin(ref_store
, refs
->gitcommondir
);
2380 return merge_ref_iterator_begin(
2381 reflog_iterator_begin(ref_store
, refs
->base
.gitdir
),
2382 reflog_iterator_begin(ref_store
, refs
->gitcommondir
),
2383 ref_iterator_select
, refs
);
2388 * If update is a direct update of head_ref (the reference pointed to
2389 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2391 static enum ref_transaction_error
split_head_update(struct ref_update
*update
,
2392 struct ref_transaction
*transaction
,
2393 const char *head_ref
,
2396 struct ref_update
*new_update
;
2398 if ((update
->flags
& REF_LOG_ONLY
) ||
2399 (update
->flags
& REF_SKIP_CREATE_REFLOG
) ||
2400 (update
->flags
& REF_IS_PRUNING
) ||
2401 (update
->flags
& REF_UPDATE_VIA_HEAD
))
2404 if (strcmp(update
->refname
, head_ref
))
2408 * First make sure that HEAD is not already in the
2409 * transaction. This check is O(lg N) in the transaction
2410 * size, but it happens at most once per transaction.
2412 if (string_list_has_string(&transaction
->refnames
, "HEAD")) {
2413 /* An entry already existed */
2415 "multiple updates for 'HEAD' (including one "
2416 "via its referent '%s') are not allowed",
2418 return REF_TRANSACTION_ERROR_NAME_CONFLICT
;
2421 new_update
= ref_transaction_add_update(
2422 transaction
, "HEAD",
2423 update
->flags
| REF_LOG_ONLY
| REF_NO_DEREF
,
2424 &update
->new_oid
, &update
->old_oid
,
2425 NULL
, NULL
, update
->committer_info
, update
->msg
);
2428 * Add "HEAD". This insertion is O(N) in the transaction
2429 * size, but it happens at most once per transaction.
2430 * Add new_update->refname instead of a literal "HEAD".
2432 if (strcmp(new_update
->refname
, "HEAD"))
2433 BUG("%s unexpectedly not 'HEAD'", new_update
->refname
);
2439 * update is for a symref that points at referent and doesn't have
2440 * REF_NO_DEREF set. Split it into two updates:
2441 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2442 * - A new, separate update for the referent reference
2443 * Note that the new update will itself be subject to splitting when
2444 * the iteration gets to it.
2446 static enum ref_transaction_error
split_symref_update(struct ref_update
*update
,
2447 const char *referent
,
2448 struct ref_transaction
*transaction
,
2451 struct ref_update
*new_update
;
2452 unsigned int new_flags
;
2455 * First make sure that referent is not already in the
2456 * transaction. This check is O(lg N) in the transaction
2457 * size, but it happens at most once per symref in a
2460 if (string_list_has_string(&transaction
->refnames
, referent
)) {
2461 /* An entry already exists */
2463 "multiple updates for '%s' (including one "
2464 "via symref '%s') are not allowed",
2465 referent
, update
->refname
);
2466 return REF_TRANSACTION_ERROR_NAME_CONFLICT
;
2469 new_flags
= update
->flags
;
2470 if (!strcmp(update
->refname
, "HEAD")) {
2472 * Record that the new update came via HEAD, so that
2473 * when we process it, split_head_update() doesn't try
2474 * to add another reflog update for HEAD. Note that
2475 * this bit will be propagated if the new_update
2476 * itself needs to be split.
2478 new_flags
|= REF_UPDATE_VIA_HEAD
;
2481 new_update
= ref_transaction_add_update(
2482 transaction
, referent
, new_flags
,
2483 update
->new_target
? NULL
: &update
->new_oid
,
2484 update
->old_target
? NULL
: &update
->old_oid
,
2485 update
->new_target
, update
->old_target
, NULL
,
2488 new_update
->parent_update
= update
;
2491 * Change the symbolic ref update to log only. Also, it
2492 * doesn't need to check its old OID value, as that will be
2493 * done when new_update is processed.
2495 update
->flags
|= REF_LOG_ONLY
| REF_NO_DEREF
;
2496 update
->flags
&= ~REF_HAVE_OLD
;
2502 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2503 * are consistent with oid, which is the reference's current value. If
2504 * everything is OK, return 0; otherwise, write an error message to
2505 * err and return -1.
2507 static enum ref_transaction_error
check_old_oid(struct ref_update
*update
,
2508 struct object_id
*oid
,
2511 if (!(update
->flags
& REF_HAVE_OLD
) ||
2512 oideq(oid
, &update
->old_oid
))
2515 if (is_null_oid(&update
->old_oid
)) {
2516 strbuf_addf(err
, "cannot lock ref '%s': "
2517 "reference already exists",
2518 ref_update_original_update_refname(update
));
2519 return REF_TRANSACTION_ERROR_CREATE_EXISTS
;
2520 } else if (is_null_oid(oid
)) {
2521 strbuf_addf(err
, "cannot lock ref '%s': "
2522 "reference is missing but expected %s",
2523 ref_update_original_update_refname(update
),
2524 oid_to_hex(&update
->old_oid
));
2525 return REF_TRANSACTION_ERROR_NONEXISTENT_REF
;
2528 strbuf_addf(err
, "cannot lock ref '%s': is at %s but expected %s",
2529 ref_update_original_update_refname(update
), oid_to_hex(oid
),
2530 oid_to_hex(&update
->old_oid
));
2532 return REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE
;
2535 struct files_transaction_backend_data
{
2536 struct ref_transaction
*packed_transaction
;
2537 int packed_refs_locked
;
2538 struct strmap ref_locks
;
2542 * Prepare for carrying out update:
2543 * - Lock the reference referred to by update.
2544 * - Read the reference under lock.
2545 * - Check that its old OID value (if specified) is correct, and in
2546 * any case record it in update->lock->old_oid for later use when
2547 * writing the reflog.
2548 * - If it is a symref update without REF_NO_DEREF, split it up into a
2549 * REF_LOG_ONLY update of the symref and add a separate update for
2550 * the referent to transaction.
2551 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2554 static enum ref_transaction_error
lock_ref_for_update(struct files_ref_store
*refs
,
2555 struct ref_update
*update
,
2557 struct ref_transaction
*transaction
,
2558 const char *head_ref
,
2559 struct string_list
*refnames_to_check
,
2562 struct strbuf referent
= STRBUF_INIT
;
2563 int mustexist
= ref_update_expects_existing_old_ref(update
);
2564 struct files_transaction_backend_data
*backend_data
;
2565 enum ref_transaction_error ret
= 0;
2566 struct ref_lock
*lock
;
2568 files_assert_main_repository(refs
, "lock_ref_for_update");
2570 backend_data
= transaction
->backend_data
;
2572 if ((update
->flags
& REF_HAVE_NEW
) && ref_update_has_null_new_value(update
))
2573 update
->flags
|= REF_DELETING
;
2576 ret
= split_head_update(update
, transaction
, head_ref
, err
);
2581 lock
= strmap_get(&backend_data
->ref_locks
, update
->refname
);
2585 ret
= lock_raw_ref(refs
, update
, update_idx
, mustexist
,
2586 refnames_to_check
, &transaction
->refnames
,
2587 &lock
, &referent
, err
);
2591 reason
= strbuf_detach(err
, NULL
);
2592 strbuf_addf(err
, "cannot lock ref '%s': %s",
2593 ref_update_original_update_refname(update
), reason
);
2598 strmap_put(&backend_data
->ref_locks
, update
->refname
, lock
);
2601 update
->backend_data
= lock
;
2603 if (update
->type
& REF_ISSYMREF
) {
2604 if (update
->flags
& REF_NO_DEREF
) {
2606 * We won't be reading the referent as part of
2607 * the transaction, so we have to read it here
2608 * to record and possibly check old_oid:
2610 if (!refs_resolve_ref_unsafe(&refs
->base
,
2612 &lock
->old_oid
, NULL
)) {
2613 if (update
->flags
& REF_HAVE_OLD
) {
2614 strbuf_addf(err
, "cannot lock ref '%s': "
2615 "error reading reference",
2616 ref_update_original_update_refname(update
));
2617 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2622 if (update
->old_target
)
2623 ret
= ref_update_check_old_target(referent
.buf
, update
, err
);
2625 ret
= check_old_oid(update
, &lock
->old_oid
, err
);
2630 * Create a new update for the reference this
2631 * symref is pointing at. Also, we will record
2632 * and verify old_oid for this update as part
2633 * of processing the split-off update, so we
2634 * don't have to do it here.
2636 ret
= split_symref_update(update
, referent
.buf
,
2642 struct ref_update
*parent_update
;
2645 * Even if the ref is a regular ref, if `old_target` is set, we
2646 * fail with an error.
2648 if (update
->old_target
) {
2649 strbuf_addf(err
, _("cannot lock ref '%s': "
2650 "expected symref with target '%s': "
2651 "but is a regular ref"),
2652 ref_update_original_update_refname(update
),
2653 update
->old_target
);
2654 ret
= REF_TRANSACTION_ERROR_EXPECTED_SYMREF
;
2657 ret
= check_old_oid(update
, &lock
->old_oid
, err
);
2664 * If this update is happening indirectly because of a
2665 * symref update, record the old OID in the parent
2668 for (parent_update
= update
->parent_update
;
2670 parent_update
= parent_update
->parent_update
) {
2671 struct ref_lock
*parent_lock
= parent_update
->backend_data
;
2672 oidcpy(&parent_lock
->old_oid
, &lock
->old_oid
);
2676 if (update
->new_target
&& !(update
->flags
& REF_LOG_ONLY
)) {
2677 if (create_symref_lock(lock
, update
->new_target
, err
)) {
2678 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2682 if (close_ref_gently(lock
)) {
2683 strbuf_addf(err
, "couldn't close '%s.lock'",
2685 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2690 * Once we have created the symref lock, the commit
2691 * phase of the transaction only needs to commit the lock.
2693 update
->flags
|= REF_NEEDS_COMMIT
;
2694 } else if ((update
->flags
& REF_HAVE_NEW
) &&
2695 !(update
->flags
& REF_DELETING
) &&
2696 !(update
->flags
& REF_LOG_ONLY
)) {
2697 if (!(update
->type
& REF_ISSYMREF
) &&
2698 oideq(&lock
->old_oid
, &update
->new_oid
)) {
2700 * The reference already has the desired
2701 * value, so we don't need to write it.
2704 ret
= write_ref_to_lockfile(
2705 refs
, lock
, &update
->new_oid
,
2706 update
->flags
& REF_SKIP_OID_VERIFICATION
,
2709 char *write_err
= strbuf_detach(err
, NULL
);
2712 * The lock was freed upon failure of
2713 * write_ref_to_lockfile():
2715 update
->backend_data
= NULL
;
2717 "cannot update ref '%s': %s",
2718 update
->refname
, write_err
);
2722 update
->flags
|= REF_NEEDS_COMMIT
;
2726 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
2728 * We didn't call write_ref_to_lockfile(), so
2729 * the lockfile is still open. Close it to
2730 * free up the file descriptor:
2732 if (close_ref_gently(lock
)) {
2733 strbuf_addf(err
, "couldn't close '%s.lock'",
2735 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2741 strbuf_release(&referent
);
2746 * Unlock any references in `transaction` that are still locked, and
2747 * mark the transaction closed.
2749 static void files_transaction_cleanup(struct files_ref_store
*refs
,
2750 struct ref_transaction
*transaction
)
2753 struct files_transaction_backend_data
*backend_data
=
2754 transaction
->backend_data
;
2755 struct strbuf err
= STRBUF_INIT
;
2757 for (i
= 0; i
< transaction
->nr
; i
++) {
2758 struct ref_update
*update
= transaction
->updates
[i
];
2759 struct ref_lock
*lock
= update
->backend_data
;
2763 update
->backend_data
= NULL
;
2768 if (backend_data
->packed_transaction
&&
2769 ref_transaction_abort(backend_data
->packed_transaction
, &err
)) {
2770 error("error aborting transaction: %s", err
.buf
);
2771 strbuf_release(&err
);
2774 if (backend_data
->packed_refs_locked
)
2775 packed_refs_unlock(refs
->packed_ref_store
);
2777 strmap_clear(&backend_data
->ref_locks
, 0);
2782 transaction
->state
= REF_TRANSACTION_CLOSED
;
2785 static int files_transaction_prepare(struct ref_store
*ref_store
,
2786 struct ref_transaction
*transaction
,
2789 struct files_ref_store
*refs
=
2790 files_downcast(ref_store
, REF_STORE_WRITE
,
2791 "ref_transaction_prepare");
2794 struct string_list refnames_to_check
= STRING_LIST_INIT_NODUP
;
2795 char *head_ref
= NULL
;
2797 struct files_transaction_backend_data
*backend_data
;
2798 struct ref_transaction
*packed_transaction
= NULL
;
2802 if (transaction
->flags
& REF_TRANSACTION_FLAG_INITIAL
)
2804 if (!transaction
->nr
)
2807 CALLOC_ARRAY(backend_data
, 1);
2808 strmap_init(&backend_data
->ref_locks
);
2809 transaction
->backend_data
= backend_data
;
2812 * Fail if any of the updates use REF_IS_PRUNING without REF_NO_DEREF.
2814 for (i
= 0; i
< transaction
->nr
; i
++) {
2815 struct ref_update
*update
= transaction
->updates
[i
];
2817 if ((update
->flags
& REF_IS_PRUNING
) &&
2818 !(update
->flags
& REF_NO_DEREF
))
2819 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2823 * Special hack: If a branch is updated directly and HEAD
2824 * points to it (may happen on the remote side of a push
2825 * for example) then logically the HEAD reflog should be
2828 * A generic solution would require reverse symref lookups,
2829 * but finding all symrefs pointing to a given branch would be
2830 * rather costly for this rare event (the direct update of a
2831 * branch) to be worth it. So let's cheat and check with HEAD
2832 * only, which should cover 99% of all usage scenarios (even
2833 * 100% of the default ones).
2835 * So if HEAD is a symbolic reference, then record the name of
2836 * the reference that it points to. If we see an update of
2837 * head_ref within the transaction, then split_head_update()
2838 * arranges for the reflog of HEAD to be updated, too.
2840 head_ref
= refs_resolve_refdup(ref_store
, "HEAD",
2841 RESOLVE_REF_NO_RECURSE
,
2844 if (head_ref
&& !(head_type
& REF_ISSYMREF
)) {
2845 FREE_AND_NULL(head_ref
);
2849 * Acquire all locks, verify old values if provided, check
2850 * that new values are valid, and write new values to the
2851 * lockfiles, ready to be activated. Only keep one lockfile
2852 * open at a time to avoid running out of file descriptors.
2853 * Note that lock_ref_for_update() might append more updates
2854 * to the transaction.
2856 for (i
= 0; i
< transaction
->nr
; i
++) {
2857 struct ref_update
*update
= transaction
->updates
[i
];
2859 ret
= lock_ref_for_update(refs
, update
, i
, transaction
,
2860 head_ref
, &refnames_to_check
,
2863 if (ref_transaction_maybe_set_rejected(transaction
, i
, ret
)) {
2872 if (update
->flags
& REF_DELETING
&&
2873 !(update
->flags
& REF_LOG_ONLY
) &&
2874 !(update
->flags
& REF_IS_PRUNING
)) {
2876 * This reference has to be deleted from
2877 * packed-refs if it exists there.
2879 if (!packed_transaction
) {
2880 packed_transaction
= ref_store_transaction_begin(
2881 refs
->packed_ref_store
,
2882 transaction
->flags
, err
);
2883 if (!packed_transaction
) {
2884 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2888 backend_data
->packed_transaction
=
2892 ref_transaction_add_update(
2893 packed_transaction
, update
->refname
,
2894 REF_HAVE_NEW
| REF_NO_DEREF
,
2895 &update
->new_oid
, NULL
,
2896 NULL
, NULL
, NULL
, NULL
);
2901 * Verify that none of the loose reference that we're about to write
2902 * conflict with any existing packed references. Ideally, we'd do this
2903 * check after the packed-refs are locked so that the file cannot
2904 * change underneath our feet. But introducing such a lock now would
2905 * probably do more harm than good as users rely on there not being a
2906 * global lock with the "files" backend.
2908 * Another alternative would be to do the check after the (optional)
2909 * lock, but that would extend the time we spend in the globally-locked
2912 * So instead, we accept the race for now.
2914 if (refs_verify_refnames_available(refs
->packed_ref_store
, &refnames_to_check
,
2915 &transaction
->refnames
, NULL
, transaction
,
2917 ret
= REF_TRANSACTION_ERROR_NAME_CONFLICT
;
2921 if (packed_transaction
) {
2922 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
2923 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2926 backend_data
->packed_refs_locked
= 1;
2928 if (is_packed_transaction_needed(refs
->packed_ref_store
,
2929 packed_transaction
)) {
2930 ret
= ref_transaction_prepare(packed_transaction
, err
);
2932 * A failure during the prepare step will abort
2933 * itself, but not free. Do that now, and disconnect
2934 * from the files_transaction so it does not try to
2935 * abort us when we hit the cleanup code below.
2938 ref_transaction_free(packed_transaction
);
2939 backend_data
->packed_transaction
= NULL
;
2943 * We can skip rewriting the `packed-refs`
2944 * file. But we do need to leave it locked, so
2945 * that somebody else doesn't pack a reference
2946 * that we are trying to delete.
2948 * We need to disconnect our transaction from
2949 * backend_data, since the abort (whether successful or
2950 * not) will free it.
2952 backend_data
->packed_transaction
= NULL
;
2953 if (ref_transaction_abort(packed_transaction
, err
)) {
2954 ret
= REF_TRANSACTION_ERROR_GENERIC
;
2962 string_list_clear(&refnames_to_check
, 1);
2965 files_transaction_cleanup(refs
, transaction
);
2967 transaction
->state
= REF_TRANSACTION_PREPARED
;
2972 static int parse_and_write_reflog(struct files_ref_store
*refs
,
2973 struct ref_update
*update
,
2974 struct ref_lock
*lock
,
2977 if (update
->new_target
) {
2979 * We want to get the resolved OID for the target, to ensure
2980 * that the correct value is added to the reflog.
2982 if (!refs_resolve_ref_unsafe(&refs
->base
, update
->new_target
,
2983 RESOLVE_REF_READING
,
2984 &update
->new_oid
, NULL
)) {
2986 * TODO: currently we skip creating reflogs for dangling
2987 * symref updates. It would be nice to capture this as
2988 * zero oid updates however.
2994 if (files_log_ref_write(refs
, lock
->ref_name
, &lock
->old_oid
,
2995 &update
->new_oid
, update
->committer_info
,
2996 update
->msg
, update
->flags
, err
)) {
2997 char *old_msg
= strbuf_detach(err
, NULL
);
2999 strbuf_addf(err
, "cannot update the ref '%s': %s",
3000 lock
->ref_name
, old_msg
);
3003 update
->backend_data
= NULL
;
3010 static int ref_present(const char *refname
, const char *referent UNUSED
,
3011 const struct object_id
*oid UNUSED
,
3015 struct string_list
*affected_refnames
= cb_data
;
3017 return string_list_has_string(affected_refnames
, refname
);
3020 static int files_transaction_finish_initial(struct files_ref_store
*refs
,
3021 struct ref_transaction
*transaction
,
3026 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3027 struct string_list refnames_to_check
= STRING_LIST_INIT_NODUP
;
3028 struct ref_transaction
*packed_transaction
= NULL
;
3029 struct ref_transaction
*loose_transaction
= NULL
;
3033 if (transaction
->state
!= REF_TRANSACTION_PREPARED
)
3034 BUG("commit called for transaction that is not prepared");
3037 * It's really undefined to call this function in an active
3038 * repository or when there are existing references: we are
3039 * only locking and changing packed-refs, so (1) any
3040 * simultaneous processes might try to change a reference at
3041 * the same time we do, and (2) any existing loose versions of
3042 * the references that we are setting would have precedence
3043 * over our values. But some remote helpers create the remote
3044 * "HEAD" and "master" branches before calling this function,
3045 * so here we really only check that none of the references
3046 * that we are creating already exists.
3048 if (refs_for_each_rawref(&refs
->base
, ref_present
,
3049 &transaction
->refnames
))
3050 BUG("initial ref transaction called with existing refs");
3052 packed_transaction
= ref_store_transaction_begin(refs
->packed_ref_store
,
3053 transaction
->flags
, err
);
3054 if (!packed_transaction
) {
3055 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3059 for (i
= 0; i
< transaction
->nr
; i
++) {
3060 struct ref_update
*update
= transaction
->updates
[i
];
3062 if ((update
->flags
& REF_HAVE_OLD
) &&
3063 !is_null_oid(&update
->old_oid
))
3064 BUG("initial ref transaction with old_sha1 set");
3066 string_list_append(&refnames_to_check
, update
->refname
);
3069 * packed-refs don't support symbolic refs, root refs and reflogs,
3070 * so we have to queue these references via the loose transaction.
3072 if (update
->new_target
||
3073 is_root_ref(update
->refname
) ||
3074 (update
->flags
& REF_LOG_ONLY
)) {
3075 if (!loose_transaction
) {
3076 loose_transaction
= ref_store_transaction_begin(&refs
->base
, 0, err
);
3077 if (!loose_transaction
) {
3078 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3083 if (update
->flags
& REF_LOG_ONLY
)
3084 ref_transaction_add_update(loose_transaction
, update
->refname
,
3085 update
->flags
, &update
->new_oid
,
3086 &update
->old_oid
, NULL
, NULL
,
3087 update
->committer_info
, update
->msg
);
3089 ref_transaction_add_update(loose_transaction
, update
->refname
,
3090 update
->flags
& ~REF_HAVE_OLD
,
3091 update
->new_target
? NULL
: &update
->new_oid
, NULL
,
3092 update
->new_target
, NULL
, update
->committer_info
,
3095 ref_transaction_add_update(packed_transaction
, update
->refname
,
3096 update
->flags
& ~REF_HAVE_OLD
,
3097 &update
->new_oid
, &update
->old_oid
,
3098 NULL
, NULL
, update
->committer_info
, NULL
);
3102 if (packed_refs_lock(refs
->packed_ref_store
, 0, err
)) {
3103 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3107 if (refs_verify_refnames_available(&refs
->base
, &refnames_to_check
,
3108 &affected_refnames
, NULL
, transaction
,
3110 packed_refs_unlock(refs
->packed_ref_store
);
3111 ret
= REF_TRANSACTION_ERROR_NAME_CONFLICT
;
3115 if (ref_transaction_commit(packed_transaction
, err
)) {
3116 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3119 packed_refs_unlock(refs
->packed_ref_store
);
3121 if (loose_transaction
) {
3122 if (ref_transaction_prepare(loose_transaction
, err
) ||
3123 ref_transaction_commit(loose_transaction
, err
)) {
3124 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3130 if (loose_transaction
)
3131 ref_transaction_free(loose_transaction
);
3132 if (packed_transaction
)
3133 ref_transaction_free(packed_transaction
);
3134 transaction
->state
= REF_TRANSACTION_CLOSED
;
3135 string_list_clear(&affected_refnames
, 0);
3136 string_list_clear(&refnames_to_check
, 0);
3140 static int files_transaction_finish(struct ref_store
*ref_store
,
3141 struct ref_transaction
*transaction
,
3144 struct files_ref_store
*refs
=
3145 files_downcast(ref_store
, 0, "ref_transaction_finish");
3148 struct strbuf sb
= STRBUF_INIT
;
3149 struct files_transaction_backend_data
*backend_data
;
3150 struct ref_transaction
*packed_transaction
;
3155 if (transaction
->flags
& REF_TRANSACTION_FLAG_INITIAL
)
3156 return files_transaction_finish_initial(refs
, transaction
, err
);
3157 if (!transaction
->nr
) {
3158 transaction
->state
= REF_TRANSACTION_CLOSED
;
3162 backend_data
= transaction
->backend_data
;
3163 packed_transaction
= backend_data
->packed_transaction
;
3165 /* Perform updates first so live commits remain referenced */
3166 for (i
= 0; i
< transaction
->nr
; i
++) {
3167 struct ref_update
*update
= transaction
->updates
[i
];
3168 struct ref_lock
*lock
= update
->backend_data
;
3170 if (update
->rejection_err
)
3173 if (update
->flags
& REF_NEEDS_COMMIT
||
3174 update
->flags
& REF_LOG_ONLY
) {
3175 if (parse_and_write_reflog(refs
, update
, lock
, err
)) {
3176 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3182 * We try creating a symlink, if that succeeds we continue to the
3183 * next update. If not, we try and create a regular symref.
3185 if (update
->new_target
&& refs
->prefer_symlink_refs
)
3186 if (!create_ref_symlink(lock
, update
->new_target
))
3189 if (update
->flags
& REF_NEEDS_COMMIT
) {
3190 clear_loose_ref_cache(refs
);
3191 if (commit_ref(lock
)) {
3192 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
3194 update
->backend_data
= NULL
;
3195 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3202 * Now that updates are safely completed, we can perform
3203 * deletes. First delete the reflogs of any references that
3204 * will be deleted, since (in the unexpected event of an
3205 * error) leaving a reference without a reflog is less bad
3206 * than leaving a reflog without a reference (the latter is a
3207 * mildly invalid repository state):
3209 for (i
= 0; i
< transaction
->nr
; i
++) {
3210 struct ref_update
*update
= transaction
->updates
[i
];
3211 if (update
->flags
& REF_DELETING
&&
3212 !(update
->flags
& REF_LOG_ONLY
) &&
3213 !(update
->flags
& REF_IS_PRUNING
)) {
3215 files_reflog_path(refs
, &sb
, update
->refname
);
3216 if (!unlink_or_warn(sb
.buf
))
3217 try_remove_empty_parents(refs
, update
->refname
,
3218 REMOVE_EMPTY_PARENTS_REFLOG
);
3223 * Perform deletes now that updates are safely completed.
3225 * First delete any packed versions of the references, while
3226 * retaining the packed-refs lock:
3228 if (packed_transaction
) {
3229 ret
= ref_transaction_commit(packed_transaction
, err
);
3230 ref_transaction_free(packed_transaction
);
3231 packed_transaction
= NULL
;
3232 backend_data
->packed_transaction
= NULL
;
3237 /* Now delete the loose versions of the references: */
3238 for (i
= 0; i
< transaction
->nr
; i
++) {
3239 struct ref_update
*update
= transaction
->updates
[i
];
3240 struct ref_lock
*lock
= update
->backend_data
;
3242 if (update
->flags
& REF_DELETING
&&
3243 !(update
->flags
& REF_LOG_ONLY
)) {
3244 update
->flags
|= REF_DELETED_RMDIR
;
3245 if (!(update
->type
& REF_ISPACKED
) ||
3246 update
->type
& REF_ISSYMREF
) {
3247 /* It is a loose reference. */
3249 files_ref_path(refs
, &sb
, lock
->ref_name
);
3250 if (unlink_or_msg(sb
.buf
, err
)) {
3251 ret
= REF_TRANSACTION_ERROR_GENERIC
;
3258 clear_loose_ref_cache(refs
);
3261 files_transaction_cleanup(refs
, transaction
);
3263 for (i
= 0; i
< transaction
->nr
; i
++) {
3264 struct ref_update
*update
= transaction
->updates
[i
];
3266 if (update
->flags
& REF_DELETED_RMDIR
) {
3268 * The reference was deleted. Delete any
3269 * empty parent directories. (Note that this
3270 * can only work because we have already
3271 * removed the lockfile.)
3273 try_remove_empty_parents(refs
, update
->refname
,
3274 REMOVE_EMPTY_PARENTS_REF
);
3278 strbuf_release(&sb
);
3282 static int files_transaction_abort(struct ref_store
*ref_store
,
3283 struct ref_transaction
*transaction
,
3284 struct strbuf
*err UNUSED
)
3286 struct files_ref_store
*refs
=
3287 files_downcast(ref_store
, 0, "ref_transaction_abort");
3289 files_transaction_cleanup(refs
, transaction
);
3293 struct expire_reflog_cb
{
3294 reflog_expiry_should_prune_fn
*should_prune_fn
;
3297 struct object_id last_kept_oid
;
3298 unsigned int rewrite
:1,
3302 static int expire_reflog_ent(struct object_id
*ooid
, struct object_id
*noid
,
3303 const char *email
, timestamp_t timestamp
, int tz
,
3304 const char *message
, void *cb_data
)
3306 struct expire_reflog_cb
*cb
= cb_data
;
3307 reflog_expiry_should_prune_fn
*fn
= cb
->should_prune_fn
;
3310 ooid
= &cb
->last_kept_oid
;
3312 if (fn(ooid
, noid
, email
, timestamp
, tz
, message
, cb
->policy_cb
))
3316 return 0; /* --dry-run */
3318 fprintf(cb
->newlog
, "%s %s %s %"PRItime
" %+05d\t%s", oid_to_hex(ooid
),
3319 oid_to_hex(noid
), email
, timestamp
, tz
, message
);
3320 oidcpy(&cb
->last_kept_oid
, noid
);
3325 static int files_reflog_expire(struct ref_store
*ref_store
,
3326 const char *refname
,
3327 unsigned int expire_flags
,
3328 reflog_expiry_prepare_fn prepare_fn
,
3329 reflog_expiry_should_prune_fn should_prune_fn
,
3330 reflog_expiry_cleanup_fn cleanup_fn
,
3331 void *policy_cb_data
)
3333 struct files_ref_store
*refs
=
3334 files_downcast(ref_store
, REF_STORE_WRITE
, "reflog_expire");
3335 struct lock_file reflog_lock
= LOCK_INIT
;
3336 struct expire_reflog_cb cb
;
3337 struct ref_lock
*lock
;
3338 struct strbuf log_file_sb
= STRBUF_INIT
;
3341 struct strbuf err
= STRBUF_INIT
;
3342 const struct object_id
*oid
;
3344 memset(&cb
, 0, sizeof(cb
));
3345 cb
.rewrite
= !!(expire_flags
& EXPIRE_REFLOGS_REWRITE
);
3346 cb
.dry_run
= !!(expire_flags
& EXPIRE_REFLOGS_DRY_RUN
);
3347 cb
.policy_cb
= policy_cb_data
;
3348 cb
.should_prune_fn
= should_prune_fn
;
3351 * The reflog file is locked by holding the lock on the
3352 * reference itself, plus we might need to update the
3353 * reference if --updateref was specified:
3355 lock
= lock_ref_oid_basic(refs
, refname
, &err
);
3357 error("cannot lock ref '%s': %s", refname
, err
.buf
);
3358 strbuf_release(&err
);
3361 oid
= &lock
->old_oid
;
3364 * When refs are deleted, their reflog is deleted before the
3365 * ref itself is deleted. This is because there is no separate
3366 * lock for reflog; instead we take a lock on the ref with
3367 * lock_ref_oid_basic().
3369 * If a race happens and the reflog doesn't exist after we've
3370 * acquired the lock that's OK. We've got nothing more to do;
3371 * We were asked to delete the reflog, but someone else
3372 * deleted it! The caller doesn't care that we deleted it,
3373 * just that it is deleted. So we can return successfully.
3375 if (!refs_reflog_exists(ref_store
, refname
)) {
3380 files_reflog_path(refs
, &log_file_sb
, refname
);
3381 log_file
= strbuf_detach(&log_file_sb
, NULL
);
3384 * Even though holding $GIT_DIR/logs/$reflog.lock has
3385 * no locking implications, we use the lock_file
3386 * machinery here anyway because it does a lot of the
3387 * work we need, including cleaning up if the program
3388 * exits unexpectedly.
3390 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
3391 struct strbuf err
= STRBUF_INIT
;
3392 unable_to_lock_message(log_file
, errno
, &err
);
3393 error("%s", err
.buf
);
3394 strbuf_release(&err
);
3397 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
3399 error("cannot fdopen %s (%s)",
3400 get_lock_file_path(&reflog_lock
), strerror(errno
));
3405 (*prepare_fn
)(refname
, oid
, cb
.policy_cb
);
3406 refs_for_each_reflog_ent(ref_store
, refname
, expire_reflog_ent
, &cb
);
3407 (*cleanup_fn
)(cb
.policy_cb
);
3411 * It doesn't make sense to adjust a reference pointed
3412 * to by a symbolic ref based on expiring entries in
3413 * the symbolic reference's reflog. Nor can we update
3414 * a reference if there are no remaining reflog
3419 if ((expire_flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
3420 !is_null_oid(&cb
.last_kept_oid
)) {
3424 ref
= refs_resolve_ref_unsafe(&refs
->base
, refname
,
3425 RESOLVE_REF_NO_RECURSE
,
3427 update
= !!(ref
&& !(type
& REF_ISSYMREF
));
3430 if (close_lock_file_gently(&reflog_lock
)) {
3431 status
|= error("couldn't write %s: %s", log_file
,
3433 rollback_lock_file(&reflog_lock
);
3434 } else if (update
&&
3435 (write_in_full(get_lock_file_fd(&lock
->lk
),
3436 oid_to_hex(&cb
.last_kept_oid
), refs
->base
.repo
->hash_algo
->hexsz
) < 0 ||
3437 write_str_in_full(get_lock_file_fd(&lock
->lk
), "\n") < 0 ||
3438 close_ref_gently(lock
) < 0)) {
3439 status
|= error("couldn't write %s",
3440 get_lock_file_path(&lock
->lk
));
3441 rollback_lock_file(&reflog_lock
);
3442 } else if (commit_lock_file(&reflog_lock
)) {
3443 status
|= error("unable to write reflog '%s' (%s)",
3444 log_file
, strerror(errno
));
3445 } else if (update
&& commit_ref(lock
)) {
3446 status
|= error("couldn't set %s", lock
->ref_name
);
3454 rollback_lock_file(&reflog_lock
);
3460 static int files_ref_store_create_on_disk(struct ref_store
*ref_store
,
3462 struct strbuf
*err UNUSED
)
3464 struct files_ref_store
*refs
=
3465 files_downcast(ref_store
, REF_STORE_WRITE
, "create");
3466 struct strbuf sb
= STRBUF_INIT
;
3469 * We need to create a "refs" dir in any case so that older versions of
3470 * Git can tell that this is a repository. This serves two main purposes:
3472 * - Clients will know to stop walking the parent-directory chain when
3473 * detecting the Git repository. Otherwise they may end up detecting
3474 * a Git repository in a parent directory instead.
3476 * - Instead of failing to detect a repository with unknown reference
3477 * format altogether, old clients will print an error saying that
3478 * they do not understand the reference format extension.
3480 strbuf_addf(&sb
, "%s/refs", ref_store
->gitdir
);
3481 safe_create_dir(the_repository
, sb
.buf
, 1);
3482 adjust_shared_perm(the_repository
, sb
.buf
);
3485 * There is no need to create directories for common refs when creating
3486 * a worktree ref store.
3488 if (!(flags
& REF_STORE_CREATE_ON_DISK_IS_WORKTREE
)) {
3490 * Create .git/refs/{heads,tags}
3493 files_ref_path(refs
, &sb
, "refs/heads");
3494 safe_create_dir(the_repository
, sb
.buf
, 1);
3497 files_ref_path(refs
, &sb
, "refs/tags");
3498 safe_create_dir(the_repository
, sb
.buf
, 1);
3501 strbuf_release(&sb
);
3505 struct remove_one_root_ref_data
{
3510 static int remove_one_root_ref(const char *refname
,
3513 struct remove_one_root_ref_data
*data
= cb_data
;
3514 struct strbuf buf
= STRBUF_INIT
;
3517 strbuf_addf(&buf
, "%s/%s", data
->gitdir
, refname
);
3519 ret
= unlink(buf
.buf
);
3521 strbuf_addf(data
->err
, "could not delete %s: %s\n",
3522 refname
, strerror(errno
));
3524 strbuf_release(&buf
);
3528 static int files_ref_store_remove_on_disk(struct ref_store
*ref_store
,
3531 struct files_ref_store
*refs
=
3532 files_downcast(ref_store
, REF_STORE_WRITE
, "remove");
3533 struct remove_one_root_ref_data data
= {
3534 .gitdir
= refs
->base
.gitdir
,
3537 struct strbuf sb
= STRBUF_INIT
;
3540 strbuf_addf(&sb
, "%s/refs", refs
->base
.gitdir
);
3541 if (remove_dir_recursively(&sb
, 0) < 0) {
3542 strbuf_addf(err
, "could not delete refs: %s",
3548 strbuf_addf(&sb
, "%s/logs", refs
->base
.gitdir
);
3549 if (remove_dir_recursively(&sb
, 0) < 0) {
3550 strbuf_addf(err
, "could not delete logs: %s",
3556 if (for_each_root_ref(refs
, remove_one_root_ref
, &data
) < 0)
3559 if (ref_store_remove_on_disk(refs
->packed_ref_store
, err
) < 0)
3562 strbuf_release(&sb
);
3567 * For refs and reflogs, they share a unified interface when scanning
3568 * the whole directory. This function is used as the callback for each
3569 * regular file or symlink in the directory.
3571 typedef int (*files_fsck_refs_fn
)(struct ref_store
*ref_store
,
3572 struct fsck_options
*o
,
3573 const char *refname
,
3574 struct dir_iterator
*iter
);
3576 static int files_fsck_symref_target(struct fsck_options
*o
,
3577 struct fsck_ref_report
*report
,
3578 struct strbuf
*referent
,
3579 unsigned int symbolic_link
)
3581 int is_referent_root
;
3582 char orig_last_byte
;
3586 orig_len
= referent
->len
;
3587 orig_last_byte
= referent
->buf
[orig_len
- 1];
3589 strbuf_rtrim(referent
);
3591 is_referent_root
= is_root_ref(referent
->buf
);
3592 if (!is_referent_root
&&
3593 !starts_with(referent
->buf
, "refs/") &&
3594 !starts_with(referent
->buf
, "worktrees/")) {
3595 ret
= fsck_report_ref(o
, report
,
3596 FSCK_MSG_SYMREF_TARGET_IS_NOT_A_REF
,
3597 "points to non-ref target '%s'", referent
->buf
);
3601 if (!is_referent_root
&& check_refname_format(referent
->buf
, 0)) {
3602 ret
= fsck_report_ref(o
, report
,
3603 FSCK_MSG_BAD_REFERENT_NAME
,
3604 "points to invalid refname '%s'", referent
->buf
);
3611 if (referent
->len
== orig_len
||
3612 (referent
->len
< orig_len
&& orig_last_byte
!= '\n')) {
3613 ret
= fsck_report_ref(o
, report
,
3614 FSCK_MSG_REF_MISSING_NEWLINE
,
3615 "misses LF at the end");
3618 if (referent
->len
!= orig_len
&& referent
->len
!= orig_len
- 1) {
3619 ret
= fsck_report_ref(o
, report
,
3620 FSCK_MSG_TRAILING_REF_CONTENT
,
3621 "has trailing whitespaces or newlines");
3628 static int files_fsck_refs_content(struct ref_store
*ref_store
,
3629 struct fsck_options
*o
,
3630 const char *target_name
,
3631 struct dir_iterator
*iter
)
3633 struct strbuf ref_content
= STRBUF_INIT
;
3634 struct strbuf abs_gitdir
= STRBUF_INIT
;
3635 struct strbuf referent
= STRBUF_INIT
;
3636 struct fsck_ref_report report
= { 0 };
3637 const char *trailing
= NULL
;
3638 unsigned int type
= 0;
3639 int failure_errno
= 0;
3640 struct object_id oid
;
3643 report
.path
= target_name
;
3645 if (S_ISLNK(iter
->st
.st_mode
)) {
3646 const char *relative_referent_path
= NULL
;
3648 ret
= fsck_report_ref(o
, &report
,
3649 FSCK_MSG_SYMLINK_REF
,
3650 "use deprecated symbolic link for symref");
3652 strbuf_add_absolute_path(&abs_gitdir
, ref_store
->repo
->gitdir
);
3653 strbuf_normalize_path(&abs_gitdir
);
3654 if (!is_dir_sep(abs_gitdir
.buf
[abs_gitdir
.len
- 1]))
3655 strbuf_addch(&abs_gitdir
, '/');
3657 strbuf_add_real_path(&ref_content
, iter
->path
.buf
);
3658 skip_prefix(ref_content
.buf
, abs_gitdir
.buf
,
3659 &relative_referent_path
);
3661 if (relative_referent_path
)
3662 strbuf_addstr(&referent
, relative_referent_path
);
3664 strbuf_addbuf(&referent
, &ref_content
);
3666 ret
|= files_fsck_symref_target(o
, &report
, &referent
, 1);
3670 if (strbuf_read_file(&ref_content
, iter
->path
.buf
, 0) < 0) {
3672 * Ref file could be removed by another concurrent process. We should
3673 * ignore this error and continue to the next ref.
3675 if (errno
== ENOENT
)
3678 ret
= error_errno(_("cannot read ref file '%s'"), iter
->path
.buf
);
3682 if (parse_loose_ref_contents(ref_store
->repo
->hash_algo
,
3683 ref_content
.buf
, &oid
, &referent
,
3684 &type
, &trailing
, &failure_errno
)) {
3685 strbuf_rtrim(&ref_content
);
3686 ret
= fsck_report_ref(o
, &report
,
3687 FSCK_MSG_BAD_REF_CONTENT
,
3688 "%s", ref_content
.buf
);
3692 if (!(type
& REF_ISSYMREF
)) {
3694 ret
= fsck_report_ref(o
, &report
,
3695 FSCK_MSG_REF_MISSING_NEWLINE
,
3696 "misses LF at the end");
3699 if (*trailing
!= '\n' || *(trailing
+ 1)) {
3700 ret
= fsck_report_ref(o
, &report
,
3701 FSCK_MSG_TRAILING_REF_CONTENT
,
3702 "has trailing garbage: '%s'", trailing
);
3706 ret
= files_fsck_symref_target(o
, &report
, &referent
, 0);
3711 strbuf_release(&ref_content
);
3712 strbuf_release(&referent
);
3713 strbuf_release(&abs_gitdir
);
3717 static int files_fsck_refs_name(struct ref_store
*ref_store UNUSED
,
3718 struct fsck_options
*o
,
3719 const char *refname
,
3720 struct dir_iterator
*iter
)
3722 struct strbuf sb
= STRBUF_INIT
;
3726 * Ignore the files ending with ".lock" as they may be lock files
3727 * However, do not allow bare ".lock" files.
3729 if (iter
->basename
[0] != '.' && ends_with(iter
->basename
, ".lock"))
3733 * This works right now because we never check the root refs.
3735 if (check_refname_format(refname
, 0)) {
3736 struct fsck_ref_report report
= { 0 };
3738 report
.path
= refname
;
3739 ret
= fsck_report_ref(o
, &report
,
3740 FSCK_MSG_BAD_REF_NAME
,
3741 "invalid refname format");
3745 strbuf_release(&sb
);
3749 static int files_fsck_refs_dir(struct ref_store
*ref_store
,
3750 struct fsck_options
*o
,
3751 const char *refs_check_dir
,
3752 struct worktree
*wt
,
3753 files_fsck_refs_fn
*fsck_refs_fn
)
3755 struct strbuf refname
= STRBUF_INIT
;
3756 struct strbuf sb
= STRBUF_INIT
;
3757 struct dir_iterator
*iter
;
3761 strbuf_addf(&sb
, "%s/%s", ref_store
->gitdir
, refs_check_dir
);
3763 iter
= dir_iterator_begin(sb
.buf
, 0);
3765 if (errno
== ENOENT
&& !is_main_worktree(wt
))
3768 ret
= error_errno(_("cannot open directory %s"), sb
.buf
);
3772 while ((iter_status
= dir_iterator_advance(iter
)) == ITER_OK
) {
3773 if (S_ISDIR(iter
->st
.st_mode
)) {
3775 } else if (S_ISREG(iter
->st
.st_mode
) ||
3776 S_ISLNK(iter
->st
.st_mode
)) {
3777 strbuf_reset(&refname
);
3779 if (!is_main_worktree(wt
))
3780 strbuf_addf(&refname
, "worktrees/%s/", wt
->id
);
3781 strbuf_addf(&refname
, "%s/%s", refs_check_dir
,
3782 iter
->relative_path
);
3785 fprintf_ln(stderr
, "Checking %s", refname
.buf
);
3787 for (size_t i
= 0; fsck_refs_fn
[i
]; i
++) {
3788 if (fsck_refs_fn
[i
](ref_store
, o
, refname
.buf
, iter
))
3792 struct fsck_ref_report report
= { .path
= iter
->basename
};
3793 if (fsck_report_ref(o
, &report
,
3794 FSCK_MSG_BAD_REF_FILETYPE
,
3795 "unexpected file type"))
3800 if (iter_status
!= ITER_DONE
)
3801 ret
= error(_("failed to iterate over '%s'"), sb
.buf
);
3804 dir_iterator_free(iter
);
3805 strbuf_release(&sb
);
3806 strbuf_release(&refname
);
3810 static int files_fsck_refs(struct ref_store
*ref_store
,
3811 struct fsck_options
*o
,
3812 struct worktree
*wt
)
3814 files_fsck_refs_fn fsck_refs_fn
[]= {
3815 files_fsck_refs_name
,
3816 files_fsck_refs_content
,
3821 fprintf_ln(stderr
, _("Checking references consistency"));
3822 return files_fsck_refs_dir(ref_store
, o
, "refs", wt
, fsck_refs_fn
);
3825 static int files_fsck(struct ref_store
*ref_store
,
3826 struct fsck_options
*o
,
3827 struct worktree
*wt
)
3829 struct files_ref_store
*refs
=
3830 files_downcast(ref_store
, REF_STORE_READ
, "fsck");
3832 return files_fsck_refs(ref_store
, o
, wt
) |
3833 refs
->packed_ref_store
->be
->fsck(refs
->packed_ref_store
, o
, wt
);
3836 struct ref_storage_be refs_be_files
= {
3838 .init
= files_ref_store_init
,
3839 .release
= files_ref_store_release
,
3840 .create_on_disk
= files_ref_store_create_on_disk
,
3841 .remove_on_disk
= files_ref_store_remove_on_disk
,
3843 .transaction_prepare
= files_transaction_prepare
,
3844 .transaction_finish
= files_transaction_finish
,
3845 .transaction_abort
= files_transaction_abort
,
3847 .pack_refs
= files_pack_refs
,
3848 .rename_ref
= files_rename_ref
,
3849 .copy_ref
= files_copy_ref
,
3851 .iterator_begin
= files_ref_iterator_begin
,
3852 .read_raw_ref
= files_read_raw_ref
,
3853 .read_symbolic_ref
= files_read_symbolic_ref
,
3855 .reflog_iterator_begin
= files_reflog_iterator_begin
,
3856 .for_each_reflog_ent
= files_for_each_reflog_ent
,
3857 .for_each_reflog_ent_reverse
= files_for_each_reflog_ent_reverse
,
3858 .reflog_exists
= files_reflog_exists
,
3859 .create_reflog
= files_create_reflog
,
3860 .delete_reflog
= files_delete_reflog
,
3861 .reflog_expire
= files_reflog_expire
,