4 #include "refs-internal.h"
6 #include "../iterator.h"
7 #include "../dir-iterator.h"
8 #include "../lockfile.h"
15 struct object_id old_oid;
19 * Return true if refname, which has the specified oid and flags, can
20 * be resolved to an object in the database. If the referred-to object
21 * does not exist, emit a warning and return false.
23 static int ref_resolves_to_object(const char *refname,
24 const struct object_id *oid,
27 if (flags & REF_ISBROKEN)
29 if (!has_sha1_file(oid->hash)) {
30 error("%s does not point to a valid object!", refname);
36 struct packed_ref_cache {
37 struct ref_cache *cache;
40 * Count of references to the data structure in this instance,
41 * including the pointer from files_ref_store::packed if any.
42 * The data will not be freed as long as the reference count
45 unsigned int referrers;
48 * Iff the packed-refs file associated with this instance is
49 * currently locked for writing, this points at the associated
50 * lock (which is owned by somebody else). The referrer count
51 * is also incremented when the file is locked and decremented
52 * when it is unlocked.
54 struct lock_file *lock;
56 /* The metadata from when this packed-refs cache was read */
57 struct stat_validity validity;
61 * Future: need to be in "struct repository"
62 * when doing a full libification.
64 struct files_ref_store {
65 struct ref_store base;
66 unsigned int store_flags;
70 char *packed_refs_path;
72 struct ref_cache *loose;
73 struct packed_ref_cache *packed;
76 /* Lock used for the main packed-refs file: */
77 static struct lock_file packlock;
80 * Increment the reference count of *packed_refs.
82 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
84 packed_refs->referrers++;
88 * Decrease the reference count of *packed_refs. If it goes to zero,
89 * free *packed_refs and return true; otherwise return false.
91 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
93 if (!--packed_refs->referrers) {
94 free_ref_cache(packed_refs->cache);
95 stat_validity_clear(&packed_refs->validity);
103 static void clear_packed_ref_cache(struct files_ref_store *refs)
106 struct packed_ref_cache *packed_refs = refs->packed;
108 if (packed_refs->lock)
109 die("internal error: packed-ref cache cleared while locked");
111 release_packed_ref_cache(packed_refs);
115 static void clear_loose_ref_cache(struct files_ref_store *refs)
118 free_ref_cache(refs->loose);
124 * Create a new submodule ref cache and add it to the internal
127 static struct ref_store *files_ref_store_create(const char *gitdir,
130 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
131 struct ref_store *ref_store = (struct ref_store *)refs;
132 struct strbuf sb = STRBUF_INIT;
134 base_ref_store_init(ref_store, &refs_be_files);
135 refs->store_flags = flags;
137 refs->gitdir = xstrdup(gitdir);
138 get_common_dir_noenv(&sb, gitdir);
139 refs->gitcommondir = strbuf_detach(&sb, NULL);
140 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
141 refs->packed_refs_path = strbuf_detach(&sb, NULL);
147 * Die if refs is not the main ref store. caller is used in any
148 * necessary error messages.
150 static void files_assert_main_repository(struct files_ref_store *refs,
153 if (refs->store_flags & REF_STORE_MAIN)
156 die("BUG: operation %s only allowed for main ref store", caller);
160 * Downcast ref_store to files_ref_store. Die if ref_store is not a
161 * files_ref_store. required_flags is compared with ref_store's
162 * store_flags to ensure the ref_store has all required capabilities.
163 * "caller" is used in any necessary error messages.
165 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
166 unsigned int required_flags,
169 struct files_ref_store *refs;
171 if (ref_store->be != &refs_be_files)
172 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
173 ref_store->be->name, caller);
175 refs = (struct files_ref_store *)ref_store;
177 if ((refs->store_flags & required_flags) != required_flags)
178 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
179 caller, required_flags, refs->store_flags);
184 /* The length of a peeled reference line in packed-refs, including EOL: */
185 #define PEELED_LINE_LENGTH 42
188 * The packed-refs header line that we write out. Perhaps other
189 * traits will be added later. The trailing space is required.
191 static const char PACKED_REFS_HEADER[] =
192 "# pack-refs with: peeled fully-peeled \n";
195 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
196 * Return a pointer to the refname within the line (null-terminated),
197 * or NULL if there was a problem.
199 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
204 * 42: the answer to everything.
206 * In this case, it happens to be the answer to
207 * 40 (length of sha1 hex representation)
208 * +1 (space in between hex and name)
209 * +1 (newline at the end of the line)
214 if (get_sha1_hex(line->buf, sha1) < 0)
216 if (!isspace(line->buf[40]))
219 ref = line->buf + 41;
223 if (line->buf[line->len - 1] != '\n')
225 line->buf[--line->len] = 0;
231 * Read f, which is a packed-refs file, into dir.
233 * A comment line of the form "# pack-refs with: " may contain zero or
234 * more traits. We interpret the traits as follows:
238 * Probably no references are peeled. But if the file contains a
239 * peeled value for a reference, we will use it.
243 * References under "refs/tags/", if they *can* be peeled, *are*
244 * peeled in this file. References outside of "refs/tags/" are
245 * probably not peeled even if they could have been, but if we find
246 * a peeled value for such a reference we will use it.
250 * All references in the file that can be peeled are peeled.
251 * Inversely (and this is more important), any references in the
252 * file for which no peeled value is recorded is not peelable. This
253 * trait should typically be written alongside "peeled" for
254 * compatibility with older clients, but we do not require it
255 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
257 static void read_packed_refs(FILE *f, struct ref_dir *dir)
259 struct ref_entry *last = NULL;
260 struct strbuf line = STRBUF_INIT;
261 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
263 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
264 unsigned char sha1[20];
268 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
269 if (strstr(traits, " fully-peeled "))
270 peeled = PEELED_FULLY;
271 else if (strstr(traits, " peeled "))
272 peeled = PEELED_TAGS;
273 /* perhaps other traits later as well */
277 refname = parse_ref_line(&line, sha1);
279 int flag = REF_ISPACKED;
281 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
282 if (!refname_is_safe(refname))
283 die("packed refname is dangerous: %s", refname);
285 flag |= REF_BAD_NAME | REF_ISBROKEN;
287 last = create_ref_entry(refname, sha1, flag, 0);
288 if (peeled == PEELED_FULLY ||
289 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
290 last->flag |= REF_KNOWS_PEELED;
291 add_ref_entry(dir, last);
295 line.buf[0] == '^' &&
296 line.len == PEELED_LINE_LENGTH &&
297 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
298 !get_sha1_hex(line.buf + 1, sha1)) {
299 hashcpy(last->u.value.peeled.hash, sha1);
301 * Regardless of what the file header said,
302 * we definitely know the value of *this*
305 last->flag |= REF_KNOWS_PEELED;
309 strbuf_release(&line);
312 static const char *files_packed_refs_path(struct files_ref_store *refs)
314 return refs->packed_refs_path;
317 static void files_reflog_path(struct files_ref_store *refs,
323 * FIXME: of course this is wrong in multi worktree
324 * setting. To be fixed real soon.
326 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
330 switch (ref_type(refname)) {
331 case REF_TYPE_PER_WORKTREE:
332 case REF_TYPE_PSEUDOREF:
333 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
335 case REF_TYPE_NORMAL:
336 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
339 die("BUG: unknown ref type %d of ref %s",
340 ref_type(refname), refname);
344 static void files_ref_path(struct files_ref_store *refs,
348 switch (ref_type(refname)) {
349 case REF_TYPE_PER_WORKTREE:
350 case REF_TYPE_PSEUDOREF:
351 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
353 case REF_TYPE_NORMAL:
354 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
357 die("BUG: unknown ref type %d of ref %s",
358 ref_type(refname), refname);
363 * Get the packed_ref_cache for the specified files_ref_store,
364 * creating it if necessary.
366 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
368 const char *packed_refs_file = files_packed_refs_path(refs);
371 !stat_validity_check(&refs->packed->validity, packed_refs_file))
372 clear_packed_ref_cache(refs);
377 refs->packed = xcalloc(1, sizeof(*refs->packed));
378 acquire_packed_ref_cache(refs->packed);
379 refs->packed->cache = create_ref_cache(&refs->base, NULL);
380 refs->packed->cache->root->flag &= ~REF_INCOMPLETE;
381 f = fopen(packed_refs_file, "r");
383 stat_validity_update(&refs->packed->validity, fileno(f));
384 read_packed_refs(f, get_ref_dir(refs->packed->cache->root));
391 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
393 return get_ref_dir(packed_ref_cache->cache->root);
396 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
398 return get_packed_ref_dir(get_packed_ref_cache(refs));
402 * Add a reference to the in-memory packed reference cache. This may
403 * only be called while the packed-refs file is locked (see
404 * lock_packed_refs()). To actually write the packed-refs file, call
405 * commit_packed_refs().
407 static void add_packed_ref(struct files_ref_store *refs,
408 const char *refname, const unsigned char *sha1)
410 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
412 if (!packed_ref_cache->lock)
413 die("internal error: packed refs not locked");
414 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
415 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
419 * Read the loose references from the namespace dirname into dir
420 * (without recursing). dirname must end with '/'. dir must be the
421 * directory entry corresponding to dirname.
423 static void loose_fill_ref_dir(struct ref_store *ref_store,
424 struct ref_dir *dir, const char *dirname)
426 struct files_ref_store *refs =
427 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
430 int dirnamelen = strlen(dirname);
431 struct strbuf refname;
432 struct strbuf path = STRBUF_INIT;
435 files_ref_path(refs, &path, dirname);
436 path_baselen = path.len;
438 d = opendir(path.buf);
440 strbuf_release(&path);
444 strbuf_init(&refname, dirnamelen + 257);
445 strbuf_add(&refname, dirname, dirnamelen);
447 while ((de = readdir(d)) != NULL) {
448 unsigned char sha1[20];
452 if (de->d_name[0] == '.')
454 if (ends_with(de->d_name, ".lock"))
456 strbuf_addstr(&refname, de->d_name);
457 strbuf_addstr(&path, de->d_name);
458 if (stat(path.buf, &st) < 0) {
459 ; /* silently ignore */
460 } else if (S_ISDIR(st.st_mode)) {
461 strbuf_addch(&refname, '/');
462 add_entry_to_dir(dir,
463 create_dir_entry(dir->cache, refname.buf,
466 if (!refs_resolve_ref_unsafe(&refs->base,
471 flag |= REF_ISBROKEN;
472 } else if (is_null_sha1(sha1)) {
474 * It is so astronomically unlikely
475 * that NULL_SHA1 is the SHA-1 of an
476 * actual object that we consider its
477 * appearance in a loose reference
478 * file to be repo corruption
479 * (probably due to a software bug).
481 flag |= REF_ISBROKEN;
484 if (check_refname_format(refname.buf,
485 REFNAME_ALLOW_ONELEVEL)) {
486 if (!refname_is_safe(refname.buf))
487 die("loose refname is dangerous: %s", refname.buf);
489 flag |= REF_BAD_NAME | REF_ISBROKEN;
491 add_entry_to_dir(dir,
492 create_ref_entry(refname.buf, sha1, flag, 0));
494 strbuf_setlen(&refname, dirnamelen);
495 strbuf_setlen(&path, path_baselen);
497 strbuf_release(&refname);
498 strbuf_release(&path);
502 * Manually add refs/bisect, which, being per-worktree, might
503 * not appear in the directory listing for refs/ in the main
506 if (!strcmp(dirname, "refs/")) {
507 int pos = search_ref_dir(dir, "refs/bisect/", 12);
510 struct ref_entry *child_entry = create_dir_entry(
511 dir->cache, "refs/bisect/", 12, 1);
512 add_entry_to_dir(dir, child_entry);
517 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
521 * Mark the top-level directory complete because we
522 * are about to read the only subdirectory that can
525 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
527 /* We're going to fill the top level ourselves: */
528 refs->loose->root->flag &= ~REF_INCOMPLETE;
531 * Add an incomplete entry for "refs/" (to be filled
534 add_entry_to_dir(get_ref_dir(refs->loose->root),
535 create_dir_entry(refs->loose, "refs/", 5, 1));
541 * Return the ref_entry for the given refname from the packed
542 * references. If it does not exist, return NULL.
544 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
547 return find_ref_entry(get_packed_refs(refs), refname);
551 * A loose ref file doesn't exist; check for a packed ref.
553 static int resolve_packed_ref(struct files_ref_store *refs,
555 unsigned char *sha1, unsigned int *flags)
557 struct ref_entry *entry;
560 * The loose reference file does not exist; check for a packed
563 entry = get_packed_ref(refs, refname);
565 hashcpy(sha1, entry->u.value.oid.hash);
566 *flags |= REF_ISPACKED;
569 /* refname is not a packed reference. */
573 static int files_read_raw_ref(struct ref_store *ref_store,
574 const char *refname, unsigned char *sha1,
575 struct strbuf *referent, unsigned int *type)
577 struct files_ref_store *refs =
578 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
579 struct strbuf sb_contents = STRBUF_INIT;
580 struct strbuf sb_path = STRBUF_INIT;
587 int remaining_retries = 3;
590 strbuf_reset(&sb_path);
592 files_ref_path(refs, &sb_path, refname);
598 * We might have to loop back here to avoid a race
599 * condition: first we lstat() the file, then we try
600 * to read it as a link or as a file. But if somebody
601 * changes the type of the file (file <-> directory
602 * <-> symlink) between the lstat() and reading, then
603 * we don't want to report that as an error but rather
604 * try again starting with the lstat().
606 * We'll keep a count of the retries, though, just to avoid
607 * any confusing situation sending us into an infinite loop.
610 if (remaining_retries-- <= 0)
613 if (lstat(path, &st) < 0) {
616 if (resolve_packed_ref(refs, refname, sha1, type)) {
624 /* Follow "normalized" - ie "refs/.." symlinks by hand */
625 if (S_ISLNK(st.st_mode)) {
626 strbuf_reset(&sb_contents);
627 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
628 if (errno == ENOENT || errno == EINVAL)
629 /* inconsistent with lstat; retry */
634 if (starts_with(sb_contents.buf, "refs/") &&
635 !check_refname_format(sb_contents.buf, 0)) {
636 strbuf_swap(&sb_contents, referent);
637 *type |= REF_ISSYMREF;
642 * It doesn't look like a refname; fall through to just
643 * treating it like a non-symlink, and reading whatever it
648 /* Is it a directory? */
649 if (S_ISDIR(st.st_mode)) {
651 * Even though there is a directory where the loose
652 * ref is supposed to be, there could still be a
655 if (resolve_packed_ref(refs, refname, sha1, type)) {
664 * Anything else, just open it and try to use it as
667 fd = open(path, O_RDONLY);
669 if (errno == ENOENT && !S_ISLNK(st.st_mode))
670 /* inconsistent with lstat; retry */
675 strbuf_reset(&sb_contents);
676 if (strbuf_read(&sb_contents, fd, 256) < 0) {
677 int save_errno = errno;
683 strbuf_rtrim(&sb_contents);
684 buf = sb_contents.buf;
685 if (starts_with(buf, "ref:")) {
687 while (isspace(*buf))
690 strbuf_reset(referent);
691 strbuf_addstr(referent, buf);
692 *type |= REF_ISSYMREF;
698 * Please note that FETCH_HEAD has additional
699 * data after the sha.
701 if (get_sha1_hex(buf, sha1) ||
702 (buf[40] != '\0' && !isspace(buf[40]))) {
703 *type |= REF_ISBROKEN;
712 strbuf_release(&sb_path);
713 strbuf_release(&sb_contents);
718 static void unlock_ref(struct ref_lock *lock)
720 /* Do not free lock->lk -- atexit() still looks at them */
722 rollback_lock_file(lock->lk);
723 free(lock->ref_name);
728 * Lock refname, without following symrefs, and set *lock_p to point
729 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
730 * and type similarly to read_raw_ref().
732 * The caller must verify that refname is a "safe" reference name (in
733 * the sense of refname_is_safe()) before calling this function.
735 * If the reference doesn't already exist, verify that refname doesn't
736 * have a D/F conflict with any existing references. extras and skip
737 * are passed to refs_verify_refname_available() for this check.
739 * If mustexist is not set and the reference is not found or is
740 * broken, lock the reference anyway but clear sha1.
742 * Return 0 on success. On failure, write an error message to err and
743 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
745 * Implementation note: This function is basically
750 * but it includes a lot more code to
751 * - Deal with possible races with other processes
752 * - Avoid calling refs_verify_refname_available() when it can be
753 * avoided, namely if we were successfully able to read the ref
754 * - Generate informative error messages in the case of failure
756 static int lock_raw_ref(struct files_ref_store *refs,
757 const char *refname, int mustexist,
758 const struct string_list *extras,
759 const struct string_list *skip,
760 struct ref_lock **lock_p,
761 struct strbuf *referent,
765 struct ref_lock *lock;
766 struct strbuf ref_file = STRBUF_INIT;
767 int attempts_remaining = 3;
768 int ret = TRANSACTION_GENERIC_ERROR;
771 files_assert_main_repository(refs, "lock_raw_ref");
775 /* First lock the file so it can't change out from under us. */
777 *lock_p = lock = xcalloc(1, sizeof(*lock));
779 lock->ref_name = xstrdup(refname);
780 files_ref_path(refs, &ref_file, refname);
783 switch (safe_create_leading_directories(ref_file.buf)) {
788 * Suppose refname is "refs/foo/bar". We just failed
789 * to create the containing directory, "refs/foo",
790 * because there was a non-directory in the way. This
791 * indicates a D/F conflict, probably because of
792 * another reference such as "refs/foo". There is no
793 * reason to expect this error to be transitory.
795 if (refs_verify_refname_available(&refs->base, refname,
796 extras, skip, err)) {
799 * To the user the relevant error is
800 * that the "mustexist" reference is
804 strbuf_addf(err, "unable to resolve reference '%s'",
808 * The error message set by
809 * refs_verify_refname_available() is
812 ret = TRANSACTION_NAME_CONFLICT;
816 * The file that is in the way isn't a loose
817 * reference. Report it as a low-level
820 strbuf_addf(err, "unable to create lock file %s.lock; "
821 "non-directory in the way",
826 /* Maybe another process was tidying up. Try again. */
827 if (--attempts_remaining > 0)
831 strbuf_addf(err, "unable to create directory for %s",
837 lock->lk = xcalloc(1, sizeof(struct lock_file));
839 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
840 if (errno == ENOENT && --attempts_remaining > 0) {
842 * Maybe somebody just deleted one of the
843 * directories leading to ref_file. Try
848 unable_to_lock_message(ref_file.buf, errno, err);
854 * Now we hold the lock and can read the reference without
855 * fear that its value will change.
858 if (files_read_raw_ref(&refs->base, refname,
859 lock->old_oid.hash, referent, type)) {
860 if (errno == ENOENT) {
862 /* Garden variety missing reference. */
863 strbuf_addf(err, "unable to resolve reference '%s'",
868 * Reference is missing, but that's OK. We
869 * know that there is not a conflict with
870 * another loose reference because
871 * (supposing that we are trying to lock
872 * reference "refs/foo/bar"):
874 * - We were successfully able to create
875 * the lockfile refs/foo/bar.lock, so we
876 * know there cannot be a loose reference
879 * - We got ENOENT and not EISDIR, so we
880 * know that there cannot be a loose
881 * reference named "refs/foo/bar/baz".
884 } else if (errno == EISDIR) {
886 * There is a directory in the way. It might have
887 * contained references that have been deleted. If
888 * we don't require that the reference already
889 * exists, try to remove the directory so that it
890 * doesn't cause trouble when we want to rename the
891 * lockfile into place later.
894 /* Garden variety missing reference. */
895 strbuf_addf(err, "unable to resolve reference '%s'",
898 } else if (remove_dir_recursively(&ref_file,
899 REMOVE_DIR_EMPTY_ONLY)) {
900 if (refs_verify_refname_available(
901 &refs->base, refname,
902 extras, skip, err)) {
904 * The error message set by
905 * verify_refname_available() is OK.
907 ret = TRANSACTION_NAME_CONFLICT;
911 * We can't delete the directory,
912 * but we also don't know of any
913 * references that it should
916 strbuf_addf(err, "there is a non-empty directory '%s' "
917 "blocking reference '%s'",
918 ref_file.buf, refname);
922 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
923 strbuf_addf(err, "unable to resolve reference '%s': "
924 "reference broken", refname);
927 strbuf_addf(err, "unable to resolve reference '%s': %s",
928 refname, strerror(errno));
933 * If the ref did not exist and we are creating it,
934 * make sure there is no existing ref that conflicts
937 if (refs_verify_refname_available(
938 &refs->base, refname,
951 strbuf_release(&ref_file);
955 static int files_peel_ref(struct ref_store *ref_store,
956 const char *refname, unsigned char *sha1)
958 struct files_ref_store *refs =
959 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
962 unsigned char base[20];
964 if (current_ref_iter && current_ref_iter->refname == refname) {
965 struct object_id peeled;
967 if (ref_iterator_peel(current_ref_iter, &peeled))
969 hashcpy(sha1, peeled.hash);
973 if (refs_read_ref_full(ref_store, refname,
974 RESOLVE_REF_READING, base, &flag))
978 * If the reference is packed, read its ref_entry from the
979 * cache in the hope that we already know its peeled value.
980 * We only try this optimization on packed references because
981 * (a) forcing the filling of the loose reference cache could
982 * be expensive and (b) loose references anyway usually do not
983 * have REF_KNOWS_PEELED.
985 if (flag & REF_ISPACKED) {
986 struct ref_entry *r = get_packed_ref(refs, refname);
988 if (peel_entry(r, 0))
990 hashcpy(sha1, r->u.value.peeled.hash);
995 return peel_object(base, sha1);
998 struct files_ref_iterator {
999 struct ref_iterator base;
1001 struct packed_ref_cache *packed_ref_cache;
1002 struct ref_iterator *iter0;
1006 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1008 struct files_ref_iterator *iter =
1009 (struct files_ref_iterator *)ref_iterator;
1012 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1013 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1014 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1017 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1018 !ref_resolves_to_object(iter->iter0->refname,
1020 iter->iter0->flags))
1023 iter->base.refname = iter->iter0->refname;
1024 iter->base.oid = iter->iter0->oid;
1025 iter->base.flags = iter->iter0->flags;
1030 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1036 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1037 struct object_id *peeled)
1039 struct files_ref_iterator *iter =
1040 (struct files_ref_iterator *)ref_iterator;
1042 return ref_iterator_peel(iter->iter0, peeled);
1045 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1047 struct files_ref_iterator *iter =
1048 (struct files_ref_iterator *)ref_iterator;
1052 ok = ref_iterator_abort(iter->iter0);
1054 release_packed_ref_cache(iter->packed_ref_cache);
1055 base_ref_iterator_free(ref_iterator);
1059 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1060 files_ref_iterator_advance,
1061 files_ref_iterator_peel,
1062 files_ref_iterator_abort
1065 static struct ref_iterator *files_ref_iterator_begin(
1066 struct ref_store *ref_store,
1067 const char *prefix, unsigned int flags)
1069 struct files_ref_store *refs;
1070 struct ref_iterator *loose_iter, *packed_iter;
1071 struct files_ref_iterator *iter;
1072 struct ref_iterator *ref_iterator;
1074 if (ref_paranoia < 0)
1075 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1077 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1079 refs = files_downcast(ref_store,
1080 REF_STORE_READ | (ref_paranoia ? 0 : REF_STORE_ODB),
1081 "ref_iterator_begin");
1083 iter = xcalloc(1, sizeof(*iter));
1084 ref_iterator = &iter->base;
1085 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1088 * We must make sure that all loose refs are read before
1089 * accessing the packed-refs file; this avoids a race
1090 * condition if loose refs are migrated to the packed-refs
1091 * file by a simultaneous process, but our in-memory view is
1092 * from before the migration. We ensure this as follows:
1093 * First, we call start the loose refs iteration with its
1094 * `prime_ref` argument set to true. This causes the loose
1095 * references in the subtree to be pre-read into the cache.
1096 * (If they've already been read, that's OK; we only need to
1097 * guarantee that they're read before the packed refs, not
1098 * *how much* before.) After that, we call
1099 * get_packed_ref_cache(), which internally checks whether the
1100 * packed-ref cache is up to date with what is on disk, and
1101 * re-reads it if not.
1104 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1107 iter->packed_ref_cache = get_packed_ref_cache(refs);
1108 acquire_packed_ref_cache(iter->packed_ref_cache);
1109 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1112 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1113 iter->flags = flags;
1115 return ref_iterator;
1119 * Verify that the reference locked by lock has the value old_sha1.
1120 * Fail if the reference doesn't exist and mustexist is set. Return 0
1121 * on success. On error, write an error message to err, set errno, and
1122 * return a negative value.
1124 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1125 const unsigned char *old_sha1, int mustexist,
1130 if (refs_read_ref_full(ref_store, lock->ref_name,
1131 mustexist ? RESOLVE_REF_READING : 0,
1132 lock->old_oid.hash, NULL)) {
1134 int save_errno = errno;
1135 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1139 oidclr(&lock->old_oid);
1143 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1144 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1146 oid_to_hex(&lock->old_oid),
1147 sha1_to_hex(old_sha1));
1154 static int remove_empty_directories(struct strbuf *path)
1157 * we want to create a file but there is a directory there;
1158 * if that is an empty directory (or a directory that contains
1159 * only empty directories), remove them.
1161 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1164 static int create_reflock(const char *path, void *cb)
1166 struct lock_file *lk = cb;
1168 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1172 * Locks a ref returning the lock on success and NULL on failure.
1173 * On failure errno is set to something meaningful.
1175 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1176 const char *refname,
1177 const unsigned char *old_sha1,
1178 const struct string_list *extras,
1179 const struct string_list *skip,
1180 unsigned int flags, int *type,
1183 struct strbuf ref_file = STRBUF_INIT;
1184 struct ref_lock *lock;
1186 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1187 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1190 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1193 lock = xcalloc(1, sizeof(struct ref_lock));
1196 resolve_flags |= RESOLVE_REF_READING;
1197 if (flags & REF_DELETING)
1198 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1200 files_ref_path(refs, &ref_file, refname);
1201 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1202 refname, resolve_flags,
1203 lock->old_oid.hash, type);
1204 if (!resolved && errno == EISDIR) {
1206 * we are trying to lock foo but we used to
1207 * have foo/bar which now does not exist;
1208 * it is normal for the empty directory 'foo'
1211 if (remove_empty_directories(&ref_file)) {
1213 if (!refs_verify_refname_available(
1215 refname, extras, skip, err))
1216 strbuf_addf(err, "there are still refs under '%s'",
1220 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1221 refname, resolve_flags,
1222 lock->old_oid.hash, type);
1226 if (last_errno != ENOTDIR ||
1227 !refs_verify_refname_available(&refs->base, refname,
1229 strbuf_addf(err, "unable to resolve reference '%s': %s",
1230 refname, strerror(last_errno));
1236 * If the ref did not exist and we are creating it, make sure
1237 * there is no existing packed ref whose name begins with our
1238 * refname, nor a packed ref whose name is a proper prefix of
1241 if (is_null_oid(&lock->old_oid) &&
1242 refs_verify_refname_available(&refs->base, refname,
1243 extras, skip, err)) {
1244 last_errno = ENOTDIR;
1248 lock->lk = xcalloc(1, sizeof(struct lock_file));
1250 lock->ref_name = xstrdup(refname);
1252 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1254 unable_to_lock_message(ref_file.buf, errno, err);
1258 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1269 strbuf_release(&ref_file);
1275 * Write an entry to the packed-refs file for the specified refname.
1276 * If peeled is non-NULL, write it as the entry's peeled value.
1278 static void write_packed_entry(FILE *fh, const char *refname,
1279 const unsigned char *sha1,
1280 const unsigned char *peeled)
1282 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1284 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1288 * Lock the packed-refs file for writing. Flags is passed to
1289 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1290 * errno appropriately and return a nonzero value.
1292 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1294 static int timeout_configured = 0;
1295 static int timeout_value = 1000;
1296 struct packed_ref_cache *packed_ref_cache;
1298 files_assert_main_repository(refs, "lock_packed_refs");
1300 if (!timeout_configured) {
1301 git_config_get_int("core.packedrefstimeout", &timeout_value);
1302 timeout_configured = 1;
1305 if (hold_lock_file_for_update_timeout(
1306 &packlock, files_packed_refs_path(refs),
1307 flags, timeout_value) < 0)
1310 * Get the current packed-refs while holding the lock. If the
1311 * packed-refs file has been modified since we last read it,
1312 * this will automatically invalidate the cache and re-read
1313 * the packed-refs file.
1315 packed_ref_cache = get_packed_ref_cache(refs);
1316 packed_ref_cache->lock = &packlock;
1317 /* Increment the reference count to prevent it from being freed: */
1318 acquire_packed_ref_cache(packed_ref_cache);
1323 * Write the current version of the packed refs cache from memory to
1324 * disk. The packed-refs file must already be locked for writing (see
1325 * lock_packed_refs()). Return zero on success. On errors, set errno
1326 * and return a nonzero value
1328 static int commit_packed_refs(struct files_ref_store *refs)
1330 struct packed_ref_cache *packed_ref_cache =
1331 get_packed_ref_cache(refs);
1335 struct ref_iterator *iter;
1337 files_assert_main_repository(refs, "commit_packed_refs");
1339 if (!packed_ref_cache->lock)
1340 die("internal error: packed-refs not locked");
1342 out = fdopen_lock_file(packed_ref_cache->lock, "w");
1344 die_errno("unable to fdopen packed-refs descriptor");
1346 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1348 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1349 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1350 struct object_id peeled;
1351 int peel_error = ref_iterator_peel(iter, &peeled);
1353 write_packed_entry(out, iter->refname, iter->oid->hash,
1354 peel_error ? NULL : peeled.hash);
1357 if (ok != ITER_DONE)
1358 die("error while iterating over references");
1360 if (commit_lock_file(packed_ref_cache->lock)) {
1364 packed_ref_cache->lock = NULL;
1365 release_packed_ref_cache(packed_ref_cache);
1371 * Rollback the lockfile for the packed-refs file, and discard the
1372 * in-memory packed reference cache. (The packed-refs file will be
1373 * read anew if it is needed again after this function is called.)
1375 static void rollback_packed_refs(struct files_ref_store *refs)
1377 struct packed_ref_cache *packed_ref_cache =
1378 get_packed_ref_cache(refs);
1380 files_assert_main_repository(refs, "rollback_packed_refs");
1382 if (!packed_ref_cache->lock)
1383 die("internal error: packed-refs not locked");
1384 rollback_lock_file(packed_ref_cache->lock);
1385 packed_ref_cache->lock = NULL;
1386 release_packed_ref_cache(packed_ref_cache);
1387 clear_packed_ref_cache(refs);
1390 struct ref_to_prune {
1391 struct ref_to_prune *next;
1392 unsigned char sha1[20];
1393 char name[FLEX_ARRAY];
1397 REMOVE_EMPTY_PARENTS_REF = 0x01,
1398 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1402 * Remove empty parent directories associated with the specified
1403 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1404 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1405 * REMOVE_EMPTY_PARENTS_REFLOG.
1407 static void try_remove_empty_parents(struct files_ref_store *refs,
1408 const char *refname,
1411 struct strbuf buf = STRBUF_INIT;
1412 struct strbuf sb = STRBUF_INIT;
1416 strbuf_addstr(&buf, refname);
1418 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1419 while (*p && *p != '/')
1421 /* tolerate duplicate slashes; see check_refname_format() */
1425 q = buf.buf + buf.len;
1426 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1427 while (q > p && *q != '/')
1429 while (q > p && *(q-1) == '/')
1433 strbuf_setlen(&buf, q - buf.buf);
1436 files_ref_path(refs, &sb, buf.buf);
1437 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1438 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1441 files_reflog_path(refs, &sb, buf.buf);
1442 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1443 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1445 strbuf_release(&buf);
1446 strbuf_release(&sb);
1449 /* make sure nobody touched the ref, and unlink */
1450 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1452 struct ref_transaction *transaction;
1453 struct strbuf err = STRBUF_INIT;
1455 if (check_refname_format(r->name, 0))
1458 transaction = ref_store_transaction_begin(&refs->base, &err);
1460 ref_transaction_delete(transaction, r->name, r->sha1,
1461 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1462 ref_transaction_commit(transaction, &err)) {
1463 ref_transaction_free(transaction);
1464 error("%s", err.buf);
1465 strbuf_release(&err);
1468 ref_transaction_free(transaction);
1469 strbuf_release(&err);
1472 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1480 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1482 struct files_ref_store *refs =
1483 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1485 struct ref_iterator *iter;
1486 struct ref_dir *packed_refs;
1488 struct ref_to_prune *refs_to_prune = NULL;
1490 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1491 packed_refs = get_packed_refs(refs);
1493 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1494 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1496 * If the loose reference can be packed, add an entry
1497 * in the packed ref cache. If the reference should be
1498 * pruned, also add it to refs_to_prune.
1500 struct ref_entry *packed_entry;
1501 int is_tag_ref = starts_with(iter->refname, "refs/tags/");
1503 /* Do not pack per-worktree refs: */
1504 if (ref_type(iter->refname) != REF_TYPE_NORMAL)
1507 /* ALWAYS pack tags */
1508 if (!(flags & PACK_REFS_ALL) && !is_tag_ref)
1511 /* Do not pack symbolic or broken refs: */
1512 if (iter->flags & REF_ISSYMREF)
1515 if (!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))
1519 * Create an entry in the packed-refs cache equivalent
1520 * to the one from the loose ref cache, except that
1521 * we don't copy the peeled status, because we want it
1524 packed_entry = find_ref_entry(packed_refs, iter->refname);
1526 /* Overwrite existing packed entry with info from loose entry */
1527 packed_entry->flag = REF_ISPACKED;
1528 oidcpy(&packed_entry->u.value.oid, iter->oid);
1530 packed_entry = create_ref_entry(iter->refname, iter->oid->hash,
1532 add_ref_entry(packed_refs, packed_entry);
1534 oidclr(&packed_entry->u.value.peeled);
1536 /* Schedule the loose reference for pruning if requested. */
1537 if ((flags & PACK_REFS_PRUNE)) {
1538 struct ref_to_prune *n;
1539 FLEX_ALLOC_STR(n, name, iter->refname);
1540 hashcpy(n->sha1, iter->oid->hash);
1541 n->next = refs_to_prune;
1545 if (ok != ITER_DONE)
1546 die("error while iterating over references");
1548 if (commit_packed_refs(refs))
1549 die_errno("unable to overwrite old ref-pack file");
1551 prune_refs(refs, refs_to_prune);
1556 * Rewrite the packed-refs file, omitting any refs listed in
1557 * 'refnames'. On error, leave packed-refs unchanged, write an error
1558 * message to 'err', and return a nonzero value.
1560 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1562 static int repack_without_refs(struct files_ref_store *refs,
1563 struct string_list *refnames, struct strbuf *err)
1565 struct ref_dir *packed;
1566 struct string_list_item *refname;
1567 int ret, needs_repacking = 0, removed = 0;
1569 files_assert_main_repository(refs, "repack_without_refs");
1572 /* Look for a packed ref */
1573 for_each_string_list_item(refname, refnames) {
1574 if (get_packed_ref(refs, refname->string)) {
1575 needs_repacking = 1;
1580 /* Avoid locking if we have nothing to do */
1581 if (!needs_repacking)
1582 return 0; /* no refname exists in packed refs */
1584 if (lock_packed_refs(refs, 0)) {
1585 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1588 packed = get_packed_refs(refs);
1590 /* Remove refnames from the cache */
1591 for_each_string_list_item(refname, refnames)
1592 if (remove_entry_from_dir(packed, refname->string) != -1)
1596 * All packed entries disappeared while we were
1597 * acquiring the lock.
1599 rollback_packed_refs(refs);
1603 /* Write what remains */
1604 ret = commit_packed_refs(refs);
1606 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1611 static int files_delete_refs(struct ref_store *ref_store,
1612 struct string_list *refnames, unsigned int flags)
1614 struct files_ref_store *refs =
1615 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1616 struct strbuf err = STRBUF_INIT;
1622 result = repack_without_refs(refs, refnames, &err);
1625 * If we failed to rewrite the packed-refs file, then
1626 * it is unsafe to try to remove loose refs, because
1627 * doing so might expose an obsolete packed value for
1628 * a reference that might even point at an object that
1629 * has been garbage collected.
1631 if (refnames->nr == 1)
1632 error(_("could not delete reference %s: %s"),
1633 refnames->items[0].string, err.buf);
1635 error(_("could not delete references: %s"), err.buf);
1640 for (i = 0; i < refnames->nr; i++) {
1641 const char *refname = refnames->items[i].string;
1643 if (refs_delete_ref(&refs->base, NULL, refname, NULL, flags))
1644 result |= error(_("could not remove reference %s"), refname);
1648 strbuf_release(&err);
1653 * People using contrib's git-new-workdir have .git/logs/refs ->
1654 * /some/other/path/.git/logs/refs, and that may live on another device.
1656 * IOW, to avoid cross device rename errors, the temporary renamed log must
1657 * live into logs/refs.
1659 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1662 const char *tmp_renamed_log;
1666 static int rename_tmp_log_callback(const char *path, void *cb_data)
1668 struct rename_cb *cb = cb_data;
1670 if (rename(cb->tmp_renamed_log, path)) {
1672 * rename(a, b) when b is an existing directory ought
1673 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1674 * Sheesh. Record the true errno for error reporting,
1675 * but report EISDIR to raceproof_create_file() so
1676 * that it knows to retry.
1678 cb->true_errno = errno;
1679 if (errno == ENOTDIR)
1687 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1689 struct strbuf path = STRBUF_INIT;
1690 struct strbuf tmp = STRBUF_INIT;
1691 struct rename_cb cb;
1694 files_reflog_path(refs, &path, newrefname);
1695 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1696 cb.tmp_renamed_log = tmp.buf;
1697 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1699 if (errno == EISDIR)
1700 error("directory not empty: %s", path.buf);
1702 error("unable to move logfile %s to %s: %s",
1704 strerror(cb.true_errno));
1707 strbuf_release(&path);
1708 strbuf_release(&tmp);
1712 static int write_ref_to_lockfile(struct ref_lock *lock,
1713 const unsigned char *sha1, struct strbuf *err);
1714 static int commit_ref_update(struct files_ref_store *refs,
1715 struct ref_lock *lock,
1716 const unsigned char *sha1, const char *logmsg,
1717 struct strbuf *err);
1719 static int files_rename_ref(struct ref_store *ref_store,
1720 const char *oldrefname, const char *newrefname,
1723 struct files_ref_store *refs =
1724 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1725 unsigned char sha1[20], orig_sha1[20];
1726 int flag = 0, logmoved = 0;
1727 struct ref_lock *lock;
1728 struct stat loginfo;
1729 struct strbuf sb_oldref = STRBUF_INIT;
1730 struct strbuf sb_newref = STRBUF_INIT;
1731 struct strbuf tmp_renamed_log = STRBUF_INIT;
1733 struct strbuf err = STRBUF_INIT;
1735 files_reflog_path(refs, &sb_oldref, oldrefname);
1736 files_reflog_path(refs, &sb_newref, newrefname);
1737 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1739 log = !lstat(sb_oldref.buf, &loginfo);
1740 if (log && S_ISLNK(loginfo.st_mode)) {
1741 ret = error("reflog for %s is a symlink", oldrefname);
1745 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1746 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1747 orig_sha1, &flag)) {
1748 ret = error("refname %s not found", oldrefname);
1752 if (flag & REF_ISSYMREF) {
1753 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1757 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1762 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1763 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1764 oldrefname, strerror(errno));
1768 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1769 orig_sha1, REF_NODEREF)) {
1770 error("unable to delete old %s", oldrefname);
1775 * Since we are doing a shallow lookup, sha1 is not the
1776 * correct value to pass to delete_ref as old_sha1. But that
1777 * doesn't matter, because an old_sha1 check wouldn't add to
1778 * the safety anyway; we want to delete the reference whatever
1779 * its current value.
1781 if (!refs_read_ref_full(&refs->base, newrefname,
1782 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1784 refs_delete_ref(&refs->base, NULL, newrefname,
1785 NULL, REF_NODEREF)) {
1786 if (errno == EISDIR) {
1787 struct strbuf path = STRBUF_INIT;
1790 files_ref_path(refs, &path, newrefname);
1791 result = remove_empty_directories(&path);
1792 strbuf_release(&path);
1795 error("Directory not empty: %s", newrefname);
1799 error("unable to delete existing %s", newrefname);
1804 if (log && rename_tmp_log(refs, newrefname))
1809 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1810 REF_NODEREF, NULL, &err);
1812 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1813 strbuf_release(&err);
1816 hashcpy(lock->old_oid.hash, orig_sha1);
1818 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
1819 commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {
1820 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1821 strbuf_release(&err);
1829 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1830 REF_NODEREF, NULL, &err);
1832 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1833 strbuf_release(&err);
1837 flag = log_all_ref_updates;
1838 log_all_ref_updates = LOG_REFS_NONE;
1839 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
1840 commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {
1841 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1842 strbuf_release(&err);
1844 log_all_ref_updates = flag;
1847 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1848 error("unable to restore logfile %s from %s: %s",
1849 oldrefname, newrefname, strerror(errno));
1850 if (!logmoved && log &&
1851 rename(tmp_renamed_log.buf, sb_oldref.buf))
1852 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1853 oldrefname, strerror(errno));
1856 strbuf_release(&sb_newref);
1857 strbuf_release(&sb_oldref);
1858 strbuf_release(&tmp_renamed_log);
1863 static int close_ref(struct ref_lock *lock)
1865 if (close_lock_file(lock->lk))
1870 static int commit_ref(struct ref_lock *lock)
1872 char *path = get_locked_file_path(lock->lk);
1875 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1877 * There is a directory at the path we want to rename
1878 * the lockfile to. Hopefully it is empty; try to
1881 size_t len = strlen(path);
1882 struct strbuf sb_path = STRBUF_INIT;
1884 strbuf_attach(&sb_path, path, len, len);
1887 * If this fails, commit_lock_file() will also fail
1888 * and will report the problem.
1890 remove_empty_directories(&sb_path);
1891 strbuf_release(&sb_path);
1896 if (commit_lock_file(lock->lk))
1901 static int open_or_create_logfile(const char *path, void *cb)
1905 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1906 return (*fd < 0) ? -1 : 0;
1910 * Create a reflog for a ref. If force_create = 0, only create the
1911 * reflog for certain refs (those for which should_autocreate_reflog
1912 * returns non-zero). Otherwise, create it regardless of the reference
1913 * name. If the logfile already existed or was created, return 0 and
1914 * set *logfd to the file descriptor opened for appending to the file.
1915 * If no logfile exists and we decided not to create one, return 0 and
1916 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1919 static int log_ref_setup(struct files_ref_store *refs,
1920 const char *refname, int force_create,
1921 int *logfd, struct strbuf *err)
1923 struct strbuf logfile_sb = STRBUF_INIT;
1926 files_reflog_path(refs, &logfile_sb, refname);
1927 logfile = strbuf_detach(&logfile_sb, NULL);
1929 if (force_create || should_autocreate_reflog(refname)) {
1930 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1931 if (errno == ENOENT)
1932 strbuf_addf(err, "unable to create directory for '%s': "
1933 "%s", logfile, strerror(errno));
1934 else if (errno == EISDIR)
1935 strbuf_addf(err, "there are still logs under '%s'",
1938 strbuf_addf(err, "unable to append to '%s': %s",
1939 logfile, strerror(errno));
1944 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1946 if (errno == ENOENT || errno == EISDIR) {
1948 * The logfile doesn't already exist,
1949 * but that is not an error; it only
1950 * means that we won't write log
1955 strbuf_addf(err, "unable to append to '%s': %s",
1956 logfile, strerror(errno));
1963 adjust_shared_perm(logfile);
1973 static int files_create_reflog(struct ref_store *ref_store,
1974 const char *refname, int force_create,
1977 struct files_ref_store *refs =
1978 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1981 if (log_ref_setup(refs, refname, force_create, &fd, err))
1990 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
1991 const unsigned char *new_sha1,
1992 const char *committer, const char *msg)
1994 int msglen, written;
1995 unsigned maxlen, len;
1998 msglen = msg ? strlen(msg) : 0;
1999 maxlen = strlen(committer) + msglen + 100;
2000 logrec = xmalloc(maxlen);
2001 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2002 sha1_to_hex(old_sha1),
2003 sha1_to_hex(new_sha1),
2006 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2008 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2016 static int files_log_ref_write(struct files_ref_store *refs,
2017 const char *refname, const unsigned char *old_sha1,
2018 const unsigned char *new_sha1, const char *msg,
2019 int flags, struct strbuf *err)
2023 if (log_all_ref_updates == LOG_REFS_UNSET)
2024 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2026 result = log_ref_setup(refs, refname,
2027 flags & REF_FORCE_CREATE_REFLOG,
2035 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2036 git_committer_info(0), msg);
2038 struct strbuf sb = STRBUF_INIT;
2039 int save_errno = errno;
2041 files_reflog_path(refs, &sb, refname);
2042 strbuf_addf(err, "unable to append to '%s': %s",
2043 sb.buf, strerror(save_errno));
2044 strbuf_release(&sb);
2049 struct strbuf sb = STRBUF_INIT;
2050 int save_errno = errno;
2052 files_reflog_path(refs, &sb, refname);
2053 strbuf_addf(err, "unable to append to '%s': %s",
2054 sb.buf, strerror(save_errno));
2055 strbuf_release(&sb);
2062 * Write sha1 into the open lockfile, then close the lockfile. On
2063 * errors, rollback the lockfile, fill in *err and
2066 static int write_ref_to_lockfile(struct ref_lock *lock,
2067 const unsigned char *sha1, struct strbuf *err)
2069 static char term = '\n';
2073 o = parse_object(sha1);
2076 "trying to write ref '%s' with nonexistent object %s",
2077 lock->ref_name, sha1_to_hex(sha1));
2081 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2083 "trying to write non-commit object %s to branch '%s'",
2084 sha1_to_hex(sha1), lock->ref_name);
2088 fd = get_lock_file_fd(lock->lk);
2089 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2090 write_in_full(fd, &term, 1) != 1 ||
2091 close_ref(lock) < 0) {
2093 "couldn't write '%s'", get_lock_file_path(lock->lk));
2101 * Commit a change to a loose reference that has already been written
2102 * to the loose reference lockfile. Also update the reflogs if
2103 * necessary, using the specified lockmsg (which can be NULL).
2105 static int commit_ref_update(struct files_ref_store *refs,
2106 struct ref_lock *lock,
2107 const unsigned char *sha1, const char *logmsg,
2110 files_assert_main_repository(refs, "commit_ref_update");
2112 clear_loose_ref_cache(refs);
2113 if (files_log_ref_write(refs, lock->ref_name,
2114 lock->old_oid.hash, sha1,
2116 char *old_msg = strbuf_detach(err, NULL);
2117 strbuf_addf(err, "cannot update the ref '%s': %s",
2118 lock->ref_name, old_msg);
2124 if (strcmp(lock->ref_name, "HEAD") != 0) {
2126 * Special hack: If a branch is updated directly and HEAD
2127 * points to it (may happen on the remote side of a push
2128 * for example) then logically the HEAD reflog should be
2130 * A generic solution implies reverse symref information,
2131 * but finding all symrefs pointing to the given branch
2132 * would be rather costly for this rare event (the direct
2133 * update of a branch) to be worth it. So let's cheat and
2134 * check with HEAD only which should cover 99% of all usage
2135 * scenarios (even 100% of the default ones).
2137 unsigned char head_sha1[20];
2139 const char *head_ref;
2141 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2142 RESOLVE_REF_READING,
2143 head_sha1, &head_flag);
2144 if (head_ref && (head_flag & REF_ISSYMREF) &&
2145 !strcmp(head_ref, lock->ref_name)) {
2146 struct strbuf log_err = STRBUF_INIT;
2147 if (files_log_ref_write(refs, "HEAD",
2148 lock->old_oid.hash, sha1,
2149 logmsg, 0, &log_err)) {
2150 error("%s", log_err.buf);
2151 strbuf_release(&log_err);
2156 if (commit_ref(lock)) {
2157 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2166 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2169 #ifndef NO_SYMLINK_HEAD
2170 char *ref_path = get_locked_file_path(lock->lk);
2172 ret = symlink(target, ref_path);
2176 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2181 static void update_symref_reflog(struct files_ref_store *refs,
2182 struct ref_lock *lock, const char *refname,
2183 const char *target, const char *logmsg)
2185 struct strbuf err = STRBUF_INIT;
2186 unsigned char new_sha1[20];
2188 !refs_read_ref_full(&refs->base, target,
2189 RESOLVE_REF_READING, new_sha1, NULL) &&
2190 files_log_ref_write(refs, refname, lock->old_oid.hash,
2191 new_sha1, logmsg, 0, &err)) {
2192 error("%s", err.buf);
2193 strbuf_release(&err);
2197 static int create_symref_locked(struct files_ref_store *refs,
2198 struct ref_lock *lock, const char *refname,
2199 const char *target, const char *logmsg)
2201 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2202 update_symref_reflog(refs, lock, refname, target, logmsg);
2206 if (!fdopen_lock_file(lock->lk, "w"))
2207 return error("unable to fdopen %s: %s",
2208 lock->lk->tempfile.filename.buf, strerror(errno));
2210 update_symref_reflog(refs, lock, refname, target, logmsg);
2212 /* no error check; commit_ref will check ferror */
2213 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2214 if (commit_ref(lock) < 0)
2215 return error("unable to write symref for %s: %s", refname,
2220 static int files_create_symref(struct ref_store *ref_store,
2221 const char *refname, const char *target,
2224 struct files_ref_store *refs =
2225 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2226 struct strbuf err = STRBUF_INIT;
2227 struct ref_lock *lock;
2230 lock = lock_ref_sha1_basic(refs, refname, NULL,
2231 NULL, NULL, REF_NODEREF, NULL,
2234 error("%s", err.buf);
2235 strbuf_release(&err);
2239 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2244 int set_worktree_head_symref(const char *gitdir, const char *target, const char *logmsg)
2247 * FIXME: this obviously will not work well for future refs
2248 * backends. This function needs to die.
2250 struct files_ref_store *refs =
2251 files_downcast(get_main_ref_store(),
2255 static struct lock_file head_lock;
2256 struct ref_lock *lock;
2257 struct strbuf head_path = STRBUF_INIT;
2258 const char *head_rel;
2261 strbuf_addf(&head_path, "%s/HEAD", absolute_path(gitdir));
2262 if (hold_lock_file_for_update(&head_lock, head_path.buf,
2263 LOCK_NO_DEREF) < 0) {
2264 struct strbuf err = STRBUF_INIT;
2265 unable_to_lock_message(head_path.buf, errno, &err);
2266 error("%s", err.buf);
2267 strbuf_release(&err);
2268 strbuf_release(&head_path);
2272 /* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for
2274 head_rel = remove_leading_path(head_path.buf,
2275 absolute_path(get_git_common_dir()));
2276 /* to make use of create_symref_locked(), initialize ref_lock */
2277 lock = xcalloc(1, sizeof(struct ref_lock));
2278 lock->lk = &head_lock;
2279 lock->ref_name = xstrdup(head_rel);
2281 ret = create_symref_locked(refs, lock, head_rel, target, logmsg);
2283 unlock_ref(lock); /* will free lock */
2284 strbuf_release(&head_path);
2288 static int files_reflog_exists(struct ref_store *ref_store,
2289 const char *refname)
2291 struct files_ref_store *refs =
2292 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2293 struct strbuf sb = STRBUF_INIT;
2297 files_reflog_path(refs, &sb, refname);
2298 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2299 strbuf_release(&sb);
2303 static int files_delete_reflog(struct ref_store *ref_store,
2304 const char *refname)
2306 struct files_ref_store *refs =
2307 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2308 struct strbuf sb = STRBUF_INIT;
2311 files_reflog_path(refs, &sb, refname);
2312 ret = remove_path(sb.buf);
2313 strbuf_release(&sb);
2317 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2319 struct object_id ooid, noid;
2320 char *email_end, *message;
2321 unsigned long timestamp;
2323 const char *p = sb->buf;
2325 /* old SP new SP name <email> SP time TAB msg LF */
2326 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2327 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2328 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2329 !(email_end = strchr(p, '>')) ||
2330 email_end[1] != ' ' ||
2331 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2332 !message || message[0] != ' ' ||
2333 (message[1] != '+' && message[1] != '-') ||
2334 !isdigit(message[2]) || !isdigit(message[3]) ||
2335 !isdigit(message[4]) || !isdigit(message[5]))
2336 return 0; /* corrupt? */
2337 email_end[1] = '\0';
2338 tz = strtol(message + 1, NULL, 10);
2339 if (message[6] != '\t')
2343 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2346 static char *find_beginning_of_line(char *bob, char *scan)
2348 while (bob < scan && *(--scan) != '\n')
2349 ; /* keep scanning backwards */
2351 * Return either beginning of the buffer, or LF at the end of
2352 * the previous line.
2357 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2358 const char *refname,
2359 each_reflog_ent_fn fn,
2362 struct files_ref_store *refs =
2363 files_downcast(ref_store, REF_STORE_READ,
2364 "for_each_reflog_ent_reverse");
2365 struct strbuf sb = STRBUF_INIT;
2368 int ret = 0, at_tail = 1;
2370 files_reflog_path(refs, &sb, refname);
2371 logfp = fopen(sb.buf, "r");
2372 strbuf_release(&sb);
2376 /* Jump to the end */
2377 if (fseek(logfp, 0, SEEK_END) < 0)
2378 ret = error("cannot seek back reflog for %s: %s",
2379 refname, strerror(errno));
2381 while (!ret && 0 < pos) {
2387 /* Fill next block from the end */
2388 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2389 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2390 ret = error("cannot seek back reflog for %s: %s",
2391 refname, strerror(errno));
2394 nread = fread(buf, cnt, 1, logfp);
2396 ret = error("cannot read %d bytes from reflog for %s: %s",
2397 cnt, refname, strerror(errno));
2402 scanp = endp = buf + cnt;
2403 if (at_tail && scanp[-1] == '\n')
2404 /* Looking at the final LF at the end of the file */
2408 while (buf < scanp) {
2410 * terminating LF of the previous line, or the beginning
2415 bp = find_beginning_of_line(buf, scanp);
2419 * The newline is the end of the previous line,
2420 * so we know we have complete line starting
2421 * at (bp + 1). Prefix it onto any prior data
2422 * we collected for the line and process it.
2424 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2427 ret = show_one_reflog_ent(&sb, fn, cb_data);
2433 * We are at the start of the buffer, and the
2434 * start of the file; there is no previous
2435 * line, and we have everything for this one.
2436 * Process it, and we can end the loop.
2438 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2439 ret = show_one_reflog_ent(&sb, fn, cb_data);
2446 * We are at the start of the buffer, and there
2447 * is more file to read backwards. Which means
2448 * we are in the middle of a line. Note that we
2449 * may get here even if *bp was a newline; that
2450 * just means we are at the exact end of the
2451 * previous line, rather than some spot in the
2454 * Save away what we have to be combined with
2455 * the data from the next read.
2457 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2464 die("BUG: reverse reflog parser had leftover data");
2467 strbuf_release(&sb);
2471 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2472 const char *refname,
2473 each_reflog_ent_fn fn, void *cb_data)
2475 struct files_ref_store *refs =
2476 files_downcast(ref_store, REF_STORE_READ,
2477 "for_each_reflog_ent");
2479 struct strbuf sb = STRBUF_INIT;
2482 files_reflog_path(refs, &sb, refname);
2483 logfp = fopen(sb.buf, "r");
2484 strbuf_release(&sb);
2488 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2489 ret = show_one_reflog_ent(&sb, fn, cb_data);
2491 strbuf_release(&sb);
2495 struct files_reflog_iterator {
2496 struct ref_iterator base;
2498 struct ref_store *ref_store;
2499 struct dir_iterator *dir_iterator;
2500 struct object_id oid;
2503 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2505 struct files_reflog_iterator *iter =
2506 (struct files_reflog_iterator *)ref_iterator;
2507 struct dir_iterator *diter = iter->dir_iterator;
2510 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2513 if (!S_ISREG(diter->st.st_mode))
2515 if (diter->basename[0] == '.')
2517 if (ends_with(diter->basename, ".lock"))
2520 if (refs_read_ref_full(iter->ref_store,
2521 diter->relative_path, 0,
2522 iter->oid.hash, &flags)) {
2523 error("bad ref for %s", diter->path.buf);
2527 iter->base.refname = diter->relative_path;
2528 iter->base.oid = &iter->oid;
2529 iter->base.flags = flags;
2533 iter->dir_iterator = NULL;
2534 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2539 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2540 struct object_id *peeled)
2542 die("BUG: ref_iterator_peel() called for reflog_iterator");
2545 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2547 struct files_reflog_iterator *iter =
2548 (struct files_reflog_iterator *)ref_iterator;
2551 if (iter->dir_iterator)
2552 ok = dir_iterator_abort(iter->dir_iterator);
2554 base_ref_iterator_free(ref_iterator);
2558 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2559 files_reflog_iterator_advance,
2560 files_reflog_iterator_peel,
2561 files_reflog_iterator_abort
2564 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2566 struct files_ref_store *refs =
2567 files_downcast(ref_store, REF_STORE_READ,
2568 "reflog_iterator_begin");
2569 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2570 struct ref_iterator *ref_iterator = &iter->base;
2571 struct strbuf sb = STRBUF_INIT;
2573 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2574 files_reflog_path(refs, &sb, NULL);
2575 iter->dir_iterator = dir_iterator_begin(sb.buf);
2576 iter->ref_store = ref_store;
2577 strbuf_release(&sb);
2578 return ref_iterator;
2581 static int ref_update_reject_duplicates(struct string_list *refnames,
2584 int i, n = refnames->nr;
2588 for (i = 1; i < n; i++)
2589 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
2591 "multiple updates for ref '%s' not allowed.",
2592 refnames->items[i].string);
2599 * If update is a direct update of head_ref (the reference pointed to
2600 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2602 static int split_head_update(struct ref_update *update,
2603 struct ref_transaction *transaction,
2604 const char *head_ref,
2605 struct string_list *affected_refnames,
2608 struct string_list_item *item;
2609 struct ref_update *new_update;
2611 if ((update->flags & REF_LOG_ONLY) ||
2612 (update->flags & REF_ISPRUNING) ||
2613 (update->flags & REF_UPDATE_VIA_HEAD))
2616 if (strcmp(update->refname, head_ref))
2620 * First make sure that HEAD is not already in the
2621 * transaction. This insertion is O(N) in the transaction
2622 * size, but it happens at most once per transaction.
2624 item = string_list_insert(affected_refnames, "HEAD");
2626 /* An entry already existed */
2628 "multiple updates for 'HEAD' (including one "
2629 "via its referent '%s') are not allowed",
2631 return TRANSACTION_NAME_CONFLICT;
2634 new_update = ref_transaction_add_update(
2635 transaction, "HEAD",
2636 update->flags | REF_LOG_ONLY | REF_NODEREF,
2637 update->new_sha1, update->old_sha1,
2640 item->util = new_update;
2646 * update is for a symref that points at referent and doesn't have
2647 * REF_NODEREF set. Split it into two updates:
2648 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2649 * - A new, separate update for the referent reference
2650 * Note that the new update will itself be subject to splitting when
2651 * the iteration gets to it.
2653 static int split_symref_update(struct files_ref_store *refs,
2654 struct ref_update *update,
2655 const char *referent,
2656 struct ref_transaction *transaction,
2657 struct string_list *affected_refnames,
2660 struct string_list_item *item;
2661 struct ref_update *new_update;
2662 unsigned int new_flags;
2665 * First make sure that referent is not already in the
2666 * transaction. This insertion is O(N) in the transaction
2667 * size, but it happens at most once per symref in a
2670 item = string_list_insert(affected_refnames, referent);
2672 /* An entry already existed */
2674 "multiple updates for '%s' (including one "
2675 "via symref '%s') are not allowed",
2676 referent, update->refname);
2677 return TRANSACTION_NAME_CONFLICT;
2680 new_flags = update->flags;
2681 if (!strcmp(update->refname, "HEAD")) {
2683 * Record that the new update came via HEAD, so that
2684 * when we process it, split_head_update() doesn't try
2685 * to add another reflog update for HEAD. Note that
2686 * this bit will be propagated if the new_update
2687 * itself needs to be split.
2689 new_flags |= REF_UPDATE_VIA_HEAD;
2692 new_update = ref_transaction_add_update(
2693 transaction, referent, new_flags,
2694 update->new_sha1, update->old_sha1,
2697 new_update->parent_update = update;
2700 * Change the symbolic ref update to log only. Also, it
2701 * doesn't need to check its old SHA-1 value, as that will be
2702 * done when new_update is processed.
2704 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2705 update->flags &= ~REF_HAVE_OLD;
2707 item->util = new_update;
2713 * Return the refname under which update was originally requested.
2715 static const char *original_update_refname(struct ref_update *update)
2717 while (update->parent_update)
2718 update = update->parent_update;
2720 return update->refname;
2724 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2725 * are consistent with oid, which is the reference's current value. If
2726 * everything is OK, return 0; otherwise, write an error message to
2727 * err and return -1.
2729 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2732 if (!(update->flags & REF_HAVE_OLD) ||
2733 !hashcmp(oid->hash, update->old_sha1))
2736 if (is_null_sha1(update->old_sha1))
2737 strbuf_addf(err, "cannot lock ref '%s': "
2738 "reference already exists",
2739 original_update_refname(update));
2740 else if (is_null_oid(oid))
2741 strbuf_addf(err, "cannot lock ref '%s': "
2742 "reference is missing but expected %s",
2743 original_update_refname(update),
2744 sha1_to_hex(update->old_sha1));
2746 strbuf_addf(err, "cannot lock ref '%s': "
2747 "is at %s but expected %s",
2748 original_update_refname(update),
2750 sha1_to_hex(update->old_sha1));
2756 * Prepare for carrying out update:
2757 * - Lock the reference referred to by update.
2758 * - Read the reference under lock.
2759 * - Check that its old SHA-1 value (if specified) is correct, and in
2760 * any case record it in update->lock->old_oid for later use when
2761 * writing the reflog.
2762 * - If it is a symref update without REF_NODEREF, split it up into a
2763 * REF_LOG_ONLY update of the symref and add a separate update for
2764 * the referent to transaction.
2765 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2768 static int lock_ref_for_update(struct files_ref_store *refs,
2769 struct ref_update *update,
2770 struct ref_transaction *transaction,
2771 const char *head_ref,
2772 struct string_list *affected_refnames,
2775 struct strbuf referent = STRBUF_INIT;
2776 int mustexist = (update->flags & REF_HAVE_OLD) &&
2777 !is_null_sha1(update->old_sha1);
2779 struct ref_lock *lock;
2781 files_assert_main_repository(refs, "lock_ref_for_update");
2783 if ((update->flags & REF_HAVE_NEW) && is_null_sha1(update->new_sha1))
2784 update->flags |= REF_DELETING;
2787 ret = split_head_update(update, transaction, head_ref,
2788 affected_refnames, err);
2793 ret = lock_raw_ref(refs, update->refname, mustexist,
2794 affected_refnames, NULL,
2796 &update->type, err);
2800 reason = strbuf_detach(err, NULL);
2801 strbuf_addf(err, "cannot lock ref '%s': %s",
2802 original_update_refname(update), reason);
2807 update->backend_data = lock;
2809 if (update->type & REF_ISSYMREF) {
2810 if (update->flags & REF_NODEREF) {
2812 * We won't be reading the referent as part of
2813 * the transaction, so we have to read it here
2814 * to record and possibly check old_sha1:
2816 if (refs_read_ref_full(&refs->base,
2818 lock->old_oid.hash, NULL)) {
2819 if (update->flags & REF_HAVE_OLD) {
2820 strbuf_addf(err, "cannot lock ref '%s': "
2821 "error reading reference",
2822 original_update_refname(update));
2825 } else if (check_old_oid(update, &lock->old_oid, err)) {
2826 return TRANSACTION_GENERIC_ERROR;
2830 * Create a new update for the reference this
2831 * symref is pointing at. Also, we will record
2832 * and verify old_sha1 for this update as part
2833 * of processing the split-off update, so we
2834 * don't have to do it here.
2836 ret = split_symref_update(refs, update,
2837 referent.buf, transaction,
2838 affected_refnames, err);
2843 struct ref_update *parent_update;
2845 if (check_old_oid(update, &lock->old_oid, err))
2846 return TRANSACTION_GENERIC_ERROR;
2849 * If this update is happening indirectly because of a
2850 * symref update, record the old SHA-1 in the parent
2853 for (parent_update = update->parent_update;
2855 parent_update = parent_update->parent_update) {
2856 struct ref_lock *parent_lock = parent_update->backend_data;
2857 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2861 if ((update->flags & REF_HAVE_NEW) &&
2862 !(update->flags & REF_DELETING) &&
2863 !(update->flags & REF_LOG_ONLY)) {
2864 if (!(update->type & REF_ISSYMREF) &&
2865 !hashcmp(lock->old_oid.hash, update->new_sha1)) {
2867 * The reference already has the desired
2868 * value, so we don't need to write it.
2870 } else if (write_ref_to_lockfile(lock, update->new_sha1,
2872 char *write_err = strbuf_detach(err, NULL);
2875 * The lock was freed upon failure of
2876 * write_ref_to_lockfile():
2878 update->backend_data = NULL;
2880 "cannot update ref '%s': %s",
2881 update->refname, write_err);
2883 return TRANSACTION_GENERIC_ERROR;
2885 update->flags |= REF_NEEDS_COMMIT;
2888 if (!(update->flags & REF_NEEDS_COMMIT)) {
2890 * We didn't call write_ref_to_lockfile(), so
2891 * the lockfile is still open. Close it to
2892 * free up the file descriptor:
2894 if (close_ref(lock)) {
2895 strbuf_addf(err, "couldn't close '%s.lock'",
2897 return TRANSACTION_GENERIC_ERROR;
2903 static int files_transaction_commit(struct ref_store *ref_store,
2904 struct ref_transaction *transaction,
2907 struct files_ref_store *refs =
2908 files_downcast(ref_store, REF_STORE_WRITE,
2909 "ref_transaction_commit");
2911 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2912 struct string_list_item *ref_to_delete;
2913 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2914 char *head_ref = NULL;
2916 struct object_id head_oid;
2917 struct strbuf sb = STRBUF_INIT;
2921 if (transaction->state != REF_TRANSACTION_OPEN)
2922 die("BUG: commit called for transaction that is not open");
2924 if (!transaction->nr) {
2925 transaction->state = REF_TRANSACTION_CLOSED;
2930 * Fail if a refname appears more than once in the
2931 * transaction. (If we end up splitting up any updates using
2932 * split_symref_update() or split_head_update(), those
2933 * functions will check that the new updates don't have the
2934 * same refname as any existing ones.)
2936 for (i = 0; i < transaction->nr; i++) {
2937 struct ref_update *update = transaction->updates[i];
2938 struct string_list_item *item =
2939 string_list_append(&affected_refnames, update->refname);
2942 * We store a pointer to update in item->util, but at
2943 * the moment we never use the value of this field
2944 * except to check whether it is non-NULL.
2946 item->util = update;
2948 string_list_sort(&affected_refnames);
2949 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2950 ret = TRANSACTION_GENERIC_ERROR;
2955 * Special hack: If a branch is updated directly and HEAD
2956 * points to it (may happen on the remote side of a push
2957 * for example) then logically the HEAD reflog should be
2960 * A generic solution would require reverse symref lookups,
2961 * but finding all symrefs pointing to a given branch would be
2962 * rather costly for this rare event (the direct update of a
2963 * branch) to be worth it. So let's cheat and check with HEAD
2964 * only, which should cover 99% of all usage scenarios (even
2965 * 100% of the default ones).
2967 * So if HEAD is a symbolic reference, then record the name of
2968 * the reference that it points to. If we see an update of
2969 * head_ref within the transaction, then split_head_update()
2970 * arranges for the reflog of HEAD to be updated, too.
2972 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2973 RESOLVE_REF_NO_RECURSE,
2974 head_oid.hash, &head_type);
2976 if (head_ref && !(head_type & REF_ISSYMREF)) {
2982 * Acquire all locks, verify old values if provided, check
2983 * that new values are valid, and write new values to the
2984 * lockfiles, ready to be activated. Only keep one lockfile
2985 * open at a time to avoid running out of file descriptors.
2987 for (i = 0; i < transaction->nr; i++) {
2988 struct ref_update *update = transaction->updates[i];
2990 ret = lock_ref_for_update(refs, update, transaction,
2991 head_ref, &affected_refnames, err);
2996 /* Perform updates first so live commits remain referenced */
2997 for (i = 0; i < transaction->nr; i++) {
2998 struct ref_update *update = transaction->updates[i];
2999 struct ref_lock *lock = update->backend_data;
3001 if (update->flags & REF_NEEDS_COMMIT ||
3002 update->flags & REF_LOG_ONLY) {
3003 if (files_log_ref_write(refs,
3007 update->msg, update->flags,
3009 char *old_msg = strbuf_detach(err, NULL);
3011 strbuf_addf(err, "cannot update the ref '%s': %s",
3012 lock->ref_name, old_msg);
3015 update->backend_data = NULL;
3016 ret = TRANSACTION_GENERIC_ERROR;
3020 if (update->flags & REF_NEEDS_COMMIT) {
3021 clear_loose_ref_cache(refs);
3022 if (commit_ref(lock)) {
3023 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3025 update->backend_data = NULL;
3026 ret = TRANSACTION_GENERIC_ERROR;
3031 /* Perform deletes now that updates are safely completed */
3032 for (i = 0; i < transaction->nr; i++) {
3033 struct ref_update *update = transaction->updates[i];
3034 struct ref_lock *lock = update->backend_data;
3036 if (update->flags & REF_DELETING &&
3037 !(update->flags & REF_LOG_ONLY)) {
3038 if (!(update->type & REF_ISPACKED) ||
3039 update->type & REF_ISSYMREF) {
3040 /* It is a loose reference. */
3042 files_ref_path(refs, &sb, lock->ref_name);
3043 if (unlink_or_msg(sb.buf, err)) {
3044 ret = TRANSACTION_GENERIC_ERROR;
3047 update->flags |= REF_DELETED_LOOSE;
3050 if (!(update->flags & REF_ISPRUNING))
3051 string_list_append(&refs_to_delete,
3056 if (repack_without_refs(refs, &refs_to_delete, err)) {
3057 ret = TRANSACTION_GENERIC_ERROR;
3061 /* Delete the reflogs of any references that were deleted: */
3062 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3064 files_reflog_path(refs, &sb, ref_to_delete->string);
3065 if (!unlink_or_warn(sb.buf))
3066 try_remove_empty_parents(refs, ref_to_delete->string,
3067 REMOVE_EMPTY_PARENTS_REFLOG);
3070 clear_loose_ref_cache(refs);
3073 strbuf_release(&sb);
3074 transaction->state = REF_TRANSACTION_CLOSED;
3076 for (i = 0; i < transaction->nr; i++) {
3077 struct ref_update *update = transaction->updates[i];
3078 struct ref_lock *lock = update->backend_data;
3083 if (update->flags & REF_DELETED_LOOSE) {
3085 * The loose reference was deleted. Delete any
3086 * empty parent directories. (Note that this
3087 * can only work because we have already
3088 * removed the lockfile.)
3090 try_remove_empty_parents(refs, update->refname,
3091 REMOVE_EMPTY_PARENTS_REF);
3095 string_list_clear(&refs_to_delete, 0);
3097 string_list_clear(&affected_refnames, 0);
3102 static int ref_present(const char *refname,
3103 const struct object_id *oid, int flags, void *cb_data)
3105 struct string_list *affected_refnames = cb_data;
3107 return string_list_has_string(affected_refnames, refname);
3110 static int files_initial_transaction_commit(struct ref_store *ref_store,
3111 struct ref_transaction *transaction,
3114 struct files_ref_store *refs =
3115 files_downcast(ref_store, REF_STORE_WRITE,
3116 "initial_ref_transaction_commit");
3118 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3122 if (transaction->state != REF_TRANSACTION_OPEN)
3123 die("BUG: commit called for transaction that is not open");
3125 /* Fail if a refname appears more than once in the transaction: */
3126 for (i = 0; i < transaction->nr; i++)
3127 string_list_append(&affected_refnames,
3128 transaction->updates[i]->refname);
3129 string_list_sort(&affected_refnames);
3130 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3131 ret = TRANSACTION_GENERIC_ERROR;
3136 * It's really undefined to call this function in an active
3137 * repository or when there are existing references: we are
3138 * only locking and changing packed-refs, so (1) any
3139 * simultaneous processes might try to change a reference at
3140 * the same time we do, and (2) any existing loose versions of
3141 * the references that we are setting would have precedence
3142 * over our values. But some remote helpers create the remote
3143 * "HEAD" and "master" branches before calling this function,
3144 * so here we really only check that none of the references
3145 * that we are creating already exists.
3147 if (refs_for_each_rawref(&refs->base, ref_present,
3148 &affected_refnames))
3149 die("BUG: initial ref transaction called with existing refs");
3151 for (i = 0; i < transaction->nr; i++) {
3152 struct ref_update *update = transaction->updates[i];
3154 if ((update->flags & REF_HAVE_OLD) &&
3155 !is_null_sha1(update->old_sha1))
3156 die("BUG: initial ref transaction with old_sha1 set");
3157 if (refs_verify_refname_available(&refs->base, update->refname,
3158 &affected_refnames, NULL,
3160 ret = TRANSACTION_NAME_CONFLICT;
3165 if (lock_packed_refs(refs, 0)) {
3166 strbuf_addf(err, "unable to lock packed-refs file: %s",
3168 ret = TRANSACTION_GENERIC_ERROR;
3172 for (i = 0; i < transaction->nr; i++) {
3173 struct ref_update *update = transaction->updates[i];
3175 if ((update->flags & REF_HAVE_NEW) &&
3176 !is_null_sha1(update->new_sha1))
3177 add_packed_ref(refs, update->refname, update->new_sha1);
3180 if (commit_packed_refs(refs)) {
3181 strbuf_addf(err, "unable to commit packed-refs file: %s",
3183 ret = TRANSACTION_GENERIC_ERROR;
3188 transaction->state = REF_TRANSACTION_CLOSED;
3189 string_list_clear(&affected_refnames, 0);
3193 struct expire_reflog_cb {
3195 reflog_expiry_should_prune_fn *should_prune_fn;
3198 struct object_id last_kept_oid;
3201 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3202 const char *email, unsigned long timestamp, int tz,
3203 const char *message, void *cb_data)
3205 struct expire_reflog_cb *cb = cb_data;
3206 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3208 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3209 ooid = &cb->last_kept_oid;
3211 if ((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,
3212 message, policy_cb)) {
3214 printf("would prune %s", message);
3215 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3216 printf("prune %s", message);
3219 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3220 oid_to_hex(ooid), oid_to_hex(noid),
3221 email, timestamp, tz, message);
3222 oidcpy(&cb->last_kept_oid, noid);
3224 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3225 printf("keep %s", message);
3230 static int files_reflog_expire(struct ref_store *ref_store,
3231 const char *refname, const unsigned char *sha1,
3233 reflog_expiry_prepare_fn prepare_fn,
3234 reflog_expiry_should_prune_fn should_prune_fn,
3235 reflog_expiry_cleanup_fn cleanup_fn,
3236 void *policy_cb_data)
3238 struct files_ref_store *refs =
3239 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3240 static struct lock_file reflog_lock;
3241 struct expire_reflog_cb cb;
3242 struct ref_lock *lock;
3243 struct strbuf log_file_sb = STRBUF_INIT;
3247 struct strbuf err = STRBUF_INIT;
3249 memset(&cb, 0, sizeof(cb));
3251 cb.policy_cb = policy_cb_data;
3252 cb.should_prune_fn = should_prune_fn;
3255 * The reflog file is locked by holding the lock on the
3256 * reference itself, plus we might need to update the
3257 * reference if --updateref was specified:
3259 lock = lock_ref_sha1_basic(refs, refname, sha1,
3260 NULL, NULL, REF_NODEREF,
3263 error("cannot lock ref '%s': %s", refname, err.buf);
3264 strbuf_release(&err);
3267 if (!refs_reflog_exists(ref_store, refname)) {
3272 files_reflog_path(refs, &log_file_sb, refname);
3273 log_file = strbuf_detach(&log_file_sb, NULL);
3274 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3276 * Even though holding $GIT_DIR/logs/$reflog.lock has
3277 * no locking implications, we use the lock_file
3278 * machinery here anyway because it does a lot of the
3279 * work we need, including cleaning up if the program
3280 * exits unexpectedly.
3282 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3283 struct strbuf err = STRBUF_INIT;
3284 unable_to_lock_message(log_file, errno, &err);
3285 error("%s", err.buf);
3286 strbuf_release(&err);
3289 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3291 error("cannot fdopen %s (%s)",
3292 get_lock_file_path(&reflog_lock), strerror(errno));
3297 (*prepare_fn)(refname, sha1, cb.policy_cb);
3298 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3299 (*cleanup_fn)(cb.policy_cb);
3301 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3303 * It doesn't make sense to adjust a reference pointed
3304 * to by a symbolic ref based on expiring entries in
3305 * the symbolic reference's reflog. Nor can we update
3306 * a reference if there are no remaining reflog
3309 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3310 !(type & REF_ISSYMREF) &&
3311 !is_null_oid(&cb.last_kept_oid);
3313 if (close_lock_file(&reflog_lock)) {
3314 status |= error("couldn't write %s: %s", log_file,
3316 } else if (update &&
3317 (write_in_full(get_lock_file_fd(lock->lk),
3318 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3319 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3320 close_ref(lock) < 0)) {
3321 status |= error("couldn't write %s",
3322 get_lock_file_path(lock->lk));
3323 rollback_lock_file(&reflog_lock);
3324 } else if (commit_lock_file(&reflog_lock)) {
3325 status |= error("unable to write reflog '%s' (%s)",
3326 log_file, strerror(errno));
3327 } else if (update && commit_ref(lock)) {
3328 status |= error("couldn't set %s", lock->ref_name);
3336 rollback_lock_file(&reflog_lock);
3342 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3344 struct files_ref_store *refs =
3345 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3346 struct strbuf sb = STRBUF_INIT;
3349 * Create .git/refs/{heads,tags}
3351 files_ref_path(refs, &sb, "refs/heads");
3352 safe_create_dir(sb.buf, 1);
3355 files_ref_path(refs, &sb, "refs/tags");
3356 safe_create_dir(sb.buf, 1);
3358 strbuf_release(&sb);
3362 struct ref_storage_be refs_be_files = {
3365 files_ref_store_create,
3367 files_transaction_commit,
3368 files_initial_transaction_commit,
3372 files_create_symref,
3376 files_ref_iterator_begin,
3379 files_reflog_iterator_begin,
3380 files_for_each_reflog_ent,
3381 files_for_each_reflog_ent_reverse,
3382 files_reflog_exists,
3383 files_create_reflog,
3384 files_delete_reflog,