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;
47 * Iff the packed-refs file associated with this instance is
48 * currently locked for writing, this points at the associated
49 * lock (which is owned by somebody else). The referrer count
50 * is also incremented when the file is locked and decremented
51 * when it is unlocked.
53 struct lock_file *lock;
55 /* The metadata from when this packed-refs cache was read */
56 struct stat_validity validity;
60 * Future: need to be in "struct repository"
61 * when doing a full libification.
63 struct files_ref_store {
64 struct ref_store base;
65 unsigned int store_flags;
69 char *packed_refs_path;
71 struct ref_cache *loose;
72 struct packed_ref_cache *packed;
75 /* Lock used for the main packed-refs file: */
76 static struct lock_file packlock;
79 * Increment the reference count of *packed_refs.
81 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
83 packed_refs->referrers++;
87 * Decrease the reference count of *packed_refs. If it goes to zero,
88 * free *packed_refs and return true; otherwise return false.
90 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
92 if (!--packed_refs->referrers) {
93 free_ref_cache(packed_refs->cache);
94 stat_validity_clear(&packed_refs->validity);
102 static void clear_packed_ref_cache(struct files_ref_store *refs)
105 struct packed_ref_cache *packed_refs = refs->packed;
107 if (packed_refs->lock)
108 die("internal error: packed-ref cache cleared while locked");
110 release_packed_ref_cache(packed_refs);
114 static void clear_loose_ref_cache(struct files_ref_store *refs)
117 free_ref_cache(refs->loose);
123 * Create a new submodule ref cache and add it to the internal
126 static struct ref_store *files_ref_store_create(const char *gitdir,
129 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
130 struct ref_store *ref_store = (struct ref_store *)refs;
131 struct strbuf sb = STRBUF_INIT;
133 base_ref_store_init(ref_store, &refs_be_files);
134 refs->store_flags = flags;
136 refs->gitdir = xstrdup(gitdir);
137 get_common_dir_noenv(&sb, gitdir);
138 refs->gitcommondir = strbuf_detach(&sb, NULL);
139 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
140 refs->packed_refs_path = strbuf_detach(&sb, NULL);
146 * Die if refs is not the main ref store. caller is used in any
147 * necessary error messages.
149 static void files_assert_main_repository(struct files_ref_store *refs,
152 if (refs->store_flags & REF_STORE_MAIN)
155 die("BUG: operation %s only allowed for main ref store", caller);
159 * Downcast ref_store to files_ref_store. Die if ref_store is not a
160 * files_ref_store. required_flags is compared with ref_store's
161 * store_flags to ensure the ref_store has all required capabilities.
162 * "caller" is used in any necessary error messages.
164 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
165 unsigned int required_flags,
168 struct files_ref_store *refs;
170 if (ref_store->be != &refs_be_files)
171 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
172 ref_store->be->name, caller);
174 refs = (struct files_ref_store *)ref_store;
176 if ((refs->store_flags & required_flags) != required_flags)
177 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
178 caller, required_flags, refs->store_flags);
183 /* The length of a peeled reference line in packed-refs, including EOL: */
184 #define PEELED_LINE_LENGTH 42
187 * The packed-refs header line that we write out. Perhaps other
188 * traits will be added later. The trailing space is required.
190 static const char PACKED_REFS_HEADER[] =
191 "# pack-refs with: peeled fully-peeled \n";
194 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
195 * Return a pointer to the refname within the line (null-terminated),
196 * or NULL if there was a problem.
198 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
202 if (parse_oid_hex(line->buf, oid, &ref) < 0)
204 if (!isspace(*ref++))
210 if (line->buf[line->len - 1] != '\n')
212 line->buf[--line->len] = 0;
218 * Read f, which is a packed-refs file, into dir.
220 * A comment line of the form "# pack-refs with: " may contain zero or
221 * more traits. We interpret the traits as follows:
225 * Probably no references are peeled. But if the file contains a
226 * peeled value for a reference, we will use it.
230 * References under "refs/tags/", if they *can* be peeled, *are*
231 * peeled in this file. References outside of "refs/tags/" are
232 * probably not peeled even if they could have been, but if we find
233 * a peeled value for such a reference we will use it.
237 * All references in the file that can be peeled are peeled.
238 * Inversely (and this is more important), any references in the
239 * file for which no peeled value is recorded is not peelable. This
240 * trait should typically be written alongside "peeled" for
241 * compatibility with older clients, but we do not require it
242 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
244 static void read_packed_refs(FILE *f, struct ref_dir *dir)
246 struct ref_entry *last = NULL;
247 struct strbuf line = STRBUF_INIT;
248 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
250 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
251 struct object_id oid;
255 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
256 if (strstr(traits, " fully-peeled "))
257 peeled = PEELED_FULLY;
258 else if (strstr(traits, " peeled "))
259 peeled = PEELED_TAGS;
260 /* perhaps other traits later as well */
264 refname = parse_ref_line(&line, &oid);
266 int flag = REF_ISPACKED;
268 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
269 if (!refname_is_safe(refname))
270 die("packed refname is dangerous: %s", refname);
272 flag |= REF_BAD_NAME | REF_ISBROKEN;
274 last = create_ref_entry(refname, &oid, flag, 0);
275 if (peeled == PEELED_FULLY ||
276 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
277 last->flag |= REF_KNOWS_PEELED;
278 add_ref_entry(dir, last);
282 line.buf[0] == '^' &&
283 line.len == PEELED_LINE_LENGTH &&
284 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
285 !get_oid_hex(line.buf + 1, &oid)) {
286 oidcpy(&last->u.value.peeled, &oid);
288 * Regardless of what the file header said,
289 * we definitely know the value of *this*
292 last->flag |= REF_KNOWS_PEELED;
296 strbuf_release(&line);
299 static const char *files_packed_refs_path(struct files_ref_store *refs)
301 return refs->packed_refs_path;
304 static void files_reflog_path(struct files_ref_store *refs,
310 * FIXME: of course this is wrong in multi worktree
311 * setting. To be fixed real soon.
313 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
317 switch (ref_type(refname)) {
318 case REF_TYPE_PER_WORKTREE:
319 case REF_TYPE_PSEUDOREF:
320 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
322 case REF_TYPE_NORMAL:
323 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
326 die("BUG: unknown ref type %d of ref %s",
327 ref_type(refname), refname);
331 static void files_ref_path(struct files_ref_store *refs,
335 switch (ref_type(refname)) {
336 case REF_TYPE_PER_WORKTREE:
337 case REF_TYPE_PSEUDOREF:
338 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
340 case REF_TYPE_NORMAL:
341 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
344 die("BUG: unknown ref type %d of ref %s",
345 ref_type(refname), refname);
350 * Get the packed_ref_cache for the specified files_ref_store,
351 * creating it if necessary.
353 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
355 const char *packed_refs_file = files_packed_refs_path(refs);
358 !stat_validity_check(&refs->packed->validity, packed_refs_file))
359 clear_packed_ref_cache(refs);
364 refs->packed = xcalloc(1, sizeof(*refs->packed));
365 acquire_packed_ref_cache(refs->packed);
366 refs->packed->cache = create_ref_cache(&refs->base, NULL);
367 refs->packed->cache->root->flag &= ~REF_INCOMPLETE;
368 f = fopen(packed_refs_file, "r");
370 stat_validity_update(&refs->packed->validity, fileno(f));
371 read_packed_refs(f, get_ref_dir(refs->packed->cache->root));
378 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
380 return get_ref_dir(packed_ref_cache->cache->root);
383 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
385 return get_packed_ref_dir(get_packed_ref_cache(refs));
389 * Add a reference to the in-memory packed reference cache. This may
390 * only be called while the packed-refs file is locked (see
391 * lock_packed_refs()). To actually write the packed-refs file, call
392 * commit_packed_refs().
394 static void add_packed_ref(struct files_ref_store *refs,
395 const char *refname, const struct object_id *oid)
397 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
399 if (!packed_ref_cache->lock)
400 die("internal error: packed refs not locked");
401 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
402 create_ref_entry(refname, oid, REF_ISPACKED, 1));
406 * Read the loose references from the namespace dirname into dir
407 * (without recursing). dirname must end with '/'. dir must be the
408 * directory entry corresponding to dirname.
410 static void loose_fill_ref_dir(struct ref_store *ref_store,
411 struct ref_dir *dir, const char *dirname)
413 struct files_ref_store *refs =
414 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
417 int dirnamelen = strlen(dirname);
418 struct strbuf refname;
419 struct strbuf path = STRBUF_INIT;
422 files_ref_path(refs, &path, dirname);
423 path_baselen = path.len;
425 d = opendir(path.buf);
427 strbuf_release(&path);
431 strbuf_init(&refname, dirnamelen + 257);
432 strbuf_add(&refname, dirname, dirnamelen);
434 while ((de = readdir(d)) != NULL) {
435 struct object_id oid;
439 if (de->d_name[0] == '.')
441 if (ends_with(de->d_name, ".lock"))
443 strbuf_addstr(&refname, de->d_name);
444 strbuf_addstr(&path, de->d_name);
445 if (stat(path.buf, &st) < 0) {
446 ; /* silently ignore */
447 } else if (S_ISDIR(st.st_mode)) {
448 strbuf_addch(&refname, '/');
449 add_entry_to_dir(dir,
450 create_dir_entry(dir->cache, refname.buf,
453 if (!refs_resolve_ref_unsafe(&refs->base,
458 flag |= REF_ISBROKEN;
459 } else if (is_null_oid(&oid)) {
461 * It is so astronomically unlikely
462 * that NULL_SHA1 is the SHA-1 of an
463 * actual object that we consider its
464 * appearance in a loose reference
465 * file to be repo corruption
466 * (probably due to a software bug).
468 flag |= REF_ISBROKEN;
471 if (check_refname_format(refname.buf,
472 REFNAME_ALLOW_ONELEVEL)) {
473 if (!refname_is_safe(refname.buf))
474 die("loose refname is dangerous: %s", refname.buf);
476 flag |= REF_BAD_NAME | REF_ISBROKEN;
478 add_entry_to_dir(dir,
479 create_ref_entry(refname.buf, &oid, flag, 0));
481 strbuf_setlen(&refname, dirnamelen);
482 strbuf_setlen(&path, path_baselen);
484 strbuf_release(&refname);
485 strbuf_release(&path);
489 * Manually add refs/bisect, which, being per-worktree, might
490 * not appear in the directory listing for refs/ in the main
493 if (!strcmp(dirname, "refs/")) {
494 int pos = search_ref_dir(dir, "refs/bisect/", 12);
497 struct ref_entry *child_entry = create_dir_entry(
498 dir->cache, "refs/bisect/", 12, 1);
499 add_entry_to_dir(dir, child_entry);
504 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
508 * Mark the top-level directory complete because we
509 * are about to read the only subdirectory that can
512 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
514 /* We're going to fill the top level ourselves: */
515 refs->loose->root->flag &= ~REF_INCOMPLETE;
518 * Add an incomplete entry for "refs/" (to be filled
521 add_entry_to_dir(get_ref_dir(refs->loose->root),
522 create_dir_entry(refs->loose, "refs/", 5, 1));
528 * Return the ref_entry for the given refname from the packed
529 * references. If it does not exist, return NULL.
531 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
534 return find_ref_entry(get_packed_refs(refs), refname);
538 * A loose ref file doesn't exist; check for a packed ref.
540 static int resolve_packed_ref(struct files_ref_store *refs,
542 unsigned char *sha1, unsigned int *flags)
544 struct ref_entry *entry;
547 * The loose reference file does not exist; check for a packed
550 entry = get_packed_ref(refs, refname);
552 hashcpy(sha1, entry->u.value.oid.hash);
553 *flags |= REF_ISPACKED;
556 /* refname is not a packed reference. */
560 static int files_read_raw_ref(struct ref_store *ref_store,
561 const char *refname, unsigned char *sha1,
562 struct strbuf *referent, unsigned int *type)
564 struct files_ref_store *refs =
565 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
566 struct strbuf sb_contents = STRBUF_INIT;
567 struct strbuf sb_path = STRBUF_INIT;
574 int remaining_retries = 3;
577 strbuf_reset(&sb_path);
579 files_ref_path(refs, &sb_path, refname);
585 * We might have to loop back here to avoid a race
586 * condition: first we lstat() the file, then we try
587 * to read it as a link or as a file. But if somebody
588 * changes the type of the file (file <-> directory
589 * <-> symlink) between the lstat() and reading, then
590 * we don't want to report that as an error but rather
591 * try again starting with the lstat().
593 * We'll keep a count of the retries, though, just to avoid
594 * any confusing situation sending us into an infinite loop.
597 if (remaining_retries-- <= 0)
600 if (lstat(path, &st) < 0) {
603 if (resolve_packed_ref(refs, refname, sha1, type)) {
611 /* Follow "normalized" - ie "refs/.." symlinks by hand */
612 if (S_ISLNK(st.st_mode)) {
613 strbuf_reset(&sb_contents);
614 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
615 if (errno == ENOENT || errno == EINVAL)
616 /* inconsistent with lstat; retry */
621 if (starts_with(sb_contents.buf, "refs/") &&
622 !check_refname_format(sb_contents.buf, 0)) {
623 strbuf_swap(&sb_contents, referent);
624 *type |= REF_ISSYMREF;
629 * It doesn't look like a refname; fall through to just
630 * treating it like a non-symlink, and reading whatever it
635 /* Is it a directory? */
636 if (S_ISDIR(st.st_mode)) {
638 * Even though there is a directory where the loose
639 * ref is supposed to be, there could still be a
642 if (resolve_packed_ref(refs, refname, sha1, type)) {
651 * Anything else, just open it and try to use it as
654 fd = open(path, O_RDONLY);
656 if (errno == ENOENT && !S_ISLNK(st.st_mode))
657 /* inconsistent with lstat; retry */
662 strbuf_reset(&sb_contents);
663 if (strbuf_read(&sb_contents, fd, 256) < 0) {
664 int save_errno = errno;
670 strbuf_rtrim(&sb_contents);
671 buf = sb_contents.buf;
672 if (starts_with(buf, "ref:")) {
674 while (isspace(*buf))
677 strbuf_reset(referent);
678 strbuf_addstr(referent, buf);
679 *type |= REF_ISSYMREF;
685 * Please note that FETCH_HEAD has additional
686 * data after the sha.
688 if (get_sha1_hex(buf, sha1) ||
689 (buf[40] != '\0' && !isspace(buf[40]))) {
690 *type |= REF_ISBROKEN;
699 strbuf_release(&sb_path);
700 strbuf_release(&sb_contents);
705 static void unlock_ref(struct ref_lock *lock)
707 /* Do not free lock->lk -- atexit() still looks at them */
709 rollback_lock_file(lock->lk);
710 free(lock->ref_name);
715 * Lock refname, without following symrefs, and set *lock_p to point
716 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
717 * and type similarly to read_raw_ref().
719 * The caller must verify that refname is a "safe" reference name (in
720 * the sense of refname_is_safe()) before calling this function.
722 * If the reference doesn't already exist, verify that refname doesn't
723 * have a D/F conflict with any existing references. extras and skip
724 * are passed to refs_verify_refname_available() for this check.
726 * If mustexist is not set and the reference is not found or is
727 * broken, lock the reference anyway but clear sha1.
729 * Return 0 on success. On failure, write an error message to err and
730 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
732 * Implementation note: This function is basically
737 * but it includes a lot more code to
738 * - Deal with possible races with other processes
739 * - Avoid calling refs_verify_refname_available() when it can be
740 * avoided, namely if we were successfully able to read the ref
741 * - Generate informative error messages in the case of failure
743 static int lock_raw_ref(struct files_ref_store *refs,
744 const char *refname, int mustexist,
745 const struct string_list *extras,
746 const struct string_list *skip,
747 struct ref_lock **lock_p,
748 struct strbuf *referent,
752 struct ref_lock *lock;
753 struct strbuf ref_file = STRBUF_INIT;
754 int attempts_remaining = 3;
755 int ret = TRANSACTION_GENERIC_ERROR;
758 files_assert_main_repository(refs, "lock_raw_ref");
762 /* First lock the file so it can't change out from under us. */
764 *lock_p = lock = xcalloc(1, sizeof(*lock));
766 lock->ref_name = xstrdup(refname);
767 files_ref_path(refs, &ref_file, refname);
770 switch (safe_create_leading_directories(ref_file.buf)) {
775 * Suppose refname is "refs/foo/bar". We just failed
776 * to create the containing directory, "refs/foo",
777 * because there was a non-directory in the way. This
778 * indicates a D/F conflict, probably because of
779 * another reference such as "refs/foo". There is no
780 * reason to expect this error to be transitory.
782 if (refs_verify_refname_available(&refs->base, refname,
783 extras, skip, err)) {
786 * To the user the relevant error is
787 * that the "mustexist" reference is
791 strbuf_addf(err, "unable to resolve reference '%s'",
795 * The error message set by
796 * refs_verify_refname_available() is
799 ret = TRANSACTION_NAME_CONFLICT;
803 * The file that is in the way isn't a loose
804 * reference. Report it as a low-level
807 strbuf_addf(err, "unable to create lock file %s.lock; "
808 "non-directory in the way",
813 /* Maybe another process was tidying up. Try again. */
814 if (--attempts_remaining > 0)
818 strbuf_addf(err, "unable to create directory for %s",
824 lock->lk = xcalloc(1, sizeof(struct lock_file));
826 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
827 if (errno == ENOENT && --attempts_remaining > 0) {
829 * Maybe somebody just deleted one of the
830 * directories leading to ref_file. Try
835 unable_to_lock_message(ref_file.buf, errno, err);
841 * Now we hold the lock and can read the reference without
842 * fear that its value will change.
845 if (files_read_raw_ref(&refs->base, refname,
846 lock->old_oid.hash, referent, type)) {
847 if (errno == ENOENT) {
849 /* Garden variety missing reference. */
850 strbuf_addf(err, "unable to resolve reference '%s'",
855 * Reference is missing, but that's OK. We
856 * know that there is not a conflict with
857 * another loose reference because
858 * (supposing that we are trying to lock
859 * reference "refs/foo/bar"):
861 * - We were successfully able to create
862 * the lockfile refs/foo/bar.lock, so we
863 * know there cannot be a loose reference
866 * - We got ENOENT and not EISDIR, so we
867 * know that there cannot be a loose
868 * reference named "refs/foo/bar/baz".
871 } else if (errno == EISDIR) {
873 * There is a directory in the way. It might have
874 * contained references that have been deleted. If
875 * we don't require that the reference already
876 * exists, try to remove the directory so that it
877 * doesn't cause trouble when we want to rename the
878 * lockfile into place later.
881 /* Garden variety missing reference. */
882 strbuf_addf(err, "unable to resolve reference '%s'",
885 } else if (remove_dir_recursively(&ref_file,
886 REMOVE_DIR_EMPTY_ONLY)) {
887 if (refs_verify_refname_available(
888 &refs->base, refname,
889 extras, skip, err)) {
891 * The error message set by
892 * verify_refname_available() is OK.
894 ret = TRANSACTION_NAME_CONFLICT;
898 * We can't delete the directory,
899 * but we also don't know of any
900 * references that it should
903 strbuf_addf(err, "there is a non-empty directory '%s' "
904 "blocking reference '%s'",
905 ref_file.buf, refname);
909 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
910 strbuf_addf(err, "unable to resolve reference '%s': "
911 "reference broken", refname);
914 strbuf_addf(err, "unable to resolve reference '%s': %s",
915 refname, strerror(errno));
920 * If the ref did not exist and we are creating it,
921 * make sure there is no existing ref that conflicts
924 if (refs_verify_refname_available(
925 &refs->base, refname,
938 strbuf_release(&ref_file);
942 static int files_peel_ref(struct ref_store *ref_store,
943 const char *refname, unsigned char *sha1)
945 struct files_ref_store *refs =
946 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
949 unsigned char base[20];
951 if (current_ref_iter && current_ref_iter->refname == refname) {
952 struct object_id peeled;
954 if (ref_iterator_peel(current_ref_iter, &peeled))
956 hashcpy(sha1, peeled.hash);
960 if (refs_read_ref_full(ref_store, refname,
961 RESOLVE_REF_READING, base, &flag))
965 * If the reference is packed, read its ref_entry from the
966 * cache in the hope that we already know its peeled value.
967 * We only try this optimization on packed references because
968 * (a) forcing the filling of the loose reference cache could
969 * be expensive and (b) loose references anyway usually do not
970 * have REF_KNOWS_PEELED.
972 if (flag & REF_ISPACKED) {
973 struct ref_entry *r = get_packed_ref(refs, refname);
975 if (peel_entry(r, 0))
977 hashcpy(sha1, r->u.value.peeled.hash);
982 return peel_object(base, sha1);
985 struct files_ref_iterator {
986 struct ref_iterator base;
988 struct packed_ref_cache *packed_ref_cache;
989 struct ref_iterator *iter0;
993 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
995 struct files_ref_iterator *iter =
996 (struct files_ref_iterator *)ref_iterator;
999 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1000 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1001 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1004 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1005 !ref_resolves_to_object(iter->iter0->refname,
1007 iter->iter0->flags))
1010 iter->base.refname = iter->iter0->refname;
1011 iter->base.oid = iter->iter0->oid;
1012 iter->base.flags = iter->iter0->flags;
1017 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1023 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1024 struct object_id *peeled)
1026 struct files_ref_iterator *iter =
1027 (struct files_ref_iterator *)ref_iterator;
1029 return ref_iterator_peel(iter->iter0, peeled);
1032 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1034 struct files_ref_iterator *iter =
1035 (struct files_ref_iterator *)ref_iterator;
1039 ok = ref_iterator_abort(iter->iter0);
1041 release_packed_ref_cache(iter->packed_ref_cache);
1042 base_ref_iterator_free(ref_iterator);
1046 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1047 files_ref_iterator_advance,
1048 files_ref_iterator_peel,
1049 files_ref_iterator_abort
1052 static struct ref_iterator *files_ref_iterator_begin(
1053 struct ref_store *ref_store,
1054 const char *prefix, unsigned int flags)
1056 struct files_ref_store *refs;
1057 struct ref_iterator *loose_iter, *packed_iter;
1058 struct files_ref_iterator *iter;
1059 struct ref_iterator *ref_iterator;
1061 if (ref_paranoia < 0)
1062 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1064 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1066 refs = files_downcast(ref_store,
1067 REF_STORE_READ | (ref_paranoia ? 0 : REF_STORE_ODB),
1068 "ref_iterator_begin");
1070 iter = xcalloc(1, sizeof(*iter));
1071 ref_iterator = &iter->base;
1072 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1075 * We must make sure that all loose refs are read before
1076 * accessing the packed-refs file; this avoids a race
1077 * condition if loose refs are migrated to the packed-refs
1078 * file by a simultaneous process, but our in-memory view is
1079 * from before the migration. We ensure this as follows:
1080 * First, we call start the loose refs iteration with its
1081 * `prime_ref` argument set to true. This causes the loose
1082 * references in the subtree to be pre-read into the cache.
1083 * (If they've already been read, that's OK; we only need to
1084 * guarantee that they're read before the packed refs, not
1085 * *how much* before.) After that, we call
1086 * get_packed_ref_cache(), which internally checks whether the
1087 * packed-ref cache is up to date with what is on disk, and
1088 * re-reads it if not.
1091 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1094 iter->packed_ref_cache = get_packed_ref_cache(refs);
1095 acquire_packed_ref_cache(iter->packed_ref_cache);
1096 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1099 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1100 iter->flags = flags;
1102 return ref_iterator;
1106 * Verify that the reference locked by lock has the value old_sha1.
1107 * Fail if the reference doesn't exist and mustexist is set. Return 0
1108 * on success. On error, write an error message to err, set errno, and
1109 * return a negative value.
1111 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1112 const unsigned char *old_sha1, int mustexist,
1117 if (refs_read_ref_full(ref_store, lock->ref_name,
1118 mustexist ? RESOLVE_REF_READING : 0,
1119 lock->old_oid.hash, NULL)) {
1121 int save_errno = errno;
1122 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1126 oidclr(&lock->old_oid);
1130 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1131 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1133 oid_to_hex(&lock->old_oid),
1134 sha1_to_hex(old_sha1));
1141 static int remove_empty_directories(struct strbuf *path)
1144 * we want to create a file but there is a directory there;
1145 * if that is an empty directory (or a directory that contains
1146 * only empty directories), remove them.
1148 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1151 static int create_reflock(const char *path, void *cb)
1153 struct lock_file *lk = cb;
1155 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1159 * Locks a ref returning the lock on success and NULL on failure.
1160 * On failure errno is set to something meaningful.
1162 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1163 const char *refname,
1164 const unsigned char *old_sha1,
1165 const struct string_list *extras,
1166 const struct string_list *skip,
1167 unsigned int flags, int *type,
1170 struct strbuf ref_file = STRBUF_INIT;
1171 struct ref_lock *lock;
1173 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1174 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1177 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1180 lock = xcalloc(1, sizeof(struct ref_lock));
1183 resolve_flags |= RESOLVE_REF_READING;
1184 if (flags & REF_DELETING)
1185 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1187 files_ref_path(refs, &ref_file, refname);
1188 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1189 refname, resolve_flags,
1190 lock->old_oid.hash, type);
1191 if (!resolved && errno == EISDIR) {
1193 * we are trying to lock foo but we used to
1194 * have foo/bar which now does not exist;
1195 * it is normal for the empty directory 'foo'
1198 if (remove_empty_directories(&ref_file)) {
1200 if (!refs_verify_refname_available(
1202 refname, extras, skip, err))
1203 strbuf_addf(err, "there are still refs under '%s'",
1207 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1208 refname, resolve_flags,
1209 lock->old_oid.hash, type);
1213 if (last_errno != ENOTDIR ||
1214 !refs_verify_refname_available(&refs->base, refname,
1216 strbuf_addf(err, "unable to resolve reference '%s': %s",
1217 refname, strerror(last_errno));
1223 * If the ref did not exist and we are creating it, make sure
1224 * there is no existing packed ref whose name begins with our
1225 * refname, nor a packed ref whose name is a proper prefix of
1228 if (is_null_oid(&lock->old_oid) &&
1229 refs_verify_refname_available(&refs->base, refname,
1230 extras, skip, err)) {
1231 last_errno = ENOTDIR;
1235 lock->lk = xcalloc(1, sizeof(struct lock_file));
1237 lock->ref_name = xstrdup(refname);
1239 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1241 unable_to_lock_message(ref_file.buf, errno, err);
1245 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1256 strbuf_release(&ref_file);
1262 * Write an entry to the packed-refs file for the specified refname.
1263 * If peeled is non-NULL, write it as the entry's peeled value.
1265 static void write_packed_entry(FILE *fh, const char *refname,
1266 const unsigned char *sha1,
1267 const unsigned char *peeled)
1269 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1271 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1275 * Lock the packed-refs file for writing. Flags is passed to
1276 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1277 * errno appropriately and return a nonzero value.
1279 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1281 static int timeout_configured = 0;
1282 static int timeout_value = 1000;
1283 struct packed_ref_cache *packed_ref_cache;
1285 files_assert_main_repository(refs, "lock_packed_refs");
1287 if (!timeout_configured) {
1288 git_config_get_int("core.packedrefstimeout", &timeout_value);
1289 timeout_configured = 1;
1292 if (hold_lock_file_for_update_timeout(
1293 &packlock, files_packed_refs_path(refs),
1294 flags, timeout_value) < 0)
1297 * Get the current packed-refs while holding the lock. If the
1298 * packed-refs file has been modified since we last read it,
1299 * this will automatically invalidate the cache and re-read
1300 * the packed-refs file.
1302 packed_ref_cache = get_packed_ref_cache(refs);
1303 packed_ref_cache->lock = &packlock;
1304 /* Increment the reference count to prevent it from being freed: */
1305 acquire_packed_ref_cache(packed_ref_cache);
1310 * Write the current version of the packed refs cache from memory to
1311 * disk. The packed-refs file must already be locked for writing (see
1312 * lock_packed_refs()). Return zero on success. On errors, set errno
1313 * and return a nonzero value
1315 static int commit_packed_refs(struct files_ref_store *refs)
1317 struct packed_ref_cache *packed_ref_cache =
1318 get_packed_ref_cache(refs);
1322 struct ref_iterator *iter;
1324 files_assert_main_repository(refs, "commit_packed_refs");
1326 if (!packed_ref_cache->lock)
1327 die("internal error: packed-refs not locked");
1329 out = fdopen_lock_file(packed_ref_cache->lock, "w");
1331 die_errno("unable to fdopen packed-refs descriptor");
1333 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1335 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1336 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1337 struct object_id peeled;
1338 int peel_error = ref_iterator_peel(iter, &peeled);
1340 write_packed_entry(out, iter->refname, iter->oid->hash,
1341 peel_error ? NULL : peeled.hash);
1344 if (ok != ITER_DONE)
1345 die("error while iterating over references");
1347 if (commit_lock_file(packed_ref_cache->lock)) {
1351 packed_ref_cache->lock = NULL;
1352 release_packed_ref_cache(packed_ref_cache);
1358 * Rollback the lockfile for the packed-refs file, and discard the
1359 * in-memory packed reference cache. (The packed-refs file will be
1360 * read anew if it is needed again after this function is called.)
1362 static void rollback_packed_refs(struct files_ref_store *refs)
1364 struct packed_ref_cache *packed_ref_cache =
1365 get_packed_ref_cache(refs);
1367 files_assert_main_repository(refs, "rollback_packed_refs");
1369 if (!packed_ref_cache->lock)
1370 die("internal error: packed-refs not locked");
1371 rollback_lock_file(packed_ref_cache->lock);
1372 packed_ref_cache->lock = NULL;
1373 release_packed_ref_cache(packed_ref_cache);
1374 clear_packed_ref_cache(refs);
1377 struct ref_to_prune {
1378 struct ref_to_prune *next;
1379 unsigned char sha1[20];
1380 char name[FLEX_ARRAY];
1384 REMOVE_EMPTY_PARENTS_REF = 0x01,
1385 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1389 * Remove empty parent directories associated with the specified
1390 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1391 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1392 * REMOVE_EMPTY_PARENTS_REFLOG.
1394 static void try_remove_empty_parents(struct files_ref_store *refs,
1395 const char *refname,
1398 struct strbuf buf = STRBUF_INIT;
1399 struct strbuf sb = STRBUF_INIT;
1403 strbuf_addstr(&buf, refname);
1405 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1406 while (*p && *p != '/')
1408 /* tolerate duplicate slashes; see check_refname_format() */
1412 q = buf.buf + buf.len;
1413 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1414 while (q > p && *q != '/')
1416 while (q > p && *(q-1) == '/')
1420 strbuf_setlen(&buf, q - buf.buf);
1423 files_ref_path(refs, &sb, buf.buf);
1424 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1425 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1428 files_reflog_path(refs, &sb, buf.buf);
1429 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1430 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1432 strbuf_release(&buf);
1433 strbuf_release(&sb);
1436 /* make sure nobody touched the ref, and unlink */
1437 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1439 struct ref_transaction *transaction;
1440 struct strbuf err = STRBUF_INIT;
1442 if (check_refname_format(r->name, 0))
1445 transaction = ref_store_transaction_begin(&refs->base, &err);
1447 ref_transaction_delete(transaction, r->name, r->sha1,
1448 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1449 ref_transaction_commit(transaction, &err)) {
1450 ref_transaction_free(transaction);
1451 error("%s", err.buf);
1452 strbuf_release(&err);
1455 ref_transaction_free(transaction);
1456 strbuf_release(&err);
1459 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1467 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1469 struct files_ref_store *refs =
1470 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1472 struct ref_iterator *iter;
1473 struct ref_dir *packed_refs;
1475 struct ref_to_prune *refs_to_prune = NULL;
1477 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1478 packed_refs = get_packed_refs(refs);
1480 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1481 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1483 * If the loose reference can be packed, add an entry
1484 * in the packed ref cache. If the reference should be
1485 * pruned, also add it to refs_to_prune.
1487 struct ref_entry *packed_entry;
1488 int is_tag_ref = starts_with(iter->refname, "refs/tags/");
1490 /* Do not pack per-worktree refs: */
1491 if (ref_type(iter->refname) != REF_TYPE_NORMAL)
1494 /* ALWAYS pack tags */
1495 if (!(flags & PACK_REFS_ALL) && !is_tag_ref)
1498 /* Do not pack symbolic or broken refs: */
1499 if (iter->flags & REF_ISSYMREF)
1502 if (!ref_resolves_to_object(iter->refname, iter->oid, iter->flags))
1506 * Create an entry in the packed-refs cache equivalent
1507 * to the one from the loose ref cache, except that
1508 * we don't copy the peeled status, because we want it
1511 packed_entry = find_ref_entry(packed_refs, iter->refname);
1513 /* Overwrite existing packed entry with info from loose entry */
1514 packed_entry->flag = REF_ISPACKED;
1515 oidcpy(&packed_entry->u.value.oid, iter->oid);
1517 packed_entry = create_ref_entry(iter->refname, iter->oid,
1519 add_ref_entry(packed_refs, packed_entry);
1521 oidclr(&packed_entry->u.value.peeled);
1523 /* Schedule the loose reference for pruning if requested. */
1524 if ((flags & PACK_REFS_PRUNE)) {
1525 struct ref_to_prune *n;
1526 FLEX_ALLOC_STR(n, name, iter->refname);
1527 hashcpy(n->sha1, iter->oid->hash);
1528 n->next = refs_to_prune;
1532 if (ok != ITER_DONE)
1533 die("error while iterating over references");
1535 if (commit_packed_refs(refs))
1536 die_errno("unable to overwrite old ref-pack file");
1538 prune_refs(refs, refs_to_prune);
1543 * Rewrite the packed-refs file, omitting any refs listed in
1544 * 'refnames'. On error, leave packed-refs unchanged, write an error
1545 * message to 'err', and return a nonzero value.
1547 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1549 static int repack_without_refs(struct files_ref_store *refs,
1550 struct string_list *refnames, struct strbuf *err)
1552 struct ref_dir *packed;
1553 struct string_list_item *refname;
1554 int ret, needs_repacking = 0, removed = 0;
1556 files_assert_main_repository(refs, "repack_without_refs");
1559 /* Look for a packed ref */
1560 for_each_string_list_item(refname, refnames) {
1561 if (get_packed_ref(refs, refname->string)) {
1562 needs_repacking = 1;
1567 /* Avoid locking if we have nothing to do */
1568 if (!needs_repacking)
1569 return 0; /* no refname exists in packed refs */
1571 if (lock_packed_refs(refs, 0)) {
1572 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1575 packed = get_packed_refs(refs);
1577 /* Remove refnames from the cache */
1578 for_each_string_list_item(refname, refnames)
1579 if (remove_entry_from_dir(packed, refname->string) != -1)
1583 * All packed entries disappeared while we were
1584 * acquiring the lock.
1586 rollback_packed_refs(refs);
1590 /* Write what remains */
1591 ret = commit_packed_refs(refs);
1593 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1598 static int files_delete_refs(struct ref_store *ref_store,
1599 struct string_list *refnames, unsigned int flags)
1601 struct files_ref_store *refs =
1602 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1603 struct strbuf err = STRBUF_INIT;
1609 result = repack_without_refs(refs, refnames, &err);
1612 * If we failed to rewrite the packed-refs file, then
1613 * it is unsafe to try to remove loose refs, because
1614 * doing so might expose an obsolete packed value for
1615 * a reference that might even point at an object that
1616 * has been garbage collected.
1618 if (refnames->nr == 1)
1619 error(_("could not delete reference %s: %s"),
1620 refnames->items[0].string, err.buf);
1622 error(_("could not delete references: %s"), err.buf);
1627 for (i = 0; i < refnames->nr; i++) {
1628 const char *refname = refnames->items[i].string;
1630 if (refs_delete_ref(&refs->base, NULL, refname, NULL, flags))
1631 result |= error(_("could not remove reference %s"), refname);
1635 strbuf_release(&err);
1640 * People using contrib's git-new-workdir have .git/logs/refs ->
1641 * /some/other/path/.git/logs/refs, and that may live on another device.
1643 * IOW, to avoid cross device rename errors, the temporary renamed log must
1644 * live into logs/refs.
1646 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1649 const char *tmp_renamed_log;
1653 static int rename_tmp_log_callback(const char *path, void *cb_data)
1655 struct rename_cb *cb = cb_data;
1657 if (rename(cb->tmp_renamed_log, path)) {
1659 * rename(a, b) when b is an existing directory ought
1660 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1661 * Sheesh. Record the true errno for error reporting,
1662 * but report EISDIR to raceproof_create_file() so
1663 * that it knows to retry.
1665 cb->true_errno = errno;
1666 if (errno == ENOTDIR)
1674 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1676 struct strbuf path = STRBUF_INIT;
1677 struct strbuf tmp = STRBUF_INIT;
1678 struct rename_cb cb;
1681 files_reflog_path(refs, &path, newrefname);
1682 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1683 cb.tmp_renamed_log = tmp.buf;
1684 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1686 if (errno == EISDIR)
1687 error("directory not empty: %s", path.buf);
1689 error("unable to move logfile %s to %s: %s",
1691 strerror(cb.true_errno));
1694 strbuf_release(&path);
1695 strbuf_release(&tmp);
1699 static int write_ref_to_lockfile(struct ref_lock *lock,
1700 const struct object_id *oid, struct strbuf *err);
1701 static int commit_ref_update(struct files_ref_store *refs,
1702 struct ref_lock *lock,
1703 const struct object_id *oid, const char *logmsg,
1704 struct strbuf *err);
1706 static int files_rename_ref(struct ref_store *ref_store,
1707 const char *oldrefname, const char *newrefname,
1710 struct files_ref_store *refs =
1711 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1712 struct object_id oid, orig_oid;
1713 int flag = 0, logmoved = 0;
1714 struct ref_lock *lock;
1715 struct stat loginfo;
1716 struct strbuf sb_oldref = STRBUF_INIT;
1717 struct strbuf sb_newref = STRBUF_INIT;
1718 struct strbuf tmp_renamed_log = STRBUF_INIT;
1720 struct strbuf err = STRBUF_INIT;
1722 files_reflog_path(refs, &sb_oldref, oldrefname);
1723 files_reflog_path(refs, &sb_newref, newrefname);
1724 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1726 log = !lstat(sb_oldref.buf, &loginfo);
1727 if (log && S_ISLNK(loginfo.st_mode)) {
1728 ret = error("reflog for %s is a symlink", oldrefname);
1732 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1733 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1734 orig_oid.hash, &flag)) {
1735 ret = error("refname %s not found", oldrefname);
1739 if (flag & REF_ISSYMREF) {
1740 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1744 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1749 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1750 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1751 oldrefname, strerror(errno));
1755 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1756 orig_oid.hash, REF_NODEREF)) {
1757 error("unable to delete old %s", oldrefname);
1762 * Since we are doing a shallow lookup, oid is not the
1763 * correct value to pass to delete_ref as old_oid. But that
1764 * doesn't matter, because an old_oid check wouldn't add to
1765 * the safety anyway; we want to delete the reference whatever
1766 * its current value.
1768 if (!refs_read_ref_full(&refs->base, newrefname,
1769 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1771 refs_delete_ref(&refs->base, NULL, newrefname,
1772 NULL, REF_NODEREF)) {
1773 if (errno == EISDIR) {
1774 struct strbuf path = STRBUF_INIT;
1777 files_ref_path(refs, &path, newrefname);
1778 result = remove_empty_directories(&path);
1779 strbuf_release(&path);
1782 error("Directory not empty: %s", newrefname);
1786 error("unable to delete existing %s", newrefname);
1791 if (log && rename_tmp_log(refs, newrefname))
1796 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1797 REF_NODEREF, NULL, &err);
1799 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1800 strbuf_release(&err);
1803 oidcpy(&lock->old_oid, &orig_oid);
1805 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1806 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1807 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1808 strbuf_release(&err);
1816 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1817 REF_NODEREF, NULL, &err);
1819 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1820 strbuf_release(&err);
1824 flag = log_all_ref_updates;
1825 log_all_ref_updates = LOG_REFS_NONE;
1826 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1827 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1828 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1829 strbuf_release(&err);
1831 log_all_ref_updates = flag;
1834 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1835 error("unable to restore logfile %s from %s: %s",
1836 oldrefname, newrefname, strerror(errno));
1837 if (!logmoved && log &&
1838 rename(tmp_renamed_log.buf, sb_oldref.buf))
1839 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1840 oldrefname, strerror(errno));
1843 strbuf_release(&sb_newref);
1844 strbuf_release(&sb_oldref);
1845 strbuf_release(&tmp_renamed_log);
1850 static int close_ref(struct ref_lock *lock)
1852 if (close_lock_file(lock->lk))
1857 static int commit_ref(struct ref_lock *lock)
1859 char *path = get_locked_file_path(lock->lk);
1862 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1864 * There is a directory at the path we want to rename
1865 * the lockfile to. Hopefully it is empty; try to
1868 size_t len = strlen(path);
1869 struct strbuf sb_path = STRBUF_INIT;
1871 strbuf_attach(&sb_path, path, len, len);
1874 * If this fails, commit_lock_file() will also fail
1875 * and will report the problem.
1877 remove_empty_directories(&sb_path);
1878 strbuf_release(&sb_path);
1883 if (commit_lock_file(lock->lk))
1888 static int open_or_create_logfile(const char *path, void *cb)
1892 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1893 return (*fd < 0) ? -1 : 0;
1897 * Create a reflog for a ref. If force_create = 0, only create the
1898 * reflog for certain refs (those for which should_autocreate_reflog
1899 * returns non-zero). Otherwise, create it regardless of the reference
1900 * name. If the logfile already existed or was created, return 0 and
1901 * set *logfd to the file descriptor opened for appending to the file.
1902 * If no logfile exists and we decided not to create one, return 0 and
1903 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1906 static int log_ref_setup(struct files_ref_store *refs,
1907 const char *refname, int force_create,
1908 int *logfd, struct strbuf *err)
1910 struct strbuf logfile_sb = STRBUF_INIT;
1913 files_reflog_path(refs, &logfile_sb, refname);
1914 logfile = strbuf_detach(&logfile_sb, NULL);
1916 if (force_create || should_autocreate_reflog(refname)) {
1917 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1918 if (errno == ENOENT)
1919 strbuf_addf(err, "unable to create directory for '%s': "
1920 "%s", logfile, strerror(errno));
1921 else if (errno == EISDIR)
1922 strbuf_addf(err, "there are still logs under '%s'",
1925 strbuf_addf(err, "unable to append to '%s': %s",
1926 logfile, strerror(errno));
1931 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1933 if (errno == ENOENT || errno == EISDIR) {
1935 * The logfile doesn't already exist,
1936 * but that is not an error; it only
1937 * means that we won't write log
1942 strbuf_addf(err, "unable to append to '%s': %s",
1943 logfile, strerror(errno));
1950 adjust_shared_perm(logfile);
1960 static int files_create_reflog(struct ref_store *ref_store,
1961 const char *refname, int force_create,
1964 struct files_ref_store *refs =
1965 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1968 if (log_ref_setup(refs, refname, force_create, &fd, err))
1977 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1978 const struct object_id *new_oid,
1979 const char *committer, const char *msg)
1981 int msglen, written;
1982 unsigned maxlen, len;
1985 msglen = msg ? strlen(msg) : 0;
1986 maxlen = strlen(committer) + msglen + 100;
1987 logrec = xmalloc(maxlen);
1988 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1989 oid_to_hex(old_oid),
1990 oid_to_hex(new_oid),
1993 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1995 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2003 static int files_log_ref_write(struct files_ref_store *refs,
2004 const char *refname, const struct object_id *old_oid,
2005 const struct object_id *new_oid, const char *msg,
2006 int flags, struct strbuf *err)
2010 if (log_all_ref_updates == LOG_REFS_UNSET)
2011 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2013 result = log_ref_setup(refs, refname,
2014 flags & REF_FORCE_CREATE_REFLOG,
2022 result = log_ref_write_fd(logfd, old_oid, new_oid,
2023 git_committer_info(0), msg);
2025 struct strbuf sb = STRBUF_INIT;
2026 int save_errno = errno;
2028 files_reflog_path(refs, &sb, refname);
2029 strbuf_addf(err, "unable to append to '%s': %s",
2030 sb.buf, strerror(save_errno));
2031 strbuf_release(&sb);
2036 struct strbuf sb = STRBUF_INIT;
2037 int save_errno = errno;
2039 files_reflog_path(refs, &sb, refname);
2040 strbuf_addf(err, "unable to append to '%s': %s",
2041 sb.buf, strerror(save_errno));
2042 strbuf_release(&sb);
2049 * Write sha1 into the open lockfile, then close the lockfile. On
2050 * errors, rollback the lockfile, fill in *err and
2053 static int write_ref_to_lockfile(struct ref_lock *lock,
2054 const struct object_id *oid, struct strbuf *err)
2056 static char term = '\n';
2060 o = parse_object(oid);
2063 "trying to write ref '%s' with nonexistent object %s",
2064 lock->ref_name, oid_to_hex(oid));
2068 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2070 "trying to write non-commit object %s to branch '%s'",
2071 oid_to_hex(oid), lock->ref_name);
2075 fd = get_lock_file_fd(lock->lk);
2076 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2077 write_in_full(fd, &term, 1) != 1 ||
2078 close_ref(lock) < 0) {
2080 "couldn't write '%s'", get_lock_file_path(lock->lk));
2088 * Commit a change to a loose reference that has already been written
2089 * to the loose reference lockfile. Also update the reflogs if
2090 * necessary, using the specified lockmsg (which can be NULL).
2092 static int commit_ref_update(struct files_ref_store *refs,
2093 struct ref_lock *lock,
2094 const struct object_id *oid, const char *logmsg,
2097 files_assert_main_repository(refs, "commit_ref_update");
2099 clear_loose_ref_cache(refs);
2100 if (files_log_ref_write(refs, lock->ref_name,
2101 &lock->old_oid, oid,
2103 char *old_msg = strbuf_detach(err, NULL);
2104 strbuf_addf(err, "cannot update the ref '%s': %s",
2105 lock->ref_name, old_msg);
2111 if (strcmp(lock->ref_name, "HEAD") != 0) {
2113 * Special hack: If a branch is updated directly and HEAD
2114 * points to it (may happen on the remote side of a push
2115 * for example) then logically the HEAD reflog should be
2117 * A generic solution implies reverse symref information,
2118 * but finding all symrefs pointing to the given branch
2119 * would be rather costly for this rare event (the direct
2120 * update of a branch) to be worth it. So let's cheat and
2121 * check with HEAD only which should cover 99% of all usage
2122 * scenarios (even 100% of the default ones).
2124 struct object_id head_oid;
2126 const char *head_ref;
2128 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2129 RESOLVE_REF_READING,
2130 head_oid.hash, &head_flag);
2131 if (head_ref && (head_flag & REF_ISSYMREF) &&
2132 !strcmp(head_ref, lock->ref_name)) {
2133 struct strbuf log_err = STRBUF_INIT;
2134 if (files_log_ref_write(refs, "HEAD",
2135 &lock->old_oid, oid,
2136 logmsg, 0, &log_err)) {
2137 error("%s", log_err.buf);
2138 strbuf_release(&log_err);
2143 if (commit_ref(lock)) {
2144 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2153 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2156 #ifndef NO_SYMLINK_HEAD
2157 char *ref_path = get_locked_file_path(lock->lk);
2159 ret = symlink(target, ref_path);
2163 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2168 static void update_symref_reflog(struct files_ref_store *refs,
2169 struct ref_lock *lock, const char *refname,
2170 const char *target, const char *logmsg)
2172 struct strbuf err = STRBUF_INIT;
2173 struct object_id new_oid;
2175 !refs_read_ref_full(&refs->base, target,
2176 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2177 files_log_ref_write(refs, refname, &lock->old_oid,
2178 &new_oid, logmsg, 0, &err)) {
2179 error("%s", err.buf);
2180 strbuf_release(&err);
2184 static int create_symref_locked(struct files_ref_store *refs,
2185 struct ref_lock *lock, const char *refname,
2186 const char *target, const char *logmsg)
2188 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2189 update_symref_reflog(refs, lock, refname, target, logmsg);
2193 if (!fdopen_lock_file(lock->lk, "w"))
2194 return error("unable to fdopen %s: %s",
2195 lock->lk->tempfile.filename.buf, strerror(errno));
2197 update_symref_reflog(refs, lock, refname, target, logmsg);
2199 /* no error check; commit_ref will check ferror */
2200 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2201 if (commit_ref(lock) < 0)
2202 return error("unable to write symref for %s: %s", refname,
2207 static int files_create_symref(struct ref_store *ref_store,
2208 const char *refname, const char *target,
2211 struct files_ref_store *refs =
2212 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2213 struct strbuf err = STRBUF_INIT;
2214 struct ref_lock *lock;
2217 lock = lock_ref_sha1_basic(refs, refname, NULL,
2218 NULL, NULL, REF_NODEREF, NULL,
2221 error("%s", err.buf);
2222 strbuf_release(&err);
2226 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2231 static int files_reflog_exists(struct ref_store *ref_store,
2232 const char *refname)
2234 struct files_ref_store *refs =
2235 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2236 struct strbuf sb = STRBUF_INIT;
2240 files_reflog_path(refs, &sb, refname);
2241 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2242 strbuf_release(&sb);
2246 static int files_delete_reflog(struct ref_store *ref_store,
2247 const char *refname)
2249 struct files_ref_store *refs =
2250 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2251 struct strbuf sb = STRBUF_INIT;
2254 files_reflog_path(refs, &sb, refname);
2255 ret = remove_path(sb.buf);
2256 strbuf_release(&sb);
2260 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2262 struct object_id ooid, noid;
2263 char *email_end, *message;
2264 timestamp_t timestamp;
2266 const char *p = sb->buf;
2268 /* old SP new SP name <email> SP time TAB msg LF */
2269 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2270 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2271 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2272 !(email_end = strchr(p, '>')) ||
2273 email_end[1] != ' ' ||
2274 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2275 !message || message[0] != ' ' ||
2276 (message[1] != '+' && message[1] != '-') ||
2277 !isdigit(message[2]) || !isdigit(message[3]) ||
2278 !isdigit(message[4]) || !isdigit(message[5]))
2279 return 0; /* corrupt? */
2280 email_end[1] = '\0';
2281 tz = strtol(message + 1, NULL, 10);
2282 if (message[6] != '\t')
2286 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2289 static char *find_beginning_of_line(char *bob, char *scan)
2291 while (bob < scan && *(--scan) != '\n')
2292 ; /* keep scanning backwards */
2294 * Return either beginning of the buffer, or LF at the end of
2295 * the previous line.
2300 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2301 const char *refname,
2302 each_reflog_ent_fn fn,
2305 struct files_ref_store *refs =
2306 files_downcast(ref_store, REF_STORE_READ,
2307 "for_each_reflog_ent_reverse");
2308 struct strbuf sb = STRBUF_INIT;
2311 int ret = 0, at_tail = 1;
2313 files_reflog_path(refs, &sb, refname);
2314 logfp = fopen(sb.buf, "r");
2315 strbuf_release(&sb);
2319 /* Jump to the end */
2320 if (fseek(logfp, 0, SEEK_END) < 0)
2321 ret = error("cannot seek back reflog for %s: %s",
2322 refname, strerror(errno));
2324 while (!ret && 0 < pos) {
2330 /* Fill next block from the end */
2331 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2332 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2333 ret = error("cannot seek back reflog for %s: %s",
2334 refname, strerror(errno));
2337 nread = fread(buf, cnt, 1, logfp);
2339 ret = error("cannot read %d bytes from reflog for %s: %s",
2340 cnt, refname, strerror(errno));
2345 scanp = endp = buf + cnt;
2346 if (at_tail && scanp[-1] == '\n')
2347 /* Looking at the final LF at the end of the file */
2351 while (buf < scanp) {
2353 * terminating LF of the previous line, or the beginning
2358 bp = find_beginning_of_line(buf, scanp);
2362 * The newline is the end of the previous line,
2363 * so we know we have complete line starting
2364 * at (bp + 1). Prefix it onto any prior data
2365 * we collected for the line and process it.
2367 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2370 ret = show_one_reflog_ent(&sb, fn, cb_data);
2376 * We are at the start of the buffer, and the
2377 * start of the file; there is no previous
2378 * line, and we have everything for this one.
2379 * Process it, and we can end the loop.
2381 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2382 ret = show_one_reflog_ent(&sb, fn, cb_data);
2389 * We are at the start of the buffer, and there
2390 * is more file to read backwards. Which means
2391 * we are in the middle of a line. Note that we
2392 * may get here even if *bp was a newline; that
2393 * just means we are at the exact end of the
2394 * previous line, rather than some spot in the
2397 * Save away what we have to be combined with
2398 * the data from the next read.
2400 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2407 die("BUG: reverse reflog parser had leftover data");
2410 strbuf_release(&sb);
2414 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2415 const char *refname,
2416 each_reflog_ent_fn fn, void *cb_data)
2418 struct files_ref_store *refs =
2419 files_downcast(ref_store, REF_STORE_READ,
2420 "for_each_reflog_ent");
2422 struct strbuf sb = STRBUF_INIT;
2425 files_reflog_path(refs, &sb, refname);
2426 logfp = fopen(sb.buf, "r");
2427 strbuf_release(&sb);
2431 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2432 ret = show_one_reflog_ent(&sb, fn, cb_data);
2434 strbuf_release(&sb);
2438 struct files_reflog_iterator {
2439 struct ref_iterator base;
2441 struct ref_store *ref_store;
2442 struct dir_iterator *dir_iterator;
2443 struct object_id oid;
2446 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2448 struct files_reflog_iterator *iter =
2449 (struct files_reflog_iterator *)ref_iterator;
2450 struct dir_iterator *diter = iter->dir_iterator;
2453 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2456 if (!S_ISREG(diter->st.st_mode))
2458 if (diter->basename[0] == '.')
2460 if (ends_with(diter->basename, ".lock"))
2463 if (refs_read_ref_full(iter->ref_store,
2464 diter->relative_path, 0,
2465 iter->oid.hash, &flags)) {
2466 error("bad ref for %s", diter->path.buf);
2470 iter->base.refname = diter->relative_path;
2471 iter->base.oid = &iter->oid;
2472 iter->base.flags = flags;
2476 iter->dir_iterator = NULL;
2477 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2482 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2483 struct object_id *peeled)
2485 die("BUG: ref_iterator_peel() called for reflog_iterator");
2488 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2490 struct files_reflog_iterator *iter =
2491 (struct files_reflog_iterator *)ref_iterator;
2494 if (iter->dir_iterator)
2495 ok = dir_iterator_abort(iter->dir_iterator);
2497 base_ref_iterator_free(ref_iterator);
2501 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2502 files_reflog_iterator_advance,
2503 files_reflog_iterator_peel,
2504 files_reflog_iterator_abort
2507 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2509 struct files_ref_store *refs =
2510 files_downcast(ref_store, REF_STORE_READ,
2511 "reflog_iterator_begin");
2512 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2513 struct ref_iterator *ref_iterator = &iter->base;
2514 struct strbuf sb = STRBUF_INIT;
2516 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2517 files_reflog_path(refs, &sb, NULL);
2518 iter->dir_iterator = dir_iterator_begin(sb.buf);
2519 iter->ref_store = ref_store;
2520 strbuf_release(&sb);
2521 return ref_iterator;
2524 static int ref_update_reject_duplicates(struct string_list *refnames,
2527 int i, n = refnames->nr;
2531 for (i = 1; i < n; i++)
2532 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
2534 "multiple updates for ref '%s' not allowed.",
2535 refnames->items[i].string);
2542 * If update is a direct update of head_ref (the reference pointed to
2543 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2545 static int split_head_update(struct ref_update *update,
2546 struct ref_transaction *transaction,
2547 const char *head_ref,
2548 struct string_list *affected_refnames,
2551 struct string_list_item *item;
2552 struct ref_update *new_update;
2554 if ((update->flags & REF_LOG_ONLY) ||
2555 (update->flags & REF_ISPRUNING) ||
2556 (update->flags & REF_UPDATE_VIA_HEAD))
2559 if (strcmp(update->refname, head_ref))
2563 * First make sure that HEAD is not already in the
2564 * transaction. This insertion is O(N) in the transaction
2565 * size, but it happens at most once per transaction.
2567 item = string_list_insert(affected_refnames, "HEAD");
2569 /* An entry already existed */
2571 "multiple updates for 'HEAD' (including one "
2572 "via its referent '%s') are not allowed",
2574 return TRANSACTION_NAME_CONFLICT;
2577 new_update = ref_transaction_add_update(
2578 transaction, "HEAD",
2579 update->flags | REF_LOG_ONLY | REF_NODEREF,
2580 update->new_oid.hash, update->old_oid.hash,
2583 item->util = new_update;
2589 * update is for a symref that points at referent and doesn't have
2590 * REF_NODEREF set. Split it into two updates:
2591 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2592 * - A new, separate update for the referent reference
2593 * Note that the new update will itself be subject to splitting when
2594 * the iteration gets to it.
2596 static int split_symref_update(struct files_ref_store *refs,
2597 struct ref_update *update,
2598 const char *referent,
2599 struct ref_transaction *transaction,
2600 struct string_list *affected_refnames,
2603 struct string_list_item *item;
2604 struct ref_update *new_update;
2605 unsigned int new_flags;
2608 * First make sure that referent is not already in the
2609 * transaction. This insertion is O(N) in the transaction
2610 * size, but it happens at most once per symref in a
2613 item = string_list_insert(affected_refnames, referent);
2615 /* An entry already existed */
2617 "multiple updates for '%s' (including one "
2618 "via symref '%s') are not allowed",
2619 referent, update->refname);
2620 return TRANSACTION_NAME_CONFLICT;
2623 new_flags = update->flags;
2624 if (!strcmp(update->refname, "HEAD")) {
2626 * Record that the new update came via HEAD, so that
2627 * when we process it, split_head_update() doesn't try
2628 * to add another reflog update for HEAD. Note that
2629 * this bit will be propagated if the new_update
2630 * itself needs to be split.
2632 new_flags |= REF_UPDATE_VIA_HEAD;
2635 new_update = ref_transaction_add_update(
2636 transaction, referent, new_flags,
2637 update->new_oid.hash, update->old_oid.hash,
2640 new_update->parent_update = update;
2643 * Change the symbolic ref update to log only. Also, it
2644 * doesn't need to check its old SHA-1 value, as that will be
2645 * done when new_update is processed.
2647 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2648 update->flags &= ~REF_HAVE_OLD;
2650 item->util = new_update;
2656 * Return the refname under which update was originally requested.
2658 static const char *original_update_refname(struct ref_update *update)
2660 while (update->parent_update)
2661 update = update->parent_update;
2663 return update->refname;
2667 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2668 * are consistent with oid, which is the reference's current value. If
2669 * everything is OK, return 0; otherwise, write an error message to
2670 * err and return -1.
2672 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2675 if (!(update->flags & REF_HAVE_OLD) ||
2676 !oidcmp(oid, &update->old_oid))
2679 if (is_null_oid(&update->old_oid))
2680 strbuf_addf(err, "cannot lock ref '%s': "
2681 "reference already exists",
2682 original_update_refname(update));
2683 else if (is_null_oid(oid))
2684 strbuf_addf(err, "cannot lock ref '%s': "
2685 "reference is missing but expected %s",
2686 original_update_refname(update),
2687 oid_to_hex(&update->old_oid));
2689 strbuf_addf(err, "cannot lock ref '%s': "
2690 "is at %s but expected %s",
2691 original_update_refname(update),
2693 oid_to_hex(&update->old_oid));
2699 * Prepare for carrying out update:
2700 * - Lock the reference referred to by update.
2701 * - Read the reference under lock.
2702 * - Check that its old SHA-1 value (if specified) is correct, and in
2703 * any case record it in update->lock->old_oid for later use when
2704 * writing the reflog.
2705 * - If it is a symref update without REF_NODEREF, split it up into a
2706 * REF_LOG_ONLY update of the symref and add a separate update for
2707 * the referent to transaction.
2708 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2711 static int lock_ref_for_update(struct files_ref_store *refs,
2712 struct ref_update *update,
2713 struct ref_transaction *transaction,
2714 const char *head_ref,
2715 struct string_list *affected_refnames,
2718 struct strbuf referent = STRBUF_INIT;
2719 int mustexist = (update->flags & REF_HAVE_OLD) &&
2720 !is_null_oid(&update->old_oid);
2722 struct ref_lock *lock;
2724 files_assert_main_repository(refs, "lock_ref_for_update");
2726 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2727 update->flags |= REF_DELETING;
2730 ret = split_head_update(update, transaction, head_ref,
2731 affected_refnames, err);
2736 ret = lock_raw_ref(refs, update->refname, mustexist,
2737 affected_refnames, NULL,
2739 &update->type, err);
2743 reason = strbuf_detach(err, NULL);
2744 strbuf_addf(err, "cannot lock ref '%s': %s",
2745 original_update_refname(update), reason);
2750 update->backend_data = lock;
2752 if (update->type & REF_ISSYMREF) {
2753 if (update->flags & REF_NODEREF) {
2755 * We won't be reading the referent as part of
2756 * the transaction, so we have to read it here
2757 * to record and possibly check old_sha1:
2759 if (refs_read_ref_full(&refs->base,
2761 lock->old_oid.hash, NULL)) {
2762 if (update->flags & REF_HAVE_OLD) {
2763 strbuf_addf(err, "cannot lock ref '%s': "
2764 "error reading reference",
2765 original_update_refname(update));
2768 } else if (check_old_oid(update, &lock->old_oid, err)) {
2769 return TRANSACTION_GENERIC_ERROR;
2773 * Create a new update for the reference this
2774 * symref is pointing at. Also, we will record
2775 * and verify old_sha1 for this update as part
2776 * of processing the split-off update, so we
2777 * don't have to do it here.
2779 ret = split_symref_update(refs, update,
2780 referent.buf, transaction,
2781 affected_refnames, err);
2786 struct ref_update *parent_update;
2788 if (check_old_oid(update, &lock->old_oid, err))
2789 return TRANSACTION_GENERIC_ERROR;
2792 * If this update is happening indirectly because of a
2793 * symref update, record the old SHA-1 in the parent
2796 for (parent_update = update->parent_update;
2798 parent_update = parent_update->parent_update) {
2799 struct ref_lock *parent_lock = parent_update->backend_data;
2800 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2804 if ((update->flags & REF_HAVE_NEW) &&
2805 !(update->flags & REF_DELETING) &&
2806 !(update->flags & REF_LOG_ONLY)) {
2807 if (!(update->type & REF_ISSYMREF) &&
2808 !oidcmp(&lock->old_oid, &update->new_oid)) {
2810 * The reference already has the desired
2811 * value, so we don't need to write it.
2813 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2815 char *write_err = strbuf_detach(err, NULL);
2818 * The lock was freed upon failure of
2819 * write_ref_to_lockfile():
2821 update->backend_data = NULL;
2823 "cannot update ref '%s': %s",
2824 update->refname, write_err);
2826 return TRANSACTION_GENERIC_ERROR;
2828 update->flags |= REF_NEEDS_COMMIT;
2831 if (!(update->flags & REF_NEEDS_COMMIT)) {
2833 * We didn't call write_ref_to_lockfile(), so
2834 * the lockfile is still open. Close it to
2835 * free up the file descriptor:
2837 if (close_ref(lock)) {
2838 strbuf_addf(err, "couldn't close '%s.lock'",
2840 return TRANSACTION_GENERIC_ERROR;
2846 static int files_transaction_commit(struct ref_store *ref_store,
2847 struct ref_transaction *transaction,
2850 struct files_ref_store *refs =
2851 files_downcast(ref_store, REF_STORE_WRITE,
2852 "ref_transaction_commit");
2854 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2855 struct string_list_item *ref_to_delete;
2856 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2857 char *head_ref = NULL;
2859 struct object_id head_oid;
2860 struct strbuf sb = STRBUF_INIT;
2864 if (transaction->state != REF_TRANSACTION_OPEN)
2865 die("BUG: commit called for transaction that is not open");
2867 if (!transaction->nr) {
2868 transaction->state = REF_TRANSACTION_CLOSED;
2873 * Fail if a refname appears more than once in the
2874 * transaction. (If we end up splitting up any updates using
2875 * split_symref_update() or split_head_update(), those
2876 * functions will check that the new updates don't have the
2877 * same refname as any existing ones.)
2879 for (i = 0; i < transaction->nr; i++) {
2880 struct ref_update *update = transaction->updates[i];
2881 struct string_list_item *item =
2882 string_list_append(&affected_refnames, update->refname);
2885 * We store a pointer to update in item->util, but at
2886 * the moment we never use the value of this field
2887 * except to check whether it is non-NULL.
2889 item->util = update;
2891 string_list_sort(&affected_refnames);
2892 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2893 ret = TRANSACTION_GENERIC_ERROR;
2898 * Special hack: If a branch is updated directly and HEAD
2899 * points to it (may happen on the remote side of a push
2900 * for example) then logically the HEAD reflog should be
2903 * A generic solution would require reverse symref lookups,
2904 * but finding all symrefs pointing to a given branch would be
2905 * rather costly for this rare event (the direct update of a
2906 * branch) to be worth it. So let's cheat and check with HEAD
2907 * only, which should cover 99% of all usage scenarios (even
2908 * 100% of the default ones).
2910 * So if HEAD is a symbolic reference, then record the name of
2911 * the reference that it points to. If we see an update of
2912 * head_ref within the transaction, then split_head_update()
2913 * arranges for the reflog of HEAD to be updated, too.
2915 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2916 RESOLVE_REF_NO_RECURSE,
2917 head_oid.hash, &head_type);
2919 if (head_ref && !(head_type & REF_ISSYMREF)) {
2925 * Acquire all locks, verify old values if provided, check
2926 * that new values are valid, and write new values to the
2927 * lockfiles, ready to be activated. Only keep one lockfile
2928 * open at a time to avoid running out of file descriptors.
2930 for (i = 0; i < transaction->nr; i++) {
2931 struct ref_update *update = transaction->updates[i];
2933 ret = lock_ref_for_update(refs, update, transaction,
2934 head_ref, &affected_refnames, err);
2939 /* Perform updates first so live commits remain referenced */
2940 for (i = 0; i < transaction->nr; i++) {
2941 struct ref_update *update = transaction->updates[i];
2942 struct ref_lock *lock = update->backend_data;
2944 if (update->flags & REF_NEEDS_COMMIT ||
2945 update->flags & REF_LOG_ONLY) {
2946 if (files_log_ref_write(refs,
2950 update->msg, update->flags,
2952 char *old_msg = strbuf_detach(err, NULL);
2954 strbuf_addf(err, "cannot update the ref '%s': %s",
2955 lock->ref_name, old_msg);
2958 update->backend_data = NULL;
2959 ret = TRANSACTION_GENERIC_ERROR;
2963 if (update->flags & REF_NEEDS_COMMIT) {
2964 clear_loose_ref_cache(refs);
2965 if (commit_ref(lock)) {
2966 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2968 update->backend_data = NULL;
2969 ret = TRANSACTION_GENERIC_ERROR;
2974 /* Perform deletes now that updates are safely completed */
2975 for (i = 0; i < transaction->nr; i++) {
2976 struct ref_update *update = transaction->updates[i];
2977 struct ref_lock *lock = update->backend_data;
2979 if (update->flags & REF_DELETING &&
2980 !(update->flags & REF_LOG_ONLY)) {
2981 if (!(update->type & REF_ISPACKED) ||
2982 update->type & REF_ISSYMREF) {
2983 /* It is a loose reference. */
2985 files_ref_path(refs, &sb, lock->ref_name);
2986 if (unlink_or_msg(sb.buf, err)) {
2987 ret = TRANSACTION_GENERIC_ERROR;
2990 update->flags |= REF_DELETED_LOOSE;
2993 if (!(update->flags & REF_ISPRUNING))
2994 string_list_append(&refs_to_delete,
2999 if (repack_without_refs(refs, &refs_to_delete, err)) {
3000 ret = TRANSACTION_GENERIC_ERROR;
3004 /* Delete the reflogs of any references that were deleted: */
3005 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3007 files_reflog_path(refs, &sb, ref_to_delete->string);
3008 if (!unlink_or_warn(sb.buf))
3009 try_remove_empty_parents(refs, ref_to_delete->string,
3010 REMOVE_EMPTY_PARENTS_REFLOG);
3013 clear_loose_ref_cache(refs);
3016 strbuf_release(&sb);
3017 transaction->state = REF_TRANSACTION_CLOSED;
3019 for (i = 0; i < transaction->nr; i++) {
3020 struct ref_update *update = transaction->updates[i];
3021 struct ref_lock *lock = update->backend_data;
3026 if (update->flags & REF_DELETED_LOOSE) {
3028 * The loose reference was deleted. Delete any
3029 * empty parent directories. (Note that this
3030 * can only work because we have already
3031 * removed the lockfile.)
3033 try_remove_empty_parents(refs, update->refname,
3034 REMOVE_EMPTY_PARENTS_REF);
3038 string_list_clear(&refs_to_delete, 0);
3040 string_list_clear(&affected_refnames, 0);
3045 static int ref_present(const char *refname,
3046 const struct object_id *oid, int flags, void *cb_data)
3048 struct string_list *affected_refnames = cb_data;
3050 return string_list_has_string(affected_refnames, refname);
3053 static int files_initial_transaction_commit(struct ref_store *ref_store,
3054 struct ref_transaction *transaction,
3057 struct files_ref_store *refs =
3058 files_downcast(ref_store, REF_STORE_WRITE,
3059 "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,