4 #include "refs-internal.h"
6 #include "packed-backend.h"
7 #include "../iterator.h"
8 #include "../dir-iterator.h"
9 #include "../lockfile.h"
10 #include "../object.h"
14 * This backend uses the following flags in `ref_update::flags` for
15 * internal bookkeeping purposes. Their numerical values must not
16 * conflict with REF_NO_DEREF, REF_FORCE_CREATE_REFLOG, REF_HAVE_NEW,
17 * REF_HAVE_OLD, or REF_IS_PRUNING, which are also stored in
18 * `ref_update::flags`.
22 * Used as a flag in ref_update::flags when a loose ref is being
23 * pruned. This flag must only be used when REF_NO_DEREF is set.
25 #define REF_IS_PRUNING (1 << 4)
28 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
29 * refs (i.e., because the reference is about to be deleted anyway).
31 #define REF_DELETING (1 << 5)
34 * Used as a flag in ref_update::flags when the lockfile needs to be
37 #define REF_NEEDS_COMMIT (1 << 6)
40 * Used as a flag in ref_update::flags when we want to log a ref
41 * update but not actually perform it. This is used when a symbolic
42 * ref update is split up.
44 #define REF_LOG_ONLY (1 << 7)
47 * Used as a flag in ref_update::flags when the ref_update was via an
50 #define REF_UPDATE_VIA_HEAD (1 << 8)
53 * Used as a flag in ref_update::flags when the loose reference has
56 #define REF_DELETED_LOOSE (1 << 9)
61 struct object_id old_oid;
65 * Future: need to be in "struct repository"
66 * when doing a full libification.
68 struct files_ref_store {
69 struct ref_store base;
70 unsigned int store_flags;
75 struct ref_cache *loose;
77 struct ref_store *packed_ref_store;
80 static void clear_loose_ref_cache(struct files_ref_store *refs)
83 free_ref_cache(refs->loose);
89 * Create a new submodule ref cache and add it to the internal
92 static struct ref_store *files_ref_store_create(const char *gitdir,
95 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
96 struct ref_store *ref_store = (struct ref_store *)refs;
97 struct strbuf sb = STRBUF_INIT;
99 base_ref_store_init(ref_store, &refs_be_files);
100 refs->store_flags = flags;
102 refs->gitdir = xstrdup(gitdir);
103 get_common_dir_noenv(&sb, gitdir);
104 refs->gitcommondir = strbuf_detach(&sb, NULL);
105 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
106 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
113 * Die if refs is not the main ref store. caller is used in any
114 * necessary error messages.
116 static void files_assert_main_repository(struct files_ref_store *refs,
119 if (refs->store_flags & REF_STORE_MAIN)
122 die("BUG: operation %s only allowed for main ref store", caller);
126 * Downcast ref_store to files_ref_store. Die if ref_store is not a
127 * files_ref_store. required_flags is compared with ref_store's
128 * store_flags to ensure the ref_store has all required capabilities.
129 * "caller" is used in any necessary error messages.
131 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
132 unsigned int required_flags,
135 struct files_ref_store *refs;
137 if (ref_store->be != &refs_be_files)
138 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
139 ref_store->be->name, caller);
141 refs = (struct files_ref_store *)ref_store;
143 if ((refs->store_flags & required_flags) != required_flags)
144 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
145 caller, required_flags, refs->store_flags);
150 static void files_reflog_path(struct files_ref_store *refs,
154 switch (ref_type(refname)) {
155 case REF_TYPE_PER_WORKTREE:
156 case REF_TYPE_PSEUDOREF:
157 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
159 case REF_TYPE_NORMAL:
160 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
163 die("BUG: unknown ref type %d of ref %s",
164 ref_type(refname), refname);
168 static void files_ref_path(struct files_ref_store *refs,
172 switch (ref_type(refname)) {
173 case REF_TYPE_PER_WORKTREE:
174 case REF_TYPE_PSEUDOREF:
175 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
177 case REF_TYPE_NORMAL:
178 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
181 die("BUG: unknown ref type %d of ref %s",
182 ref_type(refname), refname);
187 * Read the loose references from the namespace dirname into dir
188 * (without recursing). dirname must end with '/'. dir must be the
189 * directory entry corresponding to dirname.
191 static void loose_fill_ref_dir(struct ref_store *ref_store,
192 struct ref_dir *dir, const char *dirname)
194 struct files_ref_store *refs =
195 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
198 int dirnamelen = strlen(dirname);
199 struct strbuf refname;
200 struct strbuf path = STRBUF_INIT;
203 files_ref_path(refs, &path, dirname);
204 path_baselen = path.len;
206 d = opendir(path.buf);
208 strbuf_release(&path);
212 strbuf_init(&refname, dirnamelen + 257);
213 strbuf_add(&refname, dirname, dirnamelen);
215 while ((de = readdir(d)) != NULL) {
216 struct object_id oid;
220 if (de->d_name[0] == '.')
222 if (ends_with(de->d_name, ".lock"))
224 strbuf_addstr(&refname, de->d_name);
225 strbuf_addstr(&path, de->d_name);
226 if (stat(path.buf, &st) < 0) {
227 ; /* silently ignore */
228 } else if (S_ISDIR(st.st_mode)) {
229 strbuf_addch(&refname, '/');
230 add_entry_to_dir(dir,
231 create_dir_entry(dir->cache, refname.buf,
234 if (!refs_resolve_ref_unsafe(&refs->base,
239 flag |= REF_ISBROKEN;
240 } else if (is_null_oid(&oid)) {
242 * It is so astronomically unlikely
243 * that null_oid is the OID of an
244 * actual object that we consider its
245 * appearance in a loose reference
246 * file to be repo corruption
247 * (probably due to a software bug).
249 flag |= REF_ISBROKEN;
252 if (check_refname_format(refname.buf,
253 REFNAME_ALLOW_ONELEVEL)) {
254 if (!refname_is_safe(refname.buf))
255 die("loose refname is dangerous: %s", refname.buf);
257 flag |= REF_BAD_NAME | REF_ISBROKEN;
259 add_entry_to_dir(dir,
260 create_ref_entry(refname.buf, &oid, flag));
262 strbuf_setlen(&refname, dirnamelen);
263 strbuf_setlen(&path, path_baselen);
265 strbuf_release(&refname);
266 strbuf_release(&path);
270 * Manually add refs/bisect, which, being per-worktree, might
271 * not appear in the directory listing for refs/ in the main
274 if (!strcmp(dirname, "refs/")) {
275 int pos = search_ref_dir(dir, "refs/bisect/", 12);
278 struct ref_entry *child_entry = create_dir_entry(
279 dir->cache, "refs/bisect/", 12, 1);
280 add_entry_to_dir(dir, child_entry);
285 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
289 * Mark the top-level directory complete because we
290 * are about to read the only subdirectory that can
293 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
295 /* We're going to fill the top level ourselves: */
296 refs->loose->root->flag &= ~REF_INCOMPLETE;
299 * Add an incomplete entry for "refs/" (to be filled
302 add_entry_to_dir(get_ref_dir(refs->loose->root),
303 create_dir_entry(refs->loose, "refs/", 5, 1));
308 static int files_read_raw_ref(struct ref_store *ref_store,
309 const char *refname, struct object_id *oid,
310 struct strbuf *referent, unsigned int *type)
312 struct files_ref_store *refs =
313 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
314 struct strbuf sb_contents = STRBUF_INIT;
315 struct strbuf sb_path = STRBUF_INIT;
323 int remaining_retries = 3;
326 strbuf_reset(&sb_path);
328 files_ref_path(refs, &sb_path, refname);
334 * We might have to loop back here to avoid a race
335 * condition: first we lstat() the file, then we try
336 * to read it as a link or as a file. But if somebody
337 * changes the type of the file (file <-> directory
338 * <-> symlink) between the lstat() and reading, then
339 * we don't want to report that as an error but rather
340 * try again starting with the lstat().
342 * We'll keep a count of the retries, though, just to avoid
343 * any confusing situation sending us into an infinite loop.
346 if (remaining_retries-- <= 0)
349 if (lstat(path, &st) < 0) {
352 if (refs_read_raw_ref(refs->packed_ref_store, refname,
353 oid, referent, type)) {
361 /* Follow "normalized" - ie "refs/.." symlinks by hand */
362 if (S_ISLNK(st.st_mode)) {
363 strbuf_reset(&sb_contents);
364 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
365 if (errno == ENOENT || errno == EINVAL)
366 /* inconsistent with lstat; retry */
371 if (starts_with(sb_contents.buf, "refs/") &&
372 !check_refname_format(sb_contents.buf, 0)) {
373 strbuf_swap(&sb_contents, referent);
374 *type |= REF_ISSYMREF;
379 * It doesn't look like a refname; fall through to just
380 * treating it like a non-symlink, and reading whatever it
385 /* Is it a directory? */
386 if (S_ISDIR(st.st_mode)) {
388 * Even though there is a directory where the loose
389 * ref is supposed to be, there could still be a
392 if (refs_read_raw_ref(refs->packed_ref_store, refname,
393 oid, referent, type)) {
402 * Anything else, just open it and try to use it as
405 fd = open(path, O_RDONLY);
407 if (errno == ENOENT && !S_ISLNK(st.st_mode))
408 /* inconsistent with lstat; retry */
413 strbuf_reset(&sb_contents);
414 if (strbuf_read(&sb_contents, fd, 256) < 0) {
415 int save_errno = errno;
421 strbuf_rtrim(&sb_contents);
422 buf = sb_contents.buf;
423 if (starts_with(buf, "ref:")) {
425 while (isspace(*buf))
428 strbuf_reset(referent);
429 strbuf_addstr(referent, buf);
430 *type |= REF_ISSYMREF;
436 * Please note that FETCH_HEAD has additional
437 * data after the sha.
439 if (parse_oid_hex(buf, oid, &p) ||
440 (*p != '\0' && !isspace(*p))) {
441 *type |= REF_ISBROKEN;
450 strbuf_release(&sb_path);
451 strbuf_release(&sb_contents);
456 static void unlock_ref(struct ref_lock *lock)
458 rollback_lock_file(&lock->lk);
459 free(lock->ref_name);
464 * Lock refname, without following symrefs, and set *lock_p to point
465 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
466 * and type similarly to read_raw_ref().
468 * The caller must verify that refname is a "safe" reference name (in
469 * the sense of refname_is_safe()) before calling this function.
471 * If the reference doesn't already exist, verify that refname doesn't
472 * have a D/F conflict with any existing references. extras and skip
473 * are passed to refs_verify_refname_available() for this check.
475 * If mustexist is not set and the reference is not found or is
476 * broken, lock the reference anyway but clear old_oid.
478 * Return 0 on success. On failure, write an error message to err and
479 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
481 * Implementation note: This function is basically
486 * but it includes a lot more code to
487 * - Deal with possible races with other processes
488 * - Avoid calling refs_verify_refname_available() when it can be
489 * avoided, namely if we were successfully able to read the ref
490 * - Generate informative error messages in the case of failure
492 static int lock_raw_ref(struct files_ref_store *refs,
493 const char *refname, int mustexist,
494 const struct string_list *extras,
495 const struct string_list *skip,
496 struct ref_lock **lock_p,
497 struct strbuf *referent,
501 struct ref_lock *lock;
502 struct strbuf ref_file = STRBUF_INIT;
503 int attempts_remaining = 3;
504 int ret = TRANSACTION_GENERIC_ERROR;
507 files_assert_main_repository(refs, "lock_raw_ref");
511 /* First lock the file so it can't change out from under us. */
513 *lock_p = lock = xcalloc(1, sizeof(*lock));
515 lock->ref_name = xstrdup(refname);
516 files_ref_path(refs, &ref_file, refname);
519 switch (safe_create_leading_directories(ref_file.buf)) {
524 * Suppose refname is "refs/foo/bar". We just failed
525 * to create the containing directory, "refs/foo",
526 * because there was a non-directory in the way. This
527 * indicates a D/F conflict, probably because of
528 * another reference such as "refs/foo". There is no
529 * reason to expect this error to be transitory.
531 if (refs_verify_refname_available(&refs->base, refname,
532 extras, skip, err)) {
535 * To the user the relevant error is
536 * that the "mustexist" reference is
540 strbuf_addf(err, "unable to resolve reference '%s'",
544 * The error message set by
545 * refs_verify_refname_available() is
548 ret = TRANSACTION_NAME_CONFLICT;
552 * The file that is in the way isn't a loose
553 * reference. Report it as a low-level
556 strbuf_addf(err, "unable to create lock file %s.lock; "
557 "non-directory in the way",
562 /* Maybe another process was tidying up. Try again. */
563 if (--attempts_remaining > 0)
567 strbuf_addf(err, "unable to create directory for %s",
572 if (hold_lock_file_for_update_timeout(
573 &lock->lk, ref_file.buf, LOCK_NO_DEREF,
574 get_files_ref_lock_timeout_ms()) < 0) {
575 if (errno == ENOENT && --attempts_remaining > 0) {
577 * Maybe somebody just deleted one of the
578 * directories leading to ref_file. Try
583 unable_to_lock_message(ref_file.buf, errno, err);
589 * Now we hold the lock and can read the reference without
590 * fear that its value will change.
593 if (files_read_raw_ref(&refs->base, refname,
594 &lock->old_oid, referent, type)) {
595 if (errno == ENOENT) {
597 /* Garden variety missing reference. */
598 strbuf_addf(err, "unable to resolve reference '%s'",
603 * Reference is missing, but that's OK. We
604 * know that there is not a conflict with
605 * another loose reference because
606 * (supposing that we are trying to lock
607 * reference "refs/foo/bar"):
609 * - We were successfully able to create
610 * the lockfile refs/foo/bar.lock, so we
611 * know there cannot be a loose reference
614 * - We got ENOENT and not EISDIR, so we
615 * know that there cannot be a loose
616 * reference named "refs/foo/bar/baz".
619 } else if (errno == EISDIR) {
621 * There is a directory in the way. It might have
622 * contained references that have been deleted. If
623 * we don't require that the reference already
624 * exists, try to remove the directory so that it
625 * doesn't cause trouble when we want to rename the
626 * lockfile into place later.
629 /* Garden variety missing reference. */
630 strbuf_addf(err, "unable to resolve reference '%s'",
633 } else if (remove_dir_recursively(&ref_file,
634 REMOVE_DIR_EMPTY_ONLY)) {
635 if (refs_verify_refname_available(
636 &refs->base, refname,
637 extras, skip, err)) {
639 * The error message set by
640 * verify_refname_available() is OK.
642 ret = TRANSACTION_NAME_CONFLICT;
646 * We can't delete the directory,
647 * but we also don't know of any
648 * references that it should
651 strbuf_addf(err, "there is a non-empty directory '%s' "
652 "blocking reference '%s'",
653 ref_file.buf, refname);
657 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
658 strbuf_addf(err, "unable to resolve reference '%s': "
659 "reference broken", refname);
662 strbuf_addf(err, "unable to resolve reference '%s': %s",
663 refname, strerror(errno));
668 * If the ref did not exist and we are creating it,
669 * make sure there is no existing packed ref that
670 * conflicts with refname:
672 if (refs_verify_refname_available(
673 refs->packed_ref_store, refname,
686 strbuf_release(&ref_file);
690 struct files_ref_iterator {
691 struct ref_iterator base;
693 struct ref_iterator *iter0;
697 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
699 struct files_ref_iterator *iter =
700 (struct files_ref_iterator *)ref_iterator;
703 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
704 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
705 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
708 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
709 !ref_resolves_to_object(iter->iter0->refname,
714 iter->base.refname = iter->iter0->refname;
715 iter->base.oid = iter->iter0->oid;
716 iter->base.flags = iter->iter0->flags;
721 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
727 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
728 struct object_id *peeled)
730 struct files_ref_iterator *iter =
731 (struct files_ref_iterator *)ref_iterator;
733 return ref_iterator_peel(iter->iter0, peeled);
736 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
738 struct files_ref_iterator *iter =
739 (struct files_ref_iterator *)ref_iterator;
743 ok = ref_iterator_abort(iter->iter0);
745 base_ref_iterator_free(ref_iterator);
749 static struct ref_iterator_vtable files_ref_iterator_vtable = {
750 files_ref_iterator_advance,
751 files_ref_iterator_peel,
752 files_ref_iterator_abort
755 static struct ref_iterator *files_ref_iterator_begin(
756 struct ref_store *ref_store,
757 const char *prefix, unsigned int flags)
759 struct files_ref_store *refs;
760 struct ref_iterator *loose_iter, *packed_iter, *overlay_iter;
761 struct files_ref_iterator *iter;
762 struct ref_iterator *ref_iterator;
763 unsigned int required_flags = REF_STORE_READ;
765 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
766 required_flags |= REF_STORE_ODB;
768 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
771 * We must make sure that all loose refs are read before
772 * accessing the packed-refs file; this avoids a race
773 * condition if loose refs are migrated to the packed-refs
774 * file by a simultaneous process, but our in-memory view is
775 * from before the migration. We ensure this as follows:
776 * First, we call start the loose refs iteration with its
777 * `prime_ref` argument set to true. This causes the loose
778 * references in the subtree to be pre-read into the cache.
779 * (If they've already been read, that's OK; we only need to
780 * guarantee that they're read before the packed refs, not
781 * *how much* before.) After that, we call
782 * packed_ref_iterator_begin(), which internally checks
783 * whether the packed-ref cache is up to date with what is on
784 * disk, and re-reads it if not.
787 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
791 * The packed-refs file might contain broken references, for
792 * example an old version of a reference that points at an
793 * object that has since been garbage-collected. This is OK as
794 * long as there is a corresponding loose reference that
795 * overrides it, and we don't want to emit an error message in
796 * this case. So ask the packed_ref_store for all of its
797 * references, and (if needed) do our own check for broken
798 * ones in files_ref_iterator_advance(), after we have merged
799 * the packed and loose references.
801 packed_iter = refs_ref_iterator_begin(
802 refs->packed_ref_store, prefix, 0,
803 DO_FOR_EACH_INCLUDE_BROKEN);
805 overlay_iter = overlay_ref_iterator_begin(loose_iter, packed_iter);
807 iter = xcalloc(1, sizeof(*iter));
808 ref_iterator = &iter->base;
809 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable,
810 overlay_iter->ordered);
811 iter->iter0 = overlay_iter;
818 * Verify that the reference locked by lock has the value old_oid
819 * (unless it is NULL). Fail if the reference doesn't exist and
820 * mustexist is set. Return 0 on success. On error, write an error
821 * message to err, set errno, and return a negative value.
823 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
824 const struct object_id *old_oid, int mustexist,
829 if (refs_read_ref_full(ref_store, lock->ref_name,
830 mustexist ? RESOLVE_REF_READING : 0,
831 &lock->old_oid, NULL)) {
833 int save_errno = errno;
834 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
838 oidclr(&lock->old_oid);
842 if (old_oid && oidcmp(&lock->old_oid, old_oid)) {
843 strbuf_addf(err, "ref '%s' is at %s but expected %s",
845 oid_to_hex(&lock->old_oid),
846 oid_to_hex(old_oid));
853 static int remove_empty_directories(struct strbuf *path)
856 * we want to create a file but there is a directory there;
857 * if that is an empty directory (or a directory that contains
858 * only empty directories), remove them.
860 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
863 static int create_reflock(const char *path, void *cb)
865 struct lock_file *lk = cb;
867 return hold_lock_file_for_update_timeout(
868 lk, path, LOCK_NO_DEREF,
869 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
873 * Locks a ref returning the lock on success and NULL on failure.
874 * On failure errno is set to something meaningful.
876 static struct ref_lock *lock_ref_oid_basic(struct files_ref_store *refs,
878 const struct object_id *old_oid,
879 const struct string_list *extras,
880 const struct string_list *skip,
881 unsigned int flags, int *type,
884 struct strbuf ref_file = STRBUF_INIT;
885 struct ref_lock *lock;
887 int mustexist = (old_oid && !is_null_oid(old_oid));
888 int resolve_flags = RESOLVE_REF_NO_RECURSE;
891 files_assert_main_repository(refs, "lock_ref_oid_basic");
894 lock = xcalloc(1, sizeof(struct ref_lock));
897 resolve_flags |= RESOLVE_REF_READING;
898 if (flags & REF_DELETING)
899 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
901 files_ref_path(refs, &ref_file, refname);
902 resolved = !!refs_resolve_ref_unsafe(&refs->base,
903 refname, resolve_flags,
904 &lock->old_oid, type);
905 if (!resolved && errno == EISDIR) {
907 * we are trying to lock foo but we used to
908 * have foo/bar which now does not exist;
909 * it is normal for the empty directory 'foo'
912 if (remove_empty_directories(&ref_file)) {
914 if (!refs_verify_refname_available(
916 refname, extras, skip, err))
917 strbuf_addf(err, "there are still refs under '%s'",
921 resolved = !!refs_resolve_ref_unsafe(&refs->base,
922 refname, resolve_flags,
923 &lock->old_oid, type);
927 if (last_errno != ENOTDIR ||
928 !refs_verify_refname_available(&refs->base, refname,
930 strbuf_addf(err, "unable to resolve reference '%s': %s",
931 refname, strerror(last_errno));
937 * If the ref did not exist and we are creating it, make sure
938 * there is no existing packed ref whose name begins with our
939 * refname, nor a packed ref whose name is a proper prefix of
942 if (is_null_oid(&lock->old_oid) &&
943 refs_verify_refname_available(refs->packed_ref_store, refname,
944 extras, skip, err)) {
945 last_errno = ENOTDIR;
949 lock->ref_name = xstrdup(refname);
951 if (raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) {
953 unable_to_lock_message(ref_file.buf, errno, err);
957 if (verify_lock(&refs->base, lock, old_oid, mustexist, err)) {
968 strbuf_release(&ref_file);
973 struct ref_to_prune {
974 struct ref_to_prune *next;
975 struct object_id oid;
976 char name[FLEX_ARRAY];
980 REMOVE_EMPTY_PARENTS_REF = 0x01,
981 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
985 * Remove empty parent directories associated with the specified
986 * reference and/or its reflog, but spare [logs/]refs/ and immediate
987 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
988 * REMOVE_EMPTY_PARENTS_REFLOG.
990 static void try_remove_empty_parents(struct files_ref_store *refs,
994 struct strbuf buf = STRBUF_INIT;
995 struct strbuf sb = STRBUF_INIT;
999 strbuf_addstr(&buf, refname);
1001 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1002 while (*p && *p != '/')
1004 /* tolerate duplicate slashes; see check_refname_format() */
1008 q = buf.buf + buf.len;
1009 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1010 while (q > p && *q != '/')
1012 while (q > p && *(q-1) == '/')
1016 strbuf_setlen(&buf, q - buf.buf);
1019 files_ref_path(refs, &sb, buf.buf);
1020 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1021 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1024 files_reflog_path(refs, &sb, buf.buf);
1025 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1026 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1028 strbuf_release(&buf);
1029 strbuf_release(&sb);
1032 /* make sure nobody touched the ref, and unlink */
1033 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1035 struct ref_transaction *transaction;
1036 struct strbuf err = STRBUF_INIT;
1039 if (check_refname_format(r->name, 0))
1042 transaction = ref_store_transaction_begin(&refs->base, &err);
1045 ref_transaction_add_update(
1046 transaction, r->name,
1047 REF_NO_DEREF | REF_HAVE_NEW | REF_HAVE_OLD | REF_IS_PRUNING,
1048 &null_oid, &r->oid, NULL);
1049 if (ref_transaction_commit(transaction, &err))
1056 error("%s", err.buf);
1057 strbuf_release(&err);
1058 ref_transaction_free(transaction);
1063 * Prune the loose versions of the references in the linked list
1064 * `*refs_to_prune`, freeing the entries in the list as we go.
1066 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune **refs_to_prune)
1068 while (*refs_to_prune) {
1069 struct ref_to_prune *r = *refs_to_prune;
1070 *refs_to_prune = r->next;
1077 * Return true if the specified reference should be packed.
1079 static int should_pack_ref(const char *refname,
1080 const struct object_id *oid, unsigned int ref_flags,
1081 unsigned int pack_flags)
1083 /* Do not pack per-worktree refs: */
1084 if (ref_type(refname) != REF_TYPE_NORMAL)
1087 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1088 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1091 /* Do not pack symbolic refs: */
1092 if (ref_flags & REF_ISSYMREF)
1095 /* Do not pack broken refs: */
1096 if (!ref_resolves_to_object(refname, oid, ref_flags))
1102 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1104 struct files_ref_store *refs =
1105 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1107 struct ref_iterator *iter;
1109 struct ref_to_prune *refs_to_prune = NULL;
1110 struct strbuf err = STRBUF_INIT;
1111 struct ref_transaction *transaction;
1113 transaction = ref_store_transaction_begin(refs->packed_ref_store, &err);
1117 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1119 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1120 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1122 * If the loose reference can be packed, add an entry
1123 * in the packed ref cache. If the reference should be
1124 * pruned, also add it to refs_to_prune.
1126 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1131 * Add a reference creation for this reference to the
1132 * packed-refs transaction:
1134 if (ref_transaction_update(transaction, iter->refname,
1136 REF_NO_DEREF, NULL, &err))
1137 die("failure preparing to create packed reference %s: %s",
1138 iter->refname, err.buf);
1140 /* Schedule the loose reference for pruning if requested. */
1141 if ((flags & PACK_REFS_PRUNE)) {
1142 struct ref_to_prune *n;
1143 FLEX_ALLOC_STR(n, name, iter->refname);
1144 oidcpy(&n->oid, iter->oid);
1145 n->next = refs_to_prune;
1149 if (ok != ITER_DONE)
1150 die("error while iterating over references");
1152 if (ref_transaction_commit(transaction, &err))
1153 die("unable to write new packed-refs: %s", err.buf);
1155 ref_transaction_free(transaction);
1157 packed_refs_unlock(refs->packed_ref_store);
1159 prune_refs(refs, &refs_to_prune);
1160 strbuf_release(&err);
1164 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1165 struct string_list *refnames, unsigned int flags)
1167 struct files_ref_store *refs =
1168 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1169 struct strbuf err = STRBUF_INIT;
1175 if (packed_refs_lock(refs->packed_ref_store, 0, &err))
1178 if (refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {
1179 packed_refs_unlock(refs->packed_ref_store);
1183 packed_refs_unlock(refs->packed_ref_store);
1185 for (i = 0; i < refnames->nr; i++) {
1186 const char *refname = refnames->items[i].string;
1188 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1189 result |= error(_("could not remove reference %s"), refname);
1192 strbuf_release(&err);
1197 * If we failed to rewrite the packed-refs file, then it is
1198 * unsafe to try to remove loose refs, because doing so might
1199 * expose an obsolete packed value for a reference that might
1200 * even point at an object that has been garbage collected.
1202 if (refnames->nr == 1)
1203 error(_("could not delete reference %s: %s"),
1204 refnames->items[0].string, err.buf);
1206 error(_("could not delete references: %s"), err.buf);
1208 strbuf_release(&err);
1213 * People using contrib's git-new-workdir have .git/logs/refs ->
1214 * /some/other/path/.git/logs/refs, and that may live on another device.
1216 * IOW, to avoid cross device rename errors, the temporary renamed log must
1217 * live into logs/refs.
1219 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1222 const char *tmp_renamed_log;
1226 static int rename_tmp_log_callback(const char *path, void *cb_data)
1228 struct rename_cb *cb = cb_data;
1230 if (rename(cb->tmp_renamed_log, path)) {
1232 * rename(a, b) when b is an existing directory ought
1233 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1234 * Sheesh. Record the true errno for error reporting,
1235 * but report EISDIR to raceproof_create_file() so
1236 * that it knows to retry.
1238 cb->true_errno = errno;
1239 if (errno == ENOTDIR)
1247 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1249 struct strbuf path = STRBUF_INIT;
1250 struct strbuf tmp = STRBUF_INIT;
1251 struct rename_cb cb;
1254 files_reflog_path(refs, &path, newrefname);
1255 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1256 cb.tmp_renamed_log = tmp.buf;
1257 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1259 if (errno == EISDIR)
1260 error("directory not empty: %s", path.buf);
1262 error("unable to move logfile %s to %s: %s",
1264 strerror(cb.true_errno));
1267 strbuf_release(&path);
1268 strbuf_release(&tmp);
1272 static int write_ref_to_lockfile(struct ref_lock *lock,
1273 const struct object_id *oid, struct strbuf *err);
1274 static int commit_ref_update(struct files_ref_store *refs,
1275 struct ref_lock *lock,
1276 const struct object_id *oid, const char *logmsg,
1277 struct strbuf *err);
1279 static int files_copy_or_rename_ref(struct ref_store *ref_store,
1280 const char *oldrefname, const char *newrefname,
1281 const char *logmsg, int copy)
1283 struct files_ref_store *refs =
1284 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1285 struct object_id oid, orig_oid;
1286 int flag = 0, logmoved = 0;
1287 struct ref_lock *lock;
1288 struct stat loginfo;
1289 struct strbuf sb_oldref = STRBUF_INIT;
1290 struct strbuf sb_newref = STRBUF_INIT;
1291 struct strbuf tmp_renamed_log = STRBUF_INIT;
1293 struct strbuf err = STRBUF_INIT;
1295 files_reflog_path(refs, &sb_oldref, oldrefname);
1296 files_reflog_path(refs, &sb_newref, newrefname);
1297 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1299 log = !lstat(sb_oldref.buf, &loginfo);
1300 if (log && S_ISLNK(loginfo.st_mode)) {
1301 ret = error("reflog for %s is a symlink", oldrefname);
1305 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1306 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1307 &orig_oid, &flag)) {
1308 ret = error("refname %s not found", oldrefname);
1312 if (flag & REF_ISSYMREF) {
1314 ret = error("refname %s is a symbolic ref, copying it is not supported",
1317 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1321 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1326 if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1327 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1328 oldrefname, strerror(errno));
1332 if (copy && log && copy_file(tmp_renamed_log.buf, sb_oldref.buf, 0644)) {
1333 ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1334 oldrefname, strerror(errno));
1338 if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,
1339 &orig_oid, REF_NO_DEREF)) {
1340 error("unable to delete old %s", oldrefname);
1345 * Since we are doing a shallow lookup, oid is not the
1346 * correct value to pass to delete_ref as old_oid. But that
1347 * doesn't matter, because an old_oid check wouldn't add to
1348 * the safety anyway; we want to delete the reference whatever
1349 * its current value.
1351 if (!copy && !refs_read_ref_full(&refs->base, newrefname,
1352 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1354 refs_delete_ref(&refs->base, NULL, newrefname,
1355 NULL, REF_NO_DEREF)) {
1356 if (errno == EISDIR) {
1357 struct strbuf path = STRBUF_INIT;
1360 files_ref_path(refs, &path, newrefname);
1361 result = remove_empty_directories(&path);
1362 strbuf_release(&path);
1365 error("Directory not empty: %s", newrefname);
1369 error("unable to delete existing %s", newrefname);
1374 if (log && rename_tmp_log(refs, newrefname))
1379 lock = lock_ref_oid_basic(refs, newrefname, NULL, NULL, NULL,
1380 REF_NO_DEREF, NULL, &err);
1383 error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1385 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1386 strbuf_release(&err);
1389 oidcpy(&lock->old_oid, &orig_oid);
1391 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1392 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1393 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1394 strbuf_release(&err);
1402 lock = lock_ref_oid_basic(refs, oldrefname, NULL, NULL, NULL,
1403 REF_NO_DEREF, NULL, &err);
1405 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1406 strbuf_release(&err);
1410 flag = log_all_ref_updates;
1411 log_all_ref_updates = LOG_REFS_NONE;
1412 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1413 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1414 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1415 strbuf_release(&err);
1417 log_all_ref_updates = flag;
1420 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1421 error("unable to restore logfile %s from %s: %s",
1422 oldrefname, newrefname, strerror(errno));
1423 if (!logmoved && log &&
1424 rename(tmp_renamed_log.buf, sb_oldref.buf))
1425 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1426 oldrefname, strerror(errno));
1429 strbuf_release(&sb_newref);
1430 strbuf_release(&sb_oldref);
1431 strbuf_release(&tmp_renamed_log);
1436 static int files_rename_ref(struct ref_store *ref_store,
1437 const char *oldrefname, const char *newrefname,
1440 return files_copy_or_rename_ref(ref_store, oldrefname,
1441 newrefname, logmsg, 0);
1444 static int files_copy_ref(struct ref_store *ref_store,
1445 const char *oldrefname, const char *newrefname,
1448 return files_copy_or_rename_ref(ref_store, oldrefname,
1449 newrefname, logmsg, 1);
1452 static int close_ref_gently(struct ref_lock *lock)
1454 if (close_lock_file_gently(&lock->lk))
1459 static int commit_ref(struct ref_lock *lock)
1461 char *path = get_locked_file_path(&lock->lk);
1464 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1466 * There is a directory at the path we want to rename
1467 * the lockfile to. Hopefully it is empty; try to
1470 size_t len = strlen(path);
1471 struct strbuf sb_path = STRBUF_INIT;
1473 strbuf_attach(&sb_path, path, len, len);
1476 * If this fails, commit_lock_file() will also fail
1477 * and will report the problem.
1479 remove_empty_directories(&sb_path);
1480 strbuf_release(&sb_path);
1485 if (commit_lock_file(&lock->lk))
1490 static int open_or_create_logfile(const char *path, void *cb)
1494 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1495 return (*fd < 0) ? -1 : 0;
1499 * Create a reflog for a ref. If force_create = 0, only create the
1500 * reflog for certain refs (those for which should_autocreate_reflog
1501 * returns non-zero). Otherwise, create it regardless of the reference
1502 * name. If the logfile already existed or was created, return 0 and
1503 * set *logfd to the file descriptor opened for appending to the file.
1504 * If no logfile exists and we decided not to create one, return 0 and
1505 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1508 static int log_ref_setup(struct files_ref_store *refs,
1509 const char *refname, int force_create,
1510 int *logfd, struct strbuf *err)
1512 struct strbuf logfile_sb = STRBUF_INIT;
1515 files_reflog_path(refs, &logfile_sb, refname);
1516 logfile = strbuf_detach(&logfile_sb, NULL);
1518 if (force_create || should_autocreate_reflog(refname)) {
1519 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1520 if (errno == ENOENT)
1521 strbuf_addf(err, "unable to create directory for '%s': "
1522 "%s", logfile, strerror(errno));
1523 else if (errno == EISDIR)
1524 strbuf_addf(err, "there are still logs under '%s'",
1527 strbuf_addf(err, "unable to append to '%s': %s",
1528 logfile, strerror(errno));
1533 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1535 if (errno == ENOENT || errno == EISDIR) {
1537 * The logfile doesn't already exist,
1538 * but that is not an error; it only
1539 * means that we won't write log
1544 strbuf_addf(err, "unable to append to '%s': %s",
1545 logfile, strerror(errno));
1552 adjust_shared_perm(logfile);
1562 static int files_create_reflog(struct ref_store *ref_store,
1563 const char *refname, int force_create,
1566 struct files_ref_store *refs =
1567 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1570 if (log_ref_setup(refs, refname, force_create, &fd, err))
1579 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1580 const struct object_id *new_oid,
1581 const char *committer, const char *msg)
1583 int msglen, written;
1584 unsigned maxlen, len;
1587 msglen = msg ? strlen(msg) : 0;
1588 maxlen = strlen(committer) + msglen + 100;
1589 logrec = xmalloc(maxlen);
1590 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1591 oid_to_hex(old_oid),
1592 oid_to_hex(new_oid),
1595 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1597 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
1605 static int files_log_ref_write(struct files_ref_store *refs,
1606 const char *refname, const struct object_id *old_oid,
1607 const struct object_id *new_oid, const char *msg,
1608 int flags, struct strbuf *err)
1612 if (log_all_ref_updates == LOG_REFS_UNSET)
1613 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1615 result = log_ref_setup(refs, refname,
1616 flags & REF_FORCE_CREATE_REFLOG,
1624 result = log_ref_write_fd(logfd, old_oid, new_oid,
1625 git_committer_info(0), msg);
1627 struct strbuf sb = STRBUF_INIT;
1628 int save_errno = errno;
1630 files_reflog_path(refs, &sb, refname);
1631 strbuf_addf(err, "unable to append to '%s': %s",
1632 sb.buf, strerror(save_errno));
1633 strbuf_release(&sb);
1638 struct strbuf sb = STRBUF_INIT;
1639 int save_errno = errno;
1641 files_reflog_path(refs, &sb, refname);
1642 strbuf_addf(err, "unable to append to '%s': %s",
1643 sb.buf, strerror(save_errno));
1644 strbuf_release(&sb);
1651 * Write oid into the open lockfile, then close the lockfile. On
1652 * errors, rollback the lockfile, fill in *err and return -1.
1654 static int write_ref_to_lockfile(struct ref_lock *lock,
1655 const struct object_id *oid, struct strbuf *err)
1657 static char term = '\n';
1661 o = parse_object(oid);
1664 "trying to write ref '%s' with nonexistent object %s",
1665 lock->ref_name, oid_to_hex(oid));
1669 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1671 "trying to write non-commit object %s to branch '%s'",
1672 oid_to_hex(oid), lock->ref_name);
1676 fd = get_lock_file_fd(&lock->lk);
1677 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) < 0 ||
1678 write_in_full(fd, &term, 1) < 0 ||
1679 close_ref_gently(lock) < 0) {
1681 "couldn't write '%s'", get_lock_file_path(&lock->lk));
1689 * Commit a change to a loose reference that has already been written
1690 * to the loose reference lockfile. Also update the reflogs if
1691 * necessary, using the specified lockmsg (which can be NULL).
1693 static int commit_ref_update(struct files_ref_store *refs,
1694 struct ref_lock *lock,
1695 const struct object_id *oid, const char *logmsg,
1698 files_assert_main_repository(refs, "commit_ref_update");
1700 clear_loose_ref_cache(refs);
1701 if (files_log_ref_write(refs, lock->ref_name,
1702 &lock->old_oid, oid,
1704 char *old_msg = strbuf_detach(err, NULL);
1705 strbuf_addf(err, "cannot update the ref '%s': %s",
1706 lock->ref_name, old_msg);
1712 if (strcmp(lock->ref_name, "HEAD") != 0) {
1714 * Special hack: If a branch is updated directly and HEAD
1715 * points to it (may happen on the remote side of a push
1716 * for example) then logically the HEAD reflog should be
1718 * A generic solution implies reverse symref information,
1719 * but finding all symrefs pointing to the given branch
1720 * would be rather costly for this rare event (the direct
1721 * update of a branch) to be worth it. So let's cheat and
1722 * check with HEAD only which should cover 99% of all usage
1723 * scenarios (even 100% of the default ones).
1726 const char *head_ref;
1728 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1729 RESOLVE_REF_READING,
1731 if (head_ref && (head_flag & REF_ISSYMREF) &&
1732 !strcmp(head_ref, lock->ref_name)) {
1733 struct strbuf log_err = STRBUF_INIT;
1734 if (files_log_ref_write(refs, "HEAD",
1735 &lock->old_oid, oid,
1736 logmsg, 0, &log_err)) {
1737 error("%s", log_err.buf);
1738 strbuf_release(&log_err);
1743 if (commit_ref(lock)) {
1744 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1753 static int create_ref_symlink(struct ref_lock *lock, const char *target)
1756 #ifndef NO_SYMLINK_HEAD
1757 char *ref_path = get_locked_file_path(&lock->lk);
1759 ret = symlink(target, ref_path);
1763 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1768 static void update_symref_reflog(struct files_ref_store *refs,
1769 struct ref_lock *lock, const char *refname,
1770 const char *target, const char *logmsg)
1772 struct strbuf err = STRBUF_INIT;
1773 struct object_id new_oid;
1775 !refs_read_ref_full(&refs->base, target,
1776 RESOLVE_REF_READING, &new_oid, NULL) &&
1777 files_log_ref_write(refs, refname, &lock->old_oid,
1778 &new_oid, logmsg, 0, &err)) {
1779 error("%s", err.buf);
1780 strbuf_release(&err);
1784 static int create_symref_locked(struct files_ref_store *refs,
1785 struct ref_lock *lock, const char *refname,
1786 const char *target, const char *logmsg)
1788 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1789 update_symref_reflog(refs, lock, refname, target, logmsg);
1793 if (!fdopen_lock_file(&lock->lk, "w"))
1794 return error("unable to fdopen %s: %s",
1795 lock->lk.tempfile->filename.buf, strerror(errno));
1797 update_symref_reflog(refs, lock, refname, target, logmsg);
1799 /* no error check; commit_ref will check ferror */
1800 fprintf(lock->lk.tempfile->fp, "ref: %s\n", target);
1801 if (commit_ref(lock) < 0)
1802 return error("unable to write symref for %s: %s", refname,
1807 static int files_create_symref(struct ref_store *ref_store,
1808 const char *refname, const char *target,
1811 struct files_ref_store *refs =
1812 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1813 struct strbuf err = STRBUF_INIT;
1814 struct ref_lock *lock;
1817 lock = lock_ref_oid_basic(refs, refname, NULL,
1818 NULL, NULL, REF_NO_DEREF, NULL,
1821 error("%s", err.buf);
1822 strbuf_release(&err);
1826 ret = create_symref_locked(refs, lock, refname, target, logmsg);
1831 static int files_reflog_exists(struct ref_store *ref_store,
1832 const char *refname)
1834 struct files_ref_store *refs =
1835 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1836 struct strbuf sb = STRBUF_INIT;
1840 files_reflog_path(refs, &sb, refname);
1841 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1842 strbuf_release(&sb);
1846 static int files_delete_reflog(struct ref_store *ref_store,
1847 const char *refname)
1849 struct files_ref_store *refs =
1850 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1851 struct strbuf sb = STRBUF_INIT;
1854 files_reflog_path(refs, &sb, refname);
1855 ret = remove_path(sb.buf);
1856 strbuf_release(&sb);
1860 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1862 struct object_id ooid, noid;
1863 char *email_end, *message;
1864 timestamp_t timestamp;
1866 const char *p = sb->buf;
1868 /* old SP new SP name <email> SP time TAB msg LF */
1869 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1870 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1871 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1872 !(email_end = strchr(p, '>')) ||
1873 email_end[1] != ' ' ||
1874 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1875 !message || message[0] != ' ' ||
1876 (message[1] != '+' && message[1] != '-') ||
1877 !isdigit(message[2]) || !isdigit(message[3]) ||
1878 !isdigit(message[4]) || !isdigit(message[5]))
1879 return 0; /* corrupt? */
1880 email_end[1] = '\0';
1881 tz = strtol(message + 1, NULL, 10);
1882 if (message[6] != '\t')
1886 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1889 static char *find_beginning_of_line(char *bob, char *scan)
1891 while (bob < scan && *(--scan) != '\n')
1892 ; /* keep scanning backwards */
1894 * Return either beginning of the buffer, or LF at the end of
1895 * the previous line.
1900 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1901 const char *refname,
1902 each_reflog_ent_fn fn,
1905 struct files_ref_store *refs =
1906 files_downcast(ref_store, REF_STORE_READ,
1907 "for_each_reflog_ent_reverse");
1908 struct strbuf sb = STRBUF_INIT;
1911 int ret = 0, at_tail = 1;
1913 files_reflog_path(refs, &sb, refname);
1914 logfp = fopen(sb.buf, "r");
1915 strbuf_release(&sb);
1919 /* Jump to the end */
1920 if (fseek(logfp, 0, SEEK_END) < 0)
1921 ret = error("cannot seek back reflog for %s: %s",
1922 refname, strerror(errno));
1924 while (!ret && 0 < pos) {
1930 /* Fill next block from the end */
1931 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1932 if (fseek(logfp, pos - cnt, SEEK_SET)) {
1933 ret = error("cannot seek back reflog for %s: %s",
1934 refname, strerror(errno));
1937 nread = fread(buf, cnt, 1, logfp);
1939 ret = error("cannot read %d bytes from reflog for %s: %s",
1940 cnt, refname, strerror(errno));
1945 scanp = endp = buf + cnt;
1946 if (at_tail && scanp[-1] == '\n')
1947 /* Looking at the final LF at the end of the file */
1951 while (buf < scanp) {
1953 * terminating LF of the previous line, or the beginning
1958 bp = find_beginning_of_line(buf, scanp);
1962 * The newline is the end of the previous line,
1963 * so we know we have complete line starting
1964 * at (bp + 1). Prefix it onto any prior data
1965 * we collected for the line and process it.
1967 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1970 ret = show_one_reflog_ent(&sb, fn, cb_data);
1976 * We are at the start of the buffer, and the
1977 * start of the file; there is no previous
1978 * line, and we have everything for this one.
1979 * Process it, and we can end the loop.
1981 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1982 ret = show_one_reflog_ent(&sb, fn, cb_data);
1989 * We are at the start of the buffer, and there
1990 * is more file to read backwards. Which means
1991 * we are in the middle of a line. Note that we
1992 * may get here even if *bp was a newline; that
1993 * just means we are at the exact end of the
1994 * previous line, rather than some spot in the
1997 * Save away what we have to be combined with
1998 * the data from the next read.
2000 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2007 die("BUG: reverse reflog parser had leftover data");
2010 strbuf_release(&sb);
2014 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2015 const char *refname,
2016 each_reflog_ent_fn fn, void *cb_data)
2018 struct files_ref_store *refs =
2019 files_downcast(ref_store, REF_STORE_READ,
2020 "for_each_reflog_ent");
2022 struct strbuf sb = STRBUF_INIT;
2025 files_reflog_path(refs, &sb, refname);
2026 logfp = fopen(sb.buf, "r");
2027 strbuf_release(&sb);
2031 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2032 ret = show_one_reflog_ent(&sb, fn, cb_data);
2034 strbuf_release(&sb);
2038 struct files_reflog_iterator {
2039 struct ref_iterator base;
2041 struct ref_store *ref_store;
2042 struct dir_iterator *dir_iterator;
2043 struct object_id oid;
2046 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2048 struct files_reflog_iterator *iter =
2049 (struct files_reflog_iterator *)ref_iterator;
2050 struct dir_iterator *diter = iter->dir_iterator;
2053 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2056 if (!S_ISREG(diter->st.st_mode))
2058 if (diter->basename[0] == '.')
2060 if (ends_with(diter->basename, ".lock"))
2063 if (refs_read_ref_full(iter->ref_store,
2064 diter->relative_path, 0,
2065 &iter->oid, &flags)) {
2066 error("bad ref for %s", diter->path.buf);
2070 iter->base.refname = diter->relative_path;
2071 iter->base.oid = &iter->oid;
2072 iter->base.flags = flags;
2076 iter->dir_iterator = NULL;
2077 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2082 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2083 struct object_id *peeled)
2085 die("BUG: ref_iterator_peel() called for reflog_iterator");
2088 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2090 struct files_reflog_iterator *iter =
2091 (struct files_reflog_iterator *)ref_iterator;
2094 if (iter->dir_iterator)
2095 ok = dir_iterator_abort(iter->dir_iterator);
2097 base_ref_iterator_free(ref_iterator);
2101 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2102 files_reflog_iterator_advance,
2103 files_reflog_iterator_peel,
2104 files_reflog_iterator_abort
2107 static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,
2110 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2111 struct ref_iterator *ref_iterator = &iter->base;
2112 struct strbuf sb = STRBUF_INIT;
2114 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable, 0);
2115 strbuf_addf(&sb, "%s/logs", gitdir);
2116 iter->dir_iterator = dir_iterator_begin(sb.buf);
2117 iter->ref_store = ref_store;
2118 strbuf_release(&sb);
2120 return ref_iterator;
2123 static enum iterator_selection reflog_iterator_select(
2124 struct ref_iterator *iter_worktree,
2125 struct ref_iterator *iter_common,
2128 if (iter_worktree) {
2130 * We're a bit loose here. We probably should ignore
2131 * common refs if they are accidentally added as
2132 * per-worktree refs.
2134 return ITER_SELECT_0;
2135 } else if (iter_common) {
2136 if (ref_type(iter_common->refname) == REF_TYPE_NORMAL)
2137 return ITER_SELECT_1;
2140 * The main ref store may contain main worktree's
2141 * per-worktree refs, which should be ignored
2148 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2150 struct files_ref_store *refs =
2151 files_downcast(ref_store, REF_STORE_READ,
2152 "reflog_iterator_begin");
2154 if (!strcmp(refs->gitdir, refs->gitcommondir)) {
2155 return reflog_iterator_begin(ref_store, refs->gitcommondir);
2157 return merge_ref_iterator_begin(
2159 reflog_iterator_begin(ref_store, refs->gitdir),
2160 reflog_iterator_begin(ref_store, refs->gitcommondir),
2161 reflog_iterator_select, refs);
2166 * If update is a direct update of head_ref (the reference pointed to
2167 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2169 static int split_head_update(struct ref_update *update,
2170 struct ref_transaction *transaction,
2171 const char *head_ref,
2172 struct string_list *affected_refnames,
2175 struct string_list_item *item;
2176 struct ref_update *new_update;
2178 if ((update->flags & REF_LOG_ONLY) ||
2179 (update->flags & REF_IS_PRUNING) ||
2180 (update->flags & REF_UPDATE_VIA_HEAD))
2183 if (strcmp(update->refname, head_ref))
2187 * First make sure that HEAD is not already in the
2188 * transaction. This check is O(lg N) in the transaction
2189 * size, but it happens at most once per transaction.
2191 if (string_list_has_string(affected_refnames, "HEAD")) {
2192 /* An entry already existed */
2194 "multiple updates for 'HEAD' (including one "
2195 "via its referent '%s') are not allowed",
2197 return TRANSACTION_NAME_CONFLICT;
2200 new_update = ref_transaction_add_update(
2201 transaction, "HEAD",
2202 update->flags | REF_LOG_ONLY | REF_NO_DEREF,
2203 &update->new_oid, &update->old_oid,
2207 * Add "HEAD". This insertion is O(N) in the transaction
2208 * size, but it happens at most once per transaction.
2209 * Add new_update->refname instead of a literal "HEAD".
2211 if (strcmp(new_update->refname, "HEAD"))
2212 BUG("%s unexpectedly not 'HEAD'", new_update->refname);
2213 item = string_list_insert(affected_refnames, new_update->refname);
2214 item->util = new_update;
2220 * update is for a symref that points at referent and doesn't have
2221 * REF_NO_DEREF set. Split it into two updates:
2222 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2223 * - A new, separate update for the referent reference
2224 * Note that the new update will itself be subject to splitting when
2225 * the iteration gets to it.
2227 static int split_symref_update(struct files_ref_store *refs,
2228 struct ref_update *update,
2229 const char *referent,
2230 struct ref_transaction *transaction,
2231 struct string_list *affected_refnames,
2234 struct string_list_item *item;
2235 struct ref_update *new_update;
2236 unsigned int new_flags;
2239 * First make sure that referent is not already in the
2240 * transaction. This check is O(lg N) in the transaction
2241 * size, but it happens at most once per symref in a
2244 if (string_list_has_string(affected_refnames, referent)) {
2245 /* An entry already exists */
2247 "multiple updates for '%s' (including one "
2248 "via symref '%s') are not allowed",
2249 referent, update->refname);
2250 return TRANSACTION_NAME_CONFLICT;
2253 new_flags = update->flags;
2254 if (!strcmp(update->refname, "HEAD")) {
2256 * Record that the new update came via HEAD, so that
2257 * when we process it, split_head_update() doesn't try
2258 * to add another reflog update for HEAD. Note that
2259 * this bit will be propagated if the new_update
2260 * itself needs to be split.
2262 new_flags |= REF_UPDATE_VIA_HEAD;
2265 new_update = ref_transaction_add_update(
2266 transaction, referent, new_flags,
2267 &update->new_oid, &update->old_oid,
2270 new_update->parent_update = update;
2273 * Change the symbolic ref update to log only. Also, it
2274 * doesn't need to check its old OID value, as that will be
2275 * done when new_update is processed.
2277 update->flags |= REF_LOG_ONLY | REF_NO_DEREF;
2278 update->flags &= ~REF_HAVE_OLD;
2281 * Add the referent. This insertion is O(N) in the transaction
2282 * size, but it happens at most once per symref in a
2283 * transaction. Make sure to add new_update->refname, which will
2284 * be valid as long as affected_refnames is in use, and NOT
2285 * referent, which might soon be freed by our caller.
2287 item = string_list_insert(affected_refnames, new_update->refname);
2289 BUG("%s unexpectedly found in affected_refnames",
2290 new_update->refname);
2291 item->util = new_update;
2297 * Return the refname under which update was originally requested.
2299 static const char *original_update_refname(struct ref_update *update)
2301 while (update->parent_update)
2302 update = update->parent_update;
2304 return update->refname;
2308 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2309 * are consistent with oid, which is the reference's current value. If
2310 * everything is OK, return 0; otherwise, write an error message to
2311 * err and return -1.
2313 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2316 if (!(update->flags & REF_HAVE_OLD) ||
2317 !oidcmp(oid, &update->old_oid))
2320 if (is_null_oid(&update->old_oid))
2321 strbuf_addf(err, "cannot lock ref '%s': "
2322 "reference already exists",
2323 original_update_refname(update));
2324 else if (is_null_oid(oid))
2325 strbuf_addf(err, "cannot lock ref '%s': "
2326 "reference is missing but expected %s",
2327 original_update_refname(update),
2328 oid_to_hex(&update->old_oid));
2330 strbuf_addf(err, "cannot lock ref '%s': "
2331 "is at %s but expected %s",
2332 original_update_refname(update),
2334 oid_to_hex(&update->old_oid));
2340 * Prepare for carrying out update:
2341 * - Lock the reference referred to by update.
2342 * - Read the reference under lock.
2343 * - Check that its old OID value (if specified) is correct, and in
2344 * any case record it in update->lock->old_oid for later use when
2345 * writing the reflog.
2346 * - If it is a symref update without REF_NO_DEREF, split it up into a
2347 * REF_LOG_ONLY update of the symref and add a separate update for
2348 * the referent to transaction.
2349 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2352 static int lock_ref_for_update(struct files_ref_store *refs,
2353 struct ref_update *update,
2354 struct ref_transaction *transaction,
2355 const char *head_ref,
2356 struct string_list *affected_refnames,
2359 struct strbuf referent = STRBUF_INIT;
2360 int mustexist = (update->flags & REF_HAVE_OLD) &&
2361 !is_null_oid(&update->old_oid);
2363 struct ref_lock *lock;
2365 files_assert_main_repository(refs, "lock_ref_for_update");
2367 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2368 update->flags |= REF_DELETING;
2371 ret = split_head_update(update, transaction, head_ref,
2372 affected_refnames, err);
2377 ret = lock_raw_ref(refs, update->refname, mustexist,
2378 affected_refnames, NULL,
2380 &update->type, err);
2384 reason = strbuf_detach(err, NULL);
2385 strbuf_addf(err, "cannot lock ref '%s': %s",
2386 original_update_refname(update), reason);
2391 update->backend_data = lock;
2393 if (update->type & REF_ISSYMREF) {
2394 if (update->flags & REF_NO_DEREF) {
2396 * We won't be reading the referent as part of
2397 * the transaction, so we have to read it here
2398 * to record and possibly check old_oid:
2400 if (refs_read_ref_full(&refs->base,
2402 &lock->old_oid, NULL)) {
2403 if (update->flags & REF_HAVE_OLD) {
2404 strbuf_addf(err, "cannot lock ref '%s': "
2405 "error reading reference",
2406 original_update_refname(update));
2407 ret = TRANSACTION_GENERIC_ERROR;
2410 } else if (check_old_oid(update, &lock->old_oid, err)) {
2411 ret = TRANSACTION_GENERIC_ERROR;
2416 * Create a new update for the reference this
2417 * symref is pointing at. Also, we will record
2418 * and verify old_oid for this update as part
2419 * of processing the split-off update, so we
2420 * don't have to do it here.
2422 ret = split_symref_update(refs, update,
2423 referent.buf, transaction,
2424 affected_refnames, err);
2429 struct ref_update *parent_update;
2431 if (check_old_oid(update, &lock->old_oid, err)) {
2432 ret = TRANSACTION_GENERIC_ERROR;
2437 * If this update is happening indirectly because of a
2438 * symref update, record the old OID in the parent
2441 for (parent_update = update->parent_update;
2443 parent_update = parent_update->parent_update) {
2444 struct ref_lock *parent_lock = parent_update->backend_data;
2445 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2449 if ((update->flags & REF_HAVE_NEW) &&
2450 !(update->flags & REF_DELETING) &&
2451 !(update->flags & REF_LOG_ONLY)) {
2452 if (!(update->type & REF_ISSYMREF) &&
2453 !oidcmp(&lock->old_oid, &update->new_oid)) {
2455 * The reference already has the desired
2456 * value, so we don't need to write it.
2458 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2460 char *write_err = strbuf_detach(err, NULL);
2463 * The lock was freed upon failure of
2464 * write_ref_to_lockfile():
2466 update->backend_data = NULL;
2468 "cannot update ref '%s': %s",
2469 update->refname, write_err);
2471 ret = TRANSACTION_GENERIC_ERROR;
2474 update->flags |= REF_NEEDS_COMMIT;
2477 if (!(update->flags & REF_NEEDS_COMMIT)) {
2479 * We didn't call write_ref_to_lockfile(), so
2480 * the lockfile is still open. Close it to
2481 * free up the file descriptor:
2483 if (close_ref_gently(lock)) {
2484 strbuf_addf(err, "couldn't close '%s.lock'",
2486 ret = TRANSACTION_GENERIC_ERROR;
2492 strbuf_release(&referent);
2496 struct files_transaction_backend_data {
2497 struct ref_transaction *packed_transaction;
2498 int packed_refs_locked;
2502 * Unlock any references in `transaction` that are still locked, and
2503 * mark the transaction closed.
2505 static void files_transaction_cleanup(struct files_ref_store *refs,
2506 struct ref_transaction *transaction)
2509 struct files_transaction_backend_data *backend_data =
2510 transaction->backend_data;
2511 struct strbuf err = STRBUF_INIT;
2513 for (i = 0; i < transaction->nr; i++) {
2514 struct ref_update *update = transaction->updates[i];
2515 struct ref_lock *lock = update->backend_data;
2519 update->backend_data = NULL;
2523 if (backend_data->packed_transaction &&
2524 ref_transaction_abort(backend_data->packed_transaction, &err)) {
2525 error("error aborting transaction: %s", err.buf);
2526 strbuf_release(&err);
2529 if (backend_data->packed_refs_locked)
2530 packed_refs_unlock(refs->packed_ref_store);
2534 transaction->state = REF_TRANSACTION_CLOSED;
2537 static int files_transaction_prepare(struct ref_store *ref_store,
2538 struct ref_transaction *transaction,
2541 struct files_ref_store *refs =
2542 files_downcast(ref_store, REF_STORE_WRITE,
2543 "ref_transaction_prepare");
2546 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2547 char *head_ref = NULL;
2549 struct files_transaction_backend_data *backend_data;
2550 struct ref_transaction *packed_transaction = NULL;
2554 if (!transaction->nr)
2557 backend_data = xcalloc(1, sizeof(*backend_data));
2558 transaction->backend_data = backend_data;
2561 * Fail if a refname appears more than once in the
2562 * transaction. (If we end up splitting up any updates using
2563 * split_symref_update() or split_head_update(), those
2564 * functions will check that the new updates don't have the
2565 * same refname as any existing ones.) Also fail if any of the
2566 * updates use REF_IS_PRUNING without REF_NO_DEREF.
2568 for (i = 0; i < transaction->nr; i++) {
2569 struct ref_update *update = transaction->updates[i];
2570 struct string_list_item *item =
2571 string_list_append(&affected_refnames, update->refname);
2573 if ((update->flags & REF_IS_PRUNING) &&
2574 !(update->flags & REF_NO_DEREF))
2575 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2578 * We store a pointer to update in item->util, but at
2579 * the moment we never use the value of this field
2580 * except to check whether it is non-NULL.
2582 item->util = update;
2584 string_list_sort(&affected_refnames);
2585 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2586 ret = TRANSACTION_GENERIC_ERROR;
2591 * Special hack: If a branch is updated directly and HEAD
2592 * points to it (may happen on the remote side of a push
2593 * for example) then logically the HEAD reflog should be
2596 * A generic solution would require reverse symref lookups,
2597 * but finding all symrefs pointing to a given branch would be
2598 * rather costly for this rare event (the direct update of a
2599 * branch) to be worth it. So let's cheat and check with HEAD
2600 * only, which should cover 99% of all usage scenarios (even
2601 * 100% of the default ones).
2603 * So if HEAD is a symbolic reference, then record the name of
2604 * the reference that it points to. If we see an update of
2605 * head_ref within the transaction, then split_head_update()
2606 * arranges for the reflog of HEAD to be updated, too.
2608 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2609 RESOLVE_REF_NO_RECURSE,
2612 if (head_ref && !(head_type & REF_ISSYMREF)) {
2613 FREE_AND_NULL(head_ref);
2617 * Acquire all locks, verify old values if provided, check
2618 * that new values are valid, and write new values to the
2619 * lockfiles, ready to be activated. Only keep one lockfile
2620 * open at a time to avoid running out of file descriptors.
2621 * Note that lock_ref_for_update() might append more updates
2622 * to the transaction.
2624 for (i = 0; i < transaction->nr; i++) {
2625 struct ref_update *update = transaction->updates[i];
2627 ret = lock_ref_for_update(refs, update, transaction,
2628 head_ref, &affected_refnames, err);
2632 if (update->flags & REF_DELETING &&
2633 !(update->flags & REF_LOG_ONLY) &&
2634 !(update->flags & REF_IS_PRUNING)) {
2636 * This reference has to be deleted from
2637 * packed-refs if it exists there.
2639 if (!packed_transaction) {
2640 packed_transaction = ref_store_transaction_begin(
2641 refs->packed_ref_store, err);
2642 if (!packed_transaction) {
2643 ret = TRANSACTION_GENERIC_ERROR;
2647 backend_data->packed_transaction =
2651 ref_transaction_add_update(
2652 packed_transaction, update->refname,
2653 REF_HAVE_NEW | REF_NO_DEREF,
2654 &update->new_oid, NULL,
2659 if (packed_transaction) {
2660 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2661 ret = TRANSACTION_GENERIC_ERROR;
2664 backend_data->packed_refs_locked = 1;
2666 if (is_packed_transaction_needed(refs->packed_ref_store,
2667 packed_transaction)) {
2668 ret = ref_transaction_prepare(packed_transaction, err);
2671 * We can skip rewriting the `packed-refs`
2672 * file. But we do need to leave it locked, so
2673 * that somebody else doesn't pack a reference
2674 * that we are trying to delete.
2676 if (ref_transaction_abort(packed_transaction, err)) {
2677 ret = TRANSACTION_GENERIC_ERROR;
2680 backend_data->packed_transaction = NULL;
2686 string_list_clear(&affected_refnames, 0);
2689 files_transaction_cleanup(refs, transaction);
2691 transaction->state = REF_TRANSACTION_PREPARED;
2696 static int files_transaction_finish(struct ref_store *ref_store,
2697 struct ref_transaction *transaction,
2700 struct files_ref_store *refs =
2701 files_downcast(ref_store, 0, "ref_transaction_finish");
2704 struct strbuf sb = STRBUF_INIT;
2705 struct files_transaction_backend_data *backend_data;
2706 struct ref_transaction *packed_transaction;
2711 if (!transaction->nr) {
2712 transaction->state = REF_TRANSACTION_CLOSED;
2716 backend_data = transaction->backend_data;
2717 packed_transaction = backend_data->packed_transaction;
2719 /* Perform updates first so live commits remain referenced */
2720 for (i = 0; i < transaction->nr; i++) {
2721 struct ref_update *update = transaction->updates[i];
2722 struct ref_lock *lock = update->backend_data;
2724 if (update->flags & REF_NEEDS_COMMIT ||
2725 update->flags & REF_LOG_ONLY) {
2726 if (files_log_ref_write(refs,
2730 update->msg, update->flags,
2732 char *old_msg = strbuf_detach(err, NULL);
2734 strbuf_addf(err, "cannot update the ref '%s': %s",
2735 lock->ref_name, old_msg);
2738 update->backend_data = NULL;
2739 ret = TRANSACTION_GENERIC_ERROR;
2743 if (update->flags & REF_NEEDS_COMMIT) {
2744 clear_loose_ref_cache(refs);
2745 if (commit_ref(lock)) {
2746 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2748 update->backend_data = NULL;
2749 ret = TRANSACTION_GENERIC_ERROR;
2756 * Now that updates are safely completed, we can perform
2757 * deletes. First delete the reflogs of any references that
2758 * will be deleted, since (in the unexpected event of an
2759 * error) leaving a reference without a reflog is less bad
2760 * than leaving a reflog without a reference (the latter is a
2761 * mildly invalid repository state):
2763 for (i = 0; i < transaction->nr; i++) {
2764 struct ref_update *update = transaction->updates[i];
2765 if (update->flags & REF_DELETING &&
2766 !(update->flags & REF_LOG_ONLY) &&
2767 !(update->flags & REF_IS_PRUNING)) {
2769 files_reflog_path(refs, &sb, update->refname);
2770 if (!unlink_or_warn(sb.buf))
2771 try_remove_empty_parents(refs, update->refname,
2772 REMOVE_EMPTY_PARENTS_REFLOG);
2777 * Perform deletes now that updates are safely completed.
2779 * First delete any packed versions of the references, while
2780 * retaining the packed-refs lock:
2782 if (packed_transaction) {
2783 ret = ref_transaction_commit(packed_transaction, err);
2784 ref_transaction_free(packed_transaction);
2785 packed_transaction = NULL;
2786 backend_data->packed_transaction = NULL;
2791 /* Now delete the loose versions of the references: */
2792 for (i = 0; i < transaction->nr; i++) {
2793 struct ref_update *update = transaction->updates[i];
2794 struct ref_lock *lock = update->backend_data;
2796 if (update->flags & REF_DELETING &&
2797 !(update->flags & REF_LOG_ONLY)) {
2798 if (!(update->type & REF_ISPACKED) ||
2799 update->type & REF_ISSYMREF) {
2800 /* It is a loose reference. */
2802 files_ref_path(refs, &sb, lock->ref_name);
2803 if (unlink_or_msg(sb.buf, err)) {
2804 ret = TRANSACTION_GENERIC_ERROR;
2807 update->flags |= REF_DELETED_LOOSE;
2812 clear_loose_ref_cache(refs);
2815 files_transaction_cleanup(refs, transaction);
2817 for (i = 0; i < transaction->nr; i++) {
2818 struct ref_update *update = transaction->updates[i];
2820 if (update->flags & REF_DELETED_LOOSE) {
2822 * The loose reference was deleted. Delete any
2823 * empty parent directories. (Note that this
2824 * can only work because we have already
2825 * removed the lockfile.)
2827 try_remove_empty_parents(refs, update->refname,
2828 REMOVE_EMPTY_PARENTS_REF);
2832 strbuf_release(&sb);
2836 static int files_transaction_abort(struct ref_store *ref_store,
2837 struct ref_transaction *transaction,
2840 struct files_ref_store *refs =
2841 files_downcast(ref_store, 0, "ref_transaction_abort");
2843 files_transaction_cleanup(refs, transaction);
2847 static int ref_present(const char *refname,
2848 const struct object_id *oid, int flags, void *cb_data)
2850 struct string_list *affected_refnames = cb_data;
2852 return string_list_has_string(affected_refnames, refname);
2855 static int files_initial_transaction_commit(struct ref_store *ref_store,
2856 struct ref_transaction *transaction,
2859 struct files_ref_store *refs =
2860 files_downcast(ref_store, REF_STORE_WRITE,
2861 "initial_ref_transaction_commit");
2864 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2865 struct ref_transaction *packed_transaction = NULL;
2869 if (transaction->state != REF_TRANSACTION_OPEN)
2870 die("BUG: commit called for transaction that is not open");
2872 /* Fail if a refname appears more than once in the transaction: */
2873 for (i = 0; i < transaction->nr; i++)
2874 string_list_append(&affected_refnames,
2875 transaction->updates[i]->refname);
2876 string_list_sort(&affected_refnames);
2877 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2878 ret = TRANSACTION_GENERIC_ERROR;
2883 * It's really undefined to call this function in an active
2884 * repository or when there are existing references: we are
2885 * only locking and changing packed-refs, so (1) any
2886 * simultaneous processes might try to change a reference at
2887 * the same time we do, and (2) any existing loose versions of
2888 * the references that we are setting would have precedence
2889 * over our values. But some remote helpers create the remote
2890 * "HEAD" and "master" branches before calling this function,
2891 * so here we really only check that none of the references
2892 * that we are creating already exists.
2894 if (refs_for_each_rawref(&refs->base, ref_present,
2895 &affected_refnames))
2896 die("BUG: initial ref transaction called with existing refs");
2898 packed_transaction = ref_store_transaction_begin(refs->packed_ref_store, err);
2899 if (!packed_transaction) {
2900 ret = TRANSACTION_GENERIC_ERROR;
2904 for (i = 0; i < transaction->nr; i++) {
2905 struct ref_update *update = transaction->updates[i];
2907 if ((update->flags & REF_HAVE_OLD) &&
2908 !is_null_oid(&update->old_oid))
2909 die("BUG: initial ref transaction with old_sha1 set");
2910 if (refs_verify_refname_available(&refs->base, update->refname,
2911 &affected_refnames, NULL,
2913 ret = TRANSACTION_NAME_CONFLICT;
2918 * Add a reference creation for this reference to the
2919 * packed-refs transaction:
2921 ref_transaction_add_update(packed_transaction, update->refname,
2922 update->flags & ~REF_HAVE_OLD,
2923 &update->new_oid, &update->old_oid,
2927 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2928 ret = TRANSACTION_GENERIC_ERROR;
2932 if (initial_ref_transaction_commit(packed_transaction, err)) {
2933 ret = TRANSACTION_GENERIC_ERROR;
2938 if (packed_transaction)
2939 ref_transaction_free(packed_transaction);
2940 packed_refs_unlock(refs->packed_ref_store);
2941 transaction->state = REF_TRANSACTION_CLOSED;
2942 string_list_clear(&affected_refnames, 0);
2946 struct expire_reflog_cb {
2948 reflog_expiry_should_prune_fn *should_prune_fn;
2951 struct object_id last_kept_oid;
2954 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
2955 const char *email, timestamp_t timestamp, int tz,
2956 const char *message, void *cb_data)
2958 struct expire_reflog_cb *cb = cb_data;
2959 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
2961 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
2962 ooid = &cb->last_kept_oid;
2964 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
2965 message, policy_cb)) {
2967 printf("would prune %s", message);
2968 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2969 printf("prune %s", message);
2972 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
2973 oid_to_hex(ooid), oid_to_hex(noid),
2974 email, timestamp, tz, message);
2975 oidcpy(&cb->last_kept_oid, noid);
2977 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2978 printf("keep %s", message);
2983 static int files_reflog_expire(struct ref_store *ref_store,
2984 const char *refname, const struct object_id *oid,
2986 reflog_expiry_prepare_fn prepare_fn,
2987 reflog_expiry_should_prune_fn should_prune_fn,
2988 reflog_expiry_cleanup_fn cleanup_fn,
2989 void *policy_cb_data)
2991 struct files_ref_store *refs =
2992 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
2993 static struct lock_file reflog_lock;
2994 struct expire_reflog_cb cb;
2995 struct ref_lock *lock;
2996 struct strbuf log_file_sb = STRBUF_INIT;
3000 struct strbuf err = STRBUF_INIT;
3002 memset(&cb, 0, sizeof(cb));
3004 cb.policy_cb = policy_cb_data;
3005 cb.should_prune_fn = should_prune_fn;
3008 * The reflog file is locked by holding the lock on the
3009 * reference itself, plus we might need to update the
3010 * reference if --updateref was specified:
3012 lock = lock_ref_oid_basic(refs, refname, oid,
3013 NULL, NULL, REF_NO_DEREF,
3016 error("cannot lock ref '%s': %s", refname, err.buf);
3017 strbuf_release(&err);
3020 if (!refs_reflog_exists(ref_store, refname)) {
3025 files_reflog_path(refs, &log_file_sb, refname);
3026 log_file = strbuf_detach(&log_file_sb, NULL);
3027 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3029 * Even though holding $GIT_DIR/logs/$reflog.lock has
3030 * no locking implications, we use the lock_file
3031 * machinery here anyway because it does a lot of the
3032 * work we need, including cleaning up if the program
3033 * exits unexpectedly.
3035 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3036 struct strbuf err = STRBUF_INIT;
3037 unable_to_lock_message(log_file, errno, &err);
3038 error("%s", err.buf);
3039 strbuf_release(&err);
3042 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3044 error("cannot fdopen %s (%s)",
3045 get_lock_file_path(&reflog_lock), strerror(errno));
3050 (*prepare_fn)(refname, oid, cb.policy_cb);
3051 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3052 (*cleanup_fn)(cb.policy_cb);
3054 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3056 * It doesn't make sense to adjust a reference pointed
3057 * to by a symbolic ref based on expiring entries in
3058 * the symbolic reference's reflog. Nor can we update
3059 * a reference if there are no remaining reflog
3062 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3063 !(type & REF_ISSYMREF) &&
3064 !is_null_oid(&cb.last_kept_oid);
3066 if (close_lock_file_gently(&reflog_lock)) {
3067 status |= error("couldn't write %s: %s", log_file,
3069 rollback_lock_file(&reflog_lock);
3070 } else if (update &&
3071 (write_in_full(get_lock_file_fd(&lock->lk),
3072 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) < 0 ||
3073 write_str_in_full(get_lock_file_fd(&lock->lk), "\n") < 0 ||
3074 close_ref_gently(lock) < 0)) {
3075 status |= error("couldn't write %s",
3076 get_lock_file_path(&lock->lk));
3077 rollback_lock_file(&reflog_lock);
3078 } else if (commit_lock_file(&reflog_lock)) {
3079 status |= error("unable to write reflog '%s' (%s)",
3080 log_file, strerror(errno));
3081 } else if (update && commit_ref(lock)) {
3082 status |= error("couldn't set %s", lock->ref_name);
3090 rollback_lock_file(&reflog_lock);
3096 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3098 struct files_ref_store *refs =
3099 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3100 struct strbuf sb = STRBUF_INIT;
3103 * Create .git/refs/{heads,tags}
3105 files_ref_path(refs, &sb, "refs/heads");
3106 safe_create_dir(sb.buf, 1);
3109 files_ref_path(refs, &sb, "refs/tags");
3110 safe_create_dir(sb.buf, 1);
3112 strbuf_release(&sb);
3116 struct ref_storage_be refs_be_files = {
3119 files_ref_store_create,
3121 files_transaction_prepare,
3122 files_transaction_finish,
3123 files_transaction_abort,
3124 files_initial_transaction_commit,
3127 files_create_symref,
3132 files_ref_iterator_begin,
3135 files_reflog_iterator_begin,
3136 files_for_each_reflog_ent,
3137 files_for_each_reflog_ent_reverse,
3138 files_reflog_exists,
3139 files_create_reflog,
3140 files_delete_reflog,