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;
64 struct files_ref_store {
65 struct ref_store base;
66 unsigned int store_flags;
71 struct ref_cache *loose;
73 struct ref_store *packed_ref_store;
76 static void clear_loose_ref_cache(struct files_ref_store *refs)
79 free_ref_cache(refs->loose);
85 * Create a new submodule ref cache and add it to the internal
88 static struct ref_store *files_ref_store_create(const char *gitdir,
91 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
92 struct ref_store *ref_store = (struct ref_store *)refs;
93 struct strbuf sb = STRBUF_INIT;
95 base_ref_store_init(ref_store, &refs_be_files);
96 refs->store_flags = flags;
98 refs->gitdir = xstrdup(gitdir);
99 get_common_dir_noenv(&sb, gitdir);
100 refs->gitcommondir = strbuf_detach(&sb, NULL);
101 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
102 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
109 * Die if refs is not the main ref store. caller is used in any
110 * necessary error messages.
112 static void files_assert_main_repository(struct files_ref_store *refs,
115 if (refs->store_flags & REF_STORE_MAIN)
118 die("BUG: operation %s only allowed for main ref store", caller);
122 * Downcast ref_store to files_ref_store. Die if ref_store is not a
123 * files_ref_store. required_flags is compared with ref_store's
124 * store_flags to ensure the ref_store has all required capabilities.
125 * "caller" is used in any necessary error messages.
127 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
128 unsigned int required_flags,
131 struct files_ref_store *refs;
133 if (ref_store->be != &refs_be_files)
134 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
135 ref_store->be->name, caller);
137 refs = (struct files_ref_store *)ref_store;
139 if ((refs->store_flags & required_flags) != required_flags)
140 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
141 caller, required_flags, refs->store_flags);
146 static void files_reflog_path(struct files_ref_store *refs,
150 switch (ref_type(refname)) {
151 case REF_TYPE_PER_WORKTREE:
152 case REF_TYPE_PSEUDOREF:
153 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
155 case REF_TYPE_NORMAL:
156 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
159 die("BUG: unknown ref type %d of ref %s",
160 ref_type(refname), refname);
164 static void files_ref_path(struct files_ref_store *refs,
168 switch (ref_type(refname)) {
169 case REF_TYPE_PER_WORKTREE:
170 case REF_TYPE_PSEUDOREF:
171 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
173 case REF_TYPE_NORMAL:
174 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
177 die("BUG: unknown ref type %d of ref %s",
178 ref_type(refname), refname);
183 * Read the loose references from the namespace dirname into dir
184 * (without recursing). dirname must end with '/'. dir must be the
185 * directory entry corresponding to dirname.
187 static void loose_fill_ref_dir(struct ref_store *ref_store,
188 struct ref_dir *dir, const char *dirname)
190 struct files_ref_store *refs =
191 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
194 int dirnamelen = strlen(dirname);
195 struct strbuf refname;
196 struct strbuf path = STRBUF_INIT;
199 files_ref_path(refs, &path, dirname);
200 path_baselen = path.len;
202 d = opendir(path.buf);
204 strbuf_release(&path);
208 strbuf_init(&refname, dirnamelen + 257);
209 strbuf_add(&refname, dirname, dirnamelen);
211 while ((de = readdir(d)) != NULL) {
212 struct object_id oid;
216 if (de->d_name[0] == '.')
218 if (ends_with(de->d_name, ".lock"))
220 strbuf_addstr(&refname, de->d_name);
221 strbuf_addstr(&path, de->d_name);
222 if (stat(path.buf, &st) < 0) {
223 ; /* silently ignore */
224 } else if (S_ISDIR(st.st_mode)) {
225 strbuf_addch(&refname, '/');
226 add_entry_to_dir(dir,
227 create_dir_entry(dir->cache, refname.buf,
230 if (!refs_resolve_ref_unsafe(&refs->base,
235 flag |= REF_ISBROKEN;
236 } else if (is_null_oid(&oid)) {
238 * It is so astronomically unlikely
239 * that null_oid is the OID of an
240 * actual object that we consider its
241 * appearance in a loose reference
242 * file to be repo corruption
243 * (probably due to a software bug).
245 flag |= REF_ISBROKEN;
248 if (check_refname_format(refname.buf,
249 REFNAME_ALLOW_ONELEVEL)) {
250 if (!refname_is_safe(refname.buf))
251 die("loose refname is dangerous: %s", refname.buf);
253 flag |= REF_BAD_NAME | REF_ISBROKEN;
255 add_entry_to_dir(dir,
256 create_ref_entry(refname.buf, &oid, flag));
258 strbuf_setlen(&refname, dirnamelen);
259 strbuf_setlen(&path, path_baselen);
261 strbuf_release(&refname);
262 strbuf_release(&path);
266 * Manually add refs/bisect, which, being per-worktree, might
267 * not appear in the directory listing for refs/ in the main
270 if (!strcmp(dirname, "refs/")) {
271 int pos = search_ref_dir(dir, "refs/bisect/", 12);
274 struct ref_entry *child_entry = create_dir_entry(
275 dir->cache, "refs/bisect/", 12, 1);
276 add_entry_to_dir(dir, child_entry);
281 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
285 * Mark the top-level directory complete because we
286 * are about to read the only subdirectory that can
289 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
291 /* We're going to fill the top level ourselves: */
292 refs->loose->root->flag &= ~REF_INCOMPLETE;
295 * Add an incomplete entry for "refs/" (to be filled
298 add_entry_to_dir(get_ref_dir(refs->loose->root),
299 create_dir_entry(refs->loose, "refs/", 5, 1));
304 static int files_read_raw_ref(struct ref_store *ref_store,
305 const char *refname, struct object_id *oid,
306 struct strbuf *referent, unsigned int *type)
308 struct files_ref_store *refs =
309 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
310 struct strbuf sb_contents = STRBUF_INIT;
311 struct strbuf sb_path = STRBUF_INIT;
319 int remaining_retries = 3;
322 strbuf_reset(&sb_path);
324 files_ref_path(refs, &sb_path, refname);
330 * We might have to loop back here to avoid a race
331 * condition: first we lstat() the file, then we try
332 * to read it as a link or as a file. But if somebody
333 * changes the type of the file (file <-> directory
334 * <-> symlink) between the lstat() and reading, then
335 * we don't want to report that as an error but rather
336 * try again starting with the lstat().
338 * We'll keep a count of the retries, though, just to avoid
339 * any confusing situation sending us into an infinite loop.
342 if (remaining_retries-- <= 0)
345 if (lstat(path, &st) < 0) {
348 if (refs_read_raw_ref(refs->packed_ref_store, refname,
349 oid, referent, type)) {
357 /* Follow "normalized" - ie "refs/.." symlinks by hand */
358 if (S_ISLNK(st.st_mode)) {
359 strbuf_reset(&sb_contents);
360 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
361 if (errno == ENOENT || errno == EINVAL)
362 /* inconsistent with lstat; retry */
367 if (starts_with(sb_contents.buf, "refs/") &&
368 !check_refname_format(sb_contents.buf, 0)) {
369 strbuf_swap(&sb_contents, referent);
370 *type |= REF_ISSYMREF;
375 * It doesn't look like a refname; fall through to just
376 * treating it like a non-symlink, and reading whatever it
381 /* Is it a directory? */
382 if (S_ISDIR(st.st_mode)) {
384 * Even though there is a directory where the loose
385 * ref is supposed to be, there could still be a
388 if (refs_read_raw_ref(refs->packed_ref_store, refname,
389 oid, referent, type)) {
398 * Anything else, just open it and try to use it as
401 fd = open(path, O_RDONLY);
403 if (errno == ENOENT && !S_ISLNK(st.st_mode))
404 /* inconsistent with lstat; retry */
409 strbuf_reset(&sb_contents);
410 if (strbuf_read(&sb_contents, fd, 256) < 0) {
411 int save_errno = errno;
417 strbuf_rtrim(&sb_contents);
418 buf = sb_contents.buf;
419 if (starts_with(buf, "ref:")) {
421 while (isspace(*buf))
424 strbuf_reset(referent);
425 strbuf_addstr(referent, buf);
426 *type |= REF_ISSYMREF;
432 * Please note that FETCH_HEAD has additional
433 * data after the sha.
435 if (parse_oid_hex(buf, oid, &p) ||
436 (*p != '\0' && !isspace(*p))) {
437 *type |= REF_ISBROKEN;
446 strbuf_release(&sb_path);
447 strbuf_release(&sb_contents);
452 static void unlock_ref(struct ref_lock *lock)
454 rollback_lock_file(&lock->lk);
455 free(lock->ref_name);
460 * Lock refname, without following symrefs, and set *lock_p to point
461 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
462 * and type similarly to read_raw_ref().
464 * The caller must verify that refname is a "safe" reference name (in
465 * the sense of refname_is_safe()) before calling this function.
467 * If the reference doesn't already exist, verify that refname doesn't
468 * have a D/F conflict with any existing references. extras and skip
469 * are passed to refs_verify_refname_available() for this check.
471 * If mustexist is not set and the reference is not found or is
472 * broken, lock the reference anyway but clear old_oid.
474 * Return 0 on success. On failure, write an error message to err and
475 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
477 * Implementation note: This function is basically
482 * but it includes a lot more code to
483 * - Deal with possible races with other processes
484 * - Avoid calling refs_verify_refname_available() when it can be
485 * avoided, namely if we were successfully able to read the ref
486 * - Generate informative error messages in the case of failure
488 static int lock_raw_ref(struct files_ref_store *refs,
489 const char *refname, int mustexist,
490 const struct string_list *extras,
491 const struct string_list *skip,
492 struct ref_lock **lock_p,
493 struct strbuf *referent,
497 struct ref_lock *lock;
498 struct strbuf ref_file = STRBUF_INIT;
499 int attempts_remaining = 3;
500 int ret = TRANSACTION_GENERIC_ERROR;
503 files_assert_main_repository(refs, "lock_raw_ref");
507 /* First lock the file so it can't change out from under us. */
509 *lock_p = lock = xcalloc(1, sizeof(*lock));
511 lock->ref_name = xstrdup(refname);
512 files_ref_path(refs, &ref_file, refname);
515 switch (safe_create_leading_directories(ref_file.buf)) {
520 * Suppose refname is "refs/foo/bar". We just failed
521 * to create the containing directory, "refs/foo",
522 * because there was a non-directory in the way. This
523 * indicates a D/F conflict, probably because of
524 * another reference such as "refs/foo". There is no
525 * reason to expect this error to be transitory.
527 if (refs_verify_refname_available(&refs->base, refname,
528 extras, skip, err)) {
531 * To the user the relevant error is
532 * that the "mustexist" reference is
536 strbuf_addf(err, "unable to resolve reference '%s'",
540 * The error message set by
541 * refs_verify_refname_available() is
544 ret = TRANSACTION_NAME_CONFLICT;
548 * The file that is in the way isn't a loose
549 * reference. Report it as a low-level
552 strbuf_addf(err, "unable to create lock file %s.lock; "
553 "non-directory in the way",
558 /* Maybe another process was tidying up. Try again. */
559 if (--attempts_remaining > 0)
563 strbuf_addf(err, "unable to create directory for %s",
568 if (hold_lock_file_for_update_timeout(
569 &lock->lk, ref_file.buf, LOCK_NO_DEREF,
570 get_files_ref_lock_timeout_ms()) < 0) {
571 if (errno == ENOENT && --attempts_remaining > 0) {
573 * Maybe somebody just deleted one of the
574 * directories leading to ref_file. Try
579 unable_to_lock_message(ref_file.buf, errno, err);
585 * Now we hold the lock and can read the reference without
586 * fear that its value will change.
589 if (files_read_raw_ref(&refs->base, refname,
590 &lock->old_oid, referent, type)) {
591 if (errno == ENOENT) {
593 /* Garden variety missing reference. */
594 strbuf_addf(err, "unable to resolve reference '%s'",
599 * Reference is missing, but that's OK. We
600 * know that there is not a conflict with
601 * another loose reference because
602 * (supposing that we are trying to lock
603 * reference "refs/foo/bar"):
605 * - We were successfully able to create
606 * the lockfile refs/foo/bar.lock, so we
607 * know there cannot be a loose reference
610 * - We got ENOENT and not EISDIR, so we
611 * know that there cannot be a loose
612 * reference named "refs/foo/bar/baz".
615 } else if (errno == EISDIR) {
617 * There is a directory in the way. It might have
618 * contained references that have been deleted. If
619 * we don't require that the reference already
620 * exists, try to remove the directory so that it
621 * doesn't cause trouble when we want to rename the
622 * lockfile into place later.
625 /* Garden variety missing reference. */
626 strbuf_addf(err, "unable to resolve reference '%s'",
629 } else if (remove_dir_recursively(&ref_file,
630 REMOVE_DIR_EMPTY_ONLY)) {
631 if (refs_verify_refname_available(
632 &refs->base, refname,
633 extras, skip, err)) {
635 * The error message set by
636 * verify_refname_available() is OK.
638 ret = TRANSACTION_NAME_CONFLICT;
642 * We can't delete the directory,
643 * but we also don't know of any
644 * references that it should
647 strbuf_addf(err, "there is a non-empty directory '%s' "
648 "blocking reference '%s'",
649 ref_file.buf, refname);
653 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
654 strbuf_addf(err, "unable to resolve reference '%s': "
655 "reference broken", refname);
658 strbuf_addf(err, "unable to resolve reference '%s': %s",
659 refname, strerror(errno));
664 * If the ref did not exist and we are creating it,
665 * make sure there is no existing packed ref that
666 * conflicts with refname:
668 if (refs_verify_refname_available(
669 refs->packed_ref_store, refname,
682 strbuf_release(&ref_file);
686 struct files_ref_iterator {
687 struct ref_iterator base;
689 struct ref_iterator *iter0;
693 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
695 struct files_ref_iterator *iter =
696 (struct files_ref_iterator *)ref_iterator;
699 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
700 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
701 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
704 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
705 !ref_resolves_to_object(iter->iter0->refname,
710 iter->base.refname = iter->iter0->refname;
711 iter->base.oid = iter->iter0->oid;
712 iter->base.flags = iter->iter0->flags;
717 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
723 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
724 struct object_id *peeled)
726 struct files_ref_iterator *iter =
727 (struct files_ref_iterator *)ref_iterator;
729 return ref_iterator_peel(iter->iter0, peeled);
732 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
734 struct files_ref_iterator *iter =
735 (struct files_ref_iterator *)ref_iterator;
739 ok = ref_iterator_abort(iter->iter0);
741 base_ref_iterator_free(ref_iterator);
745 static struct ref_iterator_vtable files_ref_iterator_vtable = {
746 files_ref_iterator_advance,
747 files_ref_iterator_peel,
748 files_ref_iterator_abort
751 static struct ref_iterator *files_ref_iterator_begin(
752 struct ref_store *ref_store,
753 const char *prefix, unsigned int flags)
755 struct files_ref_store *refs;
756 struct ref_iterator *loose_iter, *packed_iter, *overlay_iter;
757 struct files_ref_iterator *iter;
758 struct ref_iterator *ref_iterator;
759 unsigned int required_flags = REF_STORE_READ;
761 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
762 required_flags |= REF_STORE_ODB;
764 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
767 * We must make sure that all loose refs are read before
768 * accessing the packed-refs file; this avoids a race
769 * condition if loose refs are migrated to the packed-refs
770 * file by a simultaneous process, but our in-memory view is
771 * from before the migration. We ensure this as follows:
772 * First, we call start the loose refs iteration with its
773 * `prime_ref` argument set to true. This causes the loose
774 * references in the subtree to be pre-read into the cache.
775 * (If they've already been read, that's OK; we only need to
776 * guarantee that they're read before the packed refs, not
777 * *how much* before.) After that, we call
778 * packed_ref_iterator_begin(), which internally checks
779 * whether the packed-ref cache is up to date with what is on
780 * disk, and re-reads it if not.
783 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
787 * The packed-refs file might contain broken references, for
788 * example an old version of a reference that points at an
789 * object that has since been garbage-collected. This is OK as
790 * long as there is a corresponding loose reference that
791 * overrides it, and we don't want to emit an error message in
792 * this case. So ask the packed_ref_store for all of its
793 * references, and (if needed) do our own check for broken
794 * ones in files_ref_iterator_advance(), after we have merged
795 * the packed and loose references.
797 packed_iter = refs_ref_iterator_begin(
798 refs->packed_ref_store, prefix, 0,
799 DO_FOR_EACH_INCLUDE_BROKEN);
801 overlay_iter = overlay_ref_iterator_begin(loose_iter, packed_iter);
803 iter = xcalloc(1, sizeof(*iter));
804 ref_iterator = &iter->base;
805 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable,
806 overlay_iter->ordered);
807 iter->iter0 = overlay_iter;
814 * Verify that the reference locked by lock has the value old_oid
815 * (unless it is NULL). Fail if the reference doesn't exist and
816 * mustexist is set. Return 0 on success. On error, write an error
817 * message to err, set errno, and return a negative value.
819 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
820 const struct object_id *old_oid, int mustexist,
825 if (refs_read_ref_full(ref_store, lock->ref_name,
826 mustexist ? RESOLVE_REF_READING : 0,
827 &lock->old_oid, NULL)) {
829 int save_errno = errno;
830 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
834 oidclr(&lock->old_oid);
838 if (old_oid && oidcmp(&lock->old_oid, old_oid)) {
839 strbuf_addf(err, "ref '%s' is at %s but expected %s",
841 oid_to_hex(&lock->old_oid),
842 oid_to_hex(old_oid));
849 static int remove_empty_directories(struct strbuf *path)
852 * we want to create a file but there is a directory there;
853 * if that is an empty directory (or a directory that contains
854 * only empty directories), remove them.
856 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
859 static int create_reflock(const char *path, void *cb)
861 struct lock_file *lk = cb;
863 return hold_lock_file_for_update_timeout(
864 lk, path, LOCK_NO_DEREF,
865 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
869 * Locks a ref returning the lock on success and NULL on failure.
870 * On failure errno is set to something meaningful.
872 static struct ref_lock *lock_ref_oid_basic(struct files_ref_store *refs,
874 const struct object_id *old_oid,
875 const struct string_list *extras,
876 const struct string_list *skip,
877 unsigned int flags, int *type,
880 struct strbuf ref_file = STRBUF_INIT;
881 struct ref_lock *lock;
883 int mustexist = (old_oid && !is_null_oid(old_oid));
884 int resolve_flags = RESOLVE_REF_NO_RECURSE;
887 files_assert_main_repository(refs, "lock_ref_oid_basic");
890 lock = xcalloc(1, sizeof(struct ref_lock));
893 resolve_flags |= RESOLVE_REF_READING;
894 if (flags & REF_DELETING)
895 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
897 files_ref_path(refs, &ref_file, refname);
898 resolved = !!refs_resolve_ref_unsafe(&refs->base,
899 refname, resolve_flags,
900 &lock->old_oid, type);
901 if (!resolved && errno == EISDIR) {
903 * we are trying to lock foo but we used to
904 * have foo/bar which now does not exist;
905 * it is normal for the empty directory 'foo'
908 if (remove_empty_directories(&ref_file)) {
910 if (!refs_verify_refname_available(
912 refname, extras, skip, err))
913 strbuf_addf(err, "there are still refs under '%s'",
917 resolved = !!refs_resolve_ref_unsafe(&refs->base,
918 refname, resolve_flags,
919 &lock->old_oid, type);
923 if (last_errno != ENOTDIR ||
924 !refs_verify_refname_available(&refs->base, refname,
926 strbuf_addf(err, "unable to resolve reference '%s': %s",
927 refname, strerror(last_errno));
933 * If the ref did not exist and we are creating it, make sure
934 * there is no existing packed ref whose name begins with our
935 * refname, nor a packed ref whose name is a proper prefix of
938 if (is_null_oid(&lock->old_oid) &&
939 refs_verify_refname_available(refs->packed_ref_store, refname,
940 extras, skip, err)) {
941 last_errno = ENOTDIR;
945 lock->ref_name = xstrdup(refname);
947 if (raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) {
949 unable_to_lock_message(ref_file.buf, errno, err);
953 if (verify_lock(&refs->base, lock, old_oid, mustexist, err)) {
964 strbuf_release(&ref_file);
969 struct ref_to_prune {
970 struct ref_to_prune *next;
971 struct object_id oid;
972 char name[FLEX_ARRAY];
976 REMOVE_EMPTY_PARENTS_REF = 0x01,
977 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
981 * Remove empty parent directories associated with the specified
982 * reference and/or its reflog, but spare [logs/]refs/ and immediate
983 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
984 * REMOVE_EMPTY_PARENTS_REFLOG.
986 static void try_remove_empty_parents(struct files_ref_store *refs,
990 struct strbuf buf = STRBUF_INIT;
991 struct strbuf sb = STRBUF_INIT;
995 strbuf_addstr(&buf, refname);
997 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
998 while (*p && *p != '/')
1000 /* tolerate duplicate slashes; see check_refname_format() */
1004 q = buf.buf + buf.len;
1005 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1006 while (q > p && *q != '/')
1008 while (q > p && *(q-1) == '/')
1012 strbuf_setlen(&buf, q - buf.buf);
1015 files_ref_path(refs, &sb, buf.buf);
1016 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1017 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1020 files_reflog_path(refs, &sb, buf.buf);
1021 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1022 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1024 strbuf_release(&buf);
1025 strbuf_release(&sb);
1028 /* make sure nobody touched the ref, and unlink */
1029 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1031 struct ref_transaction *transaction;
1032 struct strbuf err = STRBUF_INIT;
1035 if (check_refname_format(r->name, 0))
1038 transaction = ref_store_transaction_begin(&refs->base, &err);
1041 ref_transaction_add_update(
1042 transaction, r->name,
1043 REF_NO_DEREF | REF_HAVE_NEW | REF_HAVE_OLD | REF_IS_PRUNING,
1044 &null_oid, &r->oid, NULL);
1045 if (ref_transaction_commit(transaction, &err))
1052 error("%s", err.buf);
1053 strbuf_release(&err);
1054 ref_transaction_free(transaction);
1059 * Prune the loose versions of the references in the linked list
1060 * `*refs_to_prune`, freeing the entries in the list as we go.
1062 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune **refs_to_prune)
1064 while (*refs_to_prune) {
1065 struct ref_to_prune *r = *refs_to_prune;
1066 *refs_to_prune = r->next;
1073 * Return true if the specified reference should be packed.
1075 static int should_pack_ref(const char *refname,
1076 const struct object_id *oid, unsigned int ref_flags,
1077 unsigned int pack_flags)
1079 /* Do not pack per-worktree refs: */
1080 if (ref_type(refname) != REF_TYPE_NORMAL)
1083 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1084 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1087 /* Do not pack symbolic refs: */
1088 if (ref_flags & REF_ISSYMREF)
1091 /* Do not pack broken refs: */
1092 if (!ref_resolves_to_object(refname, oid, ref_flags))
1098 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1100 struct files_ref_store *refs =
1101 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1103 struct ref_iterator *iter;
1105 struct ref_to_prune *refs_to_prune = NULL;
1106 struct strbuf err = STRBUF_INIT;
1107 struct ref_transaction *transaction;
1109 transaction = ref_store_transaction_begin(refs->packed_ref_store, &err);
1113 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1115 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1116 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1118 * If the loose reference can be packed, add an entry
1119 * in the packed ref cache. If the reference should be
1120 * pruned, also add it to refs_to_prune.
1122 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1127 * Add a reference creation for this reference to the
1128 * packed-refs transaction:
1130 if (ref_transaction_update(transaction, iter->refname,
1132 REF_NO_DEREF, NULL, &err))
1133 die("failure preparing to create packed reference %s: %s",
1134 iter->refname, err.buf);
1136 /* Schedule the loose reference for pruning if requested. */
1137 if ((flags & PACK_REFS_PRUNE)) {
1138 struct ref_to_prune *n;
1139 FLEX_ALLOC_STR(n, name, iter->refname);
1140 oidcpy(&n->oid, iter->oid);
1141 n->next = refs_to_prune;
1145 if (ok != ITER_DONE)
1146 die("error while iterating over references");
1148 if (ref_transaction_commit(transaction, &err))
1149 die("unable to write new packed-refs: %s", err.buf);
1151 ref_transaction_free(transaction);
1153 packed_refs_unlock(refs->packed_ref_store);
1155 prune_refs(refs, &refs_to_prune);
1156 strbuf_release(&err);
1160 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1161 struct string_list *refnames, unsigned int flags)
1163 struct files_ref_store *refs =
1164 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1165 struct strbuf err = STRBUF_INIT;
1171 if (packed_refs_lock(refs->packed_ref_store, 0, &err))
1174 if (refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {
1175 packed_refs_unlock(refs->packed_ref_store);
1179 packed_refs_unlock(refs->packed_ref_store);
1181 for (i = 0; i < refnames->nr; i++) {
1182 const char *refname = refnames->items[i].string;
1184 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1185 result |= error(_("could not remove reference %s"), refname);
1188 strbuf_release(&err);
1193 * If we failed to rewrite the packed-refs file, then it is
1194 * unsafe to try to remove loose refs, because doing so might
1195 * expose an obsolete packed value for a reference that might
1196 * even point at an object that has been garbage collected.
1198 if (refnames->nr == 1)
1199 error(_("could not delete reference %s: %s"),
1200 refnames->items[0].string, err.buf);
1202 error(_("could not delete references: %s"), err.buf);
1204 strbuf_release(&err);
1209 * People using contrib's git-new-workdir have .git/logs/refs ->
1210 * /some/other/path/.git/logs/refs, and that may live on another device.
1212 * IOW, to avoid cross device rename errors, the temporary renamed log must
1213 * live into logs/refs.
1215 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1218 const char *tmp_renamed_log;
1222 static int rename_tmp_log_callback(const char *path, void *cb_data)
1224 struct rename_cb *cb = cb_data;
1226 if (rename(cb->tmp_renamed_log, path)) {
1228 * rename(a, b) when b is an existing directory ought
1229 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1230 * Sheesh. Record the true errno for error reporting,
1231 * but report EISDIR to raceproof_create_file() so
1232 * that it knows to retry.
1234 cb->true_errno = errno;
1235 if (errno == ENOTDIR)
1243 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1245 struct strbuf path = STRBUF_INIT;
1246 struct strbuf tmp = STRBUF_INIT;
1247 struct rename_cb cb;
1250 files_reflog_path(refs, &path, newrefname);
1251 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1252 cb.tmp_renamed_log = tmp.buf;
1253 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1255 if (errno == EISDIR)
1256 error("directory not empty: %s", path.buf);
1258 error("unable to move logfile %s to %s: %s",
1260 strerror(cb.true_errno));
1263 strbuf_release(&path);
1264 strbuf_release(&tmp);
1268 static int write_ref_to_lockfile(struct ref_lock *lock,
1269 const struct object_id *oid, struct strbuf *err);
1270 static int commit_ref_update(struct files_ref_store *refs,
1271 struct ref_lock *lock,
1272 const struct object_id *oid, const char *logmsg,
1273 struct strbuf *err);
1275 static int files_copy_or_rename_ref(struct ref_store *ref_store,
1276 const char *oldrefname, const char *newrefname,
1277 const char *logmsg, int copy)
1279 struct files_ref_store *refs =
1280 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1281 struct object_id oid, orig_oid;
1282 int flag = 0, logmoved = 0;
1283 struct ref_lock *lock;
1284 struct stat loginfo;
1285 struct strbuf sb_oldref = STRBUF_INIT;
1286 struct strbuf sb_newref = STRBUF_INIT;
1287 struct strbuf tmp_renamed_log = STRBUF_INIT;
1289 struct strbuf err = STRBUF_INIT;
1291 files_reflog_path(refs, &sb_oldref, oldrefname);
1292 files_reflog_path(refs, &sb_newref, newrefname);
1293 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1295 log = !lstat(sb_oldref.buf, &loginfo);
1296 if (log && S_ISLNK(loginfo.st_mode)) {
1297 ret = error("reflog for %s is a symlink", oldrefname);
1301 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1302 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1303 &orig_oid, &flag)) {
1304 ret = error("refname %s not found", oldrefname);
1308 if (flag & REF_ISSYMREF) {
1310 ret = error("refname %s is a symbolic ref, copying it is not supported",
1313 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1317 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1322 if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1323 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1324 oldrefname, strerror(errno));
1328 if (copy && log && copy_file(tmp_renamed_log.buf, sb_oldref.buf, 0644)) {
1329 ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1330 oldrefname, strerror(errno));
1334 if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,
1335 &orig_oid, REF_NO_DEREF)) {
1336 error("unable to delete old %s", oldrefname);
1341 * Since we are doing a shallow lookup, oid is not the
1342 * correct value to pass to delete_ref as old_oid. But that
1343 * doesn't matter, because an old_oid check wouldn't add to
1344 * the safety anyway; we want to delete the reference whatever
1345 * its current value.
1347 if (!copy && !refs_read_ref_full(&refs->base, newrefname,
1348 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1350 refs_delete_ref(&refs->base, NULL, newrefname,
1351 NULL, REF_NO_DEREF)) {
1352 if (errno == EISDIR) {
1353 struct strbuf path = STRBUF_INIT;
1356 files_ref_path(refs, &path, newrefname);
1357 result = remove_empty_directories(&path);
1358 strbuf_release(&path);
1361 error("Directory not empty: %s", newrefname);
1365 error("unable to delete existing %s", newrefname);
1370 if (log && rename_tmp_log(refs, newrefname))
1375 lock = lock_ref_oid_basic(refs, newrefname, NULL, NULL, NULL,
1376 REF_NO_DEREF, NULL, &err);
1379 error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1381 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1382 strbuf_release(&err);
1385 oidcpy(&lock->old_oid, &orig_oid);
1387 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1388 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1389 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1390 strbuf_release(&err);
1398 lock = lock_ref_oid_basic(refs, oldrefname, NULL, NULL, NULL,
1399 REF_NO_DEREF, NULL, &err);
1401 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1402 strbuf_release(&err);
1406 flag = log_all_ref_updates;
1407 log_all_ref_updates = LOG_REFS_NONE;
1408 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1409 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1410 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1411 strbuf_release(&err);
1413 log_all_ref_updates = flag;
1416 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1417 error("unable to restore logfile %s from %s: %s",
1418 oldrefname, newrefname, strerror(errno));
1419 if (!logmoved && log &&
1420 rename(tmp_renamed_log.buf, sb_oldref.buf))
1421 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1422 oldrefname, strerror(errno));
1425 strbuf_release(&sb_newref);
1426 strbuf_release(&sb_oldref);
1427 strbuf_release(&tmp_renamed_log);
1432 static int files_rename_ref(struct ref_store *ref_store,
1433 const char *oldrefname, const char *newrefname,
1436 return files_copy_or_rename_ref(ref_store, oldrefname,
1437 newrefname, logmsg, 0);
1440 static int files_copy_ref(struct ref_store *ref_store,
1441 const char *oldrefname, const char *newrefname,
1444 return files_copy_or_rename_ref(ref_store, oldrefname,
1445 newrefname, logmsg, 1);
1448 static int close_ref_gently(struct ref_lock *lock)
1450 if (close_lock_file_gently(&lock->lk))
1455 static int commit_ref(struct ref_lock *lock)
1457 char *path = get_locked_file_path(&lock->lk);
1460 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1462 * There is a directory at the path we want to rename
1463 * the lockfile to. Hopefully it is empty; try to
1466 size_t len = strlen(path);
1467 struct strbuf sb_path = STRBUF_INIT;
1469 strbuf_attach(&sb_path, path, len, len);
1472 * If this fails, commit_lock_file() will also fail
1473 * and will report the problem.
1475 remove_empty_directories(&sb_path);
1476 strbuf_release(&sb_path);
1481 if (commit_lock_file(&lock->lk))
1486 static int open_or_create_logfile(const char *path, void *cb)
1490 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1491 return (*fd < 0) ? -1 : 0;
1495 * Create a reflog for a ref. If force_create = 0, only create the
1496 * reflog for certain refs (those for which should_autocreate_reflog
1497 * returns non-zero). Otherwise, create it regardless of the reference
1498 * name. If the logfile already existed or was created, return 0 and
1499 * set *logfd to the file descriptor opened for appending to the file.
1500 * If no logfile exists and we decided not to create one, return 0 and
1501 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1504 static int log_ref_setup(struct files_ref_store *refs,
1505 const char *refname, int force_create,
1506 int *logfd, struct strbuf *err)
1508 struct strbuf logfile_sb = STRBUF_INIT;
1511 files_reflog_path(refs, &logfile_sb, refname);
1512 logfile = strbuf_detach(&logfile_sb, NULL);
1514 if (force_create || should_autocreate_reflog(refname)) {
1515 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1516 if (errno == ENOENT)
1517 strbuf_addf(err, "unable to create directory for '%s': "
1518 "%s", logfile, strerror(errno));
1519 else if (errno == EISDIR)
1520 strbuf_addf(err, "there are still logs under '%s'",
1523 strbuf_addf(err, "unable to append to '%s': %s",
1524 logfile, strerror(errno));
1529 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1531 if (errno == ENOENT || errno == EISDIR) {
1533 * The logfile doesn't already exist,
1534 * but that is not an error; it only
1535 * means that we won't write log
1540 strbuf_addf(err, "unable to append to '%s': %s",
1541 logfile, strerror(errno));
1548 adjust_shared_perm(logfile);
1558 static int files_create_reflog(struct ref_store *ref_store,
1559 const char *refname, int force_create,
1562 struct files_ref_store *refs =
1563 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1566 if (log_ref_setup(refs, refname, force_create, &fd, err))
1575 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1576 const struct object_id *new_oid,
1577 const char *committer, const char *msg)
1579 int msglen, written;
1580 unsigned maxlen, len;
1583 msglen = msg ? strlen(msg) : 0;
1584 maxlen = strlen(committer) + msglen + 100;
1585 logrec = xmalloc(maxlen);
1586 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1587 oid_to_hex(old_oid),
1588 oid_to_hex(new_oid),
1591 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1593 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
1601 static int files_log_ref_write(struct files_ref_store *refs,
1602 const char *refname, const struct object_id *old_oid,
1603 const struct object_id *new_oid, const char *msg,
1604 int flags, struct strbuf *err)
1608 if (log_all_ref_updates == LOG_REFS_UNSET)
1609 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1611 result = log_ref_setup(refs, refname,
1612 flags & REF_FORCE_CREATE_REFLOG,
1620 result = log_ref_write_fd(logfd, old_oid, new_oid,
1621 git_committer_info(0), msg);
1623 struct strbuf sb = STRBUF_INIT;
1624 int save_errno = errno;
1626 files_reflog_path(refs, &sb, refname);
1627 strbuf_addf(err, "unable to append to '%s': %s",
1628 sb.buf, strerror(save_errno));
1629 strbuf_release(&sb);
1634 struct strbuf sb = STRBUF_INIT;
1635 int save_errno = errno;
1637 files_reflog_path(refs, &sb, refname);
1638 strbuf_addf(err, "unable to append to '%s': %s",
1639 sb.buf, strerror(save_errno));
1640 strbuf_release(&sb);
1647 * Write oid into the open lockfile, then close the lockfile. On
1648 * errors, rollback the lockfile, fill in *err and return -1.
1650 static int write_ref_to_lockfile(struct ref_lock *lock,
1651 const struct object_id *oid, struct strbuf *err)
1653 static char term = '\n';
1657 o = parse_object(oid);
1660 "trying to write ref '%s' with nonexistent object %s",
1661 lock->ref_name, oid_to_hex(oid));
1665 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1667 "trying to write non-commit object %s to branch '%s'",
1668 oid_to_hex(oid), lock->ref_name);
1672 fd = get_lock_file_fd(&lock->lk);
1673 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) < 0 ||
1674 write_in_full(fd, &term, 1) < 0 ||
1675 close_ref_gently(lock) < 0) {
1677 "couldn't write '%s'", get_lock_file_path(&lock->lk));
1685 * Commit a change to a loose reference that has already been written
1686 * to the loose reference lockfile. Also update the reflogs if
1687 * necessary, using the specified lockmsg (which can be NULL).
1689 static int commit_ref_update(struct files_ref_store *refs,
1690 struct ref_lock *lock,
1691 const struct object_id *oid, const char *logmsg,
1694 files_assert_main_repository(refs, "commit_ref_update");
1696 clear_loose_ref_cache(refs);
1697 if (files_log_ref_write(refs, lock->ref_name,
1698 &lock->old_oid, oid,
1700 char *old_msg = strbuf_detach(err, NULL);
1701 strbuf_addf(err, "cannot update the ref '%s': %s",
1702 lock->ref_name, old_msg);
1708 if (strcmp(lock->ref_name, "HEAD") != 0) {
1710 * Special hack: If a branch is updated directly and HEAD
1711 * points to it (may happen on the remote side of a push
1712 * for example) then logically the HEAD reflog should be
1714 * A generic solution implies reverse symref information,
1715 * but finding all symrefs pointing to the given branch
1716 * would be rather costly for this rare event (the direct
1717 * update of a branch) to be worth it. So let's cheat and
1718 * check with HEAD only which should cover 99% of all usage
1719 * scenarios (even 100% of the default ones).
1722 const char *head_ref;
1724 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1725 RESOLVE_REF_READING,
1727 if (head_ref && (head_flag & REF_ISSYMREF) &&
1728 !strcmp(head_ref, lock->ref_name)) {
1729 struct strbuf log_err = STRBUF_INIT;
1730 if (files_log_ref_write(refs, "HEAD",
1731 &lock->old_oid, oid,
1732 logmsg, 0, &log_err)) {
1733 error("%s", log_err.buf);
1734 strbuf_release(&log_err);
1739 if (commit_ref(lock)) {
1740 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1749 static int create_ref_symlink(struct ref_lock *lock, const char *target)
1752 #ifndef NO_SYMLINK_HEAD
1753 char *ref_path = get_locked_file_path(&lock->lk);
1755 ret = symlink(target, ref_path);
1759 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1764 static void update_symref_reflog(struct files_ref_store *refs,
1765 struct ref_lock *lock, const char *refname,
1766 const char *target, const char *logmsg)
1768 struct strbuf err = STRBUF_INIT;
1769 struct object_id new_oid;
1771 !refs_read_ref_full(&refs->base, target,
1772 RESOLVE_REF_READING, &new_oid, NULL) &&
1773 files_log_ref_write(refs, refname, &lock->old_oid,
1774 &new_oid, logmsg, 0, &err)) {
1775 error("%s", err.buf);
1776 strbuf_release(&err);
1780 static int create_symref_locked(struct files_ref_store *refs,
1781 struct ref_lock *lock, const char *refname,
1782 const char *target, const char *logmsg)
1784 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1785 update_symref_reflog(refs, lock, refname, target, logmsg);
1789 if (!fdopen_lock_file(&lock->lk, "w"))
1790 return error("unable to fdopen %s: %s",
1791 lock->lk.tempfile->filename.buf, strerror(errno));
1793 update_symref_reflog(refs, lock, refname, target, logmsg);
1795 /* no error check; commit_ref will check ferror */
1796 fprintf(lock->lk.tempfile->fp, "ref: %s\n", target);
1797 if (commit_ref(lock) < 0)
1798 return error("unable to write symref for %s: %s", refname,
1803 static int files_create_symref(struct ref_store *ref_store,
1804 const char *refname, const char *target,
1807 struct files_ref_store *refs =
1808 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1809 struct strbuf err = STRBUF_INIT;
1810 struct ref_lock *lock;
1813 lock = lock_ref_oid_basic(refs, refname, NULL,
1814 NULL, NULL, REF_NO_DEREF, NULL,
1817 error("%s", err.buf);
1818 strbuf_release(&err);
1822 ret = create_symref_locked(refs, lock, refname, target, logmsg);
1827 static int files_reflog_exists(struct ref_store *ref_store,
1828 const char *refname)
1830 struct files_ref_store *refs =
1831 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1832 struct strbuf sb = STRBUF_INIT;
1836 files_reflog_path(refs, &sb, refname);
1837 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1838 strbuf_release(&sb);
1842 static int files_delete_reflog(struct ref_store *ref_store,
1843 const char *refname)
1845 struct files_ref_store *refs =
1846 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1847 struct strbuf sb = STRBUF_INIT;
1850 files_reflog_path(refs, &sb, refname);
1851 ret = remove_path(sb.buf);
1852 strbuf_release(&sb);
1856 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1858 struct object_id ooid, noid;
1859 char *email_end, *message;
1860 timestamp_t timestamp;
1862 const char *p = sb->buf;
1864 /* old SP new SP name <email> SP time TAB msg LF */
1865 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1866 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1867 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1868 !(email_end = strchr(p, '>')) ||
1869 email_end[1] != ' ' ||
1870 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1871 !message || message[0] != ' ' ||
1872 (message[1] != '+' && message[1] != '-') ||
1873 !isdigit(message[2]) || !isdigit(message[3]) ||
1874 !isdigit(message[4]) || !isdigit(message[5]))
1875 return 0; /* corrupt? */
1876 email_end[1] = '\0';
1877 tz = strtol(message + 1, NULL, 10);
1878 if (message[6] != '\t')
1882 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1885 static char *find_beginning_of_line(char *bob, char *scan)
1887 while (bob < scan && *(--scan) != '\n')
1888 ; /* keep scanning backwards */
1890 * Return either beginning of the buffer, or LF at the end of
1891 * the previous line.
1896 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1897 const char *refname,
1898 each_reflog_ent_fn fn,
1901 struct files_ref_store *refs =
1902 files_downcast(ref_store, REF_STORE_READ,
1903 "for_each_reflog_ent_reverse");
1904 struct strbuf sb = STRBUF_INIT;
1907 int ret = 0, at_tail = 1;
1909 files_reflog_path(refs, &sb, refname);
1910 logfp = fopen(sb.buf, "r");
1911 strbuf_release(&sb);
1915 /* Jump to the end */
1916 if (fseek(logfp, 0, SEEK_END) < 0)
1917 ret = error("cannot seek back reflog for %s: %s",
1918 refname, strerror(errno));
1920 while (!ret && 0 < pos) {
1926 /* Fill next block from the end */
1927 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1928 if (fseek(logfp, pos - cnt, SEEK_SET)) {
1929 ret = error("cannot seek back reflog for %s: %s",
1930 refname, strerror(errno));
1933 nread = fread(buf, cnt, 1, logfp);
1935 ret = error("cannot read %d bytes from reflog for %s: %s",
1936 cnt, refname, strerror(errno));
1941 scanp = endp = buf + cnt;
1942 if (at_tail && scanp[-1] == '\n')
1943 /* Looking at the final LF at the end of the file */
1947 while (buf < scanp) {
1949 * terminating LF of the previous line, or the beginning
1954 bp = find_beginning_of_line(buf, scanp);
1958 * The newline is the end of the previous line,
1959 * so we know we have complete line starting
1960 * at (bp + 1). Prefix it onto any prior data
1961 * we collected for the line and process it.
1963 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1966 ret = show_one_reflog_ent(&sb, fn, cb_data);
1972 * We are at the start of the buffer, and the
1973 * start of the file; there is no previous
1974 * line, and we have everything for this one.
1975 * Process it, and we can end the loop.
1977 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1978 ret = show_one_reflog_ent(&sb, fn, cb_data);
1985 * We are at the start of the buffer, and there
1986 * is more file to read backwards. Which means
1987 * we are in the middle of a line. Note that we
1988 * may get here even if *bp was a newline; that
1989 * just means we are at the exact end of the
1990 * previous line, rather than some spot in the
1993 * Save away what we have to be combined with
1994 * the data from the next read.
1996 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2003 die("BUG: reverse reflog parser had leftover data");
2006 strbuf_release(&sb);
2010 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2011 const char *refname,
2012 each_reflog_ent_fn fn, void *cb_data)
2014 struct files_ref_store *refs =
2015 files_downcast(ref_store, REF_STORE_READ,
2016 "for_each_reflog_ent");
2018 struct strbuf sb = STRBUF_INIT;
2021 files_reflog_path(refs, &sb, refname);
2022 logfp = fopen(sb.buf, "r");
2023 strbuf_release(&sb);
2027 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2028 ret = show_one_reflog_ent(&sb, fn, cb_data);
2030 strbuf_release(&sb);
2034 struct files_reflog_iterator {
2035 struct ref_iterator base;
2037 struct ref_store *ref_store;
2038 struct dir_iterator *dir_iterator;
2039 struct object_id oid;
2042 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2044 struct files_reflog_iterator *iter =
2045 (struct files_reflog_iterator *)ref_iterator;
2046 struct dir_iterator *diter = iter->dir_iterator;
2049 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2052 if (!S_ISREG(diter->st.st_mode))
2054 if (diter->basename[0] == '.')
2056 if (ends_with(diter->basename, ".lock"))
2059 if (refs_read_ref_full(iter->ref_store,
2060 diter->relative_path, 0,
2061 &iter->oid, &flags)) {
2062 error("bad ref for %s", diter->path.buf);
2066 iter->base.refname = diter->relative_path;
2067 iter->base.oid = &iter->oid;
2068 iter->base.flags = flags;
2072 iter->dir_iterator = NULL;
2073 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2078 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2079 struct object_id *peeled)
2081 die("BUG: ref_iterator_peel() called for reflog_iterator");
2084 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2086 struct files_reflog_iterator *iter =
2087 (struct files_reflog_iterator *)ref_iterator;
2090 if (iter->dir_iterator)
2091 ok = dir_iterator_abort(iter->dir_iterator);
2093 base_ref_iterator_free(ref_iterator);
2097 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2098 files_reflog_iterator_advance,
2099 files_reflog_iterator_peel,
2100 files_reflog_iterator_abort
2103 static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,
2106 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2107 struct ref_iterator *ref_iterator = &iter->base;
2108 struct strbuf sb = STRBUF_INIT;
2110 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable, 0);
2111 strbuf_addf(&sb, "%s/logs", gitdir);
2112 iter->dir_iterator = dir_iterator_begin(sb.buf);
2113 iter->ref_store = ref_store;
2114 strbuf_release(&sb);
2116 return ref_iterator;
2119 static enum iterator_selection reflog_iterator_select(
2120 struct ref_iterator *iter_worktree,
2121 struct ref_iterator *iter_common,
2124 if (iter_worktree) {
2126 * We're a bit loose here. We probably should ignore
2127 * common refs if they are accidentally added as
2128 * per-worktree refs.
2130 return ITER_SELECT_0;
2131 } else if (iter_common) {
2132 if (ref_type(iter_common->refname) == REF_TYPE_NORMAL)
2133 return ITER_SELECT_1;
2136 * The main ref store may contain main worktree's
2137 * per-worktree refs, which should be ignored
2144 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2146 struct files_ref_store *refs =
2147 files_downcast(ref_store, REF_STORE_READ,
2148 "reflog_iterator_begin");
2150 if (!strcmp(refs->gitdir, refs->gitcommondir)) {
2151 return reflog_iterator_begin(ref_store, refs->gitcommondir);
2153 return merge_ref_iterator_begin(
2155 reflog_iterator_begin(ref_store, refs->gitdir),
2156 reflog_iterator_begin(ref_store, refs->gitcommondir),
2157 reflog_iterator_select, refs);
2162 * If update is a direct update of head_ref (the reference pointed to
2163 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2165 static int split_head_update(struct ref_update *update,
2166 struct ref_transaction *transaction,
2167 const char *head_ref,
2168 struct string_list *affected_refnames,
2171 struct string_list_item *item;
2172 struct ref_update *new_update;
2174 if ((update->flags & REF_LOG_ONLY) ||
2175 (update->flags & REF_IS_PRUNING) ||
2176 (update->flags & REF_UPDATE_VIA_HEAD))
2179 if (strcmp(update->refname, head_ref))
2183 * First make sure that HEAD is not already in the
2184 * transaction. This check is O(lg N) in the transaction
2185 * size, but it happens at most once per transaction.
2187 if (string_list_has_string(affected_refnames, "HEAD")) {
2188 /* An entry already existed */
2190 "multiple updates for 'HEAD' (including one "
2191 "via its referent '%s') are not allowed",
2193 return TRANSACTION_NAME_CONFLICT;
2196 new_update = ref_transaction_add_update(
2197 transaction, "HEAD",
2198 update->flags | REF_LOG_ONLY | REF_NO_DEREF,
2199 &update->new_oid, &update->old_oid,
2203 * Add "HEAD". This insertion is O(N) in the transaction
2204 * size, but it happens at most once per transaction.
2205 * Add new_update->refname instead of a literal "HEAD".
2207 if (strcmp(new_update->refname, "HEAD"))
2208 BUG("%s unexpectedly not 'HEAD'", new_update->refname);
2209 item = string_list_insert(affected_refnames, new_update->refname);
2210 item->util = new_update;
2216 * update is for a symref that points at referent and doesn't have
2217 * REF_NO_DEREF set. Split it into two updates:
2218 * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2219 * - A new, separate update for the referent reference
2220 * Note that the new update will itself be subject to splitting when
2221 * the iteration gets to it.
2223 static int split_symref_update(struct files_ref_store *refs,
2224 struct ref_update *update,
2225 const char *referent,
2226 struct ref_transaction *transaction,
2227 struct string_list *affected_refnames,
2230 struct string_list_item *item;
2231 struct ref_update *new_update;
2232 unsigned int new_flags;
2235 * First make sure that referent is not already in the
2236 * transaction. This check is O(lg N) in the transaction
2237 * size, but it happens at most once per symref in a
2240 if (string_list_has_string(affected_refnames, referent)) {
2241 /* An entry already exists */
2243 "multiple updates for '%s' (including one "
2244 "via symref '%s') are not allowed",
2245 referent, update->refname);
2246 return TRANSACTION_NAME_CONFLICT;
2249 new_flags = update->flags;
2250 if (!strcmp(update->refname, "HEAD")) {
2252 * Record that the new update came via HEAD, so that
2253 * when we process it, split_head_update() doesn't try
2254 * to add another reflog update for HEAD. Note that
2255 * this bit will be propagated if the new_update
2256 * itself needs to be split.
2258 new_flags |= REF_UPDATE_VIA_HEAD;
2261 new_update = ref_transaction_add_update(
2262 transaction, referent, new_flags,
2263 &update->new_oid, &update->old_oid,
2266 new_update->parent_update = update;
2269 * Change the symbolic ref update to log only. Also, it
2270 * doesn't need to check its old OID value, as that will be
2271 * done when new_update is processed.
2273 update->flags |= REF_LOG_ONLY | REF_NO_DEREF;
2274 update->flags &= ~REF_HAVE_OLD;
2277 * Add the referent. This insertion is O(N) in the transaction
2278 * size, but it happens at most once per symref in a
2279 * transaction. Make sure to add new_update->refname, which will
2280 * be valid as long as affected_refnames is in use, and NOT
2281 * referent, which might soon be freed by our caller.
2283 item = string_list_insert(affected_refnames, new_update->refname);
2285 BUG("%s unexpectedly found in affected_refnames",
2286 new_update->refname);
2287 item->util = new_update;
2293 * Return the refname under which update was originally requested.
2295 static const char *original_update_refname(struct ref_update *update)
2297 while (update->parent_update)
2298 update = update->parent_update;
2300 return update->refname;
2304 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2305 * are consistent with oid, which is the reference's current value. If
2306 * everything is OK, return 0; otherwise, write an error message to
2307 * err and return -1.
2309 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2312 if (!(update->flags & REF_HAVE_OLD) ||
2313 !oidcmp(oid, &update->old_oid))
2316 if (is_null_oid(&update->old_oid))
2317 strbuf_addf(err, "cannot lock ref '%s': "
2318 "reference already exists",
2319 original_update_refname(update));
2320 else if (is_null_oid(oid))
2321 strbuf_addf(err, "cannot lock ref '%s': "
2322 "reference is missing but expected %s",
2323 original_update_refname(update),
2324 oid_to_hex(&update->old_oid));
2326 strbuf_addf(err, "cannot lock ref '%s': "
2327 "is at %s but expected %s",
2328 original_update_refname(update),
2330 oid_to_hex(&update->old_oid));
2336 * Prepare for carrying out update:
2337 * - Lock the reference referred to by update.
2338 * - Read the reference under lock.
2339 * - Check that its old OID value (if specified) is correct, and in
2340 * any case record it in update->lock->old_oid for later use when
2341 * writing the reflog.
2342 * - If it is a symref update without REF_NO_DEREF, split it up into a
2343 * REF_LOG_ONLY update of the symref and add a separate update for
2344 * the referent to transaction.
2345 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2348 static int lock_ref_for_update(struct files_ref_store *refs,
2349 struct ref_update *update,
2350 struct ref_transaction *transaction,
2351 const char *head_ref,
2352 struct string_list *affected_refnames,
2355 struct strbuf referent = STRBUF_INIT;
2356 int mustexist = (update->flags & REF_HAVE_OLD) &&
2357 !is_null_oid(&update->old_oid);
2359 struct ref_lock *lock;
2361 files_assert_main_repository(refs, "lock_ref_for_update");
2363 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2364 update->flags |= REF_DELETING;
2367 ret = split_head_update(update, transaction, head_ref,
2368 affected_refnames, err);
2373 ret = lock_raw_ref(refs, update->refname, mustexist,
2374 affected_refnames, NULL,
2376 &update->type, err);
2380 reason = strbuf_detach(err, NULL);
2381 strbuf_addf(err, "cannot lock ref '%s': %s",
2382 original_update_refname(update), reason);
2387 update->backend_data = lock;
2389 if (update->type & REF_ISSYMREF) {
2390 if (update->flags & REF_NO_DEREF) {
2392 * We won't be reading the referent as part of
2393 * the transaction, so we have to read it here
2394 * to record and possibly check old_oid:
2396 if (refs_read_ref_full(&refs->base,
2398 &lock->old_oid, NULL)) {
2399 if (update->flags & REF_HAVE_OLD) {
2400 strbuf_addf(err, "cannot lock ref '%s': "
2401 "error reading reference",
2402 original_update_refname(update));
2403 ret = TRANSACTION_GENERIC_ERROR;
2406 } else if (check_old_oid(update, &lock->old_oid, err)) {
2407 ret = TRANSACTION_GENERIC_ERROR;
2412 * Create a new update for the reference this
2413 * symref is pointing at. Also, we will record
2414 * and verify old_oid for this update as part
2415 * of processing the split-off update, so we
2416 * don't have to do it here.
2418 ret = split_symref_update(refs, update,
2419 referent.buf, transaction,
2420 affected_refnames, err);
2425 struct ref_update *parent_update;
2427 if (check_old_oid(update, &lock->old_oid, err)) {
2428 ret = TRANSACTION_GENERIC_ERROR;
2433 * If this update is happening indirectly because of a
2434 * symref update, record the old OID in the parent
2437 for (parent_update = update->parent_update;
2439 parent_update = parent_update->parent_update) {
2440 struct ref_lock *parent_lock = parent_update->backend_data;
2441 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2445 if ((update->flags & REF_HAVE_NEW) &&
2446 !(update->flags & REF_DELETING) &&
2447 !(update->flags & REF_LOG_ONLY)) {
2448 if (!(update->type & REF_ISSYMREF) &&
2449 !oidcmp(&lock->old_oid, &update->new_oid)) {
2451 * The reference already has the desired
2452 * value, so we don't need to write it.
2454 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2456 char *write_err = strbuf_detach(err, NULL);
2459 * The lock was freed upon failure of
2460 * write_ref_to_lockfile():
2462 update->backend_data = NULL;
2464 "cannot update ref '%s': %s",
2465 update->refname, write_err);
2467 ret = TRANSACTION_GENERIC_ERROR;
2470 update->flags |= REF_NEEDS_COMMIT;
2473 if (!(update->flags & REF_NEEDS_COMMIT)) {
2475 * We didn't call write_ref_to_lockfile(), so
2476 * the lockfile is still open. Close it to
2477 * free up the file descriptor:
2479 if (close_ref_gently(lock)) {
2480 strbuf_addf(err, "couldn't close '%s.lock'",
2482 ret = TRANSACTION_GENERIC_ERROR;
2488 strbuf_release(&referent);
2492 struct files_transaction_backend_data {
2493 struct ref_transaction *packed_transaction;
2494 int packed_refs_locked;
2498 * Unlock any references in `transaction` that are still locked, and
2499 * mark the transaction closed.
2501 static void files_transaction_cleanup(struct files_ref_store *refs,
2502 struct ref_transaction *transaction)
2505 struct files_transaction_backend_data *backend_data =
2506 transaction->backend_data;
2507 struct strbuf err = STRBUF_INIT;
2509 for (i = 0; i < transaction->nr; i++) {
2510 struct ref_update *update = transaction->updates[i];
2511 struct ref_lock *lock = update->backend_data;
2515 update->backend_data = NULL;
2519 if (backend_data->packed_transaction &&
2520 ref_transaction_abort(backend_data->packed_transaction, &err)) {
2521 error("error aborting transaction: %s", err.buf);
2522 strbuf_release(&err);
2525 if (backend_data->packed_refs_locked)
2526 packed_refs_unlock(refs->packed_ref_store);
2530 transaction->state = REF_TRANSACTION_CLOSED;
2533 static int files_transaction_prepare(struct ref_store *ref_store,
2534 struct ref_transaction *transaction,
2537 struct files_ref_store *refs =
2538 files_downcast(ref_store, REF_STORE_WRITE,
2539 "ref_transaction_prepare");
2542 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2543 char *head_ref = NULL;
2545 struct files_transaction_backend_data *backend_data;
2546 struct ref_transaction *packed_transaction = NULL;
2550 if (!transaction->nr)
2553 backend_data = xcalloc(1, sizeof(*backend_data));
2554 transaction->backend_data = backend_data;
2557 * Fail if a refname appears more than once in the
2558 * transaction. (If we end up splitting up any updates using
2559 * split_symref_update() or split_head_update(), those
2560 * functions will check that the new updates don't have the
2561 * same refname as any existing ones.) Also fail if any of the
2562 * updates use REF_IS_PRUNING without REF_NO_DEREF.
2564 for (i = 0; i < transaction->nr; i++) {
2565 struct ref_update *update = transaction->updates[i];
2566 struct string_list_item *item =
2567 string_list_append(&affected_refnames, update->refname);
2569 if ((update->flags & REF_IS_PRUNING) &&
2570 !(update->flags & REF_NO_DEREF))
2571 BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2574 * We store a pointer to update in item->util, but at
2575 * the moment we never use the value of this field
2576 * except to check whether it is non-NULL.
2578 item->util = update;
2580 string_list_sort(&affected_refnames);
2581 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2582 ret = TRANSACTION_GENERIC_ERROR;
2587 * Special hack: If a branch is updated directly and HEAD
2588 * points to it (may happen on the remote side of a push
2589 * for example) then logically the HEAD reflog should be
2592 * A generic solution would require reverse symref lookups,
2593 * but finding all symrefs pointing to a given branch would be
2594 * rather costly for this rare event (the direct update of a
2595 * branch) to be worth it. So let's cheat and check with HEAD
2596 * only, which should cover 99% of all usage scenarios (even
2597 * 100% of the default ones).
2599 * So if HEAD is a symbolic reference, then record the name of
2600 * the reference that it points to. If we see an update of
2601 * head_ref within the transaction, then split_head_update()
2602 * arranges for the reflog of HEAD to be updated, too.
2604 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2605 RESOLVE_REF_NO_RECURSE,
2608 if (head_ref && !(head_type & REF_ISSYMREF)) {
2609 FREE_AND_NULL(head_ref);
2613 * Acquire all locks, verify old values if provided, check
2614 * that new values are valid, and write new values to the
2615 * lockfiles, ready to be activated. Only keep one lockfile
2616 * open at a time to avoid running out of file descriptors.
2617 * Note that lock_ref_for_update() might append more updates
2618 * to the transaction.
2620 for (i = 0; i < transaction->nr; i++) {
2621 struct ref_update *update = transaction->updates[i];
2623 ret = lock_ref_for_update(refs, update, transaction,
2624 head_ref, &affected_refnames, err);
2628 if (update->flags & REF_DELETING &&
2629 !(update->flags & REF_LOG_ONLY) &&
2630 !(update->flags & REF_IS_PRUNING)) {
2632 * This reference has to be deleted from
2633 * packed-refs if it exists there.
2635 if (!packed_transaction) {
2636 packed_transaction = ref_store_transaction_begin(
2637 refs->packed_ref_store, err);
2638 if (!packed_transaction) {
2639 ret = TRANSACTION_GENERIC_ERROR;
2643 backend_data->packed_transaction =
2647 ref_transaction_add_update(
2648 packed_transaction, update->refname,
2649 REF_HAVE_NEW | REF_NO_DEREF,
2650 &update->new_oid, NULL,
2655 if (packed_transaction) {
2656 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2657 ret = TRANSACTION_GENERIC_ERROR;
2660 backend_data->packed_refs_locked = 1;
2662 if (is_packed_transaction_needed(refs->packed_ref_store,
2663 packed_transaction)) {
2664 ret = ref_transaction_prepare(packed_transaction, err);
2667 * We can skip rewriting the `packed-refs`
2668 * file. But we do need to leave it locked, so
2669 * that somebody else doesn't pack a reference
2670 * that we are trying to delete.
2672 if (ref_transaction_abort(packed_transaction, err)) {
2673 ret = TRANSACTION_GENERIC_ERROR;
2676 backend_data->packed_transaction = NULL;
2682 string_list_clear(&affected_refnames, 0);
2685 files_transaction_cleanup(refs, transaction);
2687 transaction->state = REF_TRANSACTION_PREPARED;
2692 static int files_transaction_finish(struct ref_store *ref_store,
2693 struct ref_transaction *transaction,
2696 struct files_ref_store *refs =
2697 files_downcast(ref_store, 0, "ref_transaction_finish");
2700 struct strbuf sb = STRBUF_INIT;
2701 struct files_transaction_backend_data *backend_data;
2702 struct ref_transaction *packed_transaction;
2707 if (!transaction->nr) {
2708 transaction->state = REF_TRANSACTION_CLOSED;
2712 backend_data = transaction->backend_data;
2713 packed_transaction = backend_data->packed_transaction;
2715 /* Perform updates first so live commits remain referenced */
2716 for (i = 0; i < transaction->nr; i++) {
2717 struct ref_update *update = transaction->updates[i];
2718 struct ref_lock *lock = update->backend_data;
2720 if (update->flags & REF_NEEDS_COMMIT ||
2721 update->flags & REF_LOG_ONLY) {
2722 if (files_log_ref_write(refs,
2726 update->msg, update->flags,
2728 char *old_msg = strbuf_detach(err, NULL);
2730 strbuf_addf(err, "cannot update the ref '%s': %s",
2731 lock->ref_name, old_msg);
2734 update->backend_data = NULL;
2735 ret = TRANSACTION_GENERIC_ERROR;
2739 if (update->flags & REF_NEEDS_COMMIT) {
2740 clear_loose_ref_cache(refs);
2741 if (commit_ref(lock)) {
2742 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2744 update->backend_data = NULL;
2745 ret = TRANSACTION_GENERIC_ERROR;
2752 * Now that updates are safely completed, we can perform
2753 * deletes. First delete the reflogs of any references that
2754 * will be deleted, since (in the unexpected event of an
2755 * error) leaving a reference without a reflog is less bad
2756 * than leaving a reflog without a reference (the latter is a
2757 * mildly invalid repository state):
2759 for (i = 0; i < transaction->nr; i++) {
2760 struct ref_update *update = transaction->updates[i];
2761 if (update->flags & REF_DELETING &&
2762 !(update->flags & REF_LOG_ONLY) &&
2763 !(update->flags & REF_IS_PRUNING)) {
2765 files_reflog_path(refs, &sb, update->refname);
2766 if (!unlink_or_warn(sb.buf))
2767 try_remove_empty_parents(refs, update->refname,
2768 REMOVE_EMPTY_PARENTS_REFLOG);
2773 * Perform deletes now that updates are safely completed.
2775 * First delete any packed versions of the references, while
2776 * retaining the packed-refs lock:
2778 if (packed_transaction) {
2779 ret = ref_transaction_commit(packed_transaction, err);
2780 ref_transaction_free(packed_transaction);
2781 packed_transaction = NULL;
2782 backend_data->packed_transaction = NULL;
2787 /* Now delete the loose versions of the references: */
2788 for (i = 0; i < transaction->nr; i++) {
2789 struct ref_update *update = transaction->updates[i];
2790 struct ref_lock *lock = update->backend_data;
2792 if (update->flags & REF_DELETING &&
2793 !(update->flags & REF_LOG_ONLY)) {
2794 if (!(update->type & REF_ISPACKED) ||
2795 update->type & REF_ISSYMREF) {
2796 /* It is a loose reference. */
2798 files_ref_path(refs, &sb, lock->ref_name);
2799 if (unlink_or_msg(sb.buf, err)) {
2800 ret = TRANSACTION_GENERIC_ERROR;
2803 update->flags |= REF_DELETED_LOOSE;
2808 clear_loose_ref_cache(refs);
2811 files_transaction_cleanup(refs, transaction);
2813 for (i = 0; i < transaction->nr; i++) {
2814 struct ref_update *update = transaction->updates[i];
2816 if (update->flags & REF_DELETED_LOOSE) {
2818 * The loose reference was deleted. Delete any
2819 * empty parent directories. (Note that this
2820 * can only work because we have already
2821 * removed the lockfile.)
2823 try_remove_empty_parents(refs, update->refname,
2824 REMOVE_EMPTY_PARENTS_REF);
2828 strbuf_release(&sb);
2832 static int files_transaction_abort(struct ref_store *ref_store,
2833 struct ref_transaction *transaction,
2836 struct files_ref_store *refs =
2837 files_downcast(ref_store, 0, "ref_transaction_abort");
2839 files_transaction_cleanup(refs, transaction);
2843 static int ref_present(const char *refname,
2844 const struct object_id *oid, int flags, void *cb_data)
2846 struct string_list *affected_refnames = cb_data;
2848 return string_list_has_string(affected_refnames, refname);
2851 static int files_initial_transaction_commit(struct ref_store *ref_store,
2852 struct ref_transaction *transaction,
2855 struct files_ref_store *refs =
2856 files_downcast(ref_store, REF_STORE_WRITE,
2857 "initial_ref_transaction_commit");
2860 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2861 struct ref_transaction *packed_transaction = NULL;
2865 if (transaction->state != REF_TRANSACTION_OPEN)
2866 die("BUG: commit called for transaction that is not open");
2868 /* Fail if a refname appears more than once in the transaction: */
2869 for (i = 0; i < transaction->nr; i++)
2870 string_list_append(&affected_refnames,
2871 transaction->updates[i]->refname);
2872 string_list_sort(&affected_refnames);
2873 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2874 ret = TRANSACTION_GENERIC_ERROR;
2879 * It's really undefined to call this function in an active
2880 * repository or when there are existing references: we are
2881 * only locking and changing packed-refs, so (1) any
2882 * simultaneous processes might try to change a reference at
2883 * the same time we do, and (2) any existing loose versions of
2884 * the references that we are setting would have precedence
2885 * over our values. But some remote helpers create the remote
2886 * "HEAD" and "master" branches before calling this function,
2887 * so here we really only check that none of the references
2888 * that we are creating already exists.
2890 if (refs_for_each_rawref(&refs->base, ref_present,
2891 &affected_refnames))
2892 die("BUG: initial ref transaction called with existing refs");
2894 packed_transaction = ref_store_transaction_begin(refs->packed_ref_store, err);
2895 if (!packed_transaction) {
2896 ret = TRANSACTION_GENERIC_ERROR;
2900 for (i = 0; i < transaction->nr; i++) {
2901 struct ref_update *update = transaction->updates[i];
2903 if ((update->flags & REF_HAVE_OLD) &&
2904 !is_null_oid(&update->old_oid))
2905 die("BUG: initial ref transaction with old_sha1 set");
2906 if (refs_verify_refname_available(&refs->base, update->refname,
2907 &affected_refnames, NULL,
2909 ret = TRANSACTION_NAME_CONFLICT;
2914 * Add a reference creation for this reference to the
2915 * packed-refs transaction:
2917 ref_transaction_add_update(packed_transaction, update->refname,
2918 update->flags & ~REF_HAVE_OLD,
2919 &update->new_oid, &update->old_oid,
2923 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2924 ret = TRANSACTION_GENERIC_ERROR;
2928 if (initial_ref_transaction_commit(packed_transaction, err)) {
2929 ret = TRANSACTION_GENERIC_ERROR;
2932 packed_refs_unlock(refs->packed_ref_store);
2934 if (packed_transaction)
2935 ref_transaction_free(packed_transaction);
2936 transaction->state = REF_TRANSACTION_CLOSED;
2937 string_list_clear(&affected_refnames, 0);
2941 struct expire_reflog_cb {
2943 reflog_expiry_should_prune_fn *should_prune_fn;
2946 struct object_id last_kept_oid;
2949 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
2950 const char *email, timestamp_t timestamp, int tz,
2951 const char *message, void *cb_data)
2953 struct expire_reflog_cb *cb = cb_data;
2954 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
2956 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
2957 ooid = &cb->last_kept_oid;
2959 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
2960 message, policy_cb)) {
2962 printf("would prune %s", message);
2963 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2964 printf("prune %s", message);
2967 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
2968 oid_to_hex(ooid), oid_to_hex(noid),
2969 email, timestamp, tz, message);
2970 oidcpy(&cb->last_kept_oid, noid);
2972 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2973 printf("keep %s", message);
2978 static int files_reflog_expire(struct ref_store *ref_store,
2979 const char *refname, const struct object_id *oid,
2981 reflog_expiry_prepare_fn prepare_fn,
2982 reflog_expiry_should_prune_fn should_prune_fn,
2983 reflog_expiry_cleanup_fn cleanup_fn,
2984 void *policy_cb_data)
2986 struct files_ref_store *refs =
2987 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
2988 static struct lock_file reflog_lock;
2989 struct expire_reflog_cb cb;
2990 struct ref_lock *lock;
2991 struct strbuf log_file_sb = STRBUF_INIT;
2995 struct strbuf err = STRBUF_INIT;
2997 memset(&cb, 0, sizeof(cb));
2999 cb.policy_cb = policy_cb_data;
3000 cb.should_prune_fn = should_prune_fn;
3003 * The reflog file is locked by holding the lock on the
3004 * reference itself, plus we might need to update the
3005 * reference if --updateref was specified:
3007 lock = lock_ref_oid_basic(refs, refname, oid,
3008 NULL, NULL, REF_NO_DEREF,
3011 error("cannot lock ref '%s': %s", refname, err.buf);
3012 strbuf_release(&err);
3015 if (!refs_reflog_exists(ref_store, refname)) {
3020 files_reflog_path(refs, &log_file_sb, refname);
3021 log_file = strbuf_detach(&log_file_sb, NULL);
3022 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3024 * Even though holding $GIT_DIR/logs/$reflog.lock has
3025 * no locking implications, we use the lock_file
3026 * machinery here anyway because it does a lot of the
3027 * work we need, including cleaning up if the program
3028 * exits unexpectedly.
3030 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3031 struct strbuf err = STRBUF_INIT;
3032 unable_to_lock_message(log_file, errno, &err);
3033 error("%s", err.buf);
3034 strbuf_release(&err);
3037 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3039 error("cannot fdopen %s (%s)",
3040 get_lock_file_path(&reflog_lock), strerror(errno));
3045 (*prepare_fn)(refname, oid, cb.policy_cb);
3046 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3047 (*cleanup_fn)(cb.policy_cb);
3049 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3051 * It doesn't make sense to adjust a reference pointed
3052 * to by a symbolic ref based on expiring entries in
3053 * the symbolic reference's reflog. Nor can we update
3054 * a reference if there are no remaining reflog
3057 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3058 !(type & REF_ISSYMREF) &&
3059 !is_null_oid(&cb.last_kept_oid);
3061 if (close_lock_file_gently(&reflog_lock)) {
3062 status |= error("couldn't write %s: %s", log_file,
3064 rollback_lock_file(&reflog_lock);
3065 } else if (update &&
3066 (write_in_full(get_lock_file_fd(&lock->lk),
3067 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) < 0 ||
3068 write_str_in_full(get_lock_file_fd(&lock->lk), "\n") < 0 ||
3069 close_ref_gently(lock) < 0)) {
3070 status |= error("couldn't write %s",
3071 get_lock_file_path(&lock->lk));
3072 rollback_lock_file(&reflog_lock);
3073 } else if (commit_lock_file(&reflog_lock)) {
3074 status |= error("unable to write reflog '%s' (%s)",
3075 log_file, strerror(errno));
3076 } else if (update && commit_ref(lock)) {
3077 status |= error("couldn't set %s", lock->ref_name);
3085 rollback_lock_file(&reflog_lock);
3091 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3093 struct files_ref_store *refs =
3094 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3095 struct strbuf sb = STRBUF_INIT;
3098 * Create .git/refs/{heads,tags}
3100 files_ref_path(refs, &sb, "refs/heads");
3101 safe_create_dir(sb.buf, 1);
3104 files_ref_path(refs, &sb, "refs/tags");
3105 safe_create_dir(sb.buf, 1);
3107 strbuf_release(&sb);
3111 struct ref_storage_be refs_be_files = {
3114 files_ref_store_create,
3116 files_transaction_prepare,
3117 files_transaction_finish,
3118 files_transaction_abort,
3119 files_initial_transaction_commit,
3122 files_create_symref,
3127 files_ref_iterator_begin,
3130 files_reflog_iterator_begin,
3131 files_for_each_reflog_ent,
3132 files_for_each_reflog_ent_reverse,
3133 files_reflog_exists,
3134 files_create_reflog,
3135 files_delete_reflog,