4 #include "refs-internal.h"
6 #include "../iterator.h"
7 #include "../dir-iterator.h"
8 #include "../lockfile.h"
15 struct object_id old_oid;
19 * Return true if refname, which has the specified oid and flags, can
20 * be resolved to an object in the database. If the referred-to object
21 * does not exist, emit a warning and return false.
23 static int ref_resolves_to_object(const char *refname,
24 const struct object_id *oid,
27 if (flags & REF_ISBROKEN)
29 if (!has_sha1_file(oid->hash)) {
30 error("%s does not point to a valid object!", refname);
36 struct packed_ref_cache {
37 struct ref_cache *cache;
40 * Count of references to the data structure in this instance,
41 * including the pointer from files_ref_store::packed if any.
42 * The data will not be freed as long as the reference count
45 unsigned int referrers;
47 /* The metadata from when this packed-refs cache was read */
48 struct stat_validity validity;
52 * Future: need to be in "struct repository"
53 * when doing a full libification.
55 struct files_ref_store {
56 struct ref_store base;
57 unsigned int store_flags;
61 char *packed_refs_path;
63 struct ref_cache *loose;
64 struct packed_ref_cache *packed;
67 * Lock used for the "packed-refs" file. Note that this (and
68 * thus the enclosing `files_ref_store`) must not be freed.
70 struct lock_file packed_refs_lock;
74 * Increment the reference count of *packed_refs.
76 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
78 packed_refs->referrers++;
82 * Decrease the reference count of *packed_refs. If it goes to zero,
83 * free *packed_refs and return true; otherwise return false.
85 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
87 if (!--packed_refs->referrers) {
88 free_ref_cache(packed_refs->cache);
89 stat_validity_clear(&packed_refs->validity);
97 static void clear_packed_ref_cache(struct files_ref_store *refs)
100 struct packed_ref_cache *packed_refs = refs->packed;
102 if (is_lock_file_locked(&refs->packed_refs_lock))
103 die("BUG: packed-ref cache cleared while locked");
105 release_packed_ref_cache(packed_refs);
109 static void clear_loose_ref_cache(struct files_ref_store *refs)
112 free_ref_cache(refs->loose);
118 * Create a new submodule ref cache and add it to the internal
121 static struct ref_store *files_ref_store_create(const char *gitdir,
124 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
125 struct ref_store *ref_store = (struct ref_store *)refs;
126 struct strbuf sb = STRBUF_INIT;
128 base_ref_store_init(ref_store, &refs_be_files);
129 refs->store_flags = flags;
131 refs->gitdir = xstrdup(gitdir);
132 get_common_dir_noenv(&sb, gitdir);
133 refs->gitcommondir = strbuf_detach(&sb, NULL);
134 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
135 refs->packed_refs_path = strbuf_detach(&sb, NULL);
141 * Die if refs is not the main ref store. caller is used in any
142 * necessary error messages.
144 static void files_assert_main_repository(struct files_ref_store *refs,
147 if (refs->store_flags & REF_STORE_MAIN)
150 die("BUG: operation %s only allowed for main ref store", caller);
154 * Downcast ref_store to files_ref_store. Die if ref_store is not a
155 * files_ref_store. required_flags is compared with ref_store's
156 * store_flags to ensure the ref_store has all required capabilities.
157 * "caller" is used in any necessary error messages.
159 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
160 unsigned int required_flags,
163 struct files_ref_store *refs;
165 if (ref_store->be != &refs_be_files)
166 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
167 ref_store->be->name, caller);
169 refs = (struct files_ref_store *)ref_store;
171 if ((refs->store_flags & required_flags) != required_flags)
172 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
173 caller, required_flags, refs->store_flags);
178 /* The length of a peeled reference line in packed-refs, including EOL: */
179 #define PEELED_LINE_LENGTH 42
182 * The packed-refs header line that we write out. Perhaps other
183 * traits will be added later. The trailing space is required.
185 static const char PACKED_REFS_HEADER[] =
186 "# pack-refs with: peeled fully-peeled \n";
189 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
190 * Return a pointer to the refname within the line (null-terminated),
191 * or NULL if there was a problem.
193 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
197 if (parse_oid_hex(line->buf, oid, &ref) < 0)
199 if (!isspace(*ref++))
205 if (line->buf[line->len - 1] != '\n')
207 line->buf[--line->len] = 0;
213 * Read from `packed_refs_file` into a newly-allocated
214 * `packed_ref_cache` and return it. The return value will already
215 * have its reference count incremented.
217 * A comment line of the form "# pack-refs with: " may contain zero or
218 * more traits. We interpret the traits as follows:
222 * Probably no references are peeled. But if the file contains a
223 * peeled value for a reference, we will use it.
227 * References under "refs/tags/", if they *can* be peeled, *are*
228 * peeled in this file. References outside of "refs/tags/" are
229 * probably not peeled even if they could have been, but if we find
230 * a peeled value for such a reference we will use it.
234 * All references in the file that can be peeled are peeled.
235 * Inversely (and this is more important), any references in the
236 * file for which no peeled value is recorded is not peelable. This
237 * trait should typically be written alongside "peeled" for
238 * compatibility with older clients, but we do not require it
239 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
241 static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
244 struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
245 struct ref_entry *last = NULL;
246 struct strbuf line = STRBUF_INIT;
247 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
250 acquire_packed_ref_cache(packed_refs);
251 packed_refs->cache = create_ref_cache(NULL, NULL);
252 packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
254 f = fopen(packed_refs_file, "r");
256 if (errno == ENOENT) {
258 * This is OK; it just means that no
259 * "packed-refs" file has been written yet,
260 * which is equivalent to it being empty.
264 die_errno("couldn't read %s", packed_refs_file);
268 stat_validity_update(&packed_refs->validity, fileno(f));
270 dir = get_ref_dir(packed_refs->cache->root);
271 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
272 struct object_id oid;
276 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
277 if (strstr(traits, " fully-peeled "))
278 peeled = PEELED_FULLY;
279 else if (strstr(traits, " peeled "))
280 peeled = PEELED_TAGS;
281 /* perhaps other traits later as well */
285 refname = parse_ref_line(&line, &oid);
287 int flag = REF_ISPACKED;
289 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
290 if (!refname_is_safe(refname))
291 die("packed refname is dangerous: %s", refname);
293 flag |= REF_BAD_NAME | REF_ISBROKEN;
295 last = create_ref_entry(refname, &oid, flag);
296 if (peeled == PEELED_FULLY ||
297 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
298 last->flag |= REF_KNOWS_PEELED;
299 add_ref_entry(dir, last);
303 line.buf[0] == '^' &&
304 line.len == PEELED_LINE_LENGTH &&
305 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
306 !get_oid_hex(line.buf + 1, &oid)) {
307 oidcpy(&last->u.value.peeled, &oid);
309 * Regardless of what the file header said,
310 * we definitely know the value of *this*
313 last->flag |= REF_KNOWS_PEELED;
318 strbuf_release(&line);
323 static const char *files_packed_refs_path(struct files_ref_store *refs)
325 return refs->packed_refs_path;
328 static void files_reflog_path(struct files_ref_store *refs,
334 * FIXME: of course this is wrong in multi worktree
335 * setting. To be fixed real soon.
337 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
341 switch (ref_type(refname)) {
342 case REF_TYPE_PER_WORKTREE:
343 case REF_TYPE_PSEUDOREF:
344 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
346 case REF_TYPE_NORMAL:
347 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
350 die("BUG: unknown ref type %d of ref %s",
351 ref_type(refname), refname);
355 static void files_ref_path(struct files_ref_store *refs,
359 switch (ref_type(refname)) {
360 case REF_TYPE_PER_WORKTREE:
361 case REF_TYPE_PSEUDOREF:
362 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
364 case REF_TYPE_NORMAL:
365 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
368 die("BUG: unknown ref type %d of ref %s",
369 ref_type(refname), refname);
374 * Check that the packed refs cache (if any) still reflects the
375 * contents of the file. If not, clear the cache.
377 static void validate_packed_ref_cache(struct files_ref_store *refs)
380 !stat_validity_check(&refs->packed->validity,
381 files_packed_refs_path(refs)))
382 clear_packed_ref_cache(refs);
386 * Get the packed_ref_cache for the specified files_ref_store,
387 * creating and populating it if it hasn't been read before or if the
388 * file has been changed (according to its `validity` field) since it
389 * was last read. On the other hand, if we hold the lock, then assume
390 * that the file hasn't been changed out from under us, so skip the
391 * extra `stat()` call in `stat_validity_check()`.
393 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
395 const char *packed_refs_file = files_packed_refs_path(refs);
397 if (!is_lock_file_locked(&refs->packed_refs_lock))
398 validate_packed_ref_cache(refs);
401 refs->packed = read_packed_refs(packed_refs_file);
406 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
408 return get_ref_dir(packed_ref_cache->cache->root);
411 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
413 return get_packed_ref_dir(get_packed_ref_cache(refs));
417 * Add a reference to the in-memory packed reference cache. This may
418 * only be called while the packed-refs file is locked (see
419 * lock_packed_refs()). To actually write the packed-refs file, call
420 * commit_packed_refs().
422 static void add_packed_ref(struct files_ref_store *refs,
423 const char *refname, const struct object_id *oid)
425 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
427 if (!is_lock_file_locked(&refs->packed_refs_lock))
428 die("BUG: packed refs not locked");
430 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
431 die("Reference has invalid format: '%s'", refname);
433 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
434 create_ref_entry(refname, oid, REF_ISPACKED));
438 * Read the loose references from the namespace dirname into dir
439 * (without recursing). dirname must end with '/'. dir must be the
440 * directory entry corresponding to dirname.
442 static void loose_fill_ref_dir(struct ref_store *ref_store,
443 struct ref_dir *dir, const char *dirname)
445 struct files_ref_store *refs =
446 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
449 int dirnamelen = strlen(dirname);
450 struct strbuf refname;
451 struct strbuf path = STRBUF_INIT;
454 files_ref_path(refs, &path, dirname);
455 path_baselen = path.len;
457 d = opendir(path.buf);
459 strbuf_release(&path);
463 strbuf_init(&refname, dirnamelen + 257);
464 strbuf_add(&refname, dirname, dirnamelen);
466 while ((de = readdir(d)) != NULL) {
467 struct object_id oid;
471 if (de->d_name[0] == '.')
473 if (ends_with(de->d_name, ".lock"))
475 strbuf_addstr(&refname, de->d_name);
476 strbuf_addstr(&path, de->d_name);
477 if (stat(path.buf, &st) < 0) {
478 ; /* silently ignore */
479 } else if (S_ISDIR(st.st_mode)) {
480 strbuf_addch(&refname, '/');
481 add_entry_to_dir(dir,
482 create_dir_entry(dir->cache, refname.buf,
485 if (!refs_resolve_ref_unsafe(&refs->base,
490 flag |= REF_ISBROKEN;
491 } else if (is_null_oid(&oid)) {
493 * It is so astronomically unlikely
494 * that NULL_SHA1 is the SHA-1 of an
495 * actual object that we consider its
496 * appearance in a loose reference
497 * file to be repo corruption
498 * (probably due to a software bug).
500 flag |= REF_ISBROKEN;
503 if (check_refname_format(refname.buf,
504 REFNAME_ALLOW_ONELEVEL)) {
505 if (!refname_is_safe(refname.buf))
506 die("loose refname is dangerous: %s", refname.buf);
508 flag |= REF_BAD_NAME | REF_ISBROKEN;
510 add_entry_to_dir(dir,
511 create_ref_entry(refname.buf, &oid, flag));
513 strbuf_setlen(&refname, dirnamelen);
514 strbuf_setlen(&path, path_baselen);
516 strbuf_release(&refname);
517 strbuf_release(&path);
521 * Manually add refs/bisect, which, being per-worktree, might
522 * not appear in the directory listing for refs/ in the main
525 if (!strcmp(dirname, "refs/")) {
526 int pos = search_ref_dir(dir, "refs/bisect/", 12);
529 struct ref_entry *child_entry = create_dir_entry(
530 dir->cache, "refs/bisect/", 12, 1);
531 add_entry_to_dir(dir, child_entry);
536 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
540 * Mark the top-level directory complete because we
541 * are about to read the only subdirectory that can
544 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
546 /* We're going to fill the top level ourselves: */
547 refs->loose->root->flag &= ~REF_INCOMPLETE;
550 * Add an incomplete entry for "refs/" (to be filled
553 add_entry_to_dir(get_ref_dir(refs->loose->root),
554 create_dir_entry(refs->loose, "refs/", 5, 1));
560 * Return the ref_entry for the given refname from the packed
561 * references. If it does not exist, return NULL.
563 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
566 return find_ref_entry(get_packed_refs(refs), refname);
570 * A loose ref file doesn't exist; check for a packed ref.
572 static int resolve_packed_ref(struct files_ref_store *refs,
574 unsigned char *sha1, unsigned int *flags)
576 struct ref_entry *entry;
579 * The loose reference file does not exist; check for a packed
582 entry = get_packed_ref(refs, refname);
584 hashcpy(sha1, entry->u.value.oid.hash);
585 *flags |= REF_ISPACKED;
588 /* refname is not a packed reference. */
592 static int files_read_raw_ref(struct ref_store *ref_store,
593 const char *refname, unsigned char *sha1,
594 struct strbuf *referent, unsigned int *type)
596 struct files_ref_store *refs =
597 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
598 struct strbuf sb_contents = STRBUF_INIT;
599 struct strbuf sb_path = STRBUF_INIT;
606 int remaining_retries = 3;
609 strbuf_reset(&sb_path);
611 files_ref_path(refs, &sb_path, refname);
617 * We might have to loop back here to avoid a race
618 * condition: first we lstat() the file, then we try
619 * to read it as a link or as a file. But if somebody
620 * changes the type of the file (file <-> directory
621 * <-> symlink) between the lstat() and reading, then
622 * we don't want to report that as an error but rather
623 * try again starting with the lstat().
625 * We'll keep a count of the retries, though, just to avoid
626 * any confusing situation sending us into an infinite loop.
629 if (remaining_retries-- <= 0)
632 if (lstat(path, &st) < 0) {
635 if (resolve_packed_ref(refs, refname, sha1, type)) {
643 /* Follow "normalized" - ie "refs/.." symlinks by hand */
644 if (S_ISLNK(st.st_mode)) {
645 strbuf_reset(&sb_contents);
646 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
647 if (errno == ENOENT || errno == EINVAL)
648 /* inconsistent with lstat; retry */
653 if (starts_with(sb_contents.buf, "refs/") &&
654 !check_refname_format(sb_contents.buf, 0)) {
655 strbuf_swap(&sb_contents, referent);
656 *type |= REF_ISSYMREF;
661 * It doesn't look like a refname; fall through to just
662 * treating it like a non-symlink, and reading whatever it
667 /* Is it a directory? */
668 if (S_ISDIR(st.st_mode)) {
670 * Even though there is a directory where the loose
671 * ref is supposed to be, there could still be a
674 if (resolve_packed_ref(refs, refname, sha1, type)) {
683 * Anything else, just open it and try to use it as
686 fd = open(path, O_RDONLY);
688 if (errno == ENOENT && !S_ISLNK(st.st_mode))
689 /* inconsistent with lstat; retry */
694 strbuf_reset(&sb_contents);
695 if (strbuf_read(&sb_contents, fd, 256) < 0) {
696 int save_errno = errno;
702 strbuf_rtrim(&sb_contents);
703 buf = sb_contents.buf;
704 if (starts_with(buf, "ref:")) {
706 while (isspace(*buf))
709 strbuf_reset(referent);
710 strbuf_addstr(referent, buf);
711 *type |= REF_ISSYMREF;
717 * Please note that FETCH_HEAD has additional
718 * data after the sha.
720 if (get_sha1_hex(buf, sha1) ||
721 (buf[40] != '\0' && !isspace(buf[40]))) {
722 *type |= REF_ISBROKEN;
731 strbuf_release(&sb_path);
732 strbuf_release(&sb_contents);
737 static void unlock_ref(struct ref_lock *lock)
739 /* Do not free lock->lk -- atexit() still looks at them */
741 rollback_lock_file(lock->lk);
742 free(lock->ref_name);
747 * Lock refname, without following symrefs, and set *lock_p to point
748 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
749 * and type similarly to read_raw_ref().
751 * The caller must verify that refname is a "safe" reference name (in
752 * the sense of refname_is_safe()) before calling this function.
754 * If the reference doesn't already exist, verify that refname doesn't
755 * have a D/F conflict with any existing references. extras and skip
756 * are passed to refs_verify_refname_available() for this check.
758 * If mustexist is not set and the reference is not found or is
759 * broken, lock the reference anyway but clear sha1.
761 * Return 0 on success. On failure, write an error message to err and
762 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
764 * Implementation note: This function is basically
769 * but it includes a lot more code to
770 * - Deal with possible races with other processes
771 * - Avoid calling refs_verify_refname_available() when it can be
772 * avoided, namely if we were successfully able to read the ref
773 * - Generate informative error messages in the case of failure
775 static int lock_raw_ref(struct files_ref_store *refs,
776 const char *refname, int mustexist,
777 const struct string_list *extras,
778 const struct string_list *skip,
779 struct ref_lock **lock_p,
780 struct strbuf *referent,
784 struct ref_lock *lock;
785 struct strbuf ref_file = STRBUF_INIT;
786 int attempts_remaining = 3;
787 int ret = TRANSACTION_GENERIC_ERROR;
790 files_assert_main_repository(refs, "lock_raw_ref");
794 /* First lock the file so it can't change out from under us. */
796 *lock_p = lock = xcalloc(1, sizeof(*lock));
798 lock->ref_name = xstrdup(refname);
799 files_ref_path(refs, &ref_file, refname);
802 switch (safe_create_leading_directories(ref_file.buf)) {
807 * Suppose refname is "refs/foo/bar". We just failed
808 * to create the containing directory, "refs/foo",
809 * because there was a non-directory in the way. This
810 * indicates a D/F conflict, probably because of
811 * another reference such as "refs/foo". There is no
812 * reason to expect this error to be transitory.
814 if (refs_verify_refname_available(&refs->base, refname,
815 extras, skip, err)) {
818 * To the user the relevant error is
819 * that the "mustexist" reference is
823 strbuf_addf(err, "unable to resolve reference '%s'",
827 * The error message set by
828 * refs_verify_refname_available() is
831 ret = TRANSACTION_NAME_CONFLICT;
835 * The file that is in the way isn't a loose
836 * reference. Report it as a low-level
839 strbuf_addf(err, "unable to create lock file %s.lock; "
840 "non-directory in the way",
845 /* Maybe another process was tidying up. Try again. */
846 if (--attempts_remaining > 0)
850 strbuf_addf(err, "unable to create directory for %s",
856 lock->lk = xcalloc(1, sizeof(struct lock_file));
858 if (hold_lock_file_for_update_timeout(
859 lock->lk, ref_file.buf, LOCK_NO_DEREF,
860 get_files_ref_lock_timeout_ms()) < 0) {
861 if (errno == ENOENT && --attempts_remaining > 0) {
863 * Maybe somebody just deleted one of the
864 * directories leading to ref_file. Try
869 unable_to_lock_message(ref_file.buf, errno, err);
875 * Now we hold the lock and can read the reference without
876 * fear that its value will change.
879 if (files_read_raw_ref(&refs->base, refname,
880 lock->old_oid.hash, referent, type)) {
881 if (errno == ENOENT) {
883 /* Garden variety missing reference. */
884 strbuf_addf(err, "unable to resolve reference '%s'",
889 * Reference is missing, but that's OK. We
890 * know that there is not a conflict with
891 * another loose reference because
892 * (supposing that we are trying to lock
893 * reference "refs/foo/bar"):
895 * - We were successfully able to create
896 * the lockfile refs/foo/bar.lock, so we
897 * know there cannot be a loose reference
900 * - We got ENOENT and not EISDIR, so we
901 * know that there cannot be a loose
902 * reference named "refs/foo/bar/baz".
905 } else if (errno == EISDIR) {
907 * There is a directory in the way. It might have
908 * contained references that have been deleted. If
909 * we don't require that the reference already
910 * exists, try to remove the directory so that it
911 * doesn't cause trouble when we want to rename the
912 * lockfile into place later.
915 /* Garden variety missing reference. */
916 strbuf_addf(err, "unable to resolve reference '%s'",
919 } else if (remove_dir_recursively(&ref_file,
920 REMOVE_DIR_EMPTY_ONLY)) {
921 if (refs_verify_refname_available(
922 &refs->base, refname,
923 extras, skip, err)) {
925 * The error message set by
926 * verify_refname_available() is OK.
928 ret = TRANSACTION_NAME_CONFLICT;
932 * We can't delete the directory,
933 * but we also don't know of any
934 * references that it should
937 strbuf_addf(err, "there is a non-empty directory '%s' "
938 "blocking reference '%s'",
939 ref_file.buf, refname);
943 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
944 strbuf_addf(err, "unable to resolve reference '%s': "
945 "reference broken", refname);
948 strbuf_addf(err, "unable to resolve reference '%s': %s",
949 refname, strerror(errno));
954 * If the ref did not exist and we are creating it,
955 * make sure there is no existing ref that conflicts
958 if (refs_verify_refname_available(
959 &refs->base, refname,
972 strbuf_release(&ref_file);
976 static int files_peel_ref(struct ref_store *ref_store,
977 const char *refname, unsigned char *sha1)
979 struct files_ref_store *refs =
980 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
983 unsigned char base[20];
985 if (current_ref_iter && current_ref_iter->refname == refname) {
986 struct object_id peeled;
988 if (ref_iterator_peel(current_ref_iter, &peeled))
990 hashcpy(sha1, peeled.hash);
994 if (refs_read_ref_full(ref_store, refname,
995 RESOLVE_REF_READING, base, &flag))
999 * If the reference is packed, read its ref_entry from the
1000 * cache in the hope that we already know its peeled value.
1001 * We only try this optimization on packed references because
1002 * (a) forcing the filling of the loose reference cache could
1003 * be expensive and (b) loose references anyway usually do not
1004 * have REF_KNOWS_PEELED.
1006 if (flag & REF_ISPACKED) {
1007 struct ref_entry *r = get_packed_ref(refs, refname);
1009 if (peel_entry(r, 0))
1011 hashcpy(sha1, r->u.value.peeled.hash);
1016 return peel_object(base, sha1);
1019 struct files_ref_iterator {
1020 struct ref_iterator base;
1022 struct packed_ref_cache *packed_ref_cache;
1023 struct ref_iterator *iter0;
1027 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1029 struct files_ref_iterator *iter =
1030 (struct files_ref_iterator *)ref_iterator;
1033 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1034 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1035 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1038 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1039 !ref_resolves_to_object(iter->iter0->refname,
1041 iter->iter0->flags))
1044 iter->base.refname = iter->iter0->refname;
1045 iter->base.oid = iter->iter0->oid;
1046 iter->base.flags = iter->iter0->flags;
1051 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1057 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1058 struct object_id *peeled)
1060 struct files_ref_iterator *iter =
1061 (struct files_ref_iterator *)ref_iterator;
1063 return ref_iterator_peel(iter->iter0, peeled);
1066 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1068 struct files_ref_iterator *iter =
1069 (struct files_ref_iterator *)ref_iterator;
1073 ok = ref_iterator_abort(iter->iter0);
1075 release_packed_ref_cache(iter->packed_ref_cache);
1076 base_ref_iterator_free(ref_iterator);
1080 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1081 files_ref_iterator_advance,
1082 files_ref_iterator_peel,
1083 files_ref_iterator_abort
1086 static struct ref_iterator *files_ref_iterator_begin(
1087 struct ref_store *ref_store,
1088 const char *prefix, unsigned int flags)
1090 struct files_ref_store *refs;
1091 struct ref_iterator *loose_iter, *packed_iter;
1092 struct files_ref_iterator *iter;
1093 struct ref_iterator *ref_iterator;
1094 unsigned int required_flags = REF_STORE_READ;
1096 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1097 required_flags |= REF_STORE_ODB;
1099 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1101 iter = xcalloc(1, sizeof(*iter));
1102 ref_iterator = &iter->base;
1103 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1106 * We must make sure that all loose refs are read before
1107 * accessing the packed-refs file; this avoids a race
1108 * condition if loose refs are migrated to the packed-refs
1109 * file by a simultaneous process, but our in-memory view is
1110 * from before the migration. We ensure this as follows:
1111 * First, we call start the loose refs iteration with its
1112 * `prime_ref` argument set to true. This causes the loose
1113 * references in the subtree to be pre-read into the cache.
1114 * (If they've already been read, that's OK; we only need to
1115 * guarantee that they're read before the packed refs, not
1116 * *how much* before.) After that, we call
1117 * get_packed_ref_cache(), which internally checks whether the
1118 * packed-ref cache is up to date with what is on disk, and
1119 * re-reads it if not.
1122 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1125 iter->packed_ref_cache = get_packed_ref_cache(refs);
1126 acquire_packed_ref_cache(iter->packed_ref_cache);
1127 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1130 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1131 iter->flags = flags;
1133 return ref_iterator;
1137 * Verify that the reference locked by lock has the value old_sha1.
1138 * Fail if the reference doesn't exist and mustexist is set. Return 0
1139 * on success. On error, write an error message to err, set errno, and
1140 * return a negative value.
1142 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1143 const unsigned char *old_sha1, int mustexist,
1148 if (refs_read_ref_full(ref_store, lock->ref_name,
1149 mustexist ? RESOLVE_REF_READING : 0,
1150 lock->old_oid.hash, NULL)) {
1152 int save_errno = errno;
1153 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1157 oidclr(&lock->old_oid);
1161 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1162 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1164 oid_to_hex(&lock->old_oid),
1165 sha1_to_hex(old_sha1));
1172 static int remove_empty_directories(struct strbuf *path)
1175 * we want to create a file but there is a directory there;
1176 * if that is an empty directory (or a directory that contains
1177 * only empty directories), remove them.
1179 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1182 static int create_reflock(const char *path, void *cb)
1184 struct lock_file *lk = cb;
1186 return hold_lock_file_for_update_timeout(
1187 lk, path, LOCK_NO_DEREF,
1188 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
1192 * Locks a ref returning the lock on success and NULL on failure.
1193 * On failure errno is set to something meaningful.
1195 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1196 const char *refname,
1197 const unsigned char *old_sha1,
1198 const struct string_list *extras,
1199 const struct string_list *skip,
1200 unsigned int flags, int *type,
1203 struct strbuf ref_file = STRBUF_INIT;
1204 struct ref_lock *lock;
1206 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1207 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1210 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1213 lock = xcalloc(1, sizeof(struct ref_lock));
1216 resolve_flags |= RESOLVE_REF_READING;
1217 if (flags & REF_DELETING)
1218 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1220 files_ref_path(refs, &ref_file, refname);
1221 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1222 refname, resolve_flags,
1223 lock->old_oid.hash, type);
1224 if (!resolved && errno == EISDIR) {
1226 * we are trying to lock foo but we used to
1227 * have foo/bar which now does not exist;
1228 * it is normal for the empty directory 'foo'
1231 if (remove_empty_directories(&ref_file)) {
1233 if (!refs_verify_refname_available(
1235 refname, extras, skip, err))
1236 strbuf_addf(err, "there are still refs under '%s'",
1240 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1241 refname, resolve_flags,
1242 lock->old_oid.hash, type);
1246 if (last_errno != ENOTDIR ||
1247 !refs_verify_refname_available(&refs->base, refname,
1249 strbuf_addf(err, "unable to resolve reference '%s': %s",
1250 refname, strerror(last_errno));
1256 * If the ref did not exist and we are creating it, make sure
1257 * there is no existing packed ref whose name begins with our
1258 * refname, nor a packed ref whose name is a proper prefix of
1261 if (is_null_oid(&lock->old_oid) &&
1262 refs_verify_refname_available(&refs->base, refname,
1263 extras, skip, err)) {
1264 last_errno = ENOTDIR;
1268 lock->lk = xcalloc(1, sizeof(struct lock_file));
1270 lock->ref_name = xstrdup(refname);
1272 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1274 unable_to_lock_message(ref_file.buf, errno, err);
1278 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1289 strbuf_release(&ref_file);
1295 * Write an entry to the packed-refs file for the specified refname.
1296 * If peeled is non-NULL, write it as the entry's peeled value.
1298 static void write_packed_entry(FILE *fh, const char *refname,
1299 const unsigned char *sha1,
1300 const unsigned char *peeled)
1302 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1304 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1308 * Lock the packed-refs file for writing. Flags is passed to
1309 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1310 * errno appropriately and return a nonzero value.
1312 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1314 static int timeout_configured = 0;
1315 static int timeout_value = 1000;
1316 struct packed_ref_cache *packed_ref_cache;
1318 files_assert_main_repository(refs, "lock_packed_refs");
1320 if (!timeout_configured) {
1321 git_config_get_int("core.packedrefstimeout", &timeout_value);
1322 timeout_configured = 1;
1325 if (hold_lock_file_for_update_timeout(
1326 &refs->packed_refs_lock, files_packed_refs_path(refs),
1327 flags, timeout_value) < 0)
1331 * Now that we hold the `packed-refs` lock, make sure that our
1332 * cache matches the current version of the file. Normally
1333 * `get_packed_ref_cache()` does that for us, but that
1334 * function assumes that when the file is locked, any existing
1335 * cache is still valid. We've just locked the file, but it
1336 * might have changed the moment *before* we locked it.
1338 validate_packed_ref_cache(refs);
1340 packed_ref_cache = get_packed_ref_cache(refs);
1341 /* Increment the reference count to prevent it from being freed: */
1342 acquire_packed_ref_cache(packed_ref_cache);
1347 * Write the current version of the packed refs cache from memory to
1348 * disk. The packed-refs file must already be locked for writing (see
1349 * lock_packed_refs()). Return zero on success. On errors, set errno
1350 * and return a nonzero value
1352 static int commit_packed_refs(struct files_ref_store *refs)
1354 struct packed_ref_cache *packed_ref_cache =
1355 get_packed_ref_cache(refs);
1359 struct ref_iterator *iter;
1361 files_assert_main_repository(refs, "commit_packed_refs");
1363 if (!is_lock_file_locked(&refs->packed_refs_lock))
1364 die("BUG: packed-refs not locked");
1366 out = fdopen_lock_file(&refs->packed_refs_lock, "w");
1368 die_errno("unable to fdopen packed-refs descriptor");
1370 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1372 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1373 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1374 struct object_id peeled;
1375 int peel_error = ref_iterator_peel(iter, &peeled);
1377 write_packed_entry(out, iter->refname, iter->oid->hash,
1378 peel_error ? NULL : peeled.hash);
1381 if (ok != ITER_DONE)
1382 die("error while iterating over references");
1384 if (commit_lock_file(&refs->packed_refs_lock)) {
1388 release_packed_ref_cache(packed_ref_cache);
1394 * Rollback the lockfile for the packed-refs file, and discard the
1395 * in-memory packed reference cache. (The packed-refs file will be
1396 * read anew if it is needed again after this function is called.)
1398 static void rollback_packed_refs(struct files_ref_store *refs)
1400 struct packed_ref_cache *packed_ref_cache =
1401 get_packed_ref_cache(refs);
1403 files_assert_main_repository(refs, "rollback_packed_refs");
1405 if (!is_lock_file_locked(&refs->packed_refs_lock))
1406 die("BUG: packed-refs not locked");
1407 rollback_lock_file(&refs->packed_refs_lock);
1408 release_packed_ref_cache(packed_ref_cache);
1409 clear_packed_ref_cache(refs);
1412 struct ref_to_prune {
1413 struct ref_to_prune *next;
1414 unsigned char sha1[20];
1415 char name[FLEX_ARRAY];
1419 REMOVE_EMPTY_PARENTS_REF = 0x01,
1420 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1424 * Remove empty parent directories associated with the specified
1425 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1426 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1427 * REMOVE_EMPTY_PARENTS_REFLOG.
1429 static void try_remove_empty_parents(struct files_ref_store *refs,
1430 const char *refname,
1433 struct strbuf buf = STRBUF_INIT;
1434 struct strbuf sb = STRBUF_INIT;
1438 strbuf_addstr(&buf, refname);
1440 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1441 while (*p && *p != '/')
1443 /* tolerate duplicate slashes; see check_refname_format() */
1447 q = buf.buf + buf.len;
1448 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1449 while (q > p && *q != '/')
1451 while (q > p && *(q-1) == '/')
1455 strbuf_setlen(&buf, q - buf.buf);
1458 files_ref_path(refs, &sb, buf.buf);
1459 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1460 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1463 files_reflog_path(refs, &sb, buf.buf);
1464 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1465 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1467 strbuf_release(&buf);
1468 strbuf_release(&sb);
1471 /* make sure nobody touched the ref, and unlink */
1472 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1474 struct ref_transaction *transaction;
1475 struct strbuf err = STRBUF_INIT;
1477 if (check_refname_format(r->name, 0))
1480 transaction = ref_store_transaction_begin(&refs->base, &err);
1482 ref_transaction_delete(transaction, r->name, r->sha1,
1483 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1484 ref_transaction_commit(transaction, &err)) {
1485 ref_transaction_free(transaction);
1486 error("%s", err.buf);
1487 strbuf_release(&err);
1490 ref_transaction_free(transaction);
1491 strbuf_release(&err);
1494 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1503 * Return true if the specified reference should be packed.
1505 static int should_pack_ref(const char *refname,
1506 const struct object_id *oid, unsigned int ref_flags,
1507 unsigned int pack_flags)
1509 /* Do not pack per-worktree refs: */
1510 if (ref_type(refname) != REF_TYPE_NORMAL)
1513 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1514 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1517 /* Do not pack symbolic refs: */
1518 if (ref_flags & REF_ISSYMREF)
1521 /* Do not pack broken refs: */
1522 if (!ref_resolves_to_object(refname, oid, ref_flags))
1528 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1530 struct files_ref_store *refs =
1531 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1533 struct ref_iterator *iter;
1534 struct ref_dir *packed_refs;
1536 struct ref_to_prune *refs_to_prune = NULL;
1538 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1539 packed_refs = get_packed_refs(refs);
1541 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1542 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1544 * If the loose reference can be packed, add an entry
1545 * in the packed ref cache. If the reference should be
1546 * pruned, also add it to refs_to_prune.
1548 struct ref_entry *packed_entry;
1550 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1555 * Create an entry in the packed-refs cache equivalent
1556 * to the one from the loose ref cache, except that
1557 * we don't copy the peeled status, because we want it
1560 packed_entry = find_ref_entry(packed_refs, iter->refname);
1562 /* Overwrite existing packed entry with info from loose entry */
1563 packed_entry->flag = REF_ISPACKED;
1564 oidcpy(&packed_entry->u.value.oid, iter->oid);
1566 packed_entry = create_ref_entry(iter->refname, iter->oid,
1568 add_ref_entry(packed_refs, packed_entry);
1570 oidclr(&packed_entry->u.value.peeled);
1572 /* Schedule the loose reference for pruning if requested. */
1573 if ((flags & PACK_REFS_PRUNE)) {
1574 struct ref_to_prune *n;
1575 FLEX_ALLOC_STR(n, name, iter->refname);
1576 hashcpy(n->sha1, iter->oid->hash);
1577 n->next = refs_to_prune;
1581 if (ok != ITER_DONE)
1582 die("error while iterating over references");
1584 if (commit_packed_refs(refs))
1585 die_errno("unable to overwrite old ref-pack file");
1587 prune_refs(refs, refs_to_prune);
1592 * Rewrite the packed-refs file, omitting any refs listed in
1593 * 'refnames'. On error, leave packed-refs unchanged, write an error
1594 * message to 'err', and return a nonzero value.
1596 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1598 static int repack_without_refs(struct files_ref_store *refs,
1599 struct string_list *refnames, struct strbuf *err)
1601 struct ref_dir *packed;
1602 struct string_list_item *refname;
1603 int ret, needs_repacking = 0, removed = 0;
1605 files_assert_main_repository(refs, "repack_without_refs");
1608 /* Look for a packed ref */
1609 for_each_string_list_item(refname, refnames) {
1610 if (get_packed_ref(refs, refname->string)) {
1611 needs_repacking = 1;
1616 /* Avoid locking if we have nothing to do */
1617 if (!needs_repacking)
1618 return 0; /* no refname exists in packed refs */
1620 if (lock_packed_refs(refs, 0)) {
1621 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1624 packed = get_packed_refs(refs);
1626 /* Remove refnames from the cache */
1627 for_each_string_list_item(refname, refnames)
1628 if (remove_entry_from_dir(packed, refname->string) != -1)
1632 * All packed entries disappeared while we were
1633 * acquiring the lock.
1635 rollback_packed_refs(refs);
1639 /* Write what remains */
1640 ret = commit_packed_refs(refs);
1642 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1647 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1648 struct string_list *refnames, unsigned int flags)
1650 struct files_ref_store *refs =
1651 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1652 struct strbuf err = STRBUF_INIT;
1658 result = repack_without_refs(refs, refnames, &err);
1661 * If we failed to rewrite the packed-refs file, then
1662 * it is unsafe to try to remove loose refs, because
1663 * doing so might expose an obsolete packed value for
1664 * a reference that might even point at an object that
1665 * has been garbage collected.
1667 if (refnames->nr == 1)
1668 error(_("could not delete reference %s: %s"),
1669 refnames->items[0].string, err.buf);
1671 error(_("could not delete references: %s"), err.buf);
1676 for (i = 0; i < refnames->nr; i++) {
1677 const char *refname = refnames->items[i].string;
1679 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1680 result |= error(_("could not remove reference %s"), refname);
1684 strbuf_release(&err);
1689 * People using contrib's git-new-workdir have .git/logs/refs ->
1690 * /some/other/path/.git/logs/refs, and that may live on another device.
1692 * IOW, to avoid cross device rename errors, the temporary renamed log must
1693 * live into logs/refs.
1695 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1698 const char *tmp_renamed_log;
1702 static int rename_tmp_log_callback(const char *path, void *cb_data)
1704 struct rename_cb *cb = cb_data;
1706 if (rename(cb->tmp_renamed_log, path)) {
1708 * rename(a, b) when b is an existing directory ought
1709 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1710 * Sheesh. Record the true errno for error reporting,
1711 * but report EISDIR to raceproof_create_file() so
1712 * that it knows to retry.
1714 cb->true_errno = errno;
1715 if (errno == ENOTDIR)
1723 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1725 struct strbuf path = STRBUF_INIT;
1726 struct strbuf tmp = STRBUF_INIT;
1727 struct rename_cb cb;
1730 files_reflog_path(refs, &path, newrefname);
1731 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1732 cb.tmp_renamed_log = tmp.buf;
1733 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1735 if (errno == EISDIR)
1736 error("directory not empty: %s", path.buf);
1738 error("unable to move logfile %s to %s: %s",
1740 strerror(cb.true_errno));
1743 strbuf_release(&path);
1744 strbuf_release(&tmp);
1748 static int write_ref_to_lockfile(struct ref_lock *lock,
1749 const struct object_id *oid, struct strbuf *err);
1750 static int commit_ref_update(struct files_ref_store *refs,
1751 struct ref_lock *lock,
1752 const struct object_id *oid, const char *logmsg,
1753 struct strbuf *err);
1755 static int files_rename_ref(struct ref_store *ref_store,
1756 const char *oldrefname, const char *newrefname,
1759 struct files_ref_store *refs =
1760 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1761 struct object_id oid, orig_oid;
1762 int flag = 0, logmoved = 0;
1763 struct ref_lock *lock;
1764 struct stat loginfo;
1765 struct strbuf sb_oldref = STRBUF_INIT;
1766 struct strbuf sb_newref = STRBUF_INIT;
1767 struct strbuf tmp_renamed_log = STRBUF_INIT;
1769 struct strbuf err = STRBUF_INIT;
1771 files_reflog_path(refs, &sb_oldref, oldrefname);
1772 files_reflog_path(refs, &sb_newref, newrefname);
1773 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1775 log = !lstat(sb_oldref.buf, &loginfo);
1776 if (log && S_ISLNK(loginfo.st_mode)) {
1777 ret = error("reflog for %s is a symlink", oldrefname);
1781 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1782 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1783 orig_oid.hash, &flag)) {
1784 ret = error("refname %s not found", oldrefname);
1788 if (flag & REF_ISSYMREF) {
1789 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1793 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1798 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1799 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1800 oldrefname, strerror(errno));
1804 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1805 orig_oid.hash, REF_NODEREF)) {
1806 error("unable to delete old %s", oldrefname);
1811 * Since we are doing a shallow lookup, oid is not the
1812 * correct value to pass to delete_ref as old_oid. But that
1813 * doesn't matter, because an old_oid check wouldn't add to
1814 * the safety anyway; we want to delete the reference whatever
1815 * its current value.
1817 if (!refs_read_ref_full(&refs->base, newrefname,
1818 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1820 refs_delete_ref(&refs->base, NULL, newrefname,
1821 NULL, REF_NODEREF)) {
1822 if (errno == EISDIR) {
1823 struct strbuf path = STRBUF_INIT;
1826 files_ref_path(refs, &path, newrefname);
1827 result = remove_empty_directories(&path);
1828 strbuf_release(&path);
1831 error("Directory not empty: %s", newrefname);
1835 error("unable to delete existing %s", newrefname);
1840 if (log && rename_tmp_log(refs, newrefname))
1845 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1846 REF_NODEREF, NULL, &err);
1848 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1849 strbuf_release(&err);
1852 oidcpy(&lock->old_oid, &orig_oid);
1854 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1855 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1856 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1857 strbuf_release(&err);
1865 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1866 REF_NODEREF, NULL, &err);
1868 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1869 strbuf_release(&err);
1873 flag = log_all_ref_updates;
1874 log_all_ref_updates = LOG_REFS_NONE;
1875 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1876 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1877 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1878 strbuf_release(&err);
1880 log_all_ref_updates = flag;
1883 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1884 error("unable to restore logfile %s from %s: %s",
1885 oldrefname, newrefname, strerror(errno));
1886 if (!logmoved && log &&
1887 rename(tmp_renamed_log.buf, sb_oldref.buf))
1888 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1889 oldrefname, strerror(errno));
1892 strbuf_release(&sb_newref);
1893 strbuf_release(&sb_oldref);
1894 strbuf_release(&tmp_renamed_log);
1899 static int close_ref(struct ref_lock *lock)
1901 if (close_lock_file(lock->lk))
1906 static int commit_ref(struct ref_lock *lock)
1908 char *path = get_locked_file_path(lock->lk);
1911 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1913 * There is a directory at the path we want to rename
1914 * the lockfile to. Hopefully it is empty; try to
1917 size_t len = strlen(path);
1918 struct strbuf sb_path = STRBUF_INIT;
1920 strbuf_attach(&sb_path, path, len, len);
1923 * If this fails, commit_lock_file() will also fail
1924 * and will report the problem.
1926 remove_empty_directories(&sb_path);
1927 strbuf_release(&sb_path);
1932 if (commit_lock_file(lock->lk))
1937 static int open_or_create_logfile(const char *path, void *cb)
1941 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1942 return (*fd < 0) ? -1 : 0;
1946 * Create a reflog for a ref. If force_create = 0, only create the
1947 * reflog for certain refs (those for which should_autocreate_reflog
1948 * returns non-zero). Otherwise, create it regardless of the reference
1949 * name. If the logfile already existed or was created, return 0 and
1950 * set *logfd to the file descriptor opened for appending to the file.
1951 * If no logfile exists and we decided not to create one, return 0 and
1952 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1955 static int log_ref_setup(struct files_ref_store *refs,
1956 const char *refname, int force_create,
1957 int *logfd, struct strbuf *err)
1959 struct strbuf logfile_sb = STRBUF_INIT;
1962 files_reflog_path(refs, &logfile_sb, refname);
1963 logfile = strbuf_detach(&logfile_sb, NULL);
1965 if (force_create || should_autocreate_reflog(refname)) {
1966 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1967 if (errno == ENOENT)
1968 strbuf_addf(err, "unable to create directory for '%s': "
1969 "%s", logfile, strerror(errno));
1970 else if (errno == EISDIR)
1971 strbuf_addf(err, "there are still logs under '%s'",
1974 strbuf_addf(err, "unable to append to '%s': %s",
1975 logfile, strerror(errno));
1980 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1982 if (errno == ENOENT || errno == EISDIR) {
1984 * The logfile doesn't already exist,
1985 * but that is not an error; it only
1986 * means that we won't write log
1991 strbuf_addf(err, "unable to append to '%s': %s",
1992 logfile, strerror(errno));
1999 adjust_shared_perm(logfile);
2009 static int files_create_reflog(struct ref_store *ref_store,
2010 const char *refname, int force_create,
2013 struct files_ref_store *refs =
2014 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2017 if (log_ref_setup(refs, refname, force_create, &fd, err))
2026 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2027 const struct object_id *new_oid,
2028 const char *committer, const char *msg)
2030 int msglen, written;
2031 unsigned maxlen, len;
2034 msglen = msg ? strlen(msg) : 0;
2035 maxlen = strlen(committer) + msglen + 100;
2036 logrec = xmalloc(maxlen);
2037 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2038 oid_to_hex(old_oid),
2039 oid_to_hex(new_oid),
2042 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2044 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2052 static int files_log_ref_write(struct files_ref_store *refs,
2053 const char *refname, const struct object_id *old_oid,
2054 const struct object_id *new_oid, const char *msg,
2055 int flags, struct strbuf *err)
2059 if (log_all_ref_updates == LOG_REFS_UNSET)
2060 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2062 result = log_ref_setup(refs, refname,
2063 flags & REF_FORCE_CREATE_REFLOG,
2071 result = log_ref_write_fd(logfd, old_oid, new_oid,
2072 git_committer_info(0), msg);
2074 struct strbuf sb = STRBUF_INIT;
2075 int save_errno = errno;
2077 files_reflog_path(refs, &sb, refname);
2078 strbuf_addf(err, "unable to append to '%s': %s",
2079 sb.buf, strerror(save_errno));
2080 strbuf_release(&sb);
2085 struct strbuf sb = STRBUF_INIT;
2086 int save_errno = errno;
2088 files_reflog_path(refs, &sb, refname);
2089 strbuf_addf(err, "unable to append to '%s': %s",
2090 sb.buf, strerror(save_errno));
2091 strbuf_release(&sb);
2098 * Write sha1 into the open lockfile, then close the lockfile. On
2099 * errors, rollback the lockfile, fill in *err and
2102 static int write_ref_to_lockfile(struct ref_lock *lock,
2103 const struct object_id *oid, struct strbuf *err)
2105 static char term = '\n';
2109 o = parse_object(oid);
2112 "trying to write ref '%s' with nonexistent object %s",
2113 lock->ref_name, oid_to_hex(oid));
2117 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2119 "trying to write non-commit object %s to branch '%s'",
2120 oid_to_hex(oid), lock->ref_name);
2124 fd = get_lock_file_fd(lock->lk);
2125 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2126 write_in_full(fd, &term, 1) != 1 ||
2127 close_ref(lock) < 0) {
2129 "couldn't write '%s'", get_lock_file_path(lock->lk));
2137 * Commit a change to a loose reference that has already been written
2138 * to the loose reference lockfile. Also update the reflogs if
2139 * necessary, using the specified lockmsg (which can be NULL).
2141 static int commit_ref_update(struct files_ref_store *refs,
2142 struct ref_lock *lock,
2143 const struct object_id *oid, const char *logmsg,
2146 files_assert_main_repository(refs, "commit_ref_update");
2148 clear_loose_ref_cache(refs);
2149 if (files_log_ref_write(refs, lock->ref_name,
2150 &lock->old_oid, oid,
2152 char *old_msg = strbuf_detach(err, NULL);
2153 strbuf_addf(err, "cannot update the ref '%s': %s",
2154 lock->ref_name, old_msg);
2160 if (strcmp(lock->ref_name, "HEAD") != 0) {
2162 * Special hack: If a branch is updated directly and HEAD
2163 * points to it (may happen on the remote side of a push
2164 * for example) then logically the HEAD reflog should be
2166 * A generic solution implies reverse symref information,
2167 * but finding all symrefs pointing to the given branch
2168 * would be rather costly for this rare event (the direct
2169 * update of a branch) to be worth it. So let's cheat and
2170 * check with HEAD only which should cover 99% of all usage
2171 * scenarios (even 100% of the default ones).
2173 struct object_id head_oid;
2175 const char *head_ref;
2177 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2178 RESOLVE_REF_READING,
2179 head_oid.hash, &head_flag);
2180 if (head_ref && (head_flag & REF_ISSYMREF) &&
2181 !strcmp(head_ref, lock->ref_name)) {
2182 struct strbuf log_err = STRBUF_INIT;
2183 if (files_log_ref_write(refs, "HEAD",
2184 &lock->old_oid, oid,
2185 logmsg, 0, &log_err)) {
2186 error("%s", log_err.buf);
2187 strbuf_release(&log_err);
2192 if (commit_ref(lock)) {
2193 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2202 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2205 #ifndef NO_SYMLINK_HEAD
2206 char *ref_path = get_locked_file_path(lock->lk);
2208 ret = symlink(target, ref_path);
2212 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2217 static void update_symref_reflog(struct files_ref_store *refs,
2218 struct ref_lock *lock, const char *refname,
2219 const char *target, const char *logmsg)
2221 struct strbuf err = STRBUF_INIT;
2222 struct object_id new_oid;
2224 !refs_read_ref_full(&refs->base, target,
2225 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2226 files_log_ref_write(refs, refname, &lock->old_oid,
2227 &new_oid, logmsg, 0, &err)) {
2228 error("%s", err.buf);
2229 strbuf_release(&err);
2233 static int create_symref_locked(struct files_ref_store *refs,
2234 struct ref_lock *lock, const char *refname,
2235 const char *target, const char *logmsg)
2237 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2238 update_symref_reflog(refs, lock, refname, target, logmsg);
2242 if (!fdopen_lock_file(lock->lk, "w"))
2243 return error("unable to fdopen %s: %s",
2244 lock->lk->tempfile.filename.buf, strerror(errno));
2246 update_symref_reflog(refs, lock, refname, target, logmsg);
2248 /* no error check; commit_ref will check ferror */
2249 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2250 if (commit_ref(lock) < 0)
2251 return error("unable to write symref for %s: %s", refname,
2256 static int files_create_symref(struct ref_store *ref_store,
2257 const char *refname, const char *target,
2260 struct files_ref_store *refs =
2261 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2262 struct strbuf err = STRBUF_INIT;
2263 struct ref_lock *lock;
2266 lock = lock_ref_sha1_basic(refs, refname, NULL,
2267 NULL, NULL, REF_NODEREF, NULL,
2270 error("%s", err.buf);
2271 strbuf_release(&err);
2275 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2280 static int files_reflog_exists(struct ref_store *ref_store,
2281 const char *refname)
2283 struct files_ref_store *refs =
2284 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2285 struct strbuf sb = STRBUF_INIT;
2289 files_reflog_path(refs, &sb, refname);
2290 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2291 strbuf_release(&sb);
2295 static int files_delete_reflog(struct ref_store *ref_store,
2296 const char *refname)
2298 struct files_ref_store *refs =
2299 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2300 struct strbuf sb = STRBUF_INIT;
2303 files_reflog_path(refs, &sb, refname);
2304 ret = remove_path(sb.buf);
2305 strbuf_release(&sb);
2309 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2311 struct object_id ooid, noid;
2312 char *email_end, *message;
2313 timestamp_t timestamp;
2315 const char *p = sb->buf;
2317 /* old SP new SP name <email> SP time TAB msg LF */
2318 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2319 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2320 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2321 !(email_end = strchr(p, '>')) ||
2322 email_end[1] != ' ' ||
2323 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2324 !message || message[0] != ' ' ||
2325 (message[1] != '+' && message[1] != '-') ||
2326 !isdigit(message[2]) || !isdigit(message[3]) ||
2327 !isdigit(message[4]) || !isdigit(message[5]))
2328 return 0; /* corrupt? */
2329 email_end[1] = '\0';
2330 tz = strtol(message + 1, NULL, 10);
2331 if (message[6] != '\t')
2335 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2338 static char *find_beginning_of_line(char *bob, char *scan)
2340 while (bob < scan && *(--scan) != '\n')
2341 ; /* keep scanning backwards */
2343 * Return either beginning of the buffer, or LF at the end of
2344 * the previous line.
2349 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2350 const char *refname,
2351 each_reflog_ent_fn fn,
2354 struct files_ref_store *refs =
2355 files_downcast(ref_store, REF_STORE_READ,
2356 "for_each_reflog_ent_reverse");
2357 struct strbuf sb = STRBUF_INIT;
2360 int ret = 0, at_tail = 1;
2362 files_reflog_path(refs, &sb, refname);
2363 logfp = fopen(sb.buf, "r");
2364 strbuf_release(&sb);
2368 /* Jump to the end */
2369 if (fseek(logfp, 0, SEEK_END) < 0)
2370 ret = error("cannot seek back reflog for %s: %s",
2371 refname, strerror(errno));
2373 while (!ret && 0 < pos) {
2379 /* Fill next block from the end */
2380 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2381 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2382 ret = error("cannot seek back reflog for %s: %s",
2383 refname, strerror(errno));
2386 nread = fread(buf, cnt, 1, logfp);
2388 ret = error("cannot read %d bytes from reflog for %s: %s",
2389 cnt, refname, strerror(errno));
2394 scanp = endp = buf + cnt;
2395 if (at_tail && scanp[-1] == '\n')
2396 /* Looking at the final LF at the end of the file */
2400 while (buf < scanp) {
2402 * terminating LF of the previous line, or the beginning
2407 bp = find_beginning_of_line(buf, scanp);
2411 * The newline is the end of the previous line,
2412 * so we know we have complete line starting
2413 * at (bp + 1). Prefix it onto any prior data
2414 * we collected for the line and process it.
2416 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2419 ret = show_one_reflog_ent(&sb, fn, cb_data);
2425 * We are at the start of the buffer, and the
2426 * start of the file; there is no previous
2427 * line, and we have everything for this one.
2428 * Process it, and we can end the loop.
2430 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2431 ret = show_one_reflog_ent(&sb, fn, cb_data);
2438 * We are at the start of the buffer, and there
2439 * is more file to read backwards. Which means
2440 * we are in the middle of a line. Note that we
2441 * may get here even if *bp was a newline; that
2442 * just means we are at the exact end of the
2443 * previous line, rather than some spot in the
2446 * Save away what we have to be combined with
2447 * the data from the next read.
2449 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2456 die("BUG: reverse reflog parser had leftover data");
2459 strbuf_release(&sb);
2463 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2464 const char *refname,
2465 each_reflog_ent_fn fn, void *cb_data)
2467 struct files_ref_store *refs =
2468 files_downcast(ref_store, REF_STORE_READ,
2469 "for_each_reflog_ent");
2471 struct strbuf sb = STRBUF_INIT;
2474 files_reflog_path(refs, &sb, refname);
2475 logfp = fopen(sb.buf, "r");
2476 strbuf_release(&sb);
2480 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2481 ret = show_one_reflog_ent(&sb, fn, cb_data);
2483 strbuf_release(&sb);
2487 struct files_reflog_iterator {
2488 struct ref_iterator base;
2490 struct ref_store *ref_store;
2491 struct dir_iterator *dir_iterator;
2492 struct object_id oid;
2495 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2497 struct files_reflog_iterator *iter =
2498 (struct files_reflog_iterator *)ref_iterator;
2499 struct dir_iterator *diter = iter->dir_iterator;
2502 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2505 if (!S_ISREG(diter->st.st_mode))
2507 if (diter->basename[0] == '.')
2509 if (ends_with(diter->basename, ".lock"))
2512 if (refs_read_ref_full(iter->ref_store,
2513 diter->relative_path, 0,
2514 iter->oid.hash, &flags)) {
2515 error("bad ref for %s", diter->path.buf);
2519 iter->base.refname = diter->relative_path;
2520 iter->base.oid = &iter->oid;
2521 iter->base.flags = flags;
2525 iter->dir_iterator = NULL;
2526 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2531 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2532 struct object_id *peeled)
2534 die("BUG: ref_iterator_peel() called for reflog_iterator");
2537 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2539 struct files_reflog_iterator *iter =
2540 (struct files_reflog_iterator *)ref_iterator;
2543 if (iter->dir_iterator)
2544 ok = dir_iterator_abort(iter->dir_iterator);
2546 base_ref_iterator_free(ref_iterator);
2550 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2551 files_reflog_iterator_advance,
2552 files_reflog_iterator_peel,
2553 files_reflog_iterator_abort
2556 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2558 struct files_ref_store *refs =
2559 files_downcast(ref_store, REF_STORE_READ,
2560 "reflog_iterator_begin");
2561 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2562 struct ref_iterator *ref_iterator = &iter->base;
2563 struct strbuf sb = STRBUF_INIT;
2565 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2566 files_reflog_path(refs, &sb, NULL);
2567 iter->dir_iterator = dir_iterator_begin(sb.buf);
2568 iter->ref_store = ref_store;
2569 strbuf_release(&sb);
2570 return ref_iterator;
2574 * If update is a direct update of head_ref (the reference pointed to
2575 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2577 static int split_head_update(struct ref_update *update,
2578 struct ref_transaction *transaction,
2579 const char *head_ref,
2580 struct string_list *affected_refnames,
2583 struct string_list_item *item;
2584 struct ref_update *new_update;
2586 if ((update->flags & REF_LOG_ONLY) ||
2587 (update->flags & REF_ISPRUNING) ||
2588 (update->flags & REF_UPDATE_VIA_HEAD))
2591 if (strcmp(update->refname, head_ref))
2595 * First make sure that HEAD is not already in the
2596 * transaction. This insertion is O(N) in the transaction
2597 * size, but it happens at most once per transaction.
2599 item = string_list_insert(affected_refnames, "HEAD");
2601 /* An entry already existed */
2603 "multiple updates for 'HEAD' (including one "
2604 "via its referent '%s') are not allowed",
2606 return TRANSACTION_NAME_CONFLICT;
2609 new_update = ref_transaction_add_update(
2610 transaction, "HEAD",
2611 update->flags | REF_LOG_ONLY | REF_NODEREF,
2612 update->new_oid.hash, update->old_oid.hash,
2615 item->util = new_update;
2621 * update is for a symref that points at referent and doesn't have
2622 * REF_NODEREF set. Split it into two updates:
2623 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2624 * - A new, separate update for the referent reference
2625 * Note that the new update will itself be subject to splitting when
2626 * the iteration gets to it.
2628 static int split_symref_update(struct files_ref_store *refs,
2629 struct ref_update *update,
2630 const char *referent,
2631 struct ref_transaction *transaction,
2632 struct string_list *affected_refnames,
2635 struct string_list_item *item;
2636 struct ref_update *new_update;
2637 unsigned int new_flags;
2640 * First make sure that referent is not already in the
2641 * transaction. This insertion is O(N) in the transaction
2642 * size, but it happens at most once per symref in a
2645 item = string_list_insert(affected_refnames, referent);
2647 /* An entry already existed */
2649 "multiple updates for '%s' (including one "
2650 "via symref '%s') are not allowed",
2651 referent, update->refname);
2652 return TRANSACTION_NAME_CONFLICT;
2655 new_flags = update->flags;
2656 if (!strcmp(update->refname, "HEAD")) {
2658 * Record that the new update came via HEAD, so that
2659 * when we process it, split_head_update() doesn't try
2660 * to add another reflog update for HEAD. Note that
2661 * this bit will be propagated if the new_update
2662 * itself needs to be split.
2664 new_flags |= REF_UPDATE_VIA_HEAD;
2667 new_update = ref_transaction_add_update(
2668 transaction, referent, new_flags,
2669 update->new_oid.hash, update->old_oid.hash,
2672 new_update->parent_update = update;
2675 * Change the symbolic ref update to log only. Also, it
2676 * doesn't need to check its old SHA-1 value, as that will be
2677 * done when new_update is processed.
2679 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2680 update->flags &= ~REF_HAVE_OLD;
2682 item->util = new_update;
2688 * Return the refname under which update was originally requested.
2690 static const char *original_update_refname(struct ref_update *update)
2692 while (update->parent_update)
2693 update = update->parent_update;
2695 return update->refname;
2699 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2700 * are consistent with oid, which is the reference's current value. If
2701 * everything is OK, return 0; otherwise, write an error message to
2702 * err and return -1.
2704 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2707 if (!(update->flags & REF_HAVE_OLD) ||
2708 !oidcmp(oid, &update->old_oid))
2711 if (is_null_oid(&update->old_oid))
2712 strbuf_addf(err, "cannot lock ref '%s': "
2713 "reference already exists",
2714 original_update_refname(update));
2715 else if (is_null_oid(oid))
2716 strbuf_addf(err, "cannot lock ref '%s': "
2717 "reference is missing but expected %s",
2718 original_update_refname(update),
2719 oid_to_hex(&update->old_oid));
2721 strbuf_addf(err, "cannot lock ref '%s': "
2722 "is at %s but expected %s",
2723 original_update_refname(update),
2725 oid_to_hex(&update->old_oid));
2731 * Prepare for carrying out update:
2732 * - Lock the reference referred to by update.
2733 * - Read the reference under lock.
2734 * - Check that its old SHA-1 value (if specified) is correct, and in
2735 * any case record it in update->lock->old_oid for later use when
2736 * writing the reflog.
2737 * - If it is a symref update without REF_NODEREF, split it up into a
2738 * REF_LOG_ONLY update of the symref and add a separate update for
2739 * the referent to transaction.
2740 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2743 static int lock_ref_for_update(struct files_ref_store *refs,
2744 struct ref_update *update,
2745 struct ref_transaction *transaction,
2746 const char *head_ref,
2747 struct string_list *affected_refnames,
2750 struct strbuf referent = STRBUF_INIT;
2751 int mustexist = (update->flags & REF_HAVE_OLD) &&
2752 !is_null_oid(&update->old_oid);
2754 struct ref_lock *lock;
2756 files_assert_main_repository(refs, "lock_ref_for_update");
2758 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2759 update->flags |= REF_DELETING;
2762 ret = split_head_update(update, transaction, head_ref,
2763 affected_refnames, err);
2768 ret = lock_raw_ref(refs, update->refname, mustexist,
2769 affected_refnames, NULL,
2771 &update->type, err);
2775 reason = strbuf_detach(err, NULL);
2776 strbuf_addf(err, "cannot lock ref '%s': %s",
2777 original_update_refname(update), reason);
2782 update->backend_data = lock;
2784 if (update->type & REF_ISSYMREF) {
2785 if (update->flags & REF_NODEREF) {
2787 * We won't be reading the referent as part of
2788 * the transaction, so we have to read it here
2789 * to record and possibly check old_sha1:
2791 if (refs_read_ref_full(&refs->base,
2793 lock->old_oid.hash, NULL)) {
2794 if (update->flags & REF_HAVE_OLD) {
2795 strbuf_addf(err, "cannot lock ref '%s': "
2796 "error reading reference",
2797 original_update_refname(update));
2800 } else if (check_old_oid(update, &lock->old_oid, err)) {
2801 return TRANSACTION_GENERIC_ERROR;
2805 * Create a new update for the reference this
2806 * symref is pointing at. Also, we will record
2807 * and verify old_sha1 for this update as part
2808 * of processing the split-off update, so we
2809 * don't have to do it here.
2811 ret = split_symref_update(refs, update,
2812 referent.buf, transaction,
2813 affected_refnames, err);
2818 struct ref_update *parent_update;
2820 if (check_old_oid(update, &lock->old_oid, err))
2821 return TRANSACTION_GENERIC_ERROR;
2824 * If this update is happening indirectly because of a
2825 * symref update, record the old SHA-1 in the parent
2828 for (parent_update = update->parent_update;
2830 parent_update = parent_update->parent_update) {
2831 struct ref_lock *parent_lock = parent_update->backend_data;
2832 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2836 if ((update->flags & REF_HAVE_NEW) &&
2837 !(update->flags & REF_DELETING) &&
2838 !(update->flags & REF_LOG_ONLY)) {
2839 if (!(update->type & REF_ISSYMREF) &&
2840 !oidcmp(&lock->old_oid, &update->new_oid)) {
2842 * The reference already has the desired
2843 * value, so we don't need to write it.
2845 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2847 char *write_err = strbuf_detach(err, NULL);
2850 * The lock was freed upon failure of
2851 * write_ref_to_lockfile():
2853 update->backend_data = NULL;
2855 "cannot update ref '%s': %s",
2856 update->refname, write_err);
2858 return TRANSACTION_GENERIC_ERROR;
2860 update->flags |= REF_NEEDS_COMMIT;
2863 if (!(update->flags & REF_NEEDS_COMMIT)) {
2865 * We didn't call write_ref_to_lockfile(), so
2866 * the lockfile is still open. Close it to
2867 * free up the file descriptor:
2869 if (close_ref(lock)) {
2870 strbuf_addf(err, "couldn't close '%s.lock'",
2872 return TRANSACTION_GENERIC_ERROR;
2879 * Unlock any references in `transaction` that are still locked, and
2880 * mark the transaction closed.
2882 static void files_transaction_cleanup(struct ref_transaction *transaction)
2886 for (i = 0; i < transaction->nr; i++) {
2887 struct ref_update *update = transaction->updates[i];
2888 struct ref_lock *lock = update->backend_data;
2892 update->backend_data = NULL;
2896 transaction->state = REF_TRANSACTION_CLOSED;
2899 static int files_transaction_prepare(struct ref_store *ref_store,
2900 struct ref_transaction *transaction,
2903 struct files_ref_store *refs =
2904 files_downcast(ref_store, REF_STORE_WRITE,
2905 "ref_transaction_prepare");
2908 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2909 char *head_ref = NULL;
2911 struct object_id head_oid;
2915 if (!transaction->nr)
2919 * Fail if a refname appears more than once in the
2920 * transaction. (If we end up splitting up any updates using
2921 * split_symref_update() or split_head_update(), those
2922 * functions will check that the new updates don't have the
2923 * same refname as any existing ones.)
2925 for (i = 0; i < transaction->nr; i++) {
2926 struct ref_update *update = transaction->updates[i];
2927 struct string_list_item *item =
2928 string_list_append(&affected_refnames, update->refname);
2931 * We store a pointer to update in item->util, but at
2932 * the moment we never use the value of this field
2933 * except to check whether it is non-NULL.
2935 item->util = update;
2937 string_list_sort(&affected_refnames);
2938 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2939 ret = TRANSACTION_GENERIC_ERROR;
2944 * Special hack: If a branch is updated directly and HEAD
2945 * points to it (may happen on the remote side of a push
2946 * for example) then logically the HEAD reflog should be
2949 * A generic solution would require reverse symref lookups,
2950 * but finding all symrefs pointing to a given branch would be
2951 * rather costly for this rare event (the direct update of a
2952 * branch) to be worth it. So let's cheat and check with HEAD
2953 * only, which should cover 99% of all usage scenarios (even
2954 * 100% of the default ones).
2956 * So if HEAD is a symbolic reference, then record the name of
2957 * the reference that it points to. If we see an update of
2958 * head_ref within the transaction, then split_head_update()
2959 * arranges for the reflog of HEAD to be updated, too.
2961 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2962 RESOLVE_REF_NO_RECURSE,
2963 head_oid.hash, &head_type);
2965 if (head_ref && !(head_type & REF_ISSYMREF)) {
2966 FREE_AND_NULL(head_ref);
2970 * Acquire all locks, verify old values if provided, check
2971 * that new values are valid, and write new values to the
2972 * lockfiles, ready to be activated. Only keep one lockfile
2973 * open at a time to avoid running out of file descriptors.
2974 * Note that lock_ref_for_update() might append more updates
2975 * to the transaction.
2977 for (i = 0; i < transaction->nr; i++) {
2978 struct ref_update *update = transaction->updates[i];
2980 ret = lock_ref_for_update(refs, update, transaction,
2981 head_ref, &affected_refnames, err);
2988 string_list_clear(&affected_refnames, 0);
2991 files_transaction_cleanup(transaction);
2993 transaction->state = REF_TRANSACTION_PREPARED;
2998 static int files_transaction_finish(struct ref_store *ref_store,
2999 struct ref_transaction *transaction,
3002 struct files_ref_store *refs =
3003 files_downcast(ref_store, 0, "ref_transaction_finish");
3006 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3007 struct string_list_item *ref_to_delete;
3008 struct strbuf sb = STRBUF_INIT;
3012 if (!transaction->nr) {
3013 transaction->state = REF_TRANSACTION_CLOSED;
3017 /* Perform updates first so live commits remain referenced */
3018 for (i = 0; i < transaction->nr; i++) {
3019 struct ref_update *update = transaction->updates[i];
3020 struct ref_lock *lock = update->backend_data;
3022 if (update->flags & REF_NEEDS_COMMIT ||
3023 update->flags & REF_LOG_ONLY) {
3024 if (files_log_ref_write(refs,
3028 update->msg, update->flags,
3030 char *old_msg = strbuf_detach(err, NULL);
3032 strbuf_addf(err, "cannot update the ref '%s': %s",
3033 lock->ref_name, old_msg);
3036 update->backend_data = NULL;
3037 ret = TRANSACTION_GENERIC_ERROR;
3041 if (update->flags & REF_NEEDS_COMMIT) {
3042 clear_loose_ref_cache(refs);
3043 if (commit_ref(lock)) {
3044 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3046 update->backend_data = NULL;
3047 ret = TRANSACTION_GENERIC_ERROR;
3052 /* Perform deletes now that updates are safely completed */
3053 for (i = 0; i < transaction->nr; i++) {
3054 struct ref_update *update = transaction->updates[i];
3055 struct ref_lock *lock = update->backend_data;
3057 if (update->flags & REF_DELETING &&
3058 !(update->flags & REF_LOG_ONLY)) {
3059 if (!(update->type & REF_ISPACKED) ||
3060 update->type & REF_ISSYMREF) {
3061 /* It is a loose reference. */
3063 files_ref_path(refs, &sb, lock->ref_name);
3064 if (unlink_or_msg(sb.buf, err)) {
3065 ret = TRANSACTION_GENERIC_ERROR;
3068 update->flags |= REF_DELETED_LOOSE;
3071 if (!(update->flags & REF_ISPRUNING))
3072 string_list_append(&refs_to_delete,
3077 if (repack_without_refs(refs, &refs_to_delete, err)) {
3078 ret = TRANSACTION_GENERIC_ERROR;
3082 /* Delete the reflogs of any references that were deleted: */
3083 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3085 files_reflog_path(refs, &sb, ref_to_delete->string);
3086 if (!unlink_or_warn(sb.buf))
3087 try_remove_empty_parents(refs, ref_to_delete->string,
3088 REMOVE_EMPTY_PARENTS_REFLOG);
3091 clear_loose_ref_cache(refs);
3094 files_transaction_cleanup(transaction);
3096 for (i = 0; i < transaction->nr; i++) {
3097 struct ref_update *update = transaction->updates[i];
3099 if (update->flags & REF_DELETED_LOOSE) {
3101 * The loose reference was deleted. Delete any
3102 * empty parent directories. (Note that this
3103 * can only work because we have already
3104 * removed the lockfile.)
3106 try_remove_empty_parents(refs, update->refname,
3107 REMOVE_EMPTY_PARENTS_REF);
3111 strbuf_release(&sb);
3112 string_list_clear(&refs_to_delete, 0);
3116 static int files_transaction_abort(struct ref_store *ref_store,
3117 struct ref_transaction *transaction,
3120 files_transaction_cleanup(transaction);
3124 static int ref_present(const char *refname,
3125 const struct object_id *oid, int flags, void *cb_data)
3127 struct string_list *affected_refnames = cb_data;
3129 return string_list_has_string(affected_refnames, refname);
3132 static int files_initial_transaction_commit(struct ref_store *ref_store,
3133 struct ref_transaction *transaction,
3136 struct files_ref_store *refs =
3137 files_downcast(ref_store, REF_STORE_WRITE,
3138 "initial_ref_transaction_commit");
3141 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3145 if (transaction->state != REF_TRANSACTION_OPEN)
3146 die("BUG: commit called for transaction that is not open");
3148 /* Fail if a refname appears more than once in the transaction: */
3149 for (i = 0; i < transaction->nr; i++)
3150 string_list_append(&affected_refnames,
3151 transaction->updates[i]->refname);
3152 string_list_sort(&affected_refnames);
3153 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3154 ret = TRANSACTION_GENERIC_ERROR;
3159 * It's really undefined to call this function in an active
3160 * repository or when there are existing references: we are
3161 * only locking and changing packed-refs, so (1) any
3162 * simultaneous processes might try to change a reference at
3163 * the same time we do, and (2) any existing loose versions of
3164 * the references that we are setting would have precedence
3165 * over our values. But some remote helpers create the remote
3166 * "HEAD" and "master" branches before calling this function,
3167 * so here we really only check that none of the references
3168 * that we are creating already exists.
3170 if (refs_for_each_rawref(&refs->base, ref_present,
3171 &affected_refnames))
3172 die("BUG: initial ref transaction called with existing refs");
3174 for (i = 0; i < transaction->nr; i++) {
3175 struct ref_update *update = transaction->updates[i];
3177 if ((update->flags & REF_HAVE_OLD) &&
3178 !is_null_oid(&update->old_oid))
3179 die("BUG: initial ref transaction with old_sha1 set");
3180 if (refs_verify_refname_available(&refs->base, update->refname,
3181 &affected_refnames, NULL,
3183 ret = TRANSACTION_NAME_CONFLICT;
3188 if (lock_packed_refs(refs, 0)) {
3189 strbuf_addf(err, "unable to lock packed-refs file: %s",
3191 ret = TRANSACTION_GENERIC_ERROR;
3195 for (i = 0; i < transaction->nr; i++) {
3196 struct ref_update *update = transaction->updates[i];
3198 if ((update->flags & REF_HAVE_NEW) &&
3199 !is_null_oid(&update->new_oid))
3200 add_packed_ref(refs, update->refname,
3204 if (commit_packed_refs(refs)) {
3205 strbuf_addf(err, "unable to commit packed-refs file: %s",
3207 ret = TRANSACTION_GENERIC_ERROR;
3212 transaction->state = REF_TRANSACTION_CLOSED;
3213 string_list_clear(&affected_refnames, 0);
3217 struct expire_reflog_cb {
3219 reflog_expiry_should_prune_fn *should_prune_fn;
3222 struct object_id last_kept_oid;
3225 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3226 const char *email, timestamp_t timestamp, int tz,
3227 const char *message, void *cb_data)
3229 struct expire_reflog_cb *cb = cb_data;
3230 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3232 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3233 ooid = &cb->last_kept_oid;
3235 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3236 message, policy_cb)) {
3238 printf("would prune %s", message);
3239 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3240 printf("prune %s", message);
3243 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3244 oid_to_hex(ooid), oid_to_hex(noid),
3245 email, timestamp, tz, message);
3246 oidcpy(&cb->last_kept_oid, noid);
3248 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3249 printf("keep %s", message);
3254 static int files_reflog_expire(struct ref_store *ref_store,
3255 const char *refname, const unsigned char *sha1,
3257 reflog_expiry_prepare_fn prepare_fn,
3258 reflog_expiry_should_prune_fn should_prune_fn,
3259 reflog_expiry_cleanup_fn cleanup_fn,
3260 void *policy_cb_data)
3262 struct files_ref_store *refs =
3263 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3264 static struct lock_file reflog_lock;
3265 struct expire_reflog_cb cb;
3266 struct ref_lock *lock;
3267 struct strbuf log_file_sb = STRBUF_INIT;
3271 struct strbuf err = STRBUF_INIT;
3272 struct object_id oid;
3274 memset(&cb, 0, sizeof(cb));
3276 cb.policy_cb = policy_cb_data;
3277 cb.should_prune_fn = should_prune_fn;
3280 * The reflog file is locked by holding the lock on the
3281 * reference itself, plus we might need to update the
3282 * reference if --updateref was specified:
3284 lock = lock_ref_sha1_basic(refs, refname, sha1,
3285 NULL, NULL, REF_NODEREF,
3288 error("cannot lock ref '%s': %s", refname, err.buf);
3289 strbuf_release(&err);
3292 if (!refs_reflog_exists(ref_store, refname)) {
3297 files_reflog_path(refs, &log_file_sb, refname);
3298 log_file = strbuf_detach(&log_file_sb, NULL);
3299 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3301 * Even though holding $GIT_DIR/logs/$reflog.lock has
3302 * no locking implications, we use the lock_file
3303 * machinery here anyway because it does a lot of the
3304 * work we need, including cleaning up if the program
3305 * exits unexpectedly.
3307 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3308 struct strbuf err = STRBUF_INIT;
3309 unable_to_lock_message(log_file, errno, &err);
3310 error("%s", err.buf);
3311 strbuf_release(&err);
3314 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3316 error("cannot fdopen %s (%s)",
3317 get_lock_file_path(&reflog_lock), strerror(errno));
3322 hashcpy(oid.hash, sha1);
3324 (*prepare_fn)(refname, &oid, cb.policy_cb);
3325 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3326 (*cleanup_fn)(cb.policy_cb);
3328 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3330 * It doesn't make sense to adjust a reference pointed
3331 * to by a symbolic ref based on expiring entries in
3332 * the symbolic reference's reflog. Nor can we update
3333 * a reference if there are no remaining reflog
3336 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3337 !(type & REF_ISSYMREF) &&
3338 !is_null_oid(&cb.last_kept_oid);
3340 if (close_lock_file(&reflog_lock)) {
3341 status |= error("couldn't write %s: %s", log_file,
3343 } else if (update &&
3344 (write_in_full(get_lock_file_fd(lock->lk),
3345 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3346 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3347 close_ref(lock) < 0)) {
3348 status |= error("couldn't write %s",
3349 get_lock_file_path(lock->lk));
3350 rollback_lock_file(&reflog_lock);
3351 } else if (commit_lock_file(&reflog_lock)) {
3352 status |= error("unable to write reflog '%s' (%s)",
3353 log_file, strerror(errno));
3354 } else if (update && commit_ref(lock)) {
3355 status |= error("couldn't set %s", lock->ref_name);
3363 rollback_lock_file(&reflog_lock);
3369 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3371 struct files_ref_store *refs =
3372 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3373 struct strbuf sb = STRBUF_INIT;
3376 * Create .git/refs/{heads,tags}
3378 files_ref_path(refs, &sb, "refs/heads");
3379 safe_create_dir(sb.buf, 1);
3382 files_ref_path(refs, &sb, "refs/tags");
3383 safe_create_dir(sb.buf, 1);
3385 strbuf_release(&sb);
3389 struct ref_storage_be refs_be_files = {
3392 files_ref_store_create,
3394 files_transaction_prepare,
3395 files_transaction_finish,
3396 files_transaction_abort,
3397 files_initial_transaction_commit,
3401 files_create_symref,
3405 files_ref_iterator_begin,
3408 files_reflog_iterator_begin,
3409 files_for_each_reflog_ent,
3410 files_for_each_reflog_ent_reverse,
3411 files_reflog_exists,
3412 files_create_reflog,
3413 files_delete_reflog,