3 #include "refs-internal.h"
5 #include "../iterator.h"
6 #include "../dir-iterator.h"
7 #include "../lockfile.h"
14 struct object_id old_oid;
18 * Return true if refname, which has the specified oid and flags, can
19 * be resolved to an object in the database. If the referred-to object
20 * does not exist, emit a warning and return false.
22 static int ref_resolves_to_object(const char *refname,
23 const struct object_id *oid,
26 if (flags & REF_ISBROKEN)
28 if (!has_sha1_file(oid->hash)) {
29 error("%s does not point to a valid object!", refname);
35 struct packed_ref_cache {
36 struct ref_cache *cache;
39 * Count of references to the data structure in this instance,
40 * including the pointer from files_ref_store::packed if any.
41 * The data will not be freed as long as the reference count
44 unsigned int referrers;
46 /* The metadata from when this packed-refs cache was read */
47 struct stat_validity validity;
51 * Future: need to be in "struct repository"
52 * when doing a full libification.
54 struct files_ref_store {
55 struct ref_store base;
56 unsigned int store_flags;
60 char *packed_refs_path;
62 struct ref_cache *loose;
63 struct packed_ref_cache *packed;
66 * Iff the packed-refs file associated with this instance is
67 * currently locked for writing, this points at the associated
68 * lock (which is owned by somebody else).
70 struct lock_file *packed_refs_lock;
73 /* Lock used for the main packed-refs file: */
74 static struct lock_file packlock;
77 * Increment the reference count of *packed_refs.
79 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
81 packed_refs->referrers++;
85 * Decrease the reference count of *packed_refs. If it goes to zero,
86 * free *packed_refs and return true; otherwise return false.
88 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
90 if (!--packed_refs->referrers) {
91 free_ref_cache(packed_refs->cache);
92 stat_validity_clear(&packed_refs->validity);
100 static void clear_packed_ref_cache(struct files_ref_store *refs)
103 struct packed_ref_cache *packed_refs = refs->packed;
105 if (refs->packed_refs_lock)
106 die("BUG: packed-ref cache cleared while locked");
108 release_packed_ref_cache(packed_refs);
112 static void clear_loose_ref_cache(struct files_ref_store *refs)
115 free_ref_cache(refs->loose);
121 * Create a new submodule ref cache and add it to the internal
124 static struct ref_store *files_ref_store_create(const char *gitdir,
127 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
128 struct ref_store *ref_store = (struct ref_store *)refs;
129 struct strbuf sb = STRBUF_INIT;
131 base_ref_store_init(ref_store, &refs_be_files);
132 refs->store_flags = flags;
134 refs->gitdir = xstrdup(gitdir);
135 get_common_dir_noenv(&sb, gitdir);
136 refs->gitcommondir = strbuf_detach(&sb, NULL);
137 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
138 refs->packed_refs_path = strbuf_detach(&sb, NULL);
144 * Die if refs is not the main ref store. caller is used in any
145 * necessary error messages.
147 static void files_assert_main_repository(struct files_ref_store *refs,
150 if (refs->store_flags & REF_STORE_MAIN)
153 die("BUG: operation %s only allowed for main ref store", caller);
157 * Downcast ref_store to files_ref_store. Die if ref_store is not a
158 * files_ref_store. required_flags is compared with ref_store's
159 * store_flags to ensure the ref_store has all required capabilities.
160 * "caller" is used in any necessary error messages.
162 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
163 unsigned int required_flags,
166 struct files_ref_store *refs;
168 if (ref_store->be != &refs_be_files)
169 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
170 ref_store->be->name, caller);
172 refs = (struct files_ref_store *)ref_store;
174 if ((refs->store_flags & required_flags) != required_flags)
175 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
176 caller, required_flags, refs->store_flags);
181 /* The length of a peeled reference line in packed-refs, including EOL: */
182 #define PEELED_LINE_LENGTH 42
185 * The packed-refs header line that we write out. Perhaps other
186 * traits will be added later. The trailing space is required.
188 static const char PACKED_REFS_HEADER[] =
189 "# pack-refs with: peeled fully-peeled \n";
192 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
193 * Return a pointer to the refname within the line (null-terminated),
194 * or NULL if there was a problem.
196 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
200 if (parse_oid_hex(line->buf, oid, &ref) < 0)
202 if (!isspace(*ref++))
208 if (line->buf[line->len - 1] != '\n')
210 line->buf[--line->len] = 0;
216 * Read f, which is a packed-refs file, into dir.
218 * A comment line of the form "# pack-refs with: " may contain zero or
219 * more traits. We interpret the traits as follows:
223 * Probably no references are peeled. But if the file contains a
224 * peeled value for a reference, we will use it.
228 * References under "refs/tags/", if they *can* be peeled, *are*
229 * peeled in this file. References outside of "refs/tags/" are
230 * probably not peeled even if they could have been, but if we find
231 * a peeled value for such a reference we will use it.
235 * All references in the file that can be peeled are peeled.
236 * Inversely (and this is more important), any references in the
237 * file for which no peeled value is recorded is not peelable. This
238 * trait should typically be written alongside "peeled" for
239 * compatibility with older clients, but we do not require it
240 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
242 static void read_packed_refs(FILE *f, struct ref_dir *dir)
244 struct ref_entry *last = NULL;
245 struct strbuf line = STRBUF_INIT;
246 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
248 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
249 struct object_id oid;
253 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
254 if (strstr(traits, " fully-peeled "))
255 peeled = PEELED_FULLY;
256 else if (strstr(traits, " peeled "))
257 peeled = PEELED_TAGS;
258 /* perhaps other traits later as well */
262 refname = parse_ref_line(&line, &oid);
264 int flag = REF_ISPACKED;
266 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
267 if (!refname_is_safe(refname))
268 die("packed refname is dangerous: %s", refname);
270 flag |= REF_BAD_NAME | REF_ISBROKEN;
272 last = create_ref_entry(refname, &oid, flag, 0);
273 if (peeled == PEELED_FULLY ||
274 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
275 last->flag |= REF_KNOWS_PEELED;
276 add_ref_entry(dir, last);
280 line.buf[0] == '^' &&
281 line.len == PEELED_LINE_LENGTH &&
282 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
283 !get_oid_hex(line.buf + 1, &oid)) {
284 oidcpy(&last->u.value.peeled, &oid);
286 * Regardless of what the file header said,
287 * we definitely know the value of *this*
290 last->flag |= REF_KNOWS_PEELED;
294 strbuf_release(&line);
297 static const char *files_packed_refs_path(struct files_ref_store *refs)
299 return refs->packed_refs_path;
302 static void files_reflog_path(struct files_ref_store *refs,
308 * FIXME: of course this is wrong in multi worktree
309 * setting. To be fixed real soon.
311 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
315 switch (ref_type(refname)) {
316 case REF_TYPE_PER_WORKTREE:
317 case REF_TYPE_PSEUDOREF:
318 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
320 case REF_TYPE_NORMAL:
321 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
324 die("BUG: unknown ref type %d of ref %s",
325 ref_type(refname), refname);
329 static void files_ref_path(struct files_ref_store *refs,
333 switch (ref_type(refname)) {
334 case REF_TYPE_PER_WORKTREE:
335 case REF_TYPE_PSEUDOREF:
336 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
338 case REF_TYPE_NORMAL:
339 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
342 die("BUG: unknown ref type %d of ref %s",
343 ref_type(refname), refname);
348 * Get the packed_ref_cache for the specified files_ref_store,
349 * creating it if necessary.
351 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
353 const char *packed_refs_file = files_packed_refs_path(refs);
356 !stat_validity_check(&refs->packed->validity, packed_refs_file))
357 clear_packed_ref_cache(refs);
362 refs->packed = xcalloc(1, sizeof(*refs->packed));
363 acquire_packed_ref_cache(refs->packed);
364 refs->packed->cache = create_ref_cache(&refs->base, NULL);
365 refs->packed->cache->root->flag &= ~REF_INCOMPLETE;
366 f = fopen(packed_refs_file, "r");
368 stat_validity_update(&refs->packed->validity, fileno(f));
369 read_packed_refs(f, get_ref_dir(refs->packed->cache->root));
376 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
378 return get_ref_dir(packed_ref_cache->cache->root);
381 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
383 return get_packed_ref_dir(get_packed_ref_cache(refs));
387 * Add a reference to the in-memory packed reference cache. This may
388 * only be called while the packed-refs file is locked (see
389 * lock_packed_refs()). To actually write the packed-refs file, call
390 * commit_packed_refs().
392 static void add_packed_ref(struct files_ref_store *refs,
393 const char *refname, const struct object_id *oid)
395 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
397 if (!refs->packed_refs_lock)
398 die("BUG: packed refs not locked");
399 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
400 create_ref_entry(refname, oid, REF_ISPACKED, 1));
404 * Read the loose references from the namespace dirname into dir
405 * (without recursing). dirname must end with '/'. dir must be the
406 * directory entry corresponding to dirname.
408 static void loose_fill_ref_dir(struct ref_store *ref_store,
409 struct ref_dir *dir, const char *dirname)
411 struct files_ref_store *refs =
412 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
415 int dirnamelen = strlen(dirname);
416 struct strbuf refname;
417 struct strbuf path = STRBUF_INIT;
420 files_ref_path(refs, &path, dirname);
421 path_baselen = path.len;
423 d = opendir(path.buf);
425 strbuf_release(&path);
429 strbuf_init(&refname, dirnamelen + 257);
430 strbuf_add(&refname, dirname, dirnamelen);
432 while ((de = readdir(d)) != NULL) {
433 struct object_id oid;
437 if (de->d_name[0] == '.')
439 if (ends_with(de->d_name, ".lock"))
441 strbuf_addstr(&refname, de->d_name);
442 strbuf_addstr(&path, de->d_name);
443 if (stat(path.buf, &st) < 0) {
444 ; /* silently ignore */
445 } else if (S_ISDIR(st.st_mode)) {
446 strbuf_addch(&refname, '/');
447 add_entry_to_dir(dir,
448 create_dir_entry(dir->cache, refname.buf,
451 if (!refs_resolve_ref_unsafe(&refs->base,
456 flag |= REF_ISBROKEN;
457 } else if (is_null_oid(&oid)) {
459 * It is so astronomically unlikely
460 * that NULL_SHA1 is the SHA-1 of an
461 * actual object that we consider its
462 * appearance in a loose reference
463 * file to be repo corruption
464 * (probably due to a software bug).
466 flag |= REF_ISBROKEN;
469 if (check_refname_format(refname.buf,
470 REFNAME_ALLOW_ONELEVEL)) {
471 if (!refname_is_safe(refname.buf))
472 die("loose refname is dangerous: %s", refname.buf);
474 flag |= REF_BAD_NAME | REF_ISBROKEN;
476 add_entry_to_dir(dir,
477 create_ref_entry(refname.buf, &oid, flag, 0));
479 strbuf_setlen(&refname, dirnamelen);
480 strbuf_setlen(&path, path_baselen);
482 strbuf_release(&refname);
483 strbuf_release(&path);
487 * Manually add refs/bisect, which, being per-worktree, might
488 * not appear in the directory listing for refs/ in the main
491 if (!strcmp(dirname, "refs/")) {
492 int pos = search_ref_dir(dir, "refs/bisect/", 12);
495 struct ref_entry *child_entry = create_dir_entry(
496 dir->cache, "refs/bisect/", 12, 1);
497 add_entry_to_dir(dir, child_entry);
502 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
506 * Mark the top-level directory complete because we
507 * are about to read the only subdirectory that can
510 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
512 /* We're going to fill the top level ourselves: */
513 refs->loose->root->flag &= ~REF_INCOMPLETE;
516 * Add an incomplete entry for "refs/" (to be filled
519 add_entry_to_dir(get_ref_dir(refs->loose->root),
520 create_dir_entry(refs->loose, "refs/", 5, 1));
526 * Return the ref_entry for the given refname from the packed
527 * references. If it does not exist, return NULL.
529 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
532 return find_ref_entry(get_packed_refs(refs), refname);
536 * A loose ref file doesn't exist; check for a packed ref.
538 static int resolve_packed_ref(struct files_ref_store *refs,
540 unsigned char *sha1, unsigned int *flags)
542 struct ref_entry *entry;
545 * The loose reference file does not exist; check for a packed
548 entry = get_packed_ref(refs, refname);
550 hashcpy(sha1, entry->u.value.oid.hash);
551 *flags |= REF_ISPACKED;
554 /* refname is not a packed reference. */
558 static int files_read_raw_ref(struct ref_store *ref_store,
559 const char *refname, unsigned char *sha1,
560 struct strbuf *referent, unsigned int *type)
562 struct files_ref_store *refs =
563 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
564 struct strbuf sb_contents = STRBUF_INIT;
565 struct strbuf sb_path = STRBUF_INIT;
572 int remaining_retries = 3;
575 strbuf_reset(&sb_path);
577 files_ref_path(refs, &sb_path, refname);
583 * We might have to loop back here to avoid a race
584 * condition: first we lstat() the file, then we try
585 * to read it as a link or as a file. But if somebody
586 * changes the type of the file (file <-> directory
587 * <-> symlink) between the lstat() and reading, then
588 * we don't want to report that as an error but rather
589 * try again starting with the lstat().
591 * We'll keep a count of the retries, though, just to avoid
592 * any confusing situation sending us into an infinite loop.
595 if (remaining_retries-- <= 0)
598 if (lstat(path, &st) < 0) {
601 if (resolve_packed_ref(refs, refname, sha1, type)) {
609 /* Follow "normalized" - ie "refs/.." symlinks by hand */
610 if (S_ISLNK(st.st_mode)) {
611 strbuf_reset(&sb_contents);
612 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
613 if (errno == ENOENT || errno == EINVAL)
614 /* inconsistent with lstat; retry */
619 if (starts_with(sb_contents.buf, "refs/") &&
620 !check_refname_format(sb_contents.buf, 0)) {
621 strbuf_swap(&sb_contents, referent);
622 *type |= REF_ISSYMREF;
627 * It doesn't look like a refname; fall through to just
628 * treating it like a non-symlink, and reading whatever it
633 /* Is it a directory? */
634 if (S_ISDIR(st.st_mode)) {
636 * Even though there is a directory where the loose
637 * ref is supposed to be, there could still be a
640 if (resolve_packed_ref(refs, refname, sha1, type)) {
649 * Anything else, just open it and try to use it as
652 fd = open(path, O_RDONLY);
654 if (errno == ENOENT && !S_ISLNK(st.st_mode))
655 /* inconsistent with lstat; retry */
660 strbuf_reset(&sb_contents);
661 if (strbuf_read(&sb_contents, fd, 256) < 0) {
662 int save_errno = errno;
668 strbuf_rtrim(&sb_contents);
669 buf = sb_contents.buf;
670 if (starts_with(buf, "ref:")) {
672 while (isspace(*buf))
675 strbuf_reset(referent);
676 strbuf_addstr(referent, buf);
677 *type |= REF_ISSYMREF;
683 * Please note that FETCH_HEAD has additional
684 * data after the sha.
686 if (get_sha1_hex(buf, sha1) ||
687 (buf[40] != '\0' && !isspace(buf[40]))) {
688 *type |= REF_ISBROKEN;
697 strbuf_release(&sb_path);
698 strbuf_release(&sb_contents);
703 static void unlock_ref(struct ref_lock *lock)
705 /* Do not free lock->lk -- atexit() still looks at them */
707 rollback_lock_file(lock->lk);
708 free(lock->ref_name);
713 * Lock refname, without following symrefs, and set *lock_p to point
714 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
715 * and type similarly to read_raw_ref().
717 * The caller must verify that refname is a "safe" reference name (in
718 * the sense of refname_is_safe()) before calling this function.
720 * If the reference doesn't already exist, verify that refname doesn't
721 * have a D/F conflict with any existing references. extras and skip
722 * are passed to refs_verify_refname_available() for this check.
724 * If mustexist is not set and the reference is not found or is
725 * broken, lock the reference anyway but clear sha1.
727 * Return 0 on success. On failure, write an error message to err and
728 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
730 * Implementation note: This function is basically
735 * but it includes a lot more code to
736 * - Deal with possible races with other processes
737 * - Avoid calling refs_verify_refname_available() when it can be
738 * avoided, namely if we were successfully able to read the ref
739 * - Generate informative error messages in the case of failure
741 static int lock_raw_ref(struct files_ref_store *refs,
742 const char *refname, int mustexist,
743 const struct string_list *extras,
744 const struct string_list *skip,
745 struct ref_lock **lock_p,
746 struct strbuf *referent,
750 struct ref_lock *lock;
751 struct strbuf ref_file = STRBUF_INIT;
752 int attempts_remaining = 3;
753 int ret = TRANSACTION_GENERIC_ERROR;
756 files_assert_main_repository(refs, "lock_raw_ref");
760 /* First lock the file so it can't change out from under us. */
762 *lock_p = lock = xcalloc(1, sizeof(*lock));
764 lock->ref_name = xstrdup(refname);
765 files_ref_path(refs, &ref_file, refname);
768 switch (safe_create_leading_directories(ref_file.buf)) {
773 * Suppose refname is "refs/foo/bar". We just failed
774 * to create the containing directory, "refs/foo",
775 * because there was a non-directory in the way. This
776 * indicates a D/F conflict, probably because of
777 * another reference such as "refs/foo". There is no
778 * reason to expect this error to be transitory.
780 if (refs_verify_refname_available(&refs->base, refname,
781 extras, skip, err)) {
784 * To the user the relevant error is
785 * that the "mustexist" reference is
789 strbuf_addf(err, "unable to resolve reference '%s'",
793 * The error message set by
794 * refs_verify_refname_available() is
797 ret = TRANSACTION_NAME_CONFLICT;
801 * The file that is in the way isn't a loose
802 * reference. Report it as a low-level
805 strbuf_addf(err, "unable to create lock file %s.lock; "
806 "non-directory in the way",
811 /* Maybe another process was tidying up. Try again. */
812 if (--attempts_remaining > 0)
816 strbuf_addf(err, "unable to create directory for %s",
822 lock->lk = xcalloc(1, sizeof(struct lock_file));
824 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
825 if (errno == ENOENT && --attempts_remaining > 0) {
827 * Maybe somebody just deleted one of the
828 * directories leading to ref_file. Try
833 unable_to_lock_message(ref_file.buf, errno, err);
839 * Now we hold the lock and can read the reference without
840 * fear that its value will change.
843 if (files_read_raw_ref(&refs->base, refname,
844 lock->old_oid.hash, referent, type)) {
845 if (errno == ENOENT) {
847 /* Garden variety missing reference. */
848 strbuf_addf(err, "unable to resolve reference '%s'",
853 * Reference is missing, but that's OK. We
854 * know that there is not a conflict with
855 * another loose reference because
856 * (supposing that we are trying to lock
857 * reference "refs/foo/bar"):
859 * - We were successfully able to create
860 * the lockfile refs/foo/bar.lock, so we
861 * know there cannot be a loose reference
864 * - We got ENOENT and not EISDIR, so we
865 * know that there cannot be a loose
866 * reference named "refs/foo/bar/baz".
869 } else if (errno == EISDIR) {
871 * There is a directory in the way. It might have
872 * contained references that have been deleted. If
873 * we don't require that the reference already
874 * exists, try to remove the directory so that it
875 * doesn't cause trouble when we want to rename the
876 * lockfile into place later.
879 /* Garden variety missing reference. */
880 strbuf_addf(err, "unable to resolve reference '%s'",
883 } else if (remove_dir_recursively(&ref_file,
884 REMOVE_DIR_EMPTY_ONLY)) {
885 if (refs_verify_refname_available(
886 &refs->base, refname,
887 extras, skip, err)) {
889 * The error message set by
890 * verify_refname_available() is OK.
892 ret = TRANSACTION_NAME_CONFLICT;
896 * We can't delete the directory,
897 * but we also don't know of any
898 * references that it should
901 strbuf_addf(err, "there is a non-empty directory '%s' "
902 "blocking reference '%s'",
903 ref_file.buf, refname);
907 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
908 strbuf_addf(err, "unable to resolve reference '%s': "
909 "reference broken", refname);
912 strbuf_addf(err, "unable to resolve reference '%s': %s",
913 refname, strerror(errno));
918 * If the ref did not exist and we are creating it,
919 * make sure there is no existing ref that conflicts
922 if (refs_verify_refname_available(
923 &refs->base, refname,
936 strbuf_release(&ref_file);
940 static int files_peel_ref(struct ref_store *ref_store,
941 const char *refname, unsigned char *sha1)
943 struct files_ref_store *refs =
944 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
947 unsigned char base[20];
949 if (current_ref_iter && current_ref_iter->refname == refname) {
950 struct object_id peeled;
952 if (ref_iterator_peel(current_ref_iter, &peeled))
954 hashcpy(sha1, peeled.hash);
958 if (refs_read_ref_full(ref_store, refname,
959 RESOLVE_REF_READING, base, &flag))
963 * If the reference is packed, read its ref_entry from the
964 * cache in the hope that we already know its peeled value.
965 * We only try this optimization on packed references because
966 * (a) forcing the filling of the loose reference cache could
967 * be expensive and (b) loose references anyway usually do not
968 * have REF_KNOWS_PEELED.
970 if (flag & REF_ISPACKED) {
971 struct ref_entry *r = get_packed_ref(refs, refname);
973 if (peel_entry(r, 0))
975 hashcpy(sha1, r->u.value.peeled.hash);
980 return peel_object(base, sha1);
983 struct files_ref_iterator {
984 struct ref_iterator base;
986 struct packed_ref_cache *packed_ref_cache;
987 struct ref_iterator *iter0;
991 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
993 struct files_ref_iterator *iter =
994 (struct files_ref_iterator *)ref_iterator;
997 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
998 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
999 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1002 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1003 !ref_resolves_to_object(iter->iter0->refname,
1005 iter->iter0->flags))
1008 iter->base.refname = iter->iter0->refname;
1009 iter->base.oid = iter->iter0->oid;
1010 iter->base.flags = iter->iter0->flags;
1015 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1021 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1022 struct object_id *peeled)
1024 struct files_ref_iterator *iter =
1025 (struct files_ref_iterator *)ref_iterator;
1027 return ref_iterator_peel(iter->iter0, peeled);
1030 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1032 struct files_ref_iterator *iter =
1033 (struct files_ref_iterator *)ref_iterator;
1037 ok = ref_iterator_abort(iter->iter0);
1039 release_packed_ref_cache(iter->packed_ref_cache);
1040 base_ref_iterator_free(ref_iterator);
1044 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1045 files_ref_iterator_advance,
1046 files_ref_iterator_peel,
1047 files_ref_iterator_abort
1050 static struct ref_iterator *files_ref_iterator_begin(
1051 struct ref_store *ref_store,
1052 const char *prefix, unsigned int flags)
1054 struct files_ref_store *refs;
1055 struct ref_iterator *loose_iter, *packed_iter;
1056 struct files_ref_iterator *iter;
1057 struct ref_iterator *ref_iterator;
1059 if (ref_paranoia < 0)
1060 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1062 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1064 refs = files_downcast(ref_store,
1065 REF_STORE_READ | (ref_paranoia ? 0 : REF_STORE_ODB),
1066 "ref_iterator_begin");
1068 iter = xcalloc(1, sizeof(*iter));
1069 ref_iterator = &iter->base;
1070 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1073 * We must make sure that all loose refs are read before
1074 * accessing the packed-refs file; this avoids a race
1075 * condition if loose refs are migrated to the packed-refs
1076 * file by a simultaneous process, but our in-memory view is
1077 * from before the migration. We ensure this as follows:
1078 * First, we call start the loose refs iteration with its
1079 * `prime_ref` argument set to true. This causes the loose
1080 * references in the subtree to be pre-read into the cache.
1081 * (If they've already been read, that's OK; we only need to
1082 * guarantee that they're read before the packed refs, not
1083 * *how much* before.) After that, we call
1084 * get_packed_ref_cache(), which internally checks whether the
1085 * packed-ref cache is up to date with what is on disk, and
1086 * re-reads it if not.
1089 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1092 iter->packed_ref_cache = get_packed_ref_cache(refs);
1093 acquire_packed_ref_cache(iter->packed_ref_cache);
1094 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1097 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1098 iter->flags = flags;
1100 return ref_iterator;
1104 * Verify that the reference locked by lock has the value old_sha1.
1105 * Fail if the reference doesn't exist and mustexist is set. Return 0
1106 * on success. On error, write an error message to err, set errno, and
1107 * return a negative value.
1109 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1110 const unsigned char *old_sha1, int mustexist,
1115 if (refs_read_ref_full(ref_store, lock->ref_name,
1116 mustexist ? RESOLVE_REF_READING : 0,
1117 lock->old_oid.hash, NULL)) {
1119 int save_errno = errno;
1120 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1124 oidclr(&lock->old_oid);
1128 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1129 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1131 oid_to_hex(&lock->old_oid),
1132 sha1_to_hex(old_sha1));
1139 static int remove_empty_directories(struct strbuf *path)
1142 * we want to create a file but there is a directory there;
1143 * if that is an empty directory (or a directory that contains
1144 * only empty directories), remove them.
1146 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1149 static int create_reflock(const char *path, void *cb)
1151 struct lock_file *lk = cb;
1153 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1157 * Locks a ref returning the lock on success and NULL on failure.
1158 * On failure errno is set to something meaningful.
1160 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1161 const char *refname,
1162 const unsigned char *old_sha1,
1163 const struct string_list *extras,
1164 const struct string_list *skip,
1165 unsigned int flags, int *type,
1168 struct strbuf ref_file = STRBUF_INIT;
1169 struct ref_lock *lock;
1171 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1172 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1175 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1178 lock = xcalloc(1, sizeof(struct ref_lock));
1181 resolve_flags |= RESOLVE_REF_READING;
1182 if (flags & REF_DELETING)
1183 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1185 files_ref_path(refs, &ref_file, refname);
1186 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1187 refname, resolve_flags,
1188 lock->old_oid.hash, type);
1189 if (!resolved && errno == EISDIR) {
1191 * we are trying to lock foo but we used to
1192 * have foo/bar which now does not exist;
1193 * it is normal for the empty directory 'foo'
1196 if (remove_empty_directories(&ref_file)) {
1198 if (!refs_verify_refname_available(
1200 refname, extras, skip, err))
1201 strbuf_addf(err, "there are still refs under '%s'",
1205 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1206 refname, resolve_flags,
1207 lock->old_oid.hash, type);
1211 if (last_errno != ENOTDIR ||
1212 !refs_verify_refname_available(&refs->base, refname,
1214 strbuf_addf(err, "unable to resolve reference '%s': %s",
1215 refname, strerror(last_errno));
1221 * If the ref did not exist and we are creating it, make sure
1222 * there is no existing packed ref whose name begins with our
1223 * refname, nor a packed ref whose name is a proper prefix of
1226 if (is_null_oid(&lock->old_oid) &&
1227 refs_verify_refname_available(&refs->base, refname,
1228 extras, skip, err)) {
1229 last_errno = ENOTDIR;
1233 lock->lk = xcalloc(1, sizeof(struct lock_file));
1235 lock->ref_name = xstrdup(refname);
1237 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1239 unable_to_lock_message(ref_file.buf, errno, err);
1243 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1254 strbuf_release(&ref_file);
1260 * Write an entry to the packed-refs file for the specified refname.
1261 * If peeled is non-NULL, write it as the entry's peeled value.
1263 static void write_packed_entry(FILE *fh, const char *refname,
1264 const unsigned char *sha1,
1265 const unsigned char *peeled)
1267 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1269 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1273 * Lock the packed-refs file for writing. Flags is passed to
1274 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1275 * errno appropriately and return a nonzero value.
1277 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1279 static int timeout_configured = 0;
1280 static int timeout_value = 1000;
1281 struct packed_ref_cache *packed_ref_cache;
1283 files_assert_main_repository(refs, "lock_packed_refs");
1285 if (!timeout_configured) {
1286 git_config_get_int("core.packedrefstimeout", &timeout_value);
1287 timeout_configured = 1;
1290 if (hold_lock_file_for_update_timeout(
1291 &packlock, files_packed_refs_path(refs),
1292 flags, timeout_value) < 0)
1295 * Get the current packed-refs while holding the lock. If the
1296 * packed-refs file has been modified since we last read it,
1297 * this will automatically invalidate the cache and re-read
1298 * the packed-refs file.
1300 packed_ref_cache = get_packed_ref_cache(refs);
1301 refs->packed_refs_lock = &packlock;
1302 /* Increment the reference count to prevent it from being freed: */
1303 acquire_packed_ref_cache(packed_ref_cache);
1308 * Write the current version of the packed refs cache from memory to
1309 * disk. The packed-refs file must already be locked for writing (see
1310 * lock_packed_refs()). Return zero on success. On errors, set errno
1311 * and return a nonzero value
1313 static int commit_packed_refs(struct files_ref_store *refs)
1315 struct packed_ref_cache *packed_ref_cache =
1316 get_packed_ref_cache(refs);
1320 struct ref_iterator *iter;
1322 files_assert_main_repository(refs, "commit_packed_refs");
1324 if (!refs->packed_refs_lock)
1325 die("BUG: packed-refs not locked");
1327 out = fdopen_lock_file(refs->packed_refs_lock, "w");
1329 die_errno("unable to fdopen packed-refs descriptor");
1331 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1333 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1334 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1335 struct object_id peeled;
1336 int peel_error = ref_iterator_peel(iter, &peeled);
1338 write_packed_entry(out, iter->refname, iter->oid->hash,
1339 peel_error ? NULL : peeled.hash);
1342 if (ok != ITER_DONE)
1343 die("error while iterating over references");
1345 if (commit_lock_file(refs->packed_refs_lock)) {
1349 refs->packed_refs_lock = NULL;
1350 release_packed_ref_cache(packed_ref_cache);
1356 * Rollback the lockfile for the packed-refs file, and discard the
1357 * in-memory packed reference cache. (The packed-refs file will be
1358 * read anew if it is needed again after this function is called.)
1360 static void rollback_packed_refs(struct files_ref_store *refs)
1362 struct packed_ref_cache *packed_ref_cache =
1363 get_packed_ref_cache(refs);
1365 files_assert_main_repository(refs, "rollback_packed_refs");
1367 if (!refs->packed_refs_lock)
1368 die("BUG: packed-refs not locked");
1369 rollback_lock_file(refs->packed_refs_lock);
1370 refs->packed_refs_lock = NULL;
1371 release_packed_ref_cache(packed_ref_cache);
1372 clear_packed_ref_cache(refs);
1375 struct ref_to_prune {
1376 struct ref_to_prune *next;
1377 unsigned char sha1[20];
1378 char name[FLEX_ARRAY];
1382 REMOVE_EMPTY_PARENTS_REF = 0x01,
1383 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1387 * Remove empty parent directories associated with the specified
1388 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1389 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1390 * REMOVE_EMPTY_PARENTS_REFLOG.
1392 static void try_remove_empty_parents(struct files_ref_store *refs,
1393 const char *refname,
1396 struct strbuf buf = STRBUF_INIT;
1397 struct strbuf sb = STRBUF_INIT;
1401 strbuf_addstr(&buf, refname);
1403 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1404 while (*p && *p != '/')
1406 /* tolerate duplicate slashes; see check_refname_format() */
1410 q = buf.buf + buf.len;
1411 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1412 while (q > p && *q != '/')
1414 while (q > p && *(q-1) == '/')
1418 strbuf_setlen(&buf, q - buf.buf);
1421 files_ref_path(refs, &sb, buf.buf);
1422 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1423 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1426 files_reflog_path(refs, &sb, buf.buf);
1427 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1428 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1430 strbuf_release(&buf);
1431 strbuf_release(&sb);
1434 /* make sure nobody touched the ref, and unlink */
1435 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1437 struct ref_transaction *transaction;
1438 struct strbuf err = STRBUF_INIT;
1440 if (check_refname_format(r->name, 0))
1443 transaction = ref_store_transaction_begin(&refs->base, &err);
1445 ref_transaction_delete(transaction, r->name, r->sha1,
1446 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1447 ref_transaction_commit(transaction, &err)) {
1448 ref_transaction_free(transaction);
1449 error("%s", err.buf);
1450 strbuf_release(&err);
1453 ref_transaction_free(transaction);
1454 strbuf_release(&err);
1457 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1465 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1467 struct files_ref_store *refs =
1468 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1470 struct ref_iterator *iter;
1471 struct ref_dir *packed_refs;
1473 struct ref_to_prune *refs_to_prune = NULL;
1475 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1476 packed_refs = get_packed_refs(refs);
1478 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1479 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1481 * If the loose reference can be packed, add an entry
1482 * in the packed ref cache. If the reference should be
1483 * pruned, also add it to refs_to_prune.
1485 struct ref_entry *packed_entry;
1486 int is_tag_ref = starts_with(iter->refname, "refs/tags/");
1488 /* Do not pack per-worktree refs: */
1489 if (ref_type(iter->refname) != REF_TYPE_NORMAL)
1492 /* ALWAYS pack tags */
1493 if (!(flags & PACK_REFS_ALL) && !is_tag_ref)
1496 /* Do not pack symbolic or broken refs: */
1497 if (iter->flags & REF_ISSYMREF)
1500 if (!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))
1504 * Create an entry in the packed-refs cache equivalent
1505 * to the one from the loose ref cache, except that
1506 * we don't copy the peeled status, because we want it
1509 packed_entry = find_ref_entry(packed_refs, iter->refname);
1511 /* Overwrite existing packed entry with info from loose entry */
1512 packed_entry->flag = REF_ISPACKED;
1513 oidcpy(&packed_entry->u.value.oid, iter->oid);
1515 packed_entry = create_ref_entry(iter->refname, iter->oid,
1517 add_ref_entry(packed_refs, packed_entry);
1519 oidclr(&packed_entry->u.value.peeled);
1521 /* Schedule the loose reference for pruning if requested. */
1522 if ((flags & PACK_REFS_PRUNE)) {
1523 struct ref_to_prune *n;
1524 FLEX_ALLOC_STR(n, name, iter->refname);
1525 hashcpy(n->sha1, iter->oid->hash);
1526 n->next = refs_to_prune;
1530 if (ok != ITER_DONE)
1531 die("error while iterating over references");
1533 if (commit_packed_refs(refs))
1534 die_errno("unable to overwrite old ref-pack file");
1536 prune_refs(refs, refs_to_prune);
1541 * Rewrite the packed-refs file, omitting any refs listed in
1542 * 'refnames'. On error, leave packed-refs unchanged, write an error
1543 * message to 'err', and return a nonzero value.
1545 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1547 static int repack_without_refs(struct files_ref_store *refs,
1548 struct string_list *refnames, struct strbuf *err)
1550 struct ref_dir *packed;
1551 struct string_list_item *refname;
1552 int ret, needs_repacking = 0, removed = 0;
1554 files_assert_main_repository(refs, "repack_without_refs");
1557 /* Look for a packed ref */
1558 for_each_string_list_item(refname, refnames) {
1559 if (get_packed_ref(refs, refname->string)) {
1560 needs_repacking = 1;
1565 /* Avoid locking if we have nothing to do */
1566 if (!needs_repacking)
1567 return 0; /* no refname exists in packed refs */
1569 if (lock_packed_refs(refs, 0)) {
1570 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1573 packed = get_packed_refs(refs);
1575 /* Remove refnames from the cache */
1576 for_each_string_list_item(refname, refnames)
1577 if (remove_entry_from_dir(packed, refname->string) != -1)
1581 * All packed entries disappeared while we were
1582 * acquiring the lock.
1584 rollback_packed_refs(refs);
1588 /* Write what remains */
1589 ret = commit_packed_refs(refs);
1591 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1596 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1597 struct string_list *refnames, unsigned int flags)
1599 struct files_ref_store *refs =
1600 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1601 struct strbuf err = STRBUF_INIT;
1607 result = repack_without_refs(refs, refnames, &err);
1610 * If we failed to rewrite the packed-refs file, then
1611 * it is unsafe to try to remove loose refs, because
1612 * doing so might expose an obsolete packed value for
1613 * a reference that might even point at an object that
1614 * has been garbage collected.
1616 if (refnames->nr == 1)
1617 error(_("could not delete reference %s: %s"),
1618 refnames->items[0].string, err.buf);
1620 error(_("could not delete references: %s"), err.buf);
1625 for (i = 0; i < refnames->nr; i++) {
1626 const char *refname = refnames->items[i].string;
1628 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1629 result |= error(_("could not remove reference %s"), refname);
1633 strbuf_release(&err);
1638 * People using contrib's git-new-workdir have .git/logs/refs ->
1639 * /some/other/path/.git/logs/refs, and that may live on another device.
1641 * IOW, to avoid cross device rename errors, the temporary renamed log must
1642 * live into logs/refs.
1644 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1647 const char *tmp_renamed_log;
1651 static int rename_tmp_log_callback(const char *path, void *cb_data)
1653 struct rename_cb *cb = cb_data;
1655 if (rename(cb->tmp_renamed_log, path)) {
1657 * rename(a, b) when b is an existing directory ought
1658 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1659 * Sheesh. Record the true errno for error reporting,
1660 * but report EISDIR to raceproof_create_file() so
1661 * that it knows to retry.
1663 cb->true_errno = errno;
1664 if (errno == ENOTDIR)
1672 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1674 struct strbuf path = STRBUF_INIT;
1675 struct strbuf tmp = STRBUF_INIT;
1676 struct rename_cb cb;
1679 files_reflog_path(refs, &path, newrefname);
1680 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1681 cb.tmp_renamed_log = tmp.buf;
1682 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1684 if (errno == EISDIR)
1685 error("directory not empty: %s", path.buf);
1687 error("unable to move logfile %s to %s: %s",
1689 strerror(cb.true_errno));
1692 strbuf_release(&path);
1693 strbuf_release(&tmp);
1697 static int write_ref_to_lockfile(struct ref_lock *lock,
1698 const struct object_id *oid, struct strbuf *err);
1699 static int commit_ref_update(struct files_ref_store *refs,
1700 struct ref_lock *lock,
1701 const struct object_id *oid, const char *logmsg,
1702 struct strbuf *err);
1704 static int files_rename_ref(struct ref_store *ref_store,
1705 const char *oldrefname, const char *newrefname,
1708 struct files_ref_store *refs =
1709 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1710 struct object_id oid, orig_oid;
1711 int flag = 0, logmoved = 0;
1712 struct ref_lock *lock;
1713 struct stat loginfo;
1714 struct strbuf sb_oldref = STRBUF_INIT;
1715 struct strbuf sb_newref = STRBUF_INIT;
1716 struct strbuf tmp_renamed_log = STRBUF_INIT;
1718 struct strbuf err = STRBUF_INIT;
1720 files_reflog_path(refs, &sb_oldref, oldrefname);
1721 files_reflog_path(refs, &sb_newref, newrefname);
1722 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1724 log = !lstat(sb_oldref.buf, &loginfo);
1725 if (log && S_ISLNK(loginfo.st_mode)) {
1726 ret = error("reflog for %s is a symlink", oldrefname);
1730 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1731 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1732 orig_oid.hash, &flag)) {
1733 ret = error("refname %s not found", oldrefname);
1737 if (flag & REF_ISSYMREF) {
1738 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1742 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1747 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1748 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1749 oldrefname, strerror(errno));
1753 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1754 orig_oid.hash, REF_NODEREF)) {
1755 error("unable to delete old %s", oldrefname);
1760 * Since we are doing a shallow lookup, oid is not the
1761 * correct value to pass to delete_ref as old_oid. But that
1762 * doesn't matter, because an old_oid check wouldn't add to
1763 * the safety anyway; we want to delete the reference whatever
1764 * its current value.
1766 if (!refs_read_ref_full(&refs->base, newrefname,
1767 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1769 refs_delete_ref(&refs->base, NULL, newrefname,
1770 NULL, REF_NODEREF)) {
1771 if (errno == EISDIR) {
1772 struct strbuf path = STRBUF_INIT;
1775 files_ref_path(refs, &path, newrefname);
1776 result = remove_empty_directories(&path);
1777 strbuf_release(&path);
1780 error("Directory not empty: %s", newrefname);
1784 error("unable to delete existing %s", newrefname);
1789 if (log && rename_tmp_log(refs, newrefname))
1794 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1795 REF_NODEREF, NULL, &err);
1797 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1798 strbuf_release(&err);
1801 oidcpy(&lock->old_oid, &orig_oid);
1803 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1804 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1805 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1806 strbuf_release(&err);
1814 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1815 REF_NODEREF, NULL, &err);
1817 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1818 strbuf_release(&err);
1822 flag = log_all_ref_updates;
1823 log_all_ref_updates = LOG_REFS_NONE;
1824 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1825 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1826 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1827 strbuf_release(&err);
1829 log_all_ref_updates = flag;
1832 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1833 error("unable to restore logfile %s from %s: %s",
1834 oldrefname, newrefname, strerror(errno));
1835 if (!logmoved && log &&
1836 rename(tmp_renamed_log.buf, sb_oldref.buf))
1837 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1838 oldrefname, strerror(errno));
1841 strbuf_release(&sb_newref);
1842 strbuf_release(&sb_oldref);
1843 strbuf_release(&tmp_renamed_log);
1848 static int close_ref(struct ref_lock *lock)
1850 if (close_lock_file(lock->lk))
1855 static int commit_ref(struct ref_lock *lock)
1857 char *path = get_locked_file_path(lock->lk);
1860 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1862 * There is a directory at the path we want to rename
1863 * the lockfile to. Hopefully it is empty; try to
1866 size_t len = strlen(path);
1867 struct strbuf sb_path = STRBUF_INIT;
1869 strbuf_attach(&sb_path, path, len, len);
1872 * If this fails, commit_lock_file() will also fail
1873 * and will report the problem.
1875 remove_empty_directories(&sb_path);
1876 strbuf_release(&sb_path);
1881 if (commit_lock_file(lock->lk))
1886 static int open_or_create_logfile(const char *path, void *cb)
1890 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1891 return (*fd < 0) ? -1 : 0;
1895 * Create a reflog for a ref. If force_create = 0, only create the
1896 * reflog for certain refs (those for which should_autocreate_reflog
1897 * returns non-zero). Otherwise, create it regardless of the reference
1898 * name. If the logfile already existed or was created, return 0 and
1899 * set *logfd to the file descriptor opened for appending to the file.
1900 * If no logfile exists and we decided not to create one, return 0 and
1901 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1904 static int log_ref_setup(struct files_ref_store *refs,
1905 const char *refname, int force_create,
1906 int *logfd, struct strbuf *err)
1908 struct strbuf logfile_sb = STRBUF_INIT;
1911 files_reflog_path(refs, &logfile_sb, refname);
1912 logfile = strbuf_detach(&logfile_sb, NULL);
1914 if (force_create || should_autocreate_reflog(refname)) {
1915 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1916 if (errno == ENOENT)
1917 strbuf_addf(err, "unable to create directory for '%s': "
1918 "%s", logfile, strerror(errno));
1919 else if (errno == EISDIR)
1920 strbuf_addf(err, "there are still logs under '%s'",
1923 strbuf_addf(err, "unable to append to '%s': %s",
1924 logfile, strerror(errno));
1929 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1931 if (errno == ENOENT || errno == EISDIR) {
1933 * The logfile doesn't already exist,
1934 * but that is not an error; it only
1935 * means that we won't write log
1940 strbuf_addf(err, "unable to append to '%s': %s",
1941 logfile, strerror(errno));
1948 adjust_shared_perm(logfile);
1958 static int files_create_reflog(struct ref_store *ref_store,
1959 const char *refname, int force_create,
1962 struct files_ref_store *refs =
1963 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1966 if (log_ref_setup(refs, refname, force_create, &fd, err))
1975 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1976 const struct object_id *new_oid,
1977 const char *committer, const char *msg)
1979 int msglen, written;
1980 unsigned maxlen, len;
1983 msglen = msg ? strlen(msg) : 0;
1984 maxlen = strlen(committer) + msglen + 100;
1985 logrec = xmalloc(maxlen);
1986 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1987 oid_to_hex(old_oid),
1988 oid_to_hex(new_oid),
1991 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1993 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2001 static int files_log_ref_write(struct files_ref_store *refs,
2002 const char *refname, const struct object_id *old_oid,
2003 const struct object_id *new_oid, const char *msg,
2004 int flags, struct strbuf *err)
2008 if (log_all_ref_updates == LOG_REFS_UNSET)
2009 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2011 result = log_ref_setup(refs, refname,
2012 flags & REF_FORCE_CREATE_REFLOG,
2020 result = log_ref_write_fd(logfd, old_oid, new_oid,
2021 git_committer_info(0), msg);
2023 struct strbuf sb = STRBUF_INIT;
2024 int save_errno = errno;
2026 files_reflog_path(refs, &sb, refname);
2027 strbuf_addf(err, "unable to append to '%s': %s",
2028 sb.buf, strerror(save_errno));
2029 strbuf_release(&sb);
2034 struct strbuf sb = STRBUF_INIT;
2035 int save_errno = errno;
2037 files_reflog_path(refs, &sb, refname);
2038 strbuf_addf(err, "unable to append to '%s': %s",
2039 sb.buf, strerror(save_errno));
2040 strbuf_release(&sb);
2047 * Write sha1 into the open lockfile, then close the lockfile. On
2048 * errors, rollback the lockfile, fill in *err and
2051 static int write_ref_to_lockfile(struct ref_lock *lock,
2052 const struct object_id *oid, struct strbuf *err)
2054 static char term = '\n';
2058 o = parse_object(oid);
2061 "trying to write ref '%s' with nonexistent object %s",
2062 lock->ref_name, oid_to_hex(oid));
2066 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2068 "trying to write non-commit object %s to branch '%s'",
2069 oid_to_hex(oid), lock->ref_name);
2073 fd = get_lock_file_fd(lock->lk);
2074 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2075 write_in_full(fd, &term, 1) != 1 ||
2076 close_ref(lock) < 0) {
2078 "couldn't write '%s'", get_lock_file_path(lock->lk));
2086 * Commit a change to a loose reference that has already been written
2087 * to the loose reference lockfile. Also update the reflogs if
2088 * necessary, using the specified lockmsg (which can be NULL).
2090 static int commit_ref_update(struct files_ref_store *refs,
2091 struct ref_lock *lock,
2092 const struct object_id *oid, const char *logmsg,
2095 files_assert_main_repository(refs, "commit_ref_update");
2097 clear_loose_ref_cache(refs);
2098 if (files_log_ref_write(refs, lock->ref_name,
2099 &lock->old_oid, oid,
2101 char *old_msg = strbuf_detach(err, NULL);
2102 strbuf_addf(err, "cannot update the ref '%s': %s",
2103 lock->ref_name, old_msg);
2109 if (strcmp(lock->ref_name, "HEAD") != 0) {
2111 * Special hack: If a branch is updated directly and HEAD
2112 * points to it (may happen on the remote side of a push
2113 * for example) then logically the HEAD reflog should be
2115 * A generic solution implies reverse symref information,
2116 * but finding all symrefs pointing to the given branch
2117 * would be rather costly for this rare event (the direct
2118 * update of a branch) to be worth it. So let's cheat and
2119 * check with HEAD only which should cover 99% of all usage
2120 * scenarios (even 100% of the default ones).
2122 struct object_id head_oid;
2124 const char *head_ref;
2126 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2127 RESOLVE_REF_READING,
2128 head_oid.hash, &head_flag);
2129 if (head_ref && (head_flag & REF_ISSYMREF) &&
2130 !strcmp(head_ref, lock->ref_name)) {
2131 struct strbuf log_err = STRBUF_INIT;
2132 if (files_log_ref_write(refs, "HEAD",
2133 &lock->old_oid, oid,
2134 logmsg, 0, &log_err)) {
2135 error("%s", log_err.buf);
2136 strbuf_release(&log_err);
2141 if (commit_ref(lock)) {
2142 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2151 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2154 #ifndef NO_SYMLINK_HEAD
2155 char *ref_path = get_locked_file_path(lock->lk);
2157 ret = symlink(target, ref_path);
2161 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2166 static void update_symref_reflog(struct files_ref_store *refs,
2167 struct ref_lock *lock, const char *refname,
2168 const char *target, const char *logmsg)
2170 struct strbuf err = STRBUF_INIT;
2171 struct object_id new_oid;
2173 !refs_read_ref_full(&refs->base, target,
2174 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2175 files_log_ref_write(refs, refname, &lock->old_oid,
2176 &new_oid, logmsg, 0, &err)) {
2177 error("%s", err.buf);
2178 strbuf_release(&err);
2182 static int create_symref_locked(struct files_ref_store *refs,
2183 struct ref_lock *lock, const char *refname,
2184 const char *target, const char *logmsg)
2186 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2187 update_symref_reflog(refs, lock, refname, target, logmsg);
2191 if (!fdopen_lock_file(lock->lk, "w"))
2192 return error("unable to fdopen %s: %s",
2193 lock->lk->tempfile.filename.buf, strerror(errno));
2195 update_symref_reflog(refs, lock, refname, target, logmsg);
2197 /* no error check; commit_ref will check ferror */
2198 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2199 if (commit_ref(lock) < 0)
2200 return error("unable to write symref for %s: %s", refname,
2205 static int files_create_symref(struct ref_store *ref_store,
2206 const char *refname, const char *target,
2209 struct files_ref_store *refs =
2210 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2211 struct strbuf err = STRBUF_INIT;
2212 struct ref_lock *lock;
2215 lock = lock_ref_sha1_basic(refs, refname, NULL,
2216 NULL, NULL, REF_NODEREF, NULL,
2219 error("%s", err.buf);
2220 strbuf_release(&err);
2224 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2229 static int files_reflog_exists(struct ref_store *ref_store,
2230 const char *refname)
2232 struct files_ref_store *refs =
2233 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2234 struct strbuf sb = STRBUF_INIT;
2238 files_reflog_path(refs, &sb, refname);
2239 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2240 strbuf_release(&sb);
2244 static int files_delete_reflog(struct ref_store *ref_store,
2245 const char *refname)
2247 struct files_ref_store *refs =
2248 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2249 struct strbuf sb = STRBUF_INIT;
2252 files_reflog_path(refs, &sb, refname);
2253 ret = remove_path(sb.buf);
2254 strbuf_release(&sb);
2258 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2260 struct object_id ooid, noid;
2261 char *email_end, *message;
2262 timestamp_t timestamp;
2264 const char *p = sb->buf;
2266 /* old SP new SP name <email> SP time TAB msg LF */
2267 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2268 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2269 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2270 !(email_end = strchr(p, '>')) ||
2271 email_end[1] != ' ' ||
2272 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2273 !message || message[0] != ' ' ||
2274 (message[1] != '+' && message[1] != '-') ||
2275 !isdigit(message[2]) || !isdigit(message[3]) ||
2276 !isdigit(message[4]) || !isdigit(message[5]))
2277 return 0; /* corrupt? */
2278 email_end[1] = '\0';
2279 tz = strtol(message + 1, NULL, 10);
2280 if (message[6] != '\t')
2284 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2287 static char *find_beginning_of_line(char *bob, char *scan)
2289 while (bob < scan && *(--scan) != '\n')
2290 ; /* keep scanning backwards */
2292 * Return either beginning of the buffer, or LF at the end of
2293 * the previous line.
2298 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2299 const char *refname,
2300 each_reflog_ent_fn fn,
2303 struct files_ref_store *refs =
2304 files_downcast(ref_store, REF_STORE_READ,
2305 "for_each_reflog_ent_reverse");
2306 struct strbuf sb = STRBUF_INIT;
2309 int ret = 0, at_tail = 1;
2311 files_reflog_path(refs, &sb, refname);
2312 logfp = fopen(sb.buf, "r");
2313 strbuf_release(&sb);
2317 /* Jump to the end */
2318 if (fseek(logfp, 0, SEEK_END) < 0)
2319 ret = error("cannot seek back reflog for %s: %s",
2320 refname, strerror(errno));
2322 while (!ret && 0 < pos) {
2328 /* Fill next block from the end */
2329 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2330 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2331 ret = error("cannot seek back reflog for %s: %s",
2332 refname, strerror(errno));
2335 nread = fread(buf, cnt, 1, logfp);
2337 ret = error("cannot read %d bytes from reflog for %s: %s",
2338 cnt, refname, strerror(errno));
2343 scanp = endp = buf + cnt;
2344 if (at_tail && scanp[-1] == '\n')
2345 /* Looking at the final LF at the end of the file */
2349 while (buf < scanp) {
2351 * terminating LF of the previous line, or the beginning
2356 bp = find_beginning_of_line(buf, scanp);
2360 * The newline is the end of the previous line,
2361 * so we know we have complete line starting
2362 * at (bp + 1). Prefix it onto any prior data
2363 * we collected for the line and process it.
2365 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2368 ret = show_one_reflog_ent(&sb, fn, cb_data);
2374 * We are at the start of the buffer, and the
2375 * start of the file; there is no previous
2376 * line, and we have everything for this one.
2377 * Process it, and we can end the loop.
2379 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2380 ret = show_one_reflog_ent(&sb, fn, cb_data);
2387 * We are at the start of the buffer, and there
2388 * is more file to read backwards. Which means
2389 * we are in the middle of a line. Note that we
2390 * may get here even if *bp was a newline; that
2391 * just means we are at the exact end of the
2392 * previous line, rather than some spot in the
2395 * Save away what we have to be combined with
2396 * the data from the next read.
2398 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2405 die("BUG: reverse reflog parser had leftover data");
2408 strbuf_release(&sb);
2412 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2413 const char *refname,
2414 each_reflog_ent_fn fn, void *cb_data)
2416 struct files_ref_store *refs =
2417 files_downcast(ref_store, REF_STORE_READ,
2418 "for_each_reflog_ent");
2420 struct strbuf sb = STRBUF_INIT;
2423 files_reflog_path(refs, &sb, refname);
2424 logfp = fopen(sb.buf, "r");
2425 strbuf_release(&sb);
2429 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2430 ret = show_one_reflog_ent(&sb, fn, cb_data);
2432 strbuf_release(&sb);
2436 struct files_reflog_iterator {
2437 struct ref_iterator base;
2439 struct ref_store *ref_store;
2440 struct dir_iterator *dir_iterator;
2441 struct object_id oid;
2444 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2446 struct files_reflog_iterator *iter =
2447 (struct files_reflog_iterator *)ref_iterator;
2448 struct dir_iterator *diter = iter->dir_iterator;
2451 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2454 if (!S_ISREG(diter->st.st_mode))
2456 if (diter->basename[0] == '.')
2458 if (ends_with(diter->basename, ".lock"))
2461 if (refs_read_ref_full(iter->ref_store,
2462 diter->relative_path, 0,
2463 iter->oid.hash, &flags)) {
2464 error("bad ref for %s", diter->path.buf);
2468 iter->base.refname = diter->relative_path;
2469 iter->base.oid = &iter->oid;
2470 iter->base.flags = flags;
2474 iter->dir_iterator = NULL;
2475 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2480 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2481 struct object_id *peeled)
2483 die("BUG: ref_iterator_peel() called for reflog_iterator");
2486 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2488 struct files_reflog_iterator *iter =
2489 (struct files_reflog_iterator *)ref_iterator;
2492 if (iter->dir_iterator)
2493 ok = dir_iterator_abort(iter->dir_iterator);
2495 base_ref_iterator_free(ref_iterator);
2499 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2500 files_reflog_iterator_advance,
2501 files_reflog_iterator_peel,
2502 files_reflog_iterator_abort
2505 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2507 struct files_ref_store *refs =
2508 files_downcast(ref_store, REF_STORE_READ,
2509 "reflog_iterator_begin");
2510 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2511 struct ref_iterator *ref_iterator = &iter->base;
2512 struct strbuf sb = STRBUF_INIT;
2514 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2515 files_reflog_path(refs, &sb, NULL);
2516 iter->dir_iterator = dir_iterator_begin(sb.buf);
2517 iter->ref_store = ref_store;
2518 strbuf_release(&sb);
2519 return ref_iterator;
2522 static int ref_update_reject_duplicates(struct string_list *refnames,
2525 int i, n = refnames->nr;
2529 for (i = 1; i < n; i++)
2530 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
2532 "multiple updates for ref '%s' not allowed.",
2533 refnames->items[i].string);
2540 * If update is a direct update of head_ref (the reference pointed to
2541 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2543 static int split_head_update(struct ref_update *update,
2544 struct ref_transaction *transaction,
2545 const char *head_ref,
2546 struct string_list *affected_refnames,
2549 struct string_list_item *item;
2550 struct ref_update *new_update;
2552 if ((update->flags & REF_LOG_ONLY) ||
2553 (update->flags & REF_ISPRUNING) ||
2554 (update->flags & REF_UPDATE_VIA_HEAD))
2557 if (strcmp(update->refname, head_ref))
2561 * First make sure that HEAD is not already in the
2562 * transaction. This insertion is O(N) in the transaction
2563 * size, but it happens at most once per transaction.
2565 item = string_list_insert(affected_refnames, "HEAD");
2567 /* An entry already existed */
2569 "multiple updates for 'HEAD' (including one "
2570 "via its referent '%s') are not allowed",
2572 return TRANSACTION_NAME_CONFLICT;
2575 new_update = ref_transaction_add_update(
2576 transaction, "HEAD",
2577 update->flags | REF_LOG_ONLY | REF_NODEREF,
2578 update->new_oid.hash, update->old_oid.hash,
2581 item->util = new_update;
2587 * update is for a symref that points at referent and doesn't have
2588 * REF_NODEREF set. Split it into two updates:
2589 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2590 * - A new, separate update for the referent reference
2591 * Note that the new update will itself be subject to splitting when
2592 * the iteration gets to it.
2594 static int split_symref_update(struct files_ref_store *refs,
2595 struct ref_update *update,
2596 const char *referent,
2597 struct ref_transaction *transaction,
2598 struct string_list *affected_refnames,
2601 struct string_list_item *item;
2602 struct ref_update *new_update;
2603 unsigned int new_flags;
2606 * First make sure that referent is not already in the
2607 * transaction. This insertion is O(N) in the transaction
2608 * size, but it happens at most once per symref in a
2611 item = string_list_insert(affected_refnames, referent);
2613 /* An entry already existed */
2615 "multiple updates for '%s' (including one "
2616 "via symref '%s') are not allowed",
2617 referent, update->refname);
2618 return TRANSACTION_NAME_CONFLICT;
2621 new_flags = update->flags;
2622 if (!strcmp(update->refname, "HEAD")) {
2624 * Record that the new update came via HEAD, so that
2625 * when we process it, split_head_update() doesn't try
2626 * to add another reflog update for HEAD. Note that
2627 * this bit will be propagated if the new_update
2628 * itself needs to be split.
2630 new_flags |= REF_UPDATE_VIA_HEAD;
2633 new_update = ref_transaction_add_update(
2634 transaction, referent, new_flags,
2635 update->new_oid.hash, update->old_oid.hash,
2638 new_update->parent_update = update;
2641 * Change the symbolic ref update to log only. Also, it
2642 * doesn't need to check its old SHA-1 value, as that will be
2643 * done when new_update is processed.
2645 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2646 update->flags &= ~REF_HAVE_OLD;
2648 item->util = new_update;
2654 * Return the refname under which update was originally requested.
2656 static const char *original_update_refname(struct ref_update *update)
2658 while (update->parent_update)
2659 update = update->parent_update;
2661 return update->refname;
2665 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2666 * are consistent with oid, which is the reference's current value. If
2667 * everything is OK, return 0; otherwise, write an error message to
2668 * err and return -1.
2670 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2673 if (!(update->flags & REF_HAVE_OLD) ||
2674 !oidcmp(oid, &update->old_oid))
2677 if (is_null_oid(&update->old_oid))
2678 strbuf_addf(err, "cannot lock ref '%s': "
2679 "reference already exists",
2680 original_update_refname(update));
2681 else if (is_null_oid(oid))
2682 strbuf_addf(err, "cannot lock ref '%s': "
2683 "reference is missing but expected %s",
2684 original_update_refname(update),
2685 oid_to_hex(&update->old_oid));
2687 strbuf_addf(err, "cannot lock ref '%s': "
2688 "is at %s but expected %s",
2689 original_update_refname(update),
2691 oid_to_hex(&update->old_oid));
2697 * Prepare for carrying out update:
2698 * - Lock the reference referred to by update.
2699 * - Read the reference under lock.
2700 * - Check that its old SHA-1 value (if specified) is correct, and in
2701 * any case record it in update->lock->old_oid for later use when
2702 * writing the reflog.
2703 * - If it is a symref update without REF_NODEREF, split it up into a
2704 * REF_LOG_ONLY update of the symref and add a separate update for
2705 * the referent to transaction.
2706 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2709 static int lock_ref_for_update(struct files_ref_store *refs,
2710 struct ref_update *update,
2711 struct ref_transaction *transaction,
2712 const char *head_ref,
2713 struct string_list *affected_refnames,
2716 struct strbuf referent = STRBUF_INIT;
2717 int mustexist = (update->flags & REF_HAVE_OLD) &&
2718 !is_null_oid(&update->old_oid);
2720 struct ref_lock *lock;
2722 files_assert_main_repository(refs, "lock_ref_for_update");
2724 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2725 update->flags |= REF_DELETING;
2728 ret = split_head_update(update, transaction, head_ref,
2729 affected_refnames, err);
2734 ret = lock_raw_ref(refs, update->refname, mustexist,
2735 affected_refnames, NULL,
2737 &update->type, err);
2741 reason = strbuf_detach(err, NULL);
2742 strbuf_addf(err, "cannot lock ref '%s': %s",
2743 original_update_refname(update), reason);
2748 update->backend_data = lock;
2750 if (update->type & REF_ISSYMREF) {
2751 if (update->flags & REF_NODEREF) {
2753 * We won't be reading the referent as part of
2754 * the transaction, so we have to read it here
2755 * to record and possibly check old_sha1:
2757 if (refs_read_ref_full(&refs->base,
2759 lock->old_oid.hash, NULL)) {
2760 if (update->flags & REF_HAVE_OLD) {
2761 strbuf_addf(err, "cannot lock ref '%s': "
2762 "error reading reference",
2763 original_update_refname(update));
2766 } else if (check_old_oid(update, &lock->old_oid, err)) {
2767 return TRANSACTION_GENERIC_ERROR;
2771 * Create a new update for the reference this
2772 * symref is pointing at. Also, we will record
2773 * and verify old_sha1 for this update as part
2774 * of processing the split-off update, so we
2775 * don't have to do it here.
2777 ret = split_symref_update(refs, update,
2778 referent.buf, transaction,
2779 affected_refnames, err);
2784 struct ref_update *parent_update;
2786 if (check_old_oid(update, &lock->old_oid, err))
2787 return TRANSACTION_GENERIC_ERROR;
2790 * If this update is happening indirectly because of a
2791 * symref update, record the old SHA-1 in the parent
2794 for (parent_update = update->parent_update;
2796 parent_update = parent_update->parent_update) {
2797 struct ref_lock *parent_lock = parent_update->backend_data;
2798 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2802 if ((update->flags & REF_HAVE_NEW) &&
2803 !(update->flags & REF_DELETING) &&
2804 !(update->flags & REF_LOG_ONLY)) {
2805 if (!(update->type & REF_ISSYMREF) &&
2806 !oidcmp(&lock->old_oid, &update->new_oid)) {
2808 * The reference already has the desired
2809 * value, so we don't need to write it.
2811 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2813 char *write_err = strbuf_detach(err, NULL);
2816 * The lock was freed upon failure of
2817 * write_ref_to_lockfile():
2819 update->backend_data = NULL;
2821 "cannot update ref '%s': %s",
2822 update->refname, write_err);
2824 return TRANSACTION_GENERIC_ERROR;
2826 update->flags |= REF_NEEDS_COMMIT;
2829 if (!(update->flags & REF_NEEDS_COMMIT)) {
2831 * We didn't call write_ref_to_lockfile(), so
2832 * the lockfile is still open. Close it to
2833 * free up the file descriptor:
2835 if (close_ref(lock)) {
2836 strbuf_addf(err, "couldn't close '%s.lock'",
2838 return TRANSACTION_GENERIC_ERROR;
2844 static int files_transaction_commit(struct ref_store *ref_store,
2845 struct ref_transaction *transaction,
2848 struct files_ref_store *refs =
2849 files_downcast(ref_store, REF_STORE_WRITE,
2850 "ref_transaction_commit");
2853 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2854 struct string_list_item *ref_to_delete;
2855 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2856 char *head_ref = NULL;
2858 struct object_id head_oid;
2859 struct strbuf sb = STRBUF_INIT;
2863 if (transaction->state != REF_TRANSACTION_OPEN)
2864 die("BUG: commit called for transaction that is not open");
2866 if (!transaction->nr) {
2867 transaction->state = REF_TRANSACTION_CLOSED;
2872 * Fail if a refname appears more than once in the
2873 * transaction. (If we end up splitting up any updates using
2874 * split_symref_update() or split_head_update(), those
2875 * functions will check that the new updates don't have the
2876 * same refname as any existing ones.)
2878 for (i = 0; i < transaction->nr; i++) {
2879 struct ref_update *update = transaction->updates[i];
2880 struct string_list_item *item =
2881 string_list_append(&affected_refnames, update->refname);
2884 * We store a pointer to update in item->util, but at
2885 * the moment we never use the value of this field
2886 * except to check whether it is non-NULL.
2888 item->util = update;
2890 string_list_sort(&affected_refnames);
2891 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2892 ret = TRANSACTION_GENERIC_ERROR;
2897 * Special hack: If a branch is updated directly and HEAD
2898 * points to it (may happen on the remote side of a push
2899 * for example) then logically the HEAD reflog should be
2902 * A generic solution would require reverse symref lookups,
2903 * but finding all symrefs pointing to a given branch would be
2904 * rather costly for this rare event (the direct update of a
2905 * branch) to be worth it. So let's cheat and check with HEAD
2906 * only, which should cover 99% of all usage scenarios (even
2907 * 100% of the default ones).
2909 * So if HEAD is a symbolic reference, then record the name of
2910 * the reference that it points to. If we see an update of
2911 * head_ref within the transaction, then split_head_update()
2912 * arranges for the reflog of HEAD to be updated, too.
2914 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2915 RESOLVE_REF_NO_RECURSE,
2916 head_oid.hash, &head_type);
2918 if (head_ref && !(head_type & REF_ISSYMREF)) {
2924 * Acquire all locks, verify old values if provided, check
2925 * that new values are valid, and write new values to the
2926 * lockfiles, ready to be activated. Only keep one lockfile
2927 * open at a time to avoid running out of file descriptors.
2929 for (i = 0; i < transaction->nr; i++) {
2930 struct ref_update *update = transaction->updates[i];
2932 ret = lock_ref_for_update(refs, update, transaction,
2933 head_ref, &affected_refnames, err);
2938 /* Perform updates first so live commits remain referenced */
2939 for (i = 0; i < transaction->nr; i++) {
2940 struct ref_update *update = transaction->updates[i];
2941 struct ref_lock *lock = update->backend_data;
2943 if (update->flags & REF_NEEDS_COMMIT ||
2944 update->flags & REF_LOG_ONLY) {
2945 if (files_log_ref_write(refs,
2949 update->msg, update->flags,
2951 char *old_msg = strbuf_detach(err, NULL);
2953 strbuf_addf(err, "cannot update the ref '%s': %s",
2954 lock->ref_name, old_msg);
2957 update->backend_data = NULL;
2958 ret = TRANSACTION_GENERIC_ERROR;
2962 if (update->flags & REF_NEEDS_COMMIT) {
2963 clear_loose_ref_cache(refs);
2964 if (commit_ref(lock)) {
2965 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2967 update->backend_data = NULL;
2968 ret = TRANSACTION_GENERIC_ERROR;
2973 /* Perform deletes now that updates are safely completed */
2974 for (i = 0; i < transaction->nr; i++) {
2975 struct ref_update *update = transaction->updates[i];
2976 struct ref_lock *lock = update->backend_data;
2978 if (update->flags & REF_DELETING &&
2979 !(update->flags & REF_LOG_ONLY)) {
2980 if (!(update->type & REF_ISPACKED) ||
2981 update->type & REF_ISSYMREF) {
2982 /* It is a loose reference. */
2984 files_ref_path(refs, &sb, lock->ref_name);
2985 if (unlink_or_msg(sb.buf, err)) {
2986 ret = TRANSACTION_GENERIC_ERROR;
2989 update->flags |= REF_DELETED_LOOSE;
2992 if (!(update->flags & REF_ISPRUNING))
2993 string_list_append(&refs_to_delete,
2998 if (repack_without_refs(refs, &refs_to_delete, err)) {
2999 ret = TRANSACTION_GENERIC_ERROR;
3003 /* Delete the reflogs of any references that were deleted: */
3004 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3006 files_reflog_path(refs, &sb, ref_to_delete->string);
3007 if (!unlink_or_warn(sb.buf))
3008 try_remove_empty_parents(refs, ref_to_delete->string,
3009 REMOVE_EMPTY_PARENTS_REFLOG);
3012 clear_loose_ref_cache(refs);
3015 strbuf_release(&sb);
3016 transaction->state = REF_TRANSACTION_CLOSED;
3018 for (i = 0; i < transaction->nr; i++) {
3019 struct ref_update *update = transaction->updates[i];
3020 struct ref_lock *lock = update->backend_data;
3025 if (update->flags & REF_DELETED_LOOSE) {
3027 * The loose reference was deleted. Delete any
3028 * empty parent directories. (Note that this
3029 * can only work because we have already
3030 * removed the lockfile.)
3032 try_remove_empty_parents(refs, update->refname,
3033 REMOVE_EMPTY_PARENTS_REF);
3037 string_list_clear(&refs_to_delete, 0);
3039 string_list_clear(&affected_refnames, 0);
3044 static int ref_present(const char *refname,
3045 const struct object_id *oid, int flags, void *cb_data)
3047 struct string_list *affected_refnames = cb_data;
3049 return string_list_has_string(affected_refnames, refname);
3052 static int files_initial_transaction_commit(struct ref_store *ref_store,
3053 struct ref_transaction *transaction,
3056 struct files_ref_store *refs =
3057 files_downcast(ref_store, REF_STORE_WRITE,
3058 "initial_ref_transaction_commit");
3061 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3065 if (transaction->state != REF_TRANSACTION_OPEN)
3066 die("BUG: commit called for transaction that is not open");
3068 /* Fail if a refname appears more than once in the transaction: */
3069 for (i = 0; i < transaction->nr; i++)
3070 string_list_append(&affected_refnames,
3071 transaction->updates[i]->refname);
3072 string_list_sort(&affected_refnames);
3073 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3074 ret = TRANSACTION_GENERIC_ERROR;
3079 * It's really undefined to call this function in an active
3080 * repository or when there are existing references: we are
3081 * only locking and changing packed-refs, so (1) any
3082 * simultaneous processes might try to change a reference at
3083 * the same time we do, and (2) any existing loose versions of
3084 * the references that we are setting would have precedence
3085 * over our values. But some remote helpers create the remote
3086 * "HEAD" and "master" branches before calling this function,
3087 * so here we really only check that none of the references
3088 * that we are creating already exists.
3090 if (refs_for_each_rawref(&refs->base, ref_present,
3091 &affected_refnames))
3092 die("BUG: initial ref transaction called with existing refs");
3094 for (i = 0; i < transaction->nr; i++) {
3095 struct ref_update *update = transaction->updates[i];
3097 if ((update->flags & REF_HAVE_OLD) &&
3098 !is_null_oid(&update->old_oid))
3099 die("BUG: initial ref transaction with old_sha1 set");
3100 if (refs_verify_refname_available(&refs->base, update->refname,
3101 &affected_refnames, NULL,
3103 ret = TRANSACTION_NAME_CONFLICT;
3108 if (lock_packed_refs(refs, 0)) {
3109 strbuf_addf(err, "unable to lock packed-refs file: %s",
3111 ret = TRANSACTION_GENERIC_ERROR;
3115 for (i = 0; i < transaction->nr; i++) {
3116 struct ref_update *update = transaction->updates[i];
3118 if ((update->flags & REF_HAVE_NEW) &&
3119 !is_null_oid(&update->new_oid))
3120 add_packed_ref(refs, update->refname,
3124 if (commit_packed_refs(refs)) {
3125 strbuf_addf(err, "unable to commit packed-refs file: %s",
3127 ret = TRANSACTION_GENERIC_ERROR;
3132 transaction->state = REF_TRANSACTION_CLOSED;
3133 string_list_clear(&affected_refnames, 0);
3137 struct expire_reflog_cb {
3139 reflog_expiry_should_prune_fn *should_prune_fn;
3142 struct object_id last_kept_oid;
3145 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3146 const char *email, timestamp_t timestamp, int tz,
3147 const char *message, void *cb_data)
3149 struct expire_reflog_cb *cb = cb_data;
3150 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3152 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3153 ooid = &cb->last_kept_oid;
3155 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3156 message, policy_cb)) {
3158 printf("would prune %s", message);
3159 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3160 printf("prune %s", message);
3163 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3164 oid_to_hex(ooid), oid_to_hex(noid),
3165 email, timestamp, tz, message);
3166 oidcpy(&cb->last_kept_oid, noid);
3168 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3169 printf("keep %s", message);
3174 static int files_reflog_expire(struct ref_store *ref_store,
3175 const char *refname, const unsigned char *sha1,
3177 reflog_expiry_prepare_fn prepare_fn,
3178 reflog_expiry_should_prune_fn should_prune_fn,
3179 reflog_expiry_cleanup_fn cleanup_fn,
3180 void *policy_cb_data)
3182 struct files_ref_store *refs =
3183 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3184 static struct lock_file reflog_lock;
3185 struct expire_reflog_cb cb;
3186 struct ref_lock *lock;
3187 struct strbuf log_file_sb = STRBUF_INIT;
3191 struct strbuf err = STRBUF_INIT;
3192 struct object_id oid;
3194 memset(&cb, 0, sizeof(cb));
3196 cb.policy_cb = policy_cb_data;
3197 cb.should_prune_fn = should_prune_fn;
3200 * The reflog file is locked by holding the lock on the
3201 * reference itself, plus we might need to update the
3202 * reference if --updateref was specified:
3204 lock = lock_ref_sha1_basic(refs, refname, sha1,
3205 NULL, NULL, REF_NODEREF,
3208 error("cannot lock ref '%s': %s", refname, err.buf);
3209 strbuf_release(&err);
3212 if (!refs_reflog_exists(ref_store, refname)) {
3217 files_reflog_path(refs, &log_file_sb, refname);
3218 log_file = strbuf_detach(&log_file_sb, NULL);
3219 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3221 * Even though holding $GIT_DIR/logs/$reflog.lock has
3222 * no locking implications, we use the lock_file
3223 * machinery here anyway because it does a lot of the
3224 * work we need, including cleaning up if the program
3225 * exits unexpectedly.
3227 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3228 struct strbuf err = STRBUF_INIT;
3229 unable_to_lock_message(log_file, errno, &err);
3230 error("%s", err.buf);
3231 strbuf_release(&err);
3234 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3236 error("cannot fdopen %s (%s)",
3237 get_lock_file_path(&reflog_lock), strerror(errno));
3242 hashcpy(oid.hash, sha1);
3244 (*prepare_fn)(refname, &oid, cb.policy_cb);
3245 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3246 (*cleanup_fn)(cb.policy_cb);
3248 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3250 * It doesn't make sense to adjust a reference pointed
3251 * to by a symbolic ref based on expiring entries in
3252 * the symbolic reference's reflog. Nor can we update
3253 * a reference if there are no remaining reflog
3256 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3257 !(type & REF_ISSYMREF) &&
3258 !is_null_oid(&cb.last_kept_oid);
3260 if (close_lock_file(&reflog_lock)) {
3261 status |= error("couldn't write %s: %s", log_file,
3263 } else if (update &&
3264 (write_in_full(get_lock_file_fd(lock->lk),
3265 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3266 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3267 close_ref(lock) < 0)) {
3268 status |= error("couldn't write %s",
3269 get_lock_file_path(lock->lk));
3270 rollback_lock_file(&reflog_lock);
3271 } else if (commit_lock_file(&reflog_lock)) {
3272 status |= error("unable to write reflog '%s' (%s)",
3273 log_file, strerror(errno));
3274 } else if (update && commit_ref(lock)) {
3275 status |= error("couldn't set %s", lock->ref_name);
3283 rollback_lock_file(&reflog_lock);
3289 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3291 struct files_ref_store *refs =
3292 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3293 struct strbuf sb = STRBUF_INIT;
3296 * Create .git/refs/{heads,tags}
3298 files_ref_path(refs, &sb, "refs/heads");
3299 safe_create_dir(sb.buf, 1);
3302 files_ref_path(refs, &sb, "refs/tags");
3303 safe_create_dir(sb.buf, 1);
3305 strbuf_release(&sb);
3309 struct ref_storage_be refs_be_files = {
3312 files_ref_store_create,
3314 files_transaction_commit,
3315 files_initial_transaction_commit,
3319 files_create_symref,
3323 files_ref_iterator_begin,
3326 files_reflog_iterator_begin,
3327 files_for_each_reflog_ent,
3328 files_for_each_reflog_ent_reverse,
3329 files_reflog_exists,
3330 files_create_reflog,
3331 files_delete_reflog,