4 #include "refs-internal.h"
6 #include "packed-backend.h"
7 #include "../iterator.h"
8 #include "../dir-iterator.h"
9 #include "../lockfile.h"
10 #include "../object.h"
16 struct object_id old_oid;
20 * Future: need to be in "struct repository"
21 * when doing a full libification.
23 struct files_ref_store {
24 struct ref_store base;
25 unsigned int store_flags;
30 struct ref_cache *loose;
32 struct ref_store *packed_ref_store;
35 static void clear_loose_ref_cache(struct files_ref_store *refs)
38 free_ref_cache(refs->loose);
44 * Create a new submodule ref cache and add it to the internal
47 static struct ref_store *files_ref_store_create(const char *gitdir,
50 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
51 struct ref_store *ref_store = (struct ref_store *)refs;
52 struct strbuf sb = STRBUF_INIT;
54 base_ref_store_init(ref_store, &refs_be_files);
55 refs->store_flags = flags;
57 refs->gitdir = xstrdup(gitdir);
58 get_common_dir_noenv(&sb, gitdir);
59 refs->gitcommondir = strbuf_detach(&sb, NULL);
60 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
61 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
68 * Die if refs is not the main ref store. caller is used in any
69 * necessary error messages.
71 static void files_assert_main_repository(struct files_ref_store *refs,
74 if (refs->store_flags & REF_STORE_MAIN)
77 die("BUG: operation %s only allowed for main ref store", caller);
81 * Downcast ref_store to files_ref_store. Die if ref_store is not a
82 * files_ref_store. required_flags is compared with ref_store's
83 * store_flags to ensure the ref_store has all required capabilities.
84 * "caller" is used in any necessary error messages.
86 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
87 unsigned int required_flags,
90 struct files_ref_store *refs;
92 if (ref_store->be != &refs_be_files)
93 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
94 ref_store->be->name, caller);
96 refs = (struct files_ref_store *)ref_store;
98 if ((refs->store_flags & required_flags) != required_flags)
99 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
100 caller, required_flags, refs->store_flags);
105 static void files_reflog_path(struct files_ref_store *refs,
109 switch (ref_type(refname)) {
110 case REF_TYPE_PER_WORKTREE:
111 case REF_TYPE_PSEUDOREF:
112 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
114 case REF_TYPE_NORMAL:
115 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
118 die("BUG: unknown ref type %d of ref %s",
119 ref_type(refname), refname);
123 static void files_ref_path(struct files_ref_store *refs,
127 switch (ref_type(refname)) {
128 case REF_TYPE_PER_WORKTREE:
129 case REF_TYPE_PSEUDOREF:
130 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
132 case REF_TYPE_NORMAL:
133 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
136 die("BUG: unknown ref type %d of ref %s",
137 ref_type(refname), refname);
142 * Read the loose references from the namespace dirname into dir
143 * (without recursing). dirname must end with '/'. dir must be the
144 * directory entry corresponding to dirname.
146 static void loose_fill_ref_dir(struct ref_store *ref_store,
147 struct ref_dir *dir, const char *dirname)
149 struct files_ref_store *refs =
150 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
153 int dirnamelen = strlen(dirname);
154 struct strbuf refname;
155 struct strbuf path = STRBUF_INIT;
158 files_ref_path(refs, &path, dirname);
159 path_baselen = path.len;
161 d = opendir(path.buf);
163 strbuf_release(&path);
167 strbuf_init(&refname, dirnamelen + 257);
168 strbuf_add(&refname, dirname, dirnamelen);
170 while ((de = readdir(d)) != NULL) {
171 struct object_id oid;
175 if (de->d_name[0] == '.')
177 if (ends_with(de->d_name, ".lock"))
179 strbuf_addstr(&refname, de->d_name);
180 strbuf_addstr(&path, de->d_name);
181 if (stat(path.buf, &st) < 0) {
182 ; /* silently ignore */
183 } else if (S_ISDIR(st.st_mode)) {
184 strbuf_addch(&refname, '/');
185 add_entry_to_dir(dir,
186 create_dir_entry(dir->cache, refname.buf,
189 if (!refs_resolve_ref_unsafe(&refs->base,
194 flag |= REF_ISBROKEN;
195 } else if (is_null_oid(&oid)) {
197 * It is so astronomically unlikely
198 * that NULL_SHA1 is the SHA-1 of an
199 * actual object that we consider its
200 * appearance in a loose reference
201 * file to be repo corruption
202 * (probably due to a software bug).
204 flag |= REF_ISBROKEN;
207 if (check_refname_format(refname.buf,
208 REFNAME_ALLOW_ONELEVEL)) {
209 if (!refname_is_safe(refname.buf))
210 die("loose refname is dangerous: %s", refname.buf);
212 flag |= REF_BAD_NAME | REF_ISBROKEN;
214 add_entry_to_dir(dir,
215 create_ref_entry(refname.buf, &oid, flag));
217 strbuf_setlen(&refname, dirnamelen);
218 strbuf_setlen(&path, path_baselen);
220 strbuf_release(&refname);
221 strbuf_release(&path);
225 * Manually add refs/bisect, which, being per-worktree, might
226 * not appear in the directory listing for refs/ in the main
229 if (!strcmp(dirname, "refs/")) {
230 int pos = search_ref_dir(dir, "refs/bisect/", 12);
233 struct ref_entry *child_entry = create_dir_entry(
234 dir->cache, "refs/bisect/", 12, 1);
235 add_entry_to_dir(dir, child_entry);
240 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
244 * Mark the top-level directory complete because we
245 * are about to read the only subdirectory that can
248 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
250 /* We're going to fill the top level ourselves: */
251 refs->loose->root->flag &= ~REF_INCOMPLETE;
254 * Add an incomplete entry for "refs/" (to be filled
257 add_entry_to_dir(get_ref_dir(refs->loose->root),
258 create_dir_entry(refs->loose, "refs/", 5, 1));
263 static int files_read_raw_ref(struct ref_store *ref_store,
264 const char *refname, unsigned char *sha1,
265 struct strbuf *referent, unsigned int *type)
267 struct files_ref_store *refs =
268 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
269 struct strbuf sb_contents = STRBUF_INIT;
270 struct strbuf sb_path = STRBUF_INIT;
277 int remaining_retries = 3;
280 strbuf_reset(&sb_path);
282 files_ref_path(refs, &sb_path, refname);
288 * We might have to loop back here to avoid a race
289 * condition: first we lstat() the file, then we try
290 * to read it as a link or as a file. But if somebody
291 * changes the type of the file (file <-> directory
292 * <-> symlink) between the lstat() and reading, then
293 * we don't want to report that as an error but rather
294 * try again starting with the lstat().
296 * We'll keep a count of the retries, though, just to avoid
297 * any confusing situation sending us into an infinite loop.
300 if (remaining_retries-- <= 0)
303 if (lstat(path, &st) < 0) {
306 if (refs_read_raw_ref(refs->packed_ref_store, refname,
307 sha1, referent, type)) {
315 /* Follow "normalized" - ie "refs/.." symlinks by hand */
316 if (S_ISLNK(st.st_mode)) {
317 strbuf_reset(&sb_contents);
318 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
319 if (errno == ENOENT || errno == EINVAL)
320 /* inconsistent with lstat; retry */
325 if (starts_with(sb_contents.buf, "refs/") &&
326 !check_refname_format(sb_contents.buf, 0)) {
327 strbuf_swap(&sb_contents, referent);
328 *type |= REF_ISSYMREF;
333 * It doesn't look like a refname; fall through to just
334 * treating it like a non-symlink, and reading whatever it
339 /* Is it a directory? */
340 if (S_ISDIR(st.st_mode)) {
342 * Even though there is a directory where the loose
343 * ref is supposed to be, there could still be a
346 if (refs_read_raw_ref(refs->packed_ref_store, refname,
347 sha1, referent, type)) {
356 * Anything else, just open it and try to use it as
359 fd = open(path, O_RDONLY);
361 if (errno == ENOENT && !S_ISLNK(st.st_mode))
362 /* inconsistent with lstat; retry */
367 strbuf_reset(&sb_contents);
368 if (strbuf_read(&sb_contents, fd, 256) < 0) {
369 int save_errno = errno;
375 strbuf_rtrim(&sb_contents);
376 buf = sb_contents.buf;
377 if (starts_with(buf, "ref:")) {
379 while (isspace(*buf))
382 strbuf_reset(referent);
383 strbuf_addstr(referent, buf);
384 *type |= REF_ISSYMREF;
390 * Please note that FETCH_HEAD has additional
391 * data after the sha.
393 if (get_sha1_hex(buf, sha1) ||
394 (buf[40] != '\0' && !isspace(buf[40]))) {
395 *type |= REF_ISBROKEN;
404 strbuf_release(&sb_path);
405 strbuf_release(&sb_contents);
410 static void unlock_ref(struct ref_lock *lock)
412 /* Do not free lock->lk -- atexit() still looks at them */
414 rollback_lock_file(lock->lk);
415 free(lock->ref_name);
420 * Lock refname, without following symrefs, and set *lock_p to point
421 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
422 * and type similarly to read_raw_ref().
424 * The caller must verify that refname is a "safe" reference name (in
425 * the sense of refname_is_safe()) before calling this function.
427 * If the reference doesn't already exist, verify that refname doesn't
428 * have a D/F conflict with any existing references. extras and skip
429 * are passed to refs_verify_refname_available() for this check.
431 * If mustexist is not set and the reference is not found or is
432 * broken, lock the reference anyway but clear sha1.
434 * Return 0 on success. On failure, write an error message to err and
435 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
437 * Implementation note: This function is basically
442 * but it includes a lot more code to
443 * - Deal with possible races with other processes
444 * - Avoid calling refs_verify_refname_available() when it can be
445 * avoided, namely if we were successfully able to read the ref
446 * - Generate informative error messages in the case of failure
448 static int lock_raw_ref(struct files_ref_store *refs,
449 const char *refname, int mustexist,
450 const struct string_list *extras,
451 const struct string_list *skip,
452 struct ref_lock **lock_p,
453 struct strbuf *referent,
457 struct ref_lock *lock;
458 struct strbuf ref_file = STRBUF_INIT;
459 int attempts_remaining = 3;
460 int ret = TRANSACTION_GENERIC_ERROR;
463 files_assert_main_repository(refs, "lock_raw_ref");
467 /* First lock the file so it can't change out from under us. */
469 *lock_p = lock = xcalloc(1, sizeof(*lock));
471 lock->ref_name = xstrdup(refname);
472 files_ref_path(refs, &ref_file, refname);
475 switch (safe_create_leading_directories(ref_file.buf)) {
480 * Suppose refname is "refs/foo/bar". We just failed
481 * to create the containing directory, "refs/foo",
482 * because there was a non-directory in the way. This
483 * indicates a D/F conflict, probably because of
484 * another reference such as "refs/foo". There is no
485 * reason to expect this error to be transitory.
487 if (refs_verify_refname_available(&refs->base, refname,
488 extras, skip, err)) {
491 * To the user the relevant error is
492 * that the "mustexist" reference is
496 strbuf_addf(err, "unable to resolve reference '%s'",
500 * The error message set by
501 * refs_verify_refname_available() is
504 ret = TRANSACTION_NAME_CONFLICT;
508 * The file that is in the way isn't a loose
509 * reference. Report it as a low-level
512 strbuf_addf(err, "unable to create lock file %s.lock; "
513 "non-directory in the way",
518 /* Maybe another process was tidying up. Try again. */
519 if (--attempts_remaining > 0)
523 strbuf_addf(err, "unable to create directory for %s",
529 lock->lk = xcalloc(1, sizeof(struct lock_file));
531 if (hold_lock_file_for_update_timeout(
532 lock->lk, ref_file.buf, LOCK_NO_DEREF,
533 get_files_ref_lock_timeout_ms()) < 0) {
534 if (errno == ENOENT && --attempts_remaining > 0) {
536 * Maybe somebody just deleted one of the
537 * directories leading to ref_file. Try
542 unable_to_lock_message(ref_file.buf, errno, err);
548 * Now we hold the lock and can read the reference without
549 * fear that its value will change.
552 if (files_read_raw_ref(&refs->base, refname,
553 lock->old_oid.hash, referent, type)) {
554 if (errno == ENOENT) {
556 /* Garden variety missing reference. */
557 strbuf_addf(err, "unable to resolve reference '%s'",
562 * Reference is missing, but that's OK. We
563 * know that there is not a conflict with
564 * another loose reference because
565 * (supposing that we are trying to lock
566 * reference "refs/foo/bar"):
568 * - We were successfully able to create
569 * the lockfile refs/foo/bar.lock, so we
570 * know there cannot be a loose reference
573 * - We got ENOENT and not EISDIR, so we
574 * know that there cannot be a loose
575 * reference named "refs/foo/bar/baz".
578 } else if (errno == EISDIR) {
580 * There is a directory in the way. It might have
581 * contained references that have been deleted. If
582 * we don't require that the reference already
583 * exists, try to remove the directory so that it
584 * doesn't cause trouble when we want to rename the
585 * lockfile into place later.
588 /* Garden variety missing reference. */
589 strbuf_addf(err, "unable to resolve reference '%s'",
592 } else if (remove_dir_recursively(&ref_file,
593 REMOVE_DIR_EMPTY_ONLY)) {
594 if (refs_verify_refname_available(
595 &refs->base, refname,
596 extras, skip, err)) {
598 * The error message set by
599 * verify_refname_available() is OK.
601 ret = TRANSACTION_NAME_CONFLICT;
605 * We can't delete the directory,
606 * but we also don't know of any
607 * references that it should
610 strbuf_addf(err, "there is a non-empty directory '%s' "
611 "blocking reference '%s'",
612 ref_file.buf, refname);
616 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
617 strbuf_addf(err, "unable to resolve reference '%s': "
618 "reference broken", refname);
621 strbuf_addf(err, "unable to resolve reference '%s': %s",
622 refname, strerror(errno));
627 * If the ref did not exist and we are creating it,
628 * make sure there is no existing packed ref that
629 * conflicts with refname:
631 if (refs_verify_refname_available(
632 refs->packed_ref_store, refname,
645 strbuf_release(&ref_file);
649 static int files_peel_ref(struct ref_store *ref_store,
650 const char *refname, unsigned char *sha1)
652 struct files_ref_store *refs =
653 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
656 unsigned char base[20];
658 if (current_ref_iter && current_ref_iter->refname == refname) {
659 struct object_id peeled;
661 if (ref_iterator_peel(current_ref_iter, &peeled))
663 hashcpy(sha1, peeled.hash);
667 if (refs_read_ref_full(ref_store, refname,
668 RESOLVE_REF_READING, base, &flag))
672 * If the reference is packed, read its ref_entry from the
673 * cache in the hope that we already know its peeled value.
674 * We only try this optimization on packed references because
675 * (a) forcing the filling of the loose reference cache could
676 * be expensive and (b) loose references anyway usually do not
677 * have REF_KNOWS_PEELED.
679 if (flag & REF_ISPACKED &&
680 !refs_peel_ref(refs->packed_ref_store, refname, sha1))
683 return peel_object(base, sha1);
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;
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");
766 iter = xcalloc(1, sizeof(*iter));
767 ref_iterator = &iter->base;
768 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
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 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
812 * Verify that the reference locked by lock has the value old_sha1.
813 * Fail if the reference doesn't exist and mustexist is set. Return 0
814 * on success. On error, write an error message to err, set errno, and
815 * return a negative value.
817 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
818 const unsigned char *old_sha1, int mustexist,
823 if (refs_read_ref_full(ref_store, lock->ref_name,
824 mustexist ? RESOLVE_REF_READING : 0,
825 lock->old_oid.hash, NULL)) {
827 int save_errno = errno;
828 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
832 oidclr(&lock->old_oid);
836 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
837 strbuf_addf(err, "ref '%s' is at %s but expected %s",
839 oid_to_hex(&lock->old_oid),
840 sha1_to_hex(old_sha1));
847 static int remove_empty_directories(struct strbuf *path)
850 * we want to create a file but there is a directory there;
851 * if that is an empty directory (or a directory that contains
852 * only empty directories), remove them.
854 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
857 static int create_reflock(const char *path, void *cb)
859 struct lock_file *lk = cb;
861 return hold_lock_file_for_update_timeout(
862 lk, path, LOCK_NO_DEREF,
863 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
867 * Locks a ref returning the lock on success and NULL on failure.
868 * On failure errno is set to something meaningful.
870 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
872 const unsigned char *old_sha1,
873 const struct string_list *extras,
874 const struct string_list *skip,
875 unsigned int flags, int *type,
878 struct strbuf ref_file = STRBUF_INIT;
879 struct ref_lock *lock;
881 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
882 int resolve_flags = RESOLVE_REF_NO_RECURSE;
885 files_assert_main_repository(refs, "lock_ref_sha1_basic");
888 lock = xcalloc(1, sizeof(struct ref_lock));
891 resolve_flags |= RESOLVE_REF_READING;
892 if (flags & REF_DELETING)
893 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
895 files_ref_path(refs, &ref_file, refname);
896 resolved = !!refs_resolve_ref_unsafe(&refs->base,
897 refname, resolve_flags,
898 lock->old_oid.hash, type);
899 if (!resolved && errno == EISDIR) {
901 * we are trying to lock foo but we used to
902 * have foo/bar which now does not exist;
903 * it is normal for the empty directory 'foo'
906 if (remove_empty_directories(&ref_file)) {
908 if (!refs_verify_refname_available(
910 refname, extras, skip, err))
911 strbuf_addf(err, "there are still refs under '%s'",
915 resolved = !!refs_resolve_ref_unsafe(&refs->base,
916 refname, resolve_flags,
917 lock->old_oid.hash, type);
921 if (last_errno != ENOTDIR ||
922 !refs_verify_refname_available(&refs->base, refname,
924 strbuf_addf(err, "unable to resolve reference '%s': %s",
925 refname, strerror(last_errno));
931 * If the ref did not exist and we are creating it, make sure
932 * there is no existing packed ref whose name begins with our
933 * refname, nor a packed ref whose name is a proper prefix of
936 if (is_null_oid(&lock->old_oid) &&
937 refs_verify_refname_available(refs->packed_ref_store, refname,
938 extras, skip, err)) {
939 last_errno = ENOTDIR;
943 lock->lk = xcalloc(1, sizeof(struct lock_file));
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_sha1, mustexist, err)) {
964 strbuf_release(&ref_file);
969 struct ref_to_prune {
970 struct ref_to_prune *next;
971 unsigned char sha1[20];
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;
1034 if (check_refname_format(r->name, 0))
1037 transaction = ref_store_transaction_begin(&refs->base, &err);
1039 ref_transaction_delete(transaction, r->name, r->sha1,
1040 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1041 ref_transaction_commit(transaction, &err)) {
1042 ref_transaction_free(transaction);
1043 error("%s", err.buf);
1044 strbuf_release(&err);
1047 ref_transaction_free(transaction);
1048 strbuf_release(&err);
1051 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1060 * Return true if the specified reference should be packed.
1062 static int should_pack_ref(const char *refname,
1063 const struct object_id *oid, unsigned int ref_flags,
1064 unsigned int pack_flags)
1066 /* Do not pack per-worktree refs: */
1067 if (ref_type(refname) != REF_TYPE_NORMAL)
1070 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1071 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1074 /* Do not pack symbolic refs: */
1075 if (ref_flags & REF_ISSYMREF)
1078 /* Do not pack broken refs: */
1079 if (!ref_resolves_to_object(refname, oid, ref_flags))
1085 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1087 struct files_ref_store *refs =
1088 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1090 struct ref_iterator *iter;
1092 struct ref_to_prune *refs_to_prune = NULL;
1093 struct strbuf err = STRBUF_INIT;
1095 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1097 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1098 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1100 * If the loose reference can be packed, add an entry
1101 * in the packed ref cache. If the reference should be
1102 * pruned, also add it to refs_to_prune.
1104 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1109 * Create an entry in the packed-refs cache equivalent
1110 * to the one from the loose ref cache, except that
1111 * we don't copy the peeled status, because we want it
1114 add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);
1116 /* Schedule the loose reference for pruning if requested. */
1117 if ((flags & PACK_REFS_PRUNE)) {
1118 struct ref_to_prune *n;
1119 FLEX_ALLOC_STR(n, name, iter->refname);
1120 hashcpy(n->sha1, iter->oid->hash);
1121 n->next = refs_to_prune;
1125 if (ok != ITER_DONE)
1126 die("error while iterating over references");
1128 if (commit_packed_refs(refs->packed_ref_store, &err))
1129 die("unable to overwrite old ref-pack file: %s", err.buf);
1130 packed_refs_unlock(refs->packed_ref_store);
1132 prune_refs(refs, refs_to_prune);
1133 strbuf_release(&err);
1137 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1138 struct string_list *refnames, unsigned int flags)
1140 struct files_ref_store *refs =
1141 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1142 struct strbuf err = STRBUF_INIT;
1148 if (packed_refs_lock(refs->packed_ref_store, 0, &err))
1151 if (repack_without_refs(refs->packed_ref_store, refnames, &err)) {
1152 packed_refs_unlock(refs->packed_ref_store);
1156 packed_refs_unlock(refs->packed_ref_store);
1158 for (i = 0; i < refnames->nr; i++) {
1159 const char *refname = refnames->items[i].string;
1161 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1162 result |= error(_("could not remove reference %s"), refname);
1165 strbuf_release(&err);
1170 * If we failed to rewrite the packed-refs file, then it is
1171 * unsafe to try to remove loose refs, because doing so might
1172 * expose an obsolete packed value for a reference that might
1173 * even point at an object that has been garbage collected.
1175 if (refnames->nr == 1)
1176 error(_("could not delete reference %s: %s"),
1177 refnames->items[0].string, err.buf);
1179 error(_("could not delete references: %s"), err.buf);
1181 strbuf_release(&err);
1186 * People using contrib's git-new-workdir have .git/logs/refs ->
1187 * /some/other/path/.git/logs/refs, and that may live on another device.
1189 * IOW, to avoid cross device rename errors, the temporary renamed log must
1190 * live into logs/refs.
1192 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1195 const char *tmp_renamed_log;
1199 static int rename_tmp_log_callback(const char *path, void *cb_data)
1201 struct rename_cb *cb = cb_data;
1203 if (rename(cb->tmp_renamed_log, path)) {
1205 * rename(a, b) when b is an existing directory ought
1206 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1207 * Sheesh. Record the true errno for error reporting,
1208 * but report EISDIR to raceproof_create_file() so
1209 * that it knows to retry.
1211 cb->true_errno = errno;
1212 if (errno == ENOTDIR)
1220 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1222 struct strbuf path = STRBUF_INIT;
1223 struct strbuf tmp = STRBUF_INIT;
1224 struct rename_cb cb;
1227 files_reflog_path(refs, &path, newrefname);
1228 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1229 cb.tmp_renamed_log = tmp.buf;
1230 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1232 if (errno == EISDIR)
1233 error("directory not empty: %s", path.buf);
1235 error("unable to move logfile %s to %s: %s",
1237 strerror(cb.true_errno));
1240 strbuf_release(&path);
1241 strbuf_release(&tmp);
1245 static int write_ref_to_lockfile(struct ref_lock *lock,
1246 const struct object_id *oid, struct strbuf *err);
1247 static int commit_ref_update(struct files_ref_store *refs,
1248 struct ref_lock *lock,
1249 const struct object_id *oid, const char *logmsg,
1250 struct strbuf *err);
1252 static int files_rename_ref(struct ref_store *ref_store,
1253 const char *oldrefname, const char *newrefname,
1256 struct files_ref_store *refs =
1257 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1258 struct object_id oid, orig_oid;
1259 int flag = 0, logmoved = 0;
1260 struct ref_lock *lock;
1261 struct stat loginfo;
1262 struct strbuf sb_oldref = STRBUF_INIT;
1263 struct strbuf sb_newref = STRBUF_INIT;
1264 struct strbuf tmp_renamed_log = STRBUF_INIT;
1266 struct strbuf err = STRBUF_INIT;
1268 files_reflog_path(refs, &sb_oldref, oldrefname);
1269 files_reflog_path(refs, &sb_newref, newrefname);
1270 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1272 log = !lstat(sb_oldref.buf, &loginfo);
1273 if (log && S_ISLNK(loginfo.st_mode)) {
1274 ret = error("reflog for %s is a symlink", oldrefname);
1278 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1279 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1280 orig_oid.hash, &flag)) {
1281 ret = error("refname %s not found", oldrefname);
1285 if (flag & REF_ISSYMREF) {
1286 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1290 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1295 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1296 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1297 oldrefname, strerror(errno));
1301 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1302 orig_oid.hash, REF_NODEREF)) {
1303 error("unable to delete old %s", oldrefname);
1308 * Since we are doing a shallow lookup, oid is not the
1309 * correct value to pass to delete_ref as old_oid. But that
1310 * doesn't matter, because an old_oid check wouldn't add to
1311 * the safety anyway; we want to delete the reference whatever
1312 * its current value.
1314 if (!refs_read_ref_full(&refs->base, newrefname,
1315 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1317 refs_delete_ref(&refs->base, NULL, newrefname,
1318 NULL, REF_NODEREF)) {
1319 if (errno == EISDIR) {
1320 struct strbuf path = STRBUF_INIT;
1323 files_ref_path(refs, &path, newrefname);
1324 result = remove_empty_directories(&path);
1325 strbuf_release(&path);
1328 error("Directory not empty: %s", newrefname);
1332 error("unable to delete existing %s", newrefname);
1337 if (log && rename_tmp_log(refs, newrefname))
1342 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1343 REF_NODEREF, NULL, &err);
1345 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1346 strbuf_release(&err);
1349 oidcpy(&lock->old_oid, &orig_oid);
1351 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1352 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1353 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1354 strbuf_release(&err);
1362 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1363 REF_NODEREF, NULL, &err);
1365 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1366 strbuf_release(&err);
1370 flag = log_all_ref_updates;
1371 log_all_ref_updates = LOG_REFS_NONE;
1372 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1373 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1374 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1375 strbuf_release(&err);
1377 log_all_ref_updates = flag;
1380 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1381 error("unable to restore logfile %s from %s: %s",
1382 oldrefname, newrefname, strerror(errno));
1383 if (!logmoved && log &&
1384 rename(tmp_renamed_log.buf, sb_oldref.buf))
1385 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1386 oldrefname, strerror(errno));
1389 strbuf_release(&sb_newref);
1390 strbuf_release(&sb_oldref);
1391 strbuf_release(&tmp_renamed_log);
1396 static int close_ref(struct ref_lock *lock)
1398 if (close_lock_file(lock->lk))
1403 static int commit_ref(struct ref_lock *lock)
1405 char *path = get_locked_file_path(lock->lk);
1408 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1410 * There is a directory at the path we want to rename
1411 * the lockfile to. Hopefully it is empty; try to
1414 size_t len = strlen(path);
1415 struct strbuf sb_path = STRBUF_INIT;
1417 strbuf_attach(&sb_path, path, len, len);
1420 * If this fails, commit_lock_file() will also fail
1421 * and will report the problem.
1423 remove_empty_directories(&sb_path);
1424 strbuf_release(&sb_path);
1429 if (commit_lock_file(lock->lk))
1434 static int open_or_create_logfile(const char *path, void *cb)
1438 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1439 return (*fd < 0) ? -1 : 0;
1443 * Create a reflog for a ref. If force_create = 0, only create the
1444 * reflog for certain refs (those for which should_autocreate_reflog
1445 * returns non-zero). Otherwise, create it regardless of the reference
1446 * name. If the logfile already existed or was created, return 0 and
1447 * set *logfd to the file descriptor opened for appending to the file.
1448 * If no logfile exists and we decided not to create one, return 0 and
1449 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1452 static int log_ref_setup(struct files_ref_store *refs,
1453 const char *refname, int force_create,
1454 int *logfd, struct strbuf *err)
1456 struct strbuf logfile_sb = STRBUF_INIT;
1459 files_reflog_path(refs, &logfile_sb, refname);
1460 logfile = strbuf_detach(&logfile_sb, NULL);
1462 if (force_create || should_autocreate_reflog(refname)) {
1463 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1464 if (errno == ENOENT)
1465 strbuf_addf(err, "unable to create directory for '%s': "
1466 "%s", logfile, strerror(errno));
1467 else if (errno == EISDIR)
1468 strbuf_addf(err, "there are still logs under '%s'",
1471 strbuf_addf(err, "unable to append to '%s': %s",
1472 logfile, strerror(errno));
1477 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1479 if (errno == ENOENT || errno == EISDIR) {
1481 * The logfile doesn't already exist,
1482 * but that is not an error; it only
1483 * means that we won't write log
1488 strbuf_addf(err, "unable to append to '%s': %s",
1489 logfile, strerror(errno));
1496 adjust_shared_perm(logfile);
1506 static int files_create_reflog(struct ref_store *ref_store,
1507 const char *refname, int force_create,
1510 struct files_ref_store *refs =
1511 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1514 if (log_ref_setup(refs, refname, force_create, &fd, err))
1523 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1524 const struct object_id *new_oid,
1525 const char *committer, const char *msg)
1527 int msglen, written;
1528 unsigned maxlen, len;
1531 msglen = msg ? strlen(msg) : 0;
1532 maxlen = strlen(committer) + msglen + 100;
1533 logrec = xmalloc(maxlen);
1534 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1535 oid_to_hex(old_oid),
1536 oid_to_hex(new_oid),
1539 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1541 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
1549 static int files_log_ref_write(struct files_ref_store *refs,
1550 const char *refname, const struct object_id *old_oid,
1551 const struct object_id *new_oid, const char *msg,
1552 int flags, struct strbuf *err)
1556 if (log_all_ref_updates == LOG_REFS_UNSET)
1557 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1559 result = log_ref_setup(refs, refname,
1560 flags & REF_FORCE_CREATE_REFLOG,
1568 result = log_ref_write_fd(logfd, old_oid, new_oid,
1569 git_committer_info(0), msg);
1571 struct strbuf sb = STRBUF_INIT;
1572 int save_errno = errno;
1574 files_reflog_path(refs, &sb, refname);
1575 strbuf_addf(err, "unable to append to '%s': %s",
1576 sb.buf, strerror(save_errno));
1577 strbuf_release(&sb);
1582 struct strbuf sb = STRBUF_INIT;
1583 int save_errno = errno;
1585 files_reflog_path(refs, &sb, refname);
1586 strbuf_addf(err, "unable to append to '%s': %s",
1587 sb.buf, strerror(save_errno));
1588 strbuf_release(&sb);
1595 * Write sha1 into the open lockfile, then close the lockfile. On
1596 * errors, rollback the lockfile, fill in *err and
1599 static int write_ref_to_lockfile(struct ref_lock *lock,
1600 const struct object_id *oid, struct strbuf *err)
1602 static char term = '\n';
1606 o = parse_object(oid);
1609 "trying to write ref '%s' with nonexistent object %s",
1610 lock->ref_name, oid_to_hex(oid));
1614 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1616 "trying to write non-commit object %s to branch '%s'",
1617 oid_to_hex(oid), lock->ref_name);
1621 fd = get_lock_file_fd(lock->lk);
1622 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
1623 write_in_full(fd, &term, 1) != 1 ||
1624 close_ref(lock) < 0) {
1626 "couldn't write '%s'", get_lock_file_path(lock->lk));
1634 * Commit a change to a loose reference that has already been written
1635 * to the loose reference lockfile. Also update the reflogs if
1636 * necessary, using the specified lockmsg (which can be NULL).
1638 static int commit_ref_update(struct files_ref_store *refs,
1639 struct ref_lock *lock,
1640 const struct object_id *oid, const char *logmsg,
1643 files_assert_main_repository(refs, "commit_ref_update");
1645 clear_loose_ref_cache(refs);
1646 if (files_log_ref_write(refs, lock->ref_name,
1647 &lock->old_oid, oid,
1649 char *old_msg = strbuf_detach(err, NULL);
1650 strbuf_addf(err, "cannot update the ref '%s': %s",
1651 lock->ref_name, old_msg);
1657 if (strcmp(lock->ref_name, "HEAD") != 0) {
1659 * Special hack: If a branch is updated directly and HEAD
1660 * points to it (may happen on the remote side of a push
1661 * for example) then logically the HEAD reflog should be
1663 * A generic solution implies reverse symref information,
1664 * but finding all symrefs pointing to the given branch
1665 * would be rather costly for this rare event (the direct
1666 * update of a branch) to be worth it. So let's cheat and
1667 * check with HEAD only which should cover 99% of all usage
1668 * scenarios (even 100% of the default ones).
1670 struct object_id head_oid;
1672 const char *head_ref;
1674 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1675 RESOLVE_REF_READING,
1676 head_oid.hash, &head_flag);
1677 if (head_ref && (head_flag & REF_ISSYMREF) &&
1678 !strcmp(head_ref, lock->ref_name)) {
1679 struct strbuf log_err = STRBUF_INIT;
1680 if (files_log_ref_write(refs, "HEAD",
1681 &lock->old_oid, oid,
1682 logmsg, 0, &log_err)) {
1683 error("%s", log_err.buf);
1684 strbuf_release(&log_err);
1689 if (commit_ref(lock)) {
1690 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1699 static int create_ref_symlink(struct ref_lock *lock, const char *target)
1702 #ifndef NO_SYMLINK_HEAD
1703 char *ref_path = get_locked_file_path(lock->lk);
1705 ret = symlink(target, ref_path);
1709 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1714 static void update_symref_reflog(struct files_ref_store *refs,
1715 struct ref_lock *lock, const char *refname,
1716 const char *target, const char *logmsg)
1718 struct strbuf err = STRBUF_INIT;
1719 struct object_id new_oid;
1721 !refs_read_ref_full(&refs->base, target,
1722 RESOLVE_REF_READING, new_oid.hash, NULL) &&
1723 files_log_ref_write(refs, refname, &lock->old_oid,
1724 &new_oid, logmsg, 0, &err)) {
1725 error("%s", err.buf);
1726 strbuf_release(&err);
1730 static int create_symref_locked(struct files_ref_store *refs,
1731 struct ref_lock *lock, const char *refname,
1732 const char *target, const char *logmsg)
1734 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1735 update_symref_reflog(refs, lock, refname, target, logmsg);
1739 if (!fdopen_lock_file(lock->lk, "w"))
1740 return error("unable to fdopen %s: %s",
1741 lock->lk->tempfile.filename.buf, strerror(errno));
1743 update_symref_reflog(refs, lock, refname, target, logmsg);
1745 /* no error check; commit_ref will check ferror */
1746 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
1747 if (commit_ref(lock) < 0)
1748 return error("unable to write symref for %s: %s", refname,
1753 static int files_create_symref(struct ref_store *ref_store,
1754 const char *refname, const char *target,
1757 struct files_ref_store *refs =
1758 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1759 struct strbuf err = STRBUF_INIT;
1760 struct ref_lock *lock;
1763 lock = lock_ref_sha1_basic(refs, refname, NULL,
1764 NULL, NULL, REF_NODEREF, NULL,
1767 error("%s", err.buf);
1768 strbuf_release(&err);
1772 ret = create_symref_locked(refs, lock, refname, target, logmsg);
1777 static int files_reflog_exists(struct ref_store *ref_store,
1778 const char *refname)
1780 struct files_ref_store *refs =
1781 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1782 struct strbuf sb = STRBUF_INIT;
1786 files_reflog_path(refs, &sb, refname);
1787 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1788 strbuf_release(&sb);
1792 static int files_delete_reflog(struct ref_store *ref_store,
1793 const char *refname)
1795 struct files_ref_store *refs =
1796 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1797 struct strbuf sb = STRBUF_INIT;
1800 files_reflog_path(refs, &sb, refname);
1801 ret = remove_path(sb.buf);
1802 strbuf_release(&sb);
1806 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1808 struct object_id ooid, noid;
1809 char *email_end, *message;
1810 timestamp_t timestamp;
1812 const char *p = sb->buf;
1814 /* old SP new SP name <email> SP time TAB msg LF */
1815 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1816 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1817 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1818 !(email_end = strchr(p, '>')) ||
1819 email_end[1] != ' ' ||
1820 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1821 !message || message[0] != ' ' ||
1822 (message[1] != '+' && message[1] != '-') ||
1823 !isdigit(message[2]) || !isdigit(message[3]) ||
1824 !isdigit(message[4]) || !isdigit(message[5]))
1825 return 0; /* corrupt? */
1826 email_end[1] = '\0';
1827 tz = strtol(message + 1, NULL, 10);
1828 if (message[6] != '\t')
1832 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1835 static char *find_beginning_of_line(char *bob, char *scan)
1837 while (bob < scan && *(--scan) != '\n')
1838 ; /* keep scanning backwards */
1840 * Return either beginning of the buffer, or LF at the end of
1841 * the previous line.
1846 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1847 const char *refname,
1848 each_reflog_ent_fn fn,
1851 struct files_ref_store *refs =
1852 files_downcast(ref_store, REF_STORE_READ,
1853 "for_each_reflog_ent_reverse");
1854 struct strbuf sb = STRBUF_INIT;
1857 int ret = 0, at_tail = 1;
1859 files_reflog_path(refs, &sb, refname);
1860 logfp = fopen(sb.buf, "r");
1861 strbuf_release(&sb);
1865 /* Jump to the end */
1866 if (fseek(logfp, 0, SEEK_END) < 0)
1867 ret = error("cannot seek back reflog for %s: %s",
1868 refname, strerror(errno));
1870 while (!ret && 0 < pos) {
1876 /* Fill next block from the end */
1877 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1878 if (fseek(logfp, pos - cnt, SEEK_SET)) {
1879 ret = error("cannot seek back reflog for %s: %s",
1880 refname, strerror(errno));
1883 nread = fread(buf, cnt, 1, logfp);
1885 ret = error("cannot read %d bytes from reflog for %s: %s",
1886 cnt, refname, strerror(errno));
1891 scanp = endp = buf + cnt;
1892 if (at_tail && scanp[-1] == '\n')
1893 /* Looking at the final LF at the end of the file */
1897 while (buf < scanp) {
1899 * terminating LF of the previous line, or the beginning
1904 bp = find_beginning_of_line(buf, scanp);
1908 * The newline is the end of the previous line,
1909 * so we know we have complete line starting
1910 * at (bp + 1). Prefix it onto any prior data
1911 * we collected for the line and process it.
1913 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1916 ret = show_one_reflog_ent(&sb, fn, cb_data);
1922 * We are at the start of the buffer, and the
1923 * start of the file; there is no previous
1924 * line, and we have everything for this one.
1925 * Process it, and we can end the loop.
1927 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1928 ret = show_one_reflog_ent(&sb, fn, cb_data);
1935 * We are at the start of the buffer, and there
1936 * is more file to read backwards. Which means
1937 * we are in the middle of a line. Note that we
1938 * may get here even if *bp was a newline; that
1939 * just means we are at the exact end of the
1940 * previous line, rather than some spot in the
1943 * Save away what we have to be combined with
1944 * the data from the next read.
1946 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1953 die("BUG: reverse reflog parser had leftover data");
1956 strbuf_release(&sb);
1960 static int files_for_each_reflog_ent(struct ref_store *ref_store,
1961 const char *refname,
1962 each_reflog_ent_fn fn, void *cb_data)
1964 struct files_ref_store *refs =
1965 files_downcast(ref_store, REF_STORE_READ,
1966 "for_each_reflog_ent");
1968 struct strbuf sb = STRBUF_INIT;
1971 files_reflog_path(refs, &sb, refname);
1972 logfp = fopen(sb.buf, "r");
1973 strbuf_release(&sb);
1977 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
1978 ret = show_one_reflog_ent(&sb, fn, cb_data);
1980 strbuf_release(&sb);
1984 struct files_reflog_iterator {
1985 struct ref_iterator base;
1987 struct ref_store *ref_store;
1988 struct dir_iterator *dir_iterator;
1989 struct object_id oid;
1992 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
1994 struct files_reflog_iterator *iter =
1995 (struct files_reflog_iterator *)ref_iterator;
1996 struct dir_iterator *diter = iter->dir_iterator;
1999 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2002 if (!S_ISREG(diter->st.st_mode))
2004 if (diter->basename[0] == '.')
2006 if (ends_with(diter->basename, ".lock"))
2009 if (refs_read_ref_full(iter->ref_store,
2010 diter->relative_path, 0,
2011 iter->oid.hash, &flags)) {
2012 error("bad ref for %s", diter->path.buf);
2016 iter->base.refname = diter->relative_path;
2017 iter->base.oid = &iter->oid;
2018 iter->base.flags = flags;
2022 iter->dir_iterator = NULL;
2023 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2028 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2029 struct object_id *peeled)
2031 die("BUG: ref_iterator_peel() called for reflog_iterator");
2034 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2036 struct files_reflog_iterator *iter =
2037 (struct files_reflog_iterator *)ref_iterator;
2040 if (iter->dir_iterator)
2041 ok = dir_iterator_abort(iter->dir_iterator);
2043 base_ref_iterator_free(ref_iterator);
2047 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2048 files_reflog_iterator_advance,
2049 files_reflog_iterator_peel,
2050 files_reflog_iterator_abort
2053 static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,
2056 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2057 struct ref_iterator *ref_iterator = &iter->base;
2058 struct strbuf sb = STRBUF_INIT;
2060 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2061 strbuf_addf(&sb, "%s/logs", gitdir);
2062 iter->dir_iterator = dir_iterator_begin(sb.buf);
2063 iter->ref_store = ref_store;
2064 strbuf_release(&sb);
2066 return ref_iterator;
2069 static enum iterator_selection reflog_iterator_select(
2070 struct ref_iterator *iter_worktree,
2071 struct ref_iterator *iter_common,
2074 if (iter_worktree) {
2076 * We're a bit loose here. We probably should ignore
2077 * common refs if they are accidentally added as
2078 * per-worktree refs.
2080 return ITER_SELECT_0;
2081 } else if (iter_common) {
2082 if (ref_type(iter_common->refname) == REF_TYPE_NORMAL)
2083 return ITER_SELECT_1;
2086 * The main ref store may contain main worktree's
2087 * per-worktree refs, which should be ignored
2094 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2096 struct files_ref_store *refs =
2097 files_downcast(ref_store, REF_STORE_READ,
2098 "reflog_iterator_begin");
2100 if (!strcmp(refs->gitdir, refs->gitcommondir)) {
2101 return reflog_iterator_begin(ref_store, refs->gitcommondir);
2103 return merge_ref_iterator_begin(
2104 reflog_iterator_begin(ref_store, refs->gitdir),
2105 reflog_iterator_begin(ref_store, refs->gitcommondir),
2106 reflog_iterator_select, refs);
2111 * If update is a direct update of head_ref (the reference pointed to
2112 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2114 static int split_head_update(struct ref_update *update,
2115 struct ref_transaction *transaction,
2116 const char *head_ref,
2117 struct string_list *affected_refnames,
2120 struct string_list_item *item;
2121 struct ref_update *new_update;
2123 if ((update->flags & REF_LOG_ONLY) ||
2124 (update->flags & REF_ISPRUNING) ||
2125 (update->flags & REF_UPDATE_VIA_HEAD))
2128 if (strcmp(update->refname, head_ref))
2132 * First make sure that HEAD is not already in the
2133 * transaction. This check is O(lg N) in the transaction
2134 * size, but it happens at most once per transaction.
2136 if (string_list_has_string(affected_refnames, "HEAD")) {
2137 /* An entry already existed */
2139 "multiple updates for 'HEAD' (including one "
2140 "via its referent '%s') are not allowed",
2142 return TRANSACTION_NAME_CONFLICT;
2145 new_update = ref_transaction_add_update(
2146 transaction, "HEAD",
2147 update->flags | REF_LOG_ONLY | REF_NODEREF,
2148 update->new_oid.hash, update->old_oid.hash,
2152 * Add "HEAD". This insertion is O(N) in the transaction
2153 * size, but it happens at most once per transaction.
2154 * Add new_update->refname instead of a literal "HEAD".
2156 if (strcmp(new_update->refname, "HEAD"))
2157 BUG("%s unexpectedly not 'HEAD'", new_update->refname);
2158 item = string_list_insert(affected_refnames, new_update->refname);
2159 item->util = new_update;
2165 * update is for a symref that points at referent and doesn't have
2166 * REF_NODEREF set. Split it into two updates:
2167 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2168 * - A new, separate update for the referent reference
2169 * Note that the new update will itself be subject to splitting when
2170 * the iteration gets to it.
2172 static int split_symref_update(struct files_ref_store *refs,
2173 struct ref_update *update,
2174 const char *referent,
2175 struct ref_transaction *transaction,
2176 struct string_list *affected_refnames,
2179 struct string_list_item *item;
2180 struct ref_update *new_update;
2181 unsigned int new_flags;
2184 * First make sure that referent is not already in the
2185 * transaction. This check is O(lg N) in the transaction
2186 * size, but it happens at most once per symref in a
2189 if (string_list_has_string(affected_refnames, referent)) {
2190 /* An entry already exists */
2192 "multiple updates for '%s' (including one "
2193 "via symref '%s') are not allowed",
2194 referent, update->refname);
2195 return TRANSACTION_NAME_CONFLICT;
2198 new_flags = update->flags;
2199 if (!strcmp(update->refname, "HEAD")) {
2201 * Record that the new update came via HEAD, so that
2202 * when we process it, split_head_update() doesn't try
2203 * to add another reflog update for HEAD. Note that
2204 * this bit will be propagated if the new_update
2205 * itself needs to be split.
2207 new_flags |= REF_UPDATE_VIA_HEAD;
2210 new_update = ref_transaction_add_update(
2211 transaction, referent, new_flags,
2212 update->new_oid.hash, update->old_oid.hash,
2215 new_update->parent_update = update;
2218 * Change the symbolic ref update to log only. Also, it
2219 * doesn't need to check its old SHA-1 value, as that will be
2220 * done when new_update is processed.
2222 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2223 update->flags &= ~REF_HAVE_OLD;
2226 * Add the referent. This insertion is O(N) in the transaction
2227 * size, but it happens at most once per symref in a
2228 * transaction. Make sure to add new_update->refname, which will
2229 * be valid as long as affected_refnames is in use, and NOT
2230 * referent, which might soon be freed by our caller.
2232 item = string_list_insert(affected_refnames, new_update->refname);
2234 BUG("%s unexpectedly found in affected_refnames",
2235 new_update->refname);
2236 item->util = new_update;
2242 * Return the refname under which update was originally requested.
2244 static const char *original_update_refname(struct ref_update *update)
2246 while (update->parent_update)
2247 update = update->parent_update;
2249 return update->refname;
2253 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2254 * are consistent with oid, which is the reference's current value. If
2255 * everything is OK, return 0; otherwise, write an error message to
2256 * err and return -1.
2258 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2261 if (!(update->flags & REF_HAVE_OLD) ||
2262 !oidcmp(oid, &update->old_oid))
2265 if (is_null_oid(&update->old_oid))
2266 strbuf_addf(err, "cannot lock ref '%s': "
2267 "reference already exists",
2268 original_update_refname(update));
2269 else if (is_null_oid(oid))
2270 strbuf_addf(err, "cannot lock ref '%s': "
2271 "reference is missing but expected %s",
2272 original_update_refname(update),
2273 oid_to_hex(&update->old_oid));
2275 strbuf_addf(err, "cannot lock ref '%s': "
2276 "is at %s but expected %s",
2277 original_update_refname(update),
2279 oid_to_hex(&update->old_oid));
2285 * Prepare for carrying out update:
2286 * - Lock the reference referred to by update.
2287 * - Read the reference under lock.
2288 * - Check that its old SHA-1 value (if specified) is correct, and in
2289 * any case record it in update->lock->old_oid for later use when
2290 * writing the reflog.
2291 * - If it is a symref update without REF_NODEREF, split it up into a
2292 * REF_LOG_ONLY update of the symref and add a separate update for
2293 * the referent to transaction.
2294 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2297 static int lock_ref_for_update(struct files_ref_store *refs,
2298 struct ref_update *update,
2299 struct ref_transaction *transaction,
2300 const char *head_ref,
2301 struct string_list *affected_refnames,
2304 struct strbuf referent = STRBUF_INIT;
2305 int mustexist = (update->flags & REF_HAVE_OLD) &&
2306 !is_null_oid(&update->old_oid);
2308 struct ref_lock *lock;
2310 files_assert_main_repository(refs, "lock_ref_for_update");
2312 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2313 update->flags |= REF_DELETING;
2316 ret = split_head_update(update, transaction, head_ref,
2317 affected_refnames, err);
2322 ret = lock_raw_ref(refs, update->refname, mustexist,
2323 affected_refnames, NULL,
2325 &update->type, err);
2329 reason = strbuf_detach(err, NULL);
2330 strbuf_addf(err, "cannot lock ref '%s': %s",
2331 original_update_refname(update), reason);
2336 update->backend_data = lock;
2338 if (update->type & REF_ISSYMREF) {
2339 if (update->flags & REF_NODEREF) {
2341 * We won't be reading the referent as part of
2342 * the transaction, so we have to read it here
2343 * to record and possibly check old_sha1:
2345 if (refs_read_ref_full(&refs->base,
2347 lock->old_oid.hash, NULL)) {
2348 if (update->flags & REF_HAVE_OLD) {
2349 strbuf_addf(err, "cannot lock ref '%s': "
2350 "error reading reference",
2351 original_update_refname(update));
2352 ret = TRANSACTION_GENERIC_ERROR;
2355 } else if (check_old_oid(update, &lock->old_oid, err)) {
2356 ret = TRANSACTION_GENERIC_ERROR;
2361 * Create a new update for the reference this
2362 * symref is pointing at. Also, we will record
2363 * and verify old_sha1 for this update as part
2364 * of processing the split-off update, so we
2365 * don't have to do it here.
2367 ret = split_symref_update(refs, update,
2368 referent.buf, transaction,
2369 affected_refnames, err);
2374 struct ref_update *parent_update;
2376 if (check_old_oid(update, &lock->old_oid, err)) {
2377 ret = TRANSACTION_GENERIC_ERROR;
2382 * If this update is happening indirectly because of a
2383 * symref update, record the old SHA-1 in the parent
2386 for (parent_update = update->parent_update;
2388 parent_update = parent_update->parent_update) {
2389 struct ref_lock *parent_lock = parent_update->backend_data;
2390 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2394 if ((update->flags & REF_HAVE_NEW) &&
2395 !(update->flags & REF_DELETING) &&
2396 !(update->flags & REF_LOG_ONLY)) {
2397 if (!(update->type & REF_ISSYMREF) &&
2398 !oidcmp(&lock->old_oid, &update->new_oid)) {
2400 * The reference already has the desired
2401 * value, so we don't need to write it.
2403 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2405 char *write_err = strbuf_detach(err, NULL);
2408 * The lock was freed upon failure of
2409 * write_ref_to_lockfile():
2411 update->backend_data = NULL;
2413 "cannot update ref '%s': %s",
2414 update->refname, write_err);
2416 ret = TRANSACTION_GENERIC_ERROR;
2419 update->flags |= REF_NEEDS_COMMIT;
2422 if (!(update->flags & REF_NEEDS_COMMIT)) {
2424 * We didn't call write_ref_to_lockfile(), so
2425 * the lockfile is still open. Close it to
2426 * free up the file descriptor:
2428 if (close_ref(lock)) {
2429 strbuf_addf(err, "couldn't close '%s.lock'",
2431 ret = TRANSACTION_GENERIC_ERROR;
2437 strbuf_release(&referent);
2442 * Unlock any references in `transaction` that are still locked, and
2443 * mark the transaction closed.
2445 static void files_transaction_cleanup(struct ref_transaction *transaction)
2449 for (i = 0; i < transaction->nr; i++) {
2450 struct ref_update *update = transaction->updates[i];
2451 struct ref_lock *lock = update->backend_data;
2455 update->backend_data = NULL;
2459 transaction->state = REF_TRANSACTION_CLOSED;
2462 static int files_transaction_prepare(struct ref_store *ref_store,
2463 struct ref_transaction *transaction,
2466 struct files_ref_store *refs =
2467 files_downcast(ref_store, REF_STORE_WRITE,
2468 "ref_transaction_prepare");
2471 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2472 char *head_ref = NULL;
2474 struct object_id head_oid;
2478 if (!transaction->nr)
2482 * Fail if a refname appears more than once in the
2483 * transaction. (If we end up splitting up any updates using
2484 * split_symref_update() or split_head_update(), those
2485 * functions will check that the new updates don't have the
2486 * same refname as any existing ones.)
2488 for (i = 0; i < transaction->nr; i++) {
2489 struct ref_update *update = transaction->updates[i];
2490 struct string_list_item *item =
2491 string_list_append(&affected_refnames, update->refname);
2494 * We store a pointer to update in item->util, but at
2495 * the moment we never use the value of this field
2496 * except to check whether it is non-NULL.
2498 item->util = update;
2500 string_list_sort(&affected_refnames);
2501 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2502 ret = TRANSACTION_GENERIC_ERROR;
2507 * Special hack: If a branch is updated directly and HEAD
2508 * points to it (may happen on the remote side of a push
2509 * for example) then logically the HEAD reflog should be
2512 * A generic solution would require reverse symref lookups,
2513 * but finding all symrefs pointing to a given branch would be
2514 * rather costly for this rare event (the direct update of a
2515 * branch) to be worth it. So let's cheat and check with HEAD
2516 * only, which should cover 99% of all usage scenarios (even
2517 * 100% of the default ones).
2519 * So if HEAD is a symbolic reference, then record the name of
2520 * the reference that it points to. If we see an update of
2521 * head_ref within the transaction, then split_head_update()
2522 * arranges for the reflog of HEAD to be updated, too.
2524 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2525 RESOLVE_REF_NO_RECURSE,
2526 head_oid.hash, &head_type);
2528 if (head_ref && !(head_type & REF_ISSYMREF)) {
2529 FREE_AND_NULL(head_ref);
2533 * Acquire all locks, verify old values if provided, check
2534 * that new values are valid, and write new values to the
2535 * lockfiles, ready to be activated. Only keep one lockfile
2536 * open at a time to avoid running out of file descriptors.
2537 * Note that lock_ref_for_update() might append more updates
2538 * to the transaction.
2540 for (i = 0; i < transaction->nr; i++) {
2541 struct ref_update *update = transaction->updates[i];
2543 ret = lock_ref_for_update(refs, update, transaction,
2544 head_ref, &affected_refnames, err);
2551 string_list_clear(&affected_refnames, 0);
2554 files_transaction_cleanup(transaction);
2556 transaction->state = REF_TRANSACTION_PREPARED;
2561 static int files_transaction_finish(struct ref_store *ref_store,
2562 struct ref_transaction *transaction,
2565 struct files_ref_store *refs =
2566 files_downcast(ref_store, 0, "ref_transaction_finish");
2569 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2570 struct string_list_item *ref_to_delete;
2571 struct strbuf sb = STRBUF_INIT;
2575 if (!transaction->nr) {
2576 transaction->state = REF_TRANSACTION_CLOSED;
2580 /* Perform updates first so live commits remain referenced */
2581 for (i = 0; i < transaction->nr; i++) {
2582 struct ref_update *update = transaction->updates[i];
2583 struct ref_lock *lock = update->backend_data;
2585 if (update->flags & REF_NEEDS_COMMIT ||
2586 update->flags & REF_LOG_ONLY) {
2587 if (files_log_ref_write(refs,
2591 update->msg, update->flags,
2593 char *old_msg = strbuf_detach(err, NULL);
2595 strbuf_addf(err, "cannot update the ref '%s': %s",
2596 lock->ref_name, old_msg);
2599 update->backend_data = NULL;
2600 ret = TRANSACTION_GENERIC_ERROR;
2604 if (update->flags & REF_NEEDS_COMMIT) {
2605 clear_loose_ref_cache(refs);
2606 if (commit_ref(lock)) {
2607 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2609 update->backend_data = NULL;
2610 ret = TRANSACTION_GENERIC_ERROR;
2615 /* Perform deletes now that updates are safely completed */
2616 for (i = 0; i < transaction->nr; i++) {
2617 struct ref_update *update = transaction->updates[i];
2618 struct ref_lock *lock = update->backend_data;
2620 if (update->flags & REF_DELETING &&
2621 !(update->flags & REF_LOG_ONLY)) {
2622 if (!(update->type & REF_ISPACKED) ||
2623 update->type & REF_ISSYMREF) {
2624 /* It is a loose reference. */
2626 files_ref_path(refs, &sb, lock->ref_name);
2627 if (unlink_or_msg(sb.buf, err)) {
2628 ret = TRANSACTION_GENERIC_ERROR;
2631 update->flags |= REF_DELETED_LOOSE;
2634 if (!(update->flags & REF_ISPRUNING))
2635 string_list_append(&refs_to_delete,
2640 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2641 ret = TRANSACTION_GENERIC_ERROR;
2645 if (repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {
2646 ret = TRANSACTION_GENERIC_ERROR;
2647 packed_refs_unlock(refs->packed_ref_store);
2651 packed_refs_unlock(refs->packed_ref_store);
2653 /* Delete the reflogs of any references that were deleted: */
2654 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2656 files_reflog_path(refs, &sb, ref_to_delete->string);
2657 if (!unlink_or_warn(sb.buf))
2658 try_remove_empty_parents(refs, ref_to_delete->string,
2659 REMOVE_EMPTY_PARENTS_REFLOG);
2662 clear_loose_ref_cache(refs);
2665 files_transaction_cleanup(transaction);
2667 for (i = 0; i < transaction->nr; i++) {
2668 struct ref_update *update = transaction->updates[i];
2670 if (update->flags & REF_DELETED_LOOSE) {
2672 * The loose reference was deleted. Delete any
2673 * empty parent directories. (Note that this
2674 * can only work because we have already
2675 * removed the lockfile.)
2677 try_remove_empty_parents(refs, update->refname,
2678 REMOVE_EMPTY_PARENTS_REF);
2682 strbuf_release(&sb);
2683 string_list_clear(&refs_to_delete, 0);
2687 static int files_transaction_abort(struct ref_store *ref_store,
2688 struct ref_transaction *transaction,
2691 files_transaction_cleanup(transaction);
2695 static int ref_present(const char *refname,
2696 const struct object_id *oid, int flags, void *cb_data)
2698 struct string_list *affected_refnames = cb_data;
2700 return string_list_has_string(affected_refnames, refname);
2703 static int files_initial_transaction_commit(struct ref_store *ref_store,
2704 struct ref_transaction *transaction,
2707 struct files_ref_store *refs =
2708 files_downcast(ref_store, REF_STORE_WRITE,
2709 "initial_ref_transaction_commit");
2712 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2716 if (transaction->state != REF_TRANSACTION_OPEN)
2717 die("BUG: commit called for transaction that is not open");
2719 /* Fail if a refname appears more than once in the transaction: */
2720 for (i = 0; i < transaction->nr; i++)
2721 string_list_append(&affected_refnames,
2722 transaction->updates[i]->refname);
2723 string_list_sort(&affected_refnames);
2724 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2725 ret = TRANSACTION_GENERIC_ERROR;
2730 * It's really undefined to call this function in an active
2731 * repository or when there are existing references: we are
2732 * only locking and changing packed-refs, so (1) any
2733 * simultaneous processes might try to change a reference at
2734 * the same time we do, and (2) any existing loose versions of
2735 * the references that we are setting would have precedence
2736 * over our values. But some remote helpers create the remote
2737 * "HEAD" and "master" branches before calling this function,
2738 * so here we really only check that none of the references
2739 * that we are creating already exists.
2741 if (refs_for_each_rawref(&refs->base, ref_present,
2742 &affected_refnames))
2743 die("BUG: initial ref transaction called with existing refs");
2745 for (i = 0; i < transaction->nr; i++) {
2746 struct ref_update *update = transaction->updates[i];
2748 if ((update->flags & REF_HAVE_OLD) &&
2749 !is_null_oid(&update->old_oid))
2750 die("BUG: initial ref transaction with old_sha1 set");
2751 if (refs_verify_refname_available(&refs->base, update->refname,
2752 &affected_refnames, NULL,
2754 ret = TRANSACTION_NAME_CONFLICT;
2759 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2760 ret = TRANSACTION_GENERIC_ERROR;
2764 for (i = 0; i < transaction->nr; i++) {
2765 struct ref_update *update = transaction->updates[i];
2767 if ((update->flags & REF_HAVE_NEW) &&
2768 !is_null_oid(&update->new_oid))
2769 add_packed_ref(refs->packed_ref_store, update->refname,
2773 if (commit_packed_refs(refs->packed_ref_store, err)) {
2774 ret = TRANSACTION_GENERIC_ERROR;
2779 packed_refs_unlock(refs->packed_ref_store);
2780 transaction->state = REF_TRANSACTION_CLOSED;
2781 string_list_clear(&affected_refnames, 0);
2785 struct expire_reflog_cb {
2787 reflog_expiry_should_prune_fn *should_prune_fn;
2790 struct object_id last_kept_oid;
2793 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
2794 const char *email, timestamp_t timestamp, int tz,
2795 const char *message, void *cb_data)
2797 struct expire_reflog_cb *cb = cb_data;
2798 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
2800 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
2801 ooid = &cb->last_kept_oid;
2803 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
2804 message, policy_cb)) {
2806 printf("would prune %s", message);
2807 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2808 printf("prune %s", message);
2811 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
2812 oid_to_hex(ooid), oid_to_hex(noid),
2813 email, timestamp, tz, message);
2814 oidcpy(&cb->last_kept_oid, noid);
2816 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2817 printf("keep %s", message);
2822 static int files_reflog_expire(struct ref_store *ref_store,
2823 const char *refname, const unsigned char *sha1,
2825 reflog_expiry_prepare_fn prepare_fn,
2826 reflog_expiry_should_prune_fn should_prune_fn,
2827 reflog_expiry_cleanup_fn cleanup_fn,
2828 void *policy_cb_data)
2830 struct files_ref_store *refs =
2831 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
2832 static struct lock_file reflog_lock;
2833 struct expire_reflog_cb cb;
2834 struct ref_lock *lock;
2835 struct strbuf log_file_sb = STRBUF_INIT;
2839 struct strbuf err = STRBUF_INIT;
2840 struct object_id oid;
2842 memset(&cb, 0, sizeof(cb));
2844 cb.policy_cb = policy_cb_data;
2845 cb.should_prune_fn = should_prune_fn;
2848 * The reflog file is locked by holding the lock on the
2849 * reference itself, plus we might need to update the
2850 * reference if --updateref was specified:
2852 lock = lock_ref_sha1_basic(refs, refname, sha1,
2853 NULL, NULL, REF_NODEREF,
2856 error("cannot lock ref '%s': %s", refname, err.buf);
2857 strbuf_release(&err);
2860 if (!refs_reflog_exists(ref_store, refname)) {
2865 files_reflog_path(refs, &log_file_sb, refname);
2866 log_file = strbuf_detach(&log_file_sb, NULL);
2867 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2869 * Even though holding $GIT_DIR/logs/$reflog.lock has
2870 * no locking implications, we use the lock_file
2871 * machinery here anyway because it does a lot of the
2872 * work we need, including cleaning up if the program
2873 * exits unexpectedly.
2875 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
2876 struct strbuf err = STRBUF_INIT;
2877 unable_to_lock_message(log_file, errno, &err);
2878 error("%s", err.buf);
2879 strbuf_release(&err);
2882 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
2884 error("cannot fdopen %s (%s)",
2885 get_lock_file_path(&reflog_lock), strerror(errno));
2890 hashcpy(oid.hash, sha1);
2892 (*prepare_fn)(refname, &oid, cb.policy_cb);
2893 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
2894 (*cleanup_fn)(cb.policy_cb);
2896 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2898 * It doesn't make sense to adjust a reference pointed
2899 * to by a symbolic ref based on expiring entries in
2900 * the symbolic reference's reflog. Nor can we update
2901 * a reference if there are no remaining reflog
2904 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
2905 !(type & REF_ISSYMREF) &&
2906 !is_null_oid(&cb.last_kept_oid);
2908 if (close_lock_file(&reflog_lock)) {
2909 status |= error("couldn't write %s: %s", log_file,
2911 } else if (update &&
2912 (write_in_full(get_lock_file_fd(lock->lk),
2913 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2914 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
2915 close_ref(lock) < 0)) {
2916 status |= error("couldn't write %s",
2917 get_lock_file_path(lock->lk));
2918 rollback_lock_file(&reflog_lock);
2919 } else if (commit_lock_file(&reflog_lock)) {
2920 status |= error("unable to write reflog '%s' (%s)",
2921 log_file, strerror(errno));
2922 } else if (update && commit_ref(lock)) {
2923 status |= error("couldn't set %s", lock->ref_name);
2931 rollback_lock_file(&reflog_lock);
2937 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
2939 struct files_ref_store *refs =
2940 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
2941 struct strbuf sb = STRBUF_INIT;
2944 * Create .git/refs/{heads,tags}
2946 files_ref_path(refs, &sb, "refs/heads");
2947 safe_create_dir(sb.buf, 1);
2950 files_ref_path(refs, &sb, "refs/tags");
2951 safe_create_dir(sb.buf, 1);
2953 strbuf_release(&sb);
2957 struct ref_storage_be refs_be_files = {
2960 files_ref_store_create,
2962 files_transaction_prepare,
2963 files_transaction_finish,
2964 files_transaction_abort,
2965 files_initial_transaction_commit,
2969 files_create_symref,
2973 files_ref_iterator_begin,
2976 files_reflog_iterator_begin,
2977 files_for_each_reflog_ent,
2978 files_for_each_reflog_ent_reverse,
2979 files_reflog_exists,
2980 files_create_reflog,
2981 files_delete_reflog,