3 #include "refs-internal.h"
5 #include "../iterator.h"
6 #include "../dir-iterator.h"
7 #include "../lockfile.h"
14 struct object_id old_oid;
18 * Return true if refname, which has the specified oid and flags, can
19 * be resolved to an object in the database. If the referred-to object
20 * does not exist, emit a warning and return false.
22 static int ref_resolves_to_object(const char *refname,
23 const struct object_id *oid,
26 if (flags & REF_ISBROKEN)
28 if (!has_sha1_file(oid->hash)) {
29 error("%s does not point to a valid object!", refname);
35 struct packed_ref_cache {
36 struct ref_cache *cache;
39 * Count of references to the data structure in this instance,
40 * including the pointer from files_ref_store::packed if any.
41 * The data will not be freed as long as the reference count
44 unsigned int referrers;
46 /* The metadata from when this packed-refs cache was read */
47 struct stat_validity validity;
51 * Future: need to be in "struct repository"
52 * when doing a full libification.
54 struct files_ref_store {
55 struct ref_store base;
56 unsigned int store_flags;
60 char *packed_refs_path;
62 struct ref_cache *loose;
63 struct packed_ref_cache *packed;
66 * Lock used for the "packed-refs" file. Note that this (and
67 * thus the enclosing `files_ref_store`) must not be freed.
69 struct lock_file packed_refs_lock;
73 * Increment the reference count of *packed_refs.
75 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
77 packed_refs->referrers++;
81 * Decrease the reference count of *packed_refs. If it goes to zero,
82 * free *packed_refs and return true; otherwise return false.
84 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
86 if (!--packed_refs->referrers) {
87 free_ref_cache(packed_refs->cache);
88 stat_validity_clear(&packed_refs->validity);
96 static void clear_packed_ref_cache(struct files_ref_store *refs)
99 struct packed_ref_cache *packed_refs = refs->packed;
101 if (is_lock_file_locked(&refs->packed_refs_lock))
102 die("BUG: packed-ref cache cleared while locked");
104 release_packed_ref_cache(packed_refs);
108 static void clear_loose_ref_cache(struct files_ref_store *refs)
111 free_ref_cache(refs->loose);
117 * Create a new submodule ref cache and add it to the internal
120 static struct ref_store *files_ref_store_create(const char *gitdir,
123 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
124 struct ref_store *ref_store = (struct ref_store *)refs;
125 struct strbuf sb = STRBUF_INIT;
127 base_ref_store_init(ref_store, &refs_be_files);
128 refs->store_flags = flags;
130 refs->gitdir = xstrdup(gitdir);
131 get_common_dir_noenv(&sb, gitdir);
132 refs->gitcommondir = strbuf_detach(&sb, NULL);
133 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
134 refs->packed_refs_path = strbuf_detach(&sb, NULL);
140 * Die if refs is not the main ref store. caller is used in any
141 * necessary error messages.
143 static void files_assert_main_repository(struct files_ref_store *refs,
146 if (refs->store_flags & REF_STORE_MAIN)
149 die("BUG: operation %s only allowed for main ref store", caller);
153 * Downcast ref_store to files_ref_store. Die if ref_store is not a
154 * files_ref_store. required_flags is compared with ref_store's
155 * store_flags to ensure the ref_store has all required capabilities.
156 * "caller" is used in any necessary error messages.
158 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
159 unsigned int required_flags,
162 struct files_ref_store *refs;
164 if (ref_store->be != &refs_be_files)
165 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
166 ref_store->be->name, caller);
168 refs = (struct files_ref_store *)ref_store;
170 if ((refs->store_flags & required_flags) != required_flags)
171 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
172 caller, required_flags, refs->store_flags);
177 /* The length of a peeled reference line in packed-refs, including EOL: */
178 #define PEELED_LINE_LENGTH 42
181 * The packed-refs header line that we write out. Perhaps other
182 * traits will be added later. The trailing space is required.
184 static const char PACKED_REFS_HEADER[] =
185 "# pack-refs with: peeled fully-peeled \n";
188 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
189 * Return a pointer to the refname within the line (null-terminated),
190 * or NULL if there was a problem.
192 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
196 if (parse_oid_hex(line->buf, oid, &ref) < 0)
198 if (!isspace(*ref++))
204 if (line->buf[line->len - 1] != '\n')
206 line->buf[--line->len] = 0;
212 * Read from `packed_refs_file` into a newly-allocated
213 * `packed_ref_cache` and return it. The return value will already
214 * have its reference count incremented.
216 * A comment line of the form "# pack-refs with: " may contain zero or
217 * more traits. We interpret the traits as follows:
221 * Probably no references are peeled. But if the file contains a
222 * peeled value for a reference, we will use it.
226 * References under "refs/tags/", if they *can* be peeled, *are*
227 * peeled in this file. References outside of "refs/tags/" are
228 * probably not peeled even if they could have been, but if we find
229 * a peeled value for such a reference we will use it.
233 * All references in the file that can be peeled are peeled.
234 * Inversely (and this is more important), any references in the
235 * file for which no peeled value is recorded is not peelable. This
236 * trait should typically be written alongside "peeled" for
237 * compatibility with older clients, but we do not require it
238 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
240 static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
243 struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
244 struct ref_entry *last = NULL;
245 struct strbuf line = STRBUF_INIT;
246 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
249 acquire_packed_ref_cache(packed_refs);
250 packed_refs->cache = create_ref_cache(NULL, NULL);
251 packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
253 f = fopen(packed_refs_file, "r");
255 if (errno == ENOENT) {
257 * This is OK; it just means that no
258 * "packed-refs" file has been written yet,
259 * which is equivalent to it being empty.
263 die_errno("couldn't read %s", packed_refs_file);
267 stat_validity_update(&packed_refs->validity, fileno(f));
269 dir = get_ref_dir(packed_refs->cache->root);
270 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
271 struct object_id oid;
275 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
276 if (strstr(traits, " fully-peeled "))
277 peeled = PEELED_FULLY;
278 else if (strstr(traits, " peeled "))
279 peeled = PEELED_TAGS;
280 /* perhaps other traits later as well */
284 refname = parse_ref_line(&line, &oid);
286 int flag = REF_ISPACKED;
288 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
289 if (!refname_is_safe(refname))
290 die("packed refname is dangerous: %s", refname);
292 flag |= REF_BAD_NAME | REF_ISBROKEN;
294 last = create_ref_entry(refname, &oid, flag);
295 if (peeled == PEELED_FULLY ||
296 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
297 last->flag |= REF_KNOWS_PEELED;
298 add_ref_entry(dir, last);
302 line.buf[0] == '^' &&
303 line.len == PEELED_LINE_LENGTH &&
304 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
305 !get_oid_hex(line.buf + 1, &oid)) {
306 oidcpy(&last->u.value.peeled, &oid);
308 * Regardless of what the file header said,
309 * we definitely know the value of *this*
312 last->flag |= REF_KNOWS_PEELED;
317 strbuf_release(&line);
322 static const char *files_packed_refs_path(struct files_ref_store *refs)
324 return refs->packed_refs_path;
327 static void files_reflog_path(struct files_ref_store *refs,
333 * FIXME: of course this is wrong in multi worktree
334 * setting. To be fixed real soon.
336 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
340 switch (ref_type(refname)) {
341 case REF_TYPE_PER_WORKTREE:
342 case REF_TYPE_PSEUDOREF:
343 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
345 case REF_TYPE_NORMAL:
346 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
349 die("BUG: unknown ref type %d of ref %s",
350 ref_type(refname), refname);
354 static void files_ref_path(struct files_ref_store *refs,
358 switch (ref_type(refname)) {
359 case REF_TYPE_PER_WORKTREE:
360 case REF_TYPE_PSEUDOREF:
361 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
363 case REF_TYPE_NORMAL:
364 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
367 die("BUG: unknown ref type %d of ref %s",
368 ref_type(refname), refname);
373 * Get the packed_ref_cache for the specified files_ref_store,
374 * creating and populating it if it hasn't been read before or if the
375 * file has been changed (according to its `validity` field) since it
376 * was last read. On the other hand, if we hold the lock, then assume
377 * that the file hasn't been changed out from under us, so skip the
378 * extra `stat()` call in `stat_validity_check()`.
380 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
382 const char *packed_refs_file = files_packed_refs_path(refs);
385 !is_lock_file_locked(&refs->packed_refs_lock) &&
386 !stat_validity_check(&refs->packed->validity, packed_refs_file))
387 clear_packed_ref_cache(refs);
390 refs->packed = read_packed_refs(packed_refs_file);
395 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
397 return get_ref_dir(packed_ref_cache->cache->root);
400 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
402 return get_packed_ref_dir(get_packed_ref_cache(refs));
406 * Add a reference to the in-memory packed reference cache. This may
407 * only be called while the packed-refs file is locked (see
408 * lock_packed_refs()). To actually write the packed-refs file, call
409 * commit_packed_refs().
411 static void add_packed_ref(struct files_ref_store *refs,
412 const char *refname, const struct object_id *oid)
414 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
416 if (!is_lock_file_locked(&refs->packed_refs_lock))
417 die("BUG: packed refs not locked");
419 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
420 die("Reference has invalid format: '%s'", refname);
422 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
423 create_ref_entry(refname, oid, REF_ISPACKED));
427 * Read the loose references from the namespace dirname into dir
428 * (without recursing). dirname must end with '/'. dir must be the
429 * directory entry corresponding to dirname.
431 static void loose_fill_ref_dir(struct ref_store *ref_store,
432 struct ref_dir *dir, const char *dirname)
434 struct files_ref_store *refs =
435 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
438 int dirnamelen = strlen(dirname);
439 struct strbuf refname;
440 struct strbuf path = STRBUF_INIT;
443 files_ref_path(refs, &path, dirname);
444 path_baselen = path.len;
446 d = opendir(path.buf);
448 strbuf_release(&path);
452 strbuf_init(&refname, dirnamelen + 257);
453 strbuf_add(&refname, dirname, dirnamelen);
455 while ((de = readdir(d)) != NULL) {
456 struct object_id oid;
460 if (de->d_name[0] == '.')
462 if (ends_with(de->d_name, ".lock"))
464 strbuf_addstr(&refname, de->d_name);
465 strbuf_addstr(&path, de->d_name);
466 if (stat(path.buf, &st) < 0) {
467 ; /* silently ignore */
468 } else if (S_ISDIR(st.st_mode)) {
469 strbuf_addch(&refname, '/');
470 add_entry_to_dir(dir,
471 create_dir_entry(dir->cache, refname.buf,
474 if (!refs_resolve_ref_unsafe(&refs->base,
479 flag |= REF_ISBROKEN;
480 } else if (is_null_oid(&oid)) {
482 * It is so astronomically unlikely
483 * that NULL_SHA1 is the SHA-1 of an
484 * actual object that we consider its
485 * appearance in a loose reference
486 * file to be repo corruption
487 * (probably due to a software bug).
489 flag |= REF_ISBROKEN;
492 if (check_refname_format(refname.buf,
493 REFNAME_ALLOW_ONELEVEL)) {
494 if (!refname_is_safe(refname.buf))
495 die("loose refname is dangerous: %s", refname.buf);
497 flag |= REF_BAD_NAME | REF_ISBROKEN;
499 add_entry_to_dir(dir,
500 create_ref_entry(refname.buf, &oid, flag));
502 strbuf_setlen(&refname, dirnamelen);
503 strbuf_setlen(&path, path_baselen);
505 strbuf_release(&refname);
506 strbuf_release(&path);
510 * Manually add refs/bisect, which, being per-worktree, might
511 * not appear in the directory listing for refs/ in the main
514 if (!strcmp(dirname, "refs/")) {
515 int pos = search_ref_dir(dir, "refs/bisect/", 12);
518 struct ref_entry *child_entry = create_dir_entry(
519 dir->cache, "refs/bisect/", 12, 1);
520 add_entry_to_dir(dir, child_entry);
525 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
529 * Mark the top-level directory complete because we
530 * are about to read the only subdirectory that can
533 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
535 /* We're going to fill the top level ourselves: */
536 refs->loose->root->flag &= ~REF_INCOMPLETE;
539 * Add an incomplete entry for "refs/" (to be filled
542 add_entry_to_dir(get_ref_dir(refs->loose->root),
543 create_dir_entry(refs->loose, "refs/", 5, 1));
549 * Return the ref_entry for the given refname from the packed
550 * references. If it does not exist, return NULL.
552 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
555 return find_ref_entry(get_packed_refs(refs), refname);
559 * A loose ref file doesn't exist; check for a packed ref.
561 static int resolve_packed_ref(struct files_ref_store *refs,
563 unsigned char *sha1, unsigned int *flags)
565 struct ref_entry *entry;
568 * The loose reference file does not exist; check for a packed
571 entry = get_packed_ref(refs, refname);
573 hashcpy(sha1, entry->u.value.oid.hash);
574 *flags |= REF_ISPACKED;
577 /* refname is not a packed reference. */
581 static int files_read_raw_ref(struct ref_store *ref_store,
582 const char *refname, unsigned char *sha1,
583 struct strbuf *referent, unsigned int *type)
585 struct files_ref_store *refs =
586 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
587 struct strbuf sb_contents = STRBUF_INIT;
588 struct strbuf sb_path = STRBUF_INIT;
595 int remaining_retries = 3;
598 strbuf_reset(&sb_path);
600 files_ref_path(refs, &sb_path, refname);
606 * We might have to loop back here to avoid a race
607 * condition: first we lstat() the file, then we try
608 * to read it as a link or as a file. But if somebody
609 * changes the type of the file (file <-> directory
610 * <-> symlink) between the lstat() and reading, then
611 * we don't want to report that as an error but rather
612 * try again starting with the lstat().
614 * We'll keep a count of the retries, though, just to avoid
615 * any confusing situation sending us into an infinite loop.
618 if (remaining_retries-- <= 0)
621 if (lstat(path, &st) < 0) {
624 if (resolve_packed_ref(refs, refname, sha1, type)) {
632 /* Follow "normalized" - ie "refs/.." symlinks by hand */
633 if (S_ISLNK(st.st_mode)) {
634 strbuf_reset(&sb_contents);
635 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
636 if (errno == ENOENT || errno == EINVAL)
637 /* inconsistent with lstat; retry */
642 if (starts_with(sb_contents.buf, "refs/") &&
643 !check_refname_format(sb_contents.buf, 0)) {
644 strbuf_swap(&sb_contents, referent);
645 *type |= REF_ISSYMREF;
650 * It doesn't look like a refname; fall through to just
651 * treating it like a non-symlink, and reading whatever it
656 /* Is it a directory? */
657 if (S_ISDIR(st.st_mode)) {
659 * Even though there is a directory where the loose
660 * ref is supposed to be, there could still be a
663 if (resolve_packed_ref(refs, refname, sha1, type)) {
672 * Anything else, just open it and try to use it as
675 fd = open(path, O_RDONLY);
677 if (errno == ENOENT && !S_ISLNK(st.st_mode))
678 /* inconsistent with lstat; retry */
683 strbuf_reset(&sb_contents);
684 if (strbuf_read(&sb_contents, fd, 256) < 0) {
685 int save_errno = errno;
691 strbuf_rtrim(&sb_contents);
692 buf = sb_contents.buf;
693 if (starts_with(buf, "ref:")) {
695 while (isspace(*buf))
698 strbuf_reset(referent);
699 strbuf_addstr(referent, buf);
700 *type |= REF_ISSYMREF;
706 * Please note that FETCH_HEAD has additional
707 * data after the sha.
709 if (get_sha1_hex(buf, sha1) ||
710 (buf[40] != '\0' && !isspace(buf[40]))) {
711 *type |= REF_ISBROKEN;
720 strbuf_release(&sb_path);
721 strbuf_release(&sb_contents);
726 static void unlock_ref(struct ref_lock *lock)
728 /* Do not free lock->lk -- atexit() still looks at them */
730 rollback_lock_file(lock->lk);
731 free(lock->ref_name);
736 * Lock refname, without following symrefs, and set *lock_p to point
737 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
738 * and type similarly to read_raw_ref().
740 * The caller must verify that refname is a "safe" reference name (in
741 * the sense of refname_is_safe()) before calling this function.
743 * If the reference doesn't already exist, verify that refname doesn't
744 * have a D/F conflict with any existing references. extras and skip
745 * are passed to refs_verify_refname_available() for this check.
747 * If mustexist is not set and the reference is not found or is
748 * broken, lock the reference anyway but clear sha1.
750 * Return 0 on success. On failure, write an error message to err and
751 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
753 * Implementation note: This function is basically
758 * but it includes a lot more code to
759 * - Deal with possible races with other processes
760 * - Avoid calling refs_verify_refname_available() when it can be
761 * avoided, namely if we were successfully able to read the ref
762 * - Generate informative error messages in the case of failure
764 static int lock_raw_ref(struct files_ref_store *refs,
765 const char *refname, int mustexist,
766 const struct string_list *extras,
767 const struct string_list *skip,
768 struct ref_lock **lock_p,
769 struct strbuf *referent,
773 struct ref_lock *lock;
774 struct strbuf ref_file = STRBUF_INIT;
775 int attempts_remaining = 3;
776 int ret = TRANSACTION_GENERIC_ERROR;
779 files_assert_main_repository(refs, "lock_raw_ref");
783 /* First lock the file so it can't change out from under us. */
785 *lock_p = lock = xcalloc(1, sizeof(*lock));
787 lock->ref_name = xstrdup(refname);
788 files_ref_path(refs, &ref_file, refname);
791 switch (safe_create_leading_directories(ref_file.buf)) {
796 * Suppose refname is "refs/foo/bar". We just failed
797 * to create the containing directory, "refs/foo",
798 * because there was a non-directory in the way. This
799 * indicates a D/F conflict, probably because of
800 * another reference such as "refs/foo". There is no
801 * reason to expect this error to be transitory.
803 if (refs_verify_refname_available(&refs->base, refname,
804 extras, skip, err)) {
807 * To the user the relevant error is
808 * that the "mustexist" reference is
812 strbuf_addf(err, "unable to resolve reference '%s'",
816 * The error message set by
817 * refs_verify_refname_available() is
820 ret = TRANSACTION_NAME_CONFLICT;
824 * The file that is in the way isn't a loose
825 * reference. Report it as a low-level
828 strbuf_addf(err, "unable to create lock file %s.lock; "
829 "non-directory in the way",
834 /* Maybe another process was tidying up. Try again. */
835 if (--attempts_remaining > 0)
839 strbuf_addf(err, "unable to create directory for %s",
845 lock->lk = xcalloc(1, sizeof(struct lock_file));
847 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
848 if (errno == ENOENT && --attempts_remaining > 0) {
850 * Maybe somebody just deleted one of the
851 * directories leading to ref_file. Try
856 unable_to_lock_message(ref_file.buf, errno, err);
862 * Now we hold the lock and can read the reference without
863 * fear that its value will change.
866 if (files_read_raw_ref(&refs->base, refname,
867 lock->old_oid.hash, referent, type)) {
868 if (errno == ENOENT) {
870 /* Garden variety missing reference. */
871 strbuf_addf(err, "unable to resolve reference '%s'",
876 * Reference is missing, but that's OK. We
877 * know that there is not a conflict with
878 * another loose reference because
879 * (supposing that we are trying to lock
880 * reference "refs/foo/bar"):
882 * - We were successfully able to create
883 * the lockfile refs/foo/bar.lock, so we
884 * know there cannot be a loose reference
887 * - We got ENOENT and not EISDIR, so we
888 * know that there cannot be a loose
889 * reference named "refs/foo/bar/baz".
892 } else if (errno == EISDIR) {
894 * There is a directory in the way. It might have
895 * contained references that have been deleted. If
896 * we don't require that the reference already
897 * exists, try to remove the directory so that it
898 * doesn't cause trouble when we want to rename the
899 * lockfile into place later.
902 /* Garden variety missing reference. */
903 strbuf_addf(err, "unable to resolve reference '%s'",
906 } else if (remove_dir_recursively(&ref_file,
907 REMOVE_DIR_EMPTY_ONLY)) {
908 if (refs_verify_refname_available(
909 &refs->base, refname,
910 extras, skip, err)) {
912 * The error message set by
913 * verify_refname_available() is OK.
915 ret = TRANSACTION_NAME_CONFLICT;
919 * We can't delete the directory,
920 * but we also don't know of any
921 * references that it should
924 strbuf_addf(err, "there is a non-empty directory '%s' "
925 "blocking reference '%s'",
926 ref_file.buf, refname);
930 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
931 strbuf_addf(err, "unable to resolve reference '%s': "
932 "reference broken", refname);
935 strbuf_addf(err, "unable to resolve reference '%s': %s",
936 refname, strerror(errno));
941 * If the ref did not exist and we are creating it,
942 * make sure there is no existing ref that conflicts
945 if (refs_verify_refname_available(
946 &refs->base, refname,
959 strbuf_release(&ref_file);
963 static int files_peel_ref(struct ref_store *ref_store,
964 const char *refname, unsigned char *sha1)
966 struct files_ref_store *refs =
967 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
970 unsigned char base[20];
972 if (current_ref_iter && current_ref_iter->refname == refname) {
973 struct object_id peeled;
975 if (ref_iterator_peel(current_ref_iter, &peeled))
977 hashcpy(sha1, peeled.hash);
981 if (refs_read_ref_full(ref_store, refname,
982 RESOLVE_REF_READING, base, &flag))
986 * If the reference is packed, read its ref_entry from the
987 * cache in the hope that we already know its peeled value.
988 * We only try this optimization on packed references because
989 * (a) forcing the filling of the loose reference cache could
990 * be expensive and (b) loose references anyway usually do not
991 * have REF_KNOWS_PEELED.
993 if (flag & REF_ISPACKED) {
994 struct ref_entry *r = get_packed_ref(refs, refname);
996 if (peel_entry(r, 0))
998 hashcpy(sha1, r->u.value.peeled.hash);
1003 return peel_object(base, sha1);
1006 struct files_ref_iterator {
1007 struct ref_iterator base;
1009 struct packed_ref_cache *packed_ref_cache;
1010 struct ref_iterator *iter0;
1014 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1016 struct files_ref_iterator *iter =
1017 (struct files_ref_iterator *)ref_iterator;
1020 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1021 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1022 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1025 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1026 !ref_resolves_to_object(iter->iter0->refname,
1028 iter->iter0->flags))
1031 iter->base.refname = iter->iter0->refname;
1032 iter->base.oid = iter->iter0->oid;
1033 iter->base.flags = iter->iter0->flags;
1038 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1044 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1045 struct object_id *peeled)
1047 struct files_ref_iterator *iter =
1048 (struct files_ref_iterator *)ref_iterator;
1050 return ref_iterator_peel(iter->iter0, peeled);
1053 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1055 struct files_ref_iterator *iter =
1056 (struct files_ref_iterator *)ref_iterator;
1060 ok = ref_iterator_abort(iter->iter0);
1062 release_packed_ref_cache(iter->packed_ref_cache);
1063 base_ref_iterator_free(ref_iterator);
1067 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1068 files_ref_iterator_advance,
1069 files_ref_iterator_peel,
1070 files_ref_iterator_abort
1073 static struct ref_iterator *files_ref_iterator_begin(
1074 struct ref_store *ref_store,
1075 const char *prefix, unsigned int flags)
1077 struct files_ref_store *refs;
1078 struct ref_iterator *loose_iter, *packed_iter;
1079 struct files_ref_iterator *iter;
1080 struct ref_iterator *ref_iterator;
1081 unsigned int required_flags = REF_STORE_READ;
1083 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1084 required_flags |= REF_STORE_ODB;
1086 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1088 iter = xcalloc(1, sizeof(*iter));
1089 ref_iterator = &iter->base;
1090 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1093 * We must make sure that all loose refs are read before
1094 * accessing the packed-refs file; this avoids a race
1095 * condition if loose refs are migrated to the packed-refs
1096 * file by a simultaneous process, but our in-memory view is
1097 * from before the migration. We ensure this as follows:
1098 * First, we call start the loose refs iteration with its
1099 * `prime_ref` argument set to true. This causes the loose
1100 * references in the subtree to be pre-read into the cache.
1101 * (If they've already been read, that's OK; we only need to
1102 * guarantee that they're read before the packed refs, not
1103 * *how much* before.) After that, we call
1104 * get_packed_ref_cache(), which internally checks whether the
1105 * packed-ref cache is up to date with what is on disk, and
1106 * re-reads it if not.
1109 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1112 iter->packed_ref_cache = get_packed_ref_cache(refs);
1113 acquire_packed_ref_cache(iter->packed_ref_cache);
1114 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1117 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1118 iter->flags = flags;
1120 return ref_iterator;
1124 * Verify that the reference locked by lock has the value old_sha1.
1125 * Fail if the reference doesn't exist and mustexist is set. Return 0
1126 * on success. On error, write an error message to err, set errno, and
1127 * return a negative value.
1129 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1130 const unsigned char *old_sha1, int mustexist,
1135 if (refs_read_ref_full(ref_store, lock->ref_name,
1136 mustexist ? RESOLVE_REF_READING : 0,
1137 lock->old_oid.hash, NULL)) {
1139 int save_errno = errno;
1140 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1144 oidclr(&lock->old_oid);
1148 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1149 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1151 oid_to_hex(&lock->old_oid),
1152 sha1_to_hex(old_sha1));
1159 static int remove_empty_directories(struct strbuf *path)
1162 * we want to create a file but there is a directory there;
1163 * if that is an empty directory (or a directory that contains
1164 * only empty directories), remove them.
1166 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1169 static int create_reflock(const char *path, void *cb)
1171 struct lock_file *lk = cb;
1173 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1177 * Locks a ref returning the lock on success and NULL on failure.
1178 * On failure errno is set to something meaningful.
1180 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1181 const char *refname,
1182 const unsigned char *old_sha1,
1183 const struct string_list *extras,
1184 const struct string_list *skip,
1185 unsigned int flags, int *type,
1188 struct strbuf ref_file = STRBUF_INIT;
1189 struct ref_lock *lock;
1191 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1192 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1195 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1198 lock = xcalloc(1, sizeof(struct ref_lock));
1201 resolve_flags |= RESOLVE_REF_READING;
1202 if (flags & REF_DELETING)
1203 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1205 files_ref_path(refs, &ref_file, refname);
1206 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1207 refname, resolve_flags,
1208 lock->old_oid.hash, type);
1209 if (!resolved && errno == EISDIR) {
1211 * we are trying to lock foo but we used to
1212 * have foo/bar which now does not exist;
1213 * it is normal for the empty directory 'foo'
1216 if (remove_empty_directories(&ref_file)) {
1218 if (!refs_verify_refname_available(
1220 refname, extras, skip, err))
1221 strbuf_addf(err, "there are still refs under '%s'",
1225 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1226 refname, resolve_flags,
1227 lock->old_oid.hash, type);
1231 if (last_errno != ENOTDIR ||
1232 !refs_verify_refname_available(&refs->base, refname,
1234 strbuf_addf(err, "unable to resolve reference '%s': %s",
1235 refname, strerror(last_errno));
1241 * If the ref did not exist and we are creating it, make sure
1242 * there is no existing packed ref whose name begins with our
1243 * refname, nor a packed ref whose name is a proper prefix of
1246 if (is_null_oid(&lock->old_oid) &&
1247 refs_verify_refname_available(&refs->base, refname,
1248 extras, skip, err)) {
1249 last_errno = ENOTDIR;
1253 lock->lk = xcalloc(1, sizeof(struct lock_file));
1255 lock->ref_name = xstrdup(refname);
1257 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1259 unable_to_lock_message(ref_file.buf, errno, err);
1263 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1274 strbuf_release(&ref_file);
1280 * Write an entry to the packed-refs file for the specified refname.
1281 * If peeled is non-NULL, write it as the entry's peeled value.
1283 static void write_packed_entry(FILE *fh, const char *refname,
1284 const unsigned char *sha1,
1285 const unsigned char *peeled)
1287 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1289 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1293 * Lock the packed-refs file for writing. Flags is passed to
1294 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1295 * errno appropriately and return a nonzero value.
1297 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1299 static int timeout_configured = 0;
1300 static int timeout_value = 1000;
1301 struct packed_ref_cache *packed_ref_cache;
1303 files_assert_main_repository(refs, "lock_packed_refs");
1305 if (!timeout_configured) {
1306 git_config_get_int("core.packedrefstimeout", &timeout_value);
1307 timeout_configured = 1;
1310 if (hold_lock_file_for_update_timeout(
1311 &refs->packed_refs_lock, files_packed_refs_path(refs),
1312 flags, timeout_value) < 0)
1315 * Get the current packed-refs while holding the lock. It is
1316 * important that we call `get_packed_ref_cache()` before
1317 * setting `packed_ref_cache->lock`, because otherwise the
1318 * former will see that the file is locked and assume that the
1319 * cache can't be stale.
1321 packed_ref_cache = get_packed_ref_cache(refs);
1322 /* Increment the reference count to prevent it from being freed: */
1323 acquire_packed_ref_cache(packed_ref_cache);
1328 * Write the current version of the packed refs cache from memory to
1329 * disk. The packed-refs file must already be locked for writing (see
1330 * lock_packed_refs()). Return zero on success. On errors, set errno
1331 * and return a nonzero value
1333 static int commit_packed_refs(struct files_ref_store *refs)
1335 struct packed_ref_cache *packed_ref_cache =
1336 get_packed_ref_cache(refs);
1340 struct ref_iterator *iter;
1342 files_assert_main_repository(refs, "commit_packed_refs");
1344 if (!is_lock_file_locked(&refs->packed_refs_lock))
1345 die("BUG: packed-refs not locked");
1347 out = fdopen_lock_file(&refs->packed_refs_lock, "w");
1349 die_errno("unable to fdopen packed-refs descriptor");
1351 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1353 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1354 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1355 struct object_id peeled;
1356 int peel_error = ref_iterator_peel(iter, &peeled);
1358 write_packed_entry(out, iter->refname, iter->oid->hash,
1359 peel_error ? NULL : peeled.hash);
1362 if (ok != ITER_DONE)
1363 die("error while iterating over references");
1365 if (commit_lock_file(&refs->packed_refs_lock)) {
1369 release_packed_ref_cache(packed_ref_cache);
1375 * Rollback the lockfile for the packed-refs file, and discard the
1376 * in-memory packed reference cache. (The packed-refs file will be
1377 * read anew if it is needed again after this function is called.)
1379 static void rollback_packed_refs(struct files_ref_store *refs)
1381 struct packed_ref_cache *packed_ref_cache =
1382 get_packed_ref_cache(refs);
1384 files_assert_main_repository(refs, "rollback_packed_refs");
1386 if (!is_lock_file_locked(&refs->packed_refs_lock))
1387 die("BUG: packed-refs not locked");
1388 rollback_lock_file(&refs->packed_refs_lock);
1389 release_packed_ref_cache(packed_ref_cache);
1390 clear_packed_ref_cache(refs);
1393 struct ref_to_prune {
1394 struct ref_to_prune *next;
1395 unsigned char sha1[20];
1396 char name[FLEX_ARRAY];
1400 REMOVE_EMPTY_PARENTS_REF = 0x01,
1401 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1405 * Remove empty parent directories associated with the specified
1406 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1407 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1408 * REMOVE_EMPTY_PARENTS_REFLOG.
1410 static void try_remove_empty_parents(struct files_ref_store *refs,
1411 const char *refname,
1414 struct strbuf buf = STRBUF_INIT;
1415 struct strbuf sb = STRBUF_INIT;
1419 strbuf_addstr(&buf, refname);
1421 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1422 while (*p && *p != '/')
1424 /* tolerate duplicate slashes; see check_refname_format() */
1428 q = buf.buf + buf.len;
1429 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1430 while (q > p && *q != '/')
1432 while (q > p && *(q-1) == '/')
1436 strbuf_setlen(&buf, q - buf.buf);
1439 files_ref_path(refs, &sb, buf.buf);
1440 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1441 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1444 files_reflog_path(refs, &sb, buf.buf);
1445 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1446 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1448 strbuf_release(&buf);
1449 strbuf_release(&sb);
1452 /* make sure nobody touched the ref, and unlink */
1453 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1455 struct ref_transaction *transaction;
1456 struct strbuf err = STRBUF_INIT;
1458 if (check_refname_format(r->name, 0))
1461 transaction = ref_store_transaction_begin(&refs->base, &err);
1463 ref_transaction_delete(transaction, r->name, r->sha1,
1464 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1465 ref_transaction_commit(transaction, &err)) {
1466 ref_transaction_free(transaction);
1467 error("%s", err.buf);
1468 strbuf_release(&err);
1471 ref_transaction_free(transaction);
1472 strbuf_release(&err);
1475 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1484 * Return true if the specified reference should be packed.
1486 static int should_pack_ref(const char *refname,
1487 const struct object_id *oid, unsigned int ref_flags,
1488 unsigned int pack_flags)
1490 /* Do not pack per-worktree refs: */
1491 if (ref_type(refname) != REF_TYPE_NORMAL)
1494 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1495 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1498 /* Do not pack symbolic refs: */
1499 if (ref_flags & REF_ISSYMREF)
1502 /* Do not pack broken refs: */
1503 if (!ref_resolves_to_object(refname, oid, ref_flags))
1509 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1511 struct files_ref_store *refs =
1512 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1514 struct ref_iterator *iter;
1515 struct ref_dir *packed_refs;
1517 struct ref_to_prune *refs_to_prune = NULL;
1519 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1520 packed_refs = get_packed_refs(refs);
1522 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1523 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1525 * If the loose reference can be packed, add an entry
1526 * in the packed ref cache. If the reference should be
1527 * pruned, also add it to refs_to_prune.
1529 struct ref_entry *packed_entry;
1531 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1536 * Create an entry in the packed-refs cache equivalent
1537 * to the one from the loose ref cache, except that
1538 * we don't copy the peeled status, because we want it
1541 packed_entry = find_ref_entry(packed_refs, iter->refname);
1543 /* Overwrite existing packed entry with info from loose entry */
1544 packed_entry->flag = REF_ISPACKED;
1545 oidcpy(&packed_entry->u.value.oid, iter->oid);
1547 packed_entry = create_ref_entry(iter->refname, iter->oid,
1549 add_ref_entry(packed_refs, packed_entry);
1551 oidclr(&packed_entry->u.value.peeled);
1553 /* Schedule the loose reference for pruning if requested. */
1554 if ((flags & PACK_REFS_PRUNE)) {
1555 struct ref_to_prune *n;
1556 FLEX_ALLOC_STR(n, name, iter->refname);
1557 hashcpy(n->sha1, iter->oid->hash);
1558 n->next = refs_to_prune;
1562 if (ok != ITER_DONE)
1563 die("error while iterating over references");
1565 if (commit_packed_refs(refs))
1566 die_errno("unable to overwrite old ref-pack file");
1568 prune_refs(refs, refs_to_prune);
1573 * Rewrite the packed-refs file, omitting any refs listed in
1574 * 'refnames'. On error, leave packed-refs unchanged, write an error
1575 * message to 'err', and return a nonzero value.
1577 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1579 static int repack_without_refs(struct files_ref_store *refs,
1580 struct string_list *refnames, struct strbuf *err)
1582 struct ref_dir *packed;
1583 struct string_list_item *refname;
1584 int ret, needs_repacking = 0, removed = 0;
1586 files_assert_main_repository(refs, "repack_without_refs");
1589 /* Look for a packed ref */
1590 for_each_string_list_item(refname, refnames) {
1591 if (get_packed_ref(refs, refname->string)) {
1592 needs_repacking = 1;
1597 /* Avoid locking if we have nothing to do */
1598 if (!needs_repacking)
1599 return 0; /* no refname exists in packed refs */
1601 if (lock_packed_refs(refs, 0)) {
1602 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1605 packed = get_packed_refs(refs);
1607 /* Remove refnames from the cache */
1608 for_each_string_list_item(refname, refnames)
1609 if (remove_entry_from_dir(packed, refname->string) != -1)
1613 * All packed entries disappeared while we were
1614 * acquiring the lock.
1616 rollback_packed_refs(refs);
1620 /* Write what remains */
1621 ret = commit_packed_refs(refs);
1623 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1628 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1629 struct string_list *refnames, unsigned int flags)
1631 struct files_ref_store *refs =
1632 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1633 struct strbuf err = STRBUF_INIT;
1639 result = repack_without_refs(refs, refnames, &err);
1642 * If we failed to rewrite the packed-refs file, then
1643 * it is unsafe to try to remove loose refs, because
1644 * doing so might expose an obsolete packed value for
1645 * a reference that might even point at an object that
1646 * has been garbage collected.
1648 if (refnames->nr == 1)
1649 error(_("could not delete reference %s: %s"),
1650 refnames->items[0].string, err.buf);
1652 error(_("could not delete references: %s"), err.buf);
1657 for (i = 0; i < refnames->nr; i++) {
1658 const char *refname = refnames->items[i].string;
1660 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1661 result |= error(_("could not remove reference %s"), refname);
1665 strbuf_release(&err);
1670 * People using contrib's git-new-workdir have .git/logs/refs ->
1671 * /some/other/path/.git/logs/refs, and that may live on another device.
1673 * IOW, to avoid cross device rename errors, the temporary renamed log must
1674 * live into logs/refs.
1676 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1679 const char *tmp_renamed_log;
1683 static int rename_tmp_log_callback(const char *path, void *cb_data)
1685 struct rename_cb *cb = cb_data;
1687 if (rename(cb->tmp_renamed_log, path)) {
1689 * rename(a, b) when b is an existing directory ought
1690 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1691 * Sheesh. Record the true errno for error reporting,
1692 * but report EISDIR to raceproof_create_file() so
1693 * that it knows to retry.
1695 cb->true_errno = errno;
1696 if (errno == ENOTDIR)
1704 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1706 struct strbuf path = STRBUF_INIT;
1707 struct strbuf tmp = STRBUF_INIT;
1708 struct rename_cb cb;
1711 files_reflog_path(refs, &path, newrefname);
1712 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1713 cb.tmp_renamed_log = tmp.buf;
1714 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1716 if (errno == EISDIR)
1717 error("directory not empty: %s", path.buf);
1719 error("unable to move logfile %s to %s: %s",
1721 strerror(cb.true_errno));
1724 strbuf_release(&path);
1725 strbuf_release(&tmp);
1729 static int write_ref_to_lockfile(struct ref_lock *lock,
1730 const struct object_id *oid, struct strbuf *err);
1731 static int commit_ref_update(struct files_ref_store *refs,
1732 struct ref_lock *lock,
1733 const struct object_id *oid, const char *logmsg,
1734 struct strbuf *err);
1736 static int files_copy_or_rename_ref(struct ref_store *ref_store,
1737 const char *oldrefname, const char *newrefname,
1738 const char *logmsg, int copy)
1740 struct files_ref_store *refs =
1741 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1742 struct object_id oid, orig_oid;
1743 int flag = 0, logmoved = 0;
1744 struct ref_lock *lock;
1745 struct stat loginfo;
1746 struct strbuf sb_oldref = STRBUF_INIT;
1747 struct strbuf sb_newref = STRBUF_INIT;
1748 struct strbuf tmp_renamed_log = STRBUF_INIT;
1750 struct strbuf err = STRBUF_INIT;
1752 files_reflog_path(refs, &sb_oldref, oldrefname);
1753 files_reflog_path(refs, &sb_newref, newrefname);
1754 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1756 log = !lstat(sb_oldref.buf, &loginfo);
1757 if (log && S_ISLNK(loginfo.st_mode)) {
1758 ret = error("reflog for %s is a symlink", oldrefname);
1762 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1763 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1764 orig_oid.hash, &flag)) {
1765 ret = error("refname %s not found", oldrefname);
1769 if (flag & REF_ISSYMREF) {
1771 ret = error("refname %s is a symbolic ref, copying it is not supported",
1774 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1778 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1783 if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1784 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1785 oldrefname, strerror(errno));
1789 if (copy && log && copy_file(tmp_renamed_log.buf, sb_oldref.buf, 0644)) {
1790 ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1791 oldrefname, strerror(errno));
1795 if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,
1796 orig_oid.hash, REF_NODEREF)) {
1797 error("unable to delete old %s", oldrefname);
1802 * Since we are doing a shallow lookup, oid is not the
1803 * correct value to pass to delete_ref as old_oid. But that
1804 * doesn't matter, because an old_oid check wouldn't add to
1805 * the safety anyway; we want to delete the reference whatever
1806 * its current value.
1808 if (!copy && !refs_read_ref_full(&refs->base, newrefname,
1809 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1811 refs_delete_ref(&refs->base, NULL, newrefname,
1812 NULL, REF_NODEREF)) {
1813 if (errno == EISDIR) {
1814 struct strbuf path = STRBUF_INIT;
1817 files_ref_path(refs, &path, newrefname);
1818 result = remove_empty_directories(&path);
1819 strbuf_release(&path);
1822 error("Directory not empty: %s", newrefname);
1826 error("unable to delete existing %s", newrefname);
1831 if (log && rename_tmp_log(refs, newrefname))
1836 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1837 REF_NODEREF, NULL, &err);
1840 error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1842 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1843 strbuf_release(&err);
1846 oidcpy(&lock->old_oid, &orig_oid);
1848 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1849 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1850 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1851 strbuf_release(&err);
1859 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1860 REF_NODEREF, NULL, &err);
1862 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1863 strbuf_release(&err);
1867 flag = log_all_ref_updates;
1868 log_all_ref_updates = LOG_REFS_NONE;
1869 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1870 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1871 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1872 strbuf_release(&err);
1874 log_all_ref_updates = flag;
1877 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1878 error("unable to restore logfile %s from %s: %s",
1879 oldrefname, newrefname, strerror(errno));
1880 if (!logmoved && log &&
1881 rename(tmp_renamed_log.buf, sb_oldref.buf))
1882 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1883 oldrefname, strerror(errno));
1886 strbuf_release(&sb_newref);
1887 strbuf_release(&sb_oldref);
1888 strbuf_release(&tmp_renamed_log);
1893 static int files_rename_ref(struct ref_store *ref_store,
1894 const char *oldrefname, const char *newrefname,
1897 return files_copy_or_rename_ref(ref_store, oldrefname,
1898 newrefname, logmsg, 0);
1901 static int files_copy_ref(struct ref_store *ref_store,
1902 const char *oldrefname, const char *newrefname,
1905 return files_copy_or_rename_ref(ref_store, oldrefname,
1906 newrefname, logmsg, 1);
1909 static int close_ref(struct ref_lock *lock)
1911 if (close_lock_file(lock->lk))
1916 static int commit_ref(struct ref_lock *lock)
1918 char *path = get_locked_file_path(lock->lk);
1921 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1923 * There is a directory at the path we want to rename
1924 * the lockfile to. Hopefully it is empty; try to
1927 size_t len = strlen(path);
1928 struct strbuf sb_path = STRBUF_INIT;
1930 strbuf_attach(&sb_path, path, len, len);
1933 * If this fails, commit_lock_file() will also fail
1934 * and will report the problem.
1936 remove_empty_directories(&sb_path);
1937 strbuf_release(&sb_path);
1942 if (commit_lock_file(lock->lk))
1947 static int open_or_create_logfile(const char *path, void *cb)
1951 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1952 return (*fd < 0) ? -1 : 0;
1956 * Create a reflog for a ref. If force_create = 0, only create the
1957 * reflog for certain refs (those for which should_autocreate_reflog
1958 * returns non-zero). Otherwise, create it regardless of the reference
1959 * name. If the logfile already existed or was created, return 0 and
1960 * set *logfd to the file descriptor opened for appending to the file.
1961 * If no logfile exists and we decided not to create one, return 0 and
1962 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1965 static int log_ref_setup(struct files_ref_store *refs,
1966 const char *refname, int force_create,
1967 int *logfd, struct strbuf *err)
1969 struct strbuf logfile_sb = STRBUF_INIT;
1972 files_reflog_path(refs, &logfile_sb, refname);
1973 logfile = strbuf_detach(&logfile_sb, NULL);
1975 if (force_create || should_autocreate_reflog(refname)) {
1976 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1977 if (errno == ENOENT)
1978 strbuf_addf(err, "unable to create directory for '%s': "
1979 "%s", logfile, strerror(errno));
1980 else if (errno == EISDIR)
1981 strbuf_addf(err, "there are still logs under '%s'",
1984 strbuf_addf(err, "unable to append to '%s': %s",
1985 logfile, strerror(errno));
1990 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1992 if (errno == ENOENT || errno == EISDIR) {
1994 * The logfile doesn't already exist,
1995 * but that is not an error; it only
1996 * means that we won't write log
2001 strbuf_addf(err, "unable to append to '%s': %s",
2002 logfile, strerror(errno));
2009 adjust_shared_perm(logfile);
2019 static int files_create_reflog(struct ref_store *ref_store,
2020 const char *refname, int force_create,
2023 struct files_ref_store *refs =
2024 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2027 if (log_ref_setup(refs, refname, force_create, &fd, err))
2036 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2037 const struct object_id *new_oid,
2038 const char *committer, const char *msg)
2040 int msglen, written;
2041 unsigned maxlen, len;
2044 msglen = msg ? strlen(msg) : 0;
2045 maxlen = strlen(committer) + msglen + 100;
2046 logrec = xmalloc(maxlen);
2047 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2048 oid_to_hex(old_oid),
2049 oid_to_hex(new_oid),
2052 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2054 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2062 static int files_log_ref_write(struct files_ref_store *refs,
2063 const char *refname, const struct object_id *old_oid,
2064 const struct object_id *new_oid, const char *msg,
2065 int flags, struct strbuf *err)
2069 if (log_all_ref_updates == LOG_REFS_UNSET)
2070 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2072 result = log_ref_setup(refs, refname,
2073 flags & REF_FORCE_CREATE_REFLOG,
2081 result = log_ref_write_fd(logfd, old_oid, new_oid,
2082 git_committer_info(0), msg);
2084 struct strbuf sb = STRBUF_INIT;
2085 int save_errno = errno;
2087 files_reflog_path(refs, &sb, refname);
2088 strbuf_addf(err, "unable to append to '%s': %s",
2089 sb.buf, strerror(save_errno));
2090 strbuf_release(&sb);
2095 struct strbuf sb = STRBUF_INIT;
2096 int save_errno = errno;
2098 files_reflog_path(refs, &sb, refname);
2099 strbuf_addf(err, "unable to append to '%s': %s",
2100 sb.buf, strerror(save_errno));
2101 strbuf_release(&sb);
2108 * Write sha1 into the open lockfile, then close the lockfile. On
2109 * errors, rollback the lockfile, fill in *err and
2112 static int write_ref_to_lockfile(struct ref_lock *lock,
2113 const struct object_id *oid, struct strbuf *err)
2115 static char term = '\n';
2119 o = parse_object(oid);
2122 "trying to write ref '%s' with nonexistent object %s",
2123 lock->ref_name, oid_to_hex(oid));
2127 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2129 "trying to write non-commit object %s to branch '%s'",
2130 oid_to_hex(oid), lock->ref_name);
2134 fd = get_lock_file_fd(lock->lk);
2135 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2136 write_in_full(fd, &term, 1) != 1 ||
2137 close_ref(lock) < 0) {
2139 "couldn't write '%s'", get_lock_file_path(lock->lk));
2147 * Commit a change to a loose reference that has already been written
2148 * to the loose reference lockfile. Also update the reflogs if
2149 * necessary, using the specified lockmsg (which can be NULL).
2151 static int commit_ref_update(struct files_ref_store *refs,
2152 struct ref_lock *lock,
2153 const struct object_id *oid, const char *logmsg,
2156 files_assert_main_repository(refs, "commit_ref_update");
2158 clear_loose_ref_cache(refs);
2159 if (files_log_ref_write(refs, lock->ref_name,
2160 &lock->old_oid, oid,
2162 char *old_msg = strbuf_detach(err, NULL);
2163 strbuf_addf(err, "cannot update the ref '%s': %s",
2164 lock->ref_name, old_msg);
2170 if (strcmp(lock->ref_name, "HEAD") != 0) {
2172 * Special hack: If a branch is updated directly and HEAD
2173 * points to it (may happen on the remote side of a push
2174 * for example) then logically the HEAD reflog should be
2176 * A generic solution implies reverse symref information,
2177 * but finding all symrefs pointing to the given branch
2178 * would be rather costly for this rare event (the direct
2179 * update of a branch) to be worth it. So let's cheat and
2180 * check with HEAD only which should cover 99% of all usage
2181 * scenarios (even 100% of the default ones).
2183 struct object_id head_oid;
2185 const char *head_ref;
2187 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2188 RESOLVE_REF_READING,
2189 head_oid.hash, &head_flag);
2190 if (head_ref && (head_flag & REF_ISSYMREF) &&
2191 !strcmp(head_ref, lock->ref_name)) {
2192 struct strbuf log_err = STRBUF_INIT;
2193 if (files_log_ref_write(refs, "HEAD",
2194 &lock->old_oid, oid,
2195 logmsg, 0, &log_err)) {
2196 error("%s", log_err.buf);
2197 strbuf_release(&log_err);
2202 if (commit_ref(lock)) {
2203 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2212 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2215 #ifndef NO_SYMLINK_HEAD
2216 char *ref_path = get_locked_file_path(lock->lk);
2218 ret = symlink(target, ref_path);
2222 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2227 static void update_symref_reflog(struct files_ref_store *refs,
2228 struct ref_lock *lock, const char *refname,
2229 const char *target, const char *logmsg)
2231 struct strbuf err = STRBUF_INIT;
2232 struct object_id new_oid;
2234 !refs_read_ref_full(&refs->base, target,
2235 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2236 files_log_ref_write(refs, refname, &lock->old_oid,
2237 &new_oid, logmsg, 0, &err)) {
2238 error("%s", err.buf);
2239 strbuf_release(&err);
2243 static int create_symref_locked(struct files_ref_store *refs,
2244 struct ref_lock *lock, const char *refname,
2245 const char *target, const char *logmsg)
2247 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2248 update_symref_reflog(refs, lock, refname, target, logmsg);
2252 if (!fdopen_lock_file(lock->lk, "w"))
2253 return error("unable to fdopen %s: %s",
2254 lock->lk->tempfile.filename.buf, strerror(errno));
2256 update_symref_reflog(refs, lock, refname, target, logmsg);
2258 /* no error check; commit_ref will check ferror */
2259 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2260 if (commit_ref(lock) < 0)
2261 return error("unable to write symref for %s: %s", refname,
2266 static int files_create_symref(struct ref_store *ref_store,
2267 const char *refname, const char *target,
2270 struct files_ref_store *refs =
2271 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2272 struct strbuf err = STRBUF_INIT;
2273 struct ref_lock *lock;
2276 lock = lock_ref_sha1_basic(refs, refname, NULL,
2277 NULL, NULL, REF_NODEREF, NULL,
2280 error("%s", err.buf);
2281 strbuf_release(&err);
2285 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2290 static int files_reflog_exists(struct ref_store *ref_store,
2291 const char *refname)
2293 struct files_ref_store *refs =
2294 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2295 struct strbuf sb = STRBUF_INIT;
2299 files_reflog_path(refs, &sb, refname);
2300 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2301 strbuf_release(&sb);
2305 static int files_delete_reflog(struct ref_store *ref_store,
2306 const char *refname)
2308 struct files_ref_store *refs =
2309 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2310 struct strbuf sb = STRBUF_INIT;
2313 files_reflog_path(refs, &sb, refname);
2314 ret = remove_path(sb.buf);
2315 strbuf_release(&sb);
2319 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2321 struct object_id ooid, noid;
2322 char *email_end, *message;
2323 timestamp_t timestamp;
2325 const char *p = sb->buf;
2327 /* old SP new SP name <email> SP time TAB msg LF */
2328 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2329 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2330 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2331 !(email_end = strchr(p, '>')) ||
2332 email_end[1] != ' ' ||
2333 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2334 !message || message[0] != ' ' ||
2335 (message[1] != '+' && message[1] != '-') ||
2336 !isdigit(message[2]) || !isdigit(message[3]) ||
2337 !isdigit(message[4]) || !isdigit(message[5]))
2338 return 0; /* corrupt? */
2339 email_end[1] = '\0';
2340 tz = strtol(message + 1, NULL, 10);
2341 if (message[6] != '\t')
2345 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2348 static char *find_beginning_of_line(char *bob, char *scan)
2350 while (bob < scan && *(--scan) != '\n')
2351 ; /* keep scanning backwards */
2353 * Return either beginning of the buffer, or LF at the end of
2354 * the previous line.
2359 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2360 const char *refname,
2361 each_reflog_ent_fn fn,
2364 struct files_ref_store *refs =
2365 files_downcast(ref_store, REF_STORE_READ,
2366 "for_each_reflog_ent_reverse");
2367 struct strbuf sb = STRBUF_INIT;
2370 int ret = 0, at_tail = 1;
2372 files_reflog_path(refs, &sb, refname);
2373 logfp = fopen(sb.buf, "r");
2374 strbuf_release(&sb);
2378 /* Jump to the end */
2379 if (fseek(logfp, 0, SEEK_END) < 0)
2380 ret = error("cannot seek back reflog for %s: %s",
2381 refname, strerror(errno));
2383 while (!ret && 0 < pos) {
2389 /* Fill next block from the end */
2390 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2391 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2392 ret = error("cannot seek back reflog for %s: %s",
2393 refname, strerror(errno));
2396 nread = fread(buf, cnt, 1, logfp);
2398 ret = error("cannot read %d bytes from reflog for %s: %s",
2399 cnt, refname, strerror(errno));
2404 scanp = endp = buf + cnt;
2405 if (at_tail && scanp[-1] == '\n')
2406 /* Looking at the final LF at the end of the file */
2410 while (buf < scanp) {
2412 * terminating LF of the previous line, or the beginning
2417 bp = find_beginning_of_line(buf, scanp);
2421 * The newline is the end of the previous line,
2422 * so we know we have complete line starting
2423 * at (bp + 1). Prefix it onto any prior data
2424 * we collected for the line and process it.
2426 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2429 ret = show_one_reflog_ent(&sb, fn, cb_data);
2435 * We are at the start of the buffer, and the
2436 * start of the file; there is no previous
2437 * line, and we have everything for this one.
2438 * Process it, and we can end the loop.
2440 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2441 ret = show_one_reflog_ent(&sb, fn, cb_data);
2448 * We are at the start of the buffer, and there
2449 * is more file to read backwards. Which means
2450 * we are in the middle of a line. Note that we
2451 * may get here even if *bp was a newline; that
2452 * just means we are at the exact end of the
2453 * previous line, rather than some spot in the
2456 * Save away what we have to be combined with
2457 * the data from the next read.
2459 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2466 die("BUG: reverse reflog parser had leftover data");
2469 strbuf_release(&sb);
2473 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2474 const char *refname,
2475 each_reflog_ent_fn fn, void *cb_data)
2477 struct files_ref_store *refs =
2478 files_downcast(ref_store, REF_STORE_READ,
2479 "for_each_reflog_ent");
2481 struct strbuf sb = STRBUF_INIT;
2484 files_reflog_path(refs, &sb, refname);
2485 logfp = fopen(sb.buf, "r");
2486 strbuf_release(&sb);
2490 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2491 ret = show_one_reflog_ent(&sb, fn, cb_data);
2493 strbuf_release(&sb);
2497 struct files_reflog_iterator {
2498 struct ref_iterator base;
2500 struct ref_store *ref_store;
2501 struct dir_iterator *dir_iterator;
2502 struct object_id oid;
2505 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2507 struct files_reflog_iterator *iter =
2508 (struct files_reflog_iterator *)ref_iterator;
2509 struct dir_iterator *diter = iter->dir_iterator;
2512 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2515 if (!S_ISREG(diter->st.st_mode))
2517 if (diter->basename[0] == '.')
2519 if (ends_with(diter->basename, ".lock"))
2522 if (refs_read_ref_full(iter->ref_store,
2523 diter->relative_path, 0,
2524 iter->oid.hash, &flags)) {
2525 error("bad ref for %s", diter->path.buf);
2529 iter->base.refname = diter->relative_path;
2530 iter->base.oid = &iter->oid;
2531 iter->base.flags = flags;
2535 iter->dir_iterator = NULL;
2536 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2541 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2542 struct object_id *peeled)
2544 die("BUG: ref_iterator_peel() called for reflog_iterator");
2547 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2549 struct files_reflog_iterator *iter =
2550 (struct files_reflog_iterator *)ref_iterator;
2553 if (iter->dir_iterator)
2554 ok = dir_iterator_abort(iter->dir_iterator);
2556 base_ref_iterator_free(ref_iterator);
2560 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2561 files_reflog_iterator_advance,
2562 files_reflog_iterator_peel,
2563 files_reflog_iterator_abort
2566 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2568 struct files_ref_store *refs =
2569 files_downcast(ref_store, REF_STORE_READ,
2570 "reflog_iterator_begin");
2571 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2572 struct ref_iterator *ref_iterator = &iter->base;
2573 struct strbuf sb = STRBUF_INIT;
2575 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2576 files_reflog_path(refs, &sb, NULL);
2577 iter->dir_iterator = dir_iterator_begin(sb.buf);
2578 iter->ref_store = ref_store;
2579 strbuf_release(&sb);
2580 return ref_iterator;
2584 * If update is a direct update of head_ref (the reference pointed to
2585 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2587 static int split_head_update(struct ref_update *update,
2588 struct ref_transaction *transaction,
2589 const char *head_ref,
2590 struct string_list *affected_refnames,
2593 struct string_list_item *item;
2594 struct ref_update *new_update;
2596 if ((update->flags & REF_LOG_ONLY) ||
2597 (update->flags & REF_ISPRUNING) ||
2598 (update->flags & REF_UPDATE_VIA_HEAD))
2601 if (strcmp(update->refname, head_ref))
2605 * First make sure that HEAD is not already in the
2606 * transaction. This insertion is O(N) in the transaction
2607 * size, but it happens at most once per transaction.
2609 item = string_list_insert(affected_refnames, "HEAD");
2611 /* An entry already existed */
2613 "multiple updates for 'HEAD' (including one "
2614 "via its referent '%s') are not allowed",
2616 return TRANSACTION_NAME_CONFLICT;
2619 new_update = ref_transaction_add_update(
2620 transaction, "HEAD",
2621 update->flags | REF_LOG_ONLY | REF_NODEREF,
2622 update->new_oid.hash, update->old_oid.hash,
2625 item->util = new_update;
2631 * update is for a symref that points at referent and doesn't have
2632 * REF_NODEREF set. Split it into two updates:
2633 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2634 * - A new, separate update for the referent reference
2635 * Note that the new update will itself be subject to splitting when
2636 * the iteration gets to it.
2638 static int split_symref_update(struct files_ref_store *refs,
2639 struct ref_update *update,
2640 const char *referent,
2641 struct ref_transaction *transaction,
2642 struct string_list *affected_refnames,
2645 struct string_list_item *item;
2646 struct ref_update *new_update;
2647 unsigned int new_flags;
2650 * First make sure that referent is not already in the
2651 * transaction. This insertion is O(N) in the transaction
2652 * size, but it happens at most once per symref in a
2655 item = string_list_insert(affected_refnames, referent);
2657 /* An entry already existed */
2659 "multiple updates for '%s' (including one "
2660 "via symref '%s') are not allowed",
2661 referent, update->refname);
2662 return TRANSACTION_NAME_CONFLICT;
2665 new_flags = update->flags;
2666 if (!strcmp(update->refname, "HEAD")) {
2668 * Record that the new update came via HEAD, so that
2669 * when we process it, split_head_update() doesn't try
2670 * to add another reflog update for HEAD. Note that
2671 * this bit will be propagated if the new_update
2672 * itself needs to be split.
2674 new_flags |= REF_UPDATE_VIA_HEAD;
2677 new_update = ref_transaction_add_update(
2678 transaction, referent, new_flags,
2679 update->new_oid.hash, update->old_oid.hash,
2682 new_update->parent_update = update;
2685 * Change the symbolic ref update to log only. Also, it
2686 * doesn't need to check its old SHA-1 value, as that will be
2687 * done when new_update is processed.
2689 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2690 update->flags &= ~REF_HAVE_OLD;
2692 item->util = new_update;
2698 * Return the refname under which update was originally requested.
2700 static const char *original_update_refname(struct ref_update *update)
2702 while (update->parent_update)
2703 update = update->parent_update;
2705 return update->refname;
2709 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2710 * are consistent with oid, which is the reference's current value. If
2711 * everything is OK, return 0; otherwise, write an error message to
2712 * err and return -1.
2714 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2717 if (!(update->flags & REF_HAVE_OLD) ||
2718 !oidcmp(oid, &update->old_oid))
2721 if (is_null_oid(&update->old_oid))
2722 strbuf_addf(err, "cannot lock ref '%s': "
2723 "reference already exists",
2724 original_update_refname(update));
2725 else if (is_null_oid(oid))
2726 strbuf_addf(err, "cannot lock ref '%s': "
2727 "reference is missing but expected %s",
2728 original_update_refname(update),
2729 oid_to_hex(&update->old_oid));
2731 strbuf_addf(err, "cannot lock ref '%s': "
2732 "is at %s but expected %s",
2733 original_update_refname(update),
2735 oid_to_hex(&update->old_oid));
2741 * Prepare for carrying out update:
2742 * - Lock the reference referred to by update.
2743 * - Read the reference under lock.
2744 * - Check that its old SHA-1 value (if specified) is correct, and in
2745 * any case record it in update->lock->old_oid for later use when
2746 * writing the reflog.
2747 * - If it is a symref update without REF_NODEREF, split it up into a
2748 * REF_LOG_ONLY update of the symref and add a separate update for
2749 * the referent to transaction.
2750 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2753 static int lock_ref_for_update(struct files_ref_store *refs,
2754 struct ref_update *update,
2755 struct ref_transaction *transaction,
2756 const char *head_ref,
2757 struct string_list *affected_refnames,
2760 struct strbuf referent = STRBUF_INIT;
2761 int mustexist = (update->flags & REF_HAVE_OLD) &&
2762 !is_null_oid(&update->old_oid);
2764 struct ref_lock *lock;
2766 files_assert_main_repository(refs, "lock_ref_for_update");
2768 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2769 update->flags |= REF_DELETING;
2772 ret = split_head_update(update, transaction, head_ref,
2773 affected_refnames, err);
2778 ret = lock_raw_ref(refs, update->refname, mustexist,
2779 affected_refnames, NULL,
2781 &update->type, err);
2785 reason = strbuf_detach(err, NULL);
2786 strbuf_addf(err, "cannot lock ref '%s': %s",
2787 original_update_refname(update), reason);
2792 update->backend_data = lock;
2794 if (update->type & REF_ISSYMREF) {
2795 if (update->flags & REF_NODEREF) {
2797 * We won't be reading the referent as part of
2798 * the transaction, so we have to read it here
2799 * to record and possibly check old_sha1:
2801 if (refs_read_ref_full(&refs->base,
2803 lock->old_oid.hash, NULL)) {
2804 if (update->flags & REF_HAVE_OLD) {
2805 strbuf_addf(err, "cannot lock ref '%s': "
2806 "error reading reference",
2807 original_update_refname(update));
2810 } else if (check_old_oid(update, &lock->old_oid, err)) {
2811 return TRANSACTION_GENERIC_ERROR;
2815 * Create a new update for the reference this
2816 * symref is pointing at. Also, we will record
2817 * and verify old_sha1 for this update as part
2818 * of processing the split-off update, so we
2819 * don't have to do it here.
2821 ret = split_symref_update(refs, update,
2822 referent.buf, transaction,
2823 affected_refnames, err);
2828 struct ref_update *parent_update;
2830 if (check_old_oid(update, &lock->old_oid, err))
2831 return TRANSACTION_GENERIC_ERROR;
2834 * If this update is happening indirectly because of a
2835 * symref update, record the old SHA-1 in the parent
2838 for (parent_update = update->parent_update;
2840 parent_update = parent_update->parent_update) {
2841 struct ref_lock *parent_lock = parent_update->backend_data;
2842 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2846 if ((update->flags & REF_HAVE_NEW) &&
2847 !(update->flags & REF_DELETING) &&
2848 !(update->flags & REF_LOG_ONLY)) {
2849 if (!(update->type & REF_ISSYMREF) &&
2850 !oidcmp(&lock->old_oid, &update->new_oid)) {
2852 * The reference already has the desired
2853 * value, so we don't need to write it.
2855 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2857 char *write_err = strbuf_detach(err, NULL);
2860 * The lock was freed upon failure of
2861 * write_ref_to_lockfile():
2863 update->backend_data = NULL;
2865 "cannot update ref '%s': %s",
2866 update->refname, write_err);
2868 return TRANSACTION_GENERIC_ERROR;
2870 update->flags |= REF_NEEDS_COMMIT;
2873 if (!(update->flags & REF_NEEDS_COMMIT)) {
2875 * We didn't call write_ref_to_lockfile(), so
2876 * the lockfile is still open. Close it to
2877 * free up the file descriptor:
2879 if (close_ref(lock)) {
2880 strbuf_addf(err, "couldn't close '%s.lock'",
2882 return TRANSACTION_GENERIC_ERROR;
2889 * Unlock any references in `transaction` that are still locked, and
2890 * mark the transaction closed.
2892 static void files_transaction_cleanup(struct ref_transaction *transaction)
2896 for (i = 0; i < transaction->nr; i++) {
2897 struct ref_update *update = transaction->updates[i];
2898 struct ref_lock *lock = update->backend_data;
2902 update->backend_data = NULL;
2906 transaction->state = REF_TRANSACTION_CLOSED;
2909 static int files_transaction_prepare(struct ref_store *ref_store,
2910 struct ref_transaction *transaction,
2913 struct files_ref_store *refs =
2914 files_downcast(ref_store, REF_STORE_WRITE,
2915 "ref_transaction_prepare");
2918 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2919 char *head_ref = NULL;
2921 struct object_id head_oid;
2925 if (!transaction->nr)
2929 * Fail if a refname appears more than once in the
2930 * transaction. (If we end up splitting up any updates using
2931 * split_symref_update() or split_head_update(), those
2932 * functions will check that the new updates don't have the
2933 * same refname as any existing ones.)
2935 for (i = 0; i < transaction->nr; i++) {
2936 struct ref_update *update = transaction->updates[i];
2937 struct string_list_item *item =
2938 string_list_append(&affected_refnames, update->refname);
2941 * We store a pointer to update in item->util, but at
2942 * the moment we never use the value of this field
2943 * except to check whether it is non-NULL.
2945 item->util = update;
2947 string_list_sort(&affected_refnames);
2948 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2949 ret = TRANSACTION_GENERIC_ERROR;
2954 * Special hack: If a branch is updated directly and HEAD
2955 * points to it (may happen on the remote side of a push
2956 * for example) then logically the HEAD reflog should be
2959 * A generic solution would require reverse symref lookups,
2960 * but finding all symrefs pointing to a given branch would be
2961 * rather costly for this rare event (the direct update of a
2962 * branch) to be worth it. So let's cheat and check with HEAD
2963 * only, which should cover 99% of all usage scenarios (even
2964 * 100% of the default ones).
2966 * So if HEAD is a symbolic reference, then record the name of
2967 * the reference that it points to. If we see an update of
2968 * head_ref within the transaction, then split_head_update()
2969 * arranges for the reflog of HEAD to be updated, too.
2971 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2972 RESOLVE_REF_NO_RECURSE,
2973 head_oid.hash, &head_type);
2975 if (head_ref && !(head_type & REF_ISSYMREF)) {
2981 * Acquire all locks, verify old values if provided, check
2982 * that new values are valid, and write new values to the
2983 * lockfiles, ready to be activated. Only keep one lockfile
2984 * open at a time to avoid running out of file descriptors.
2985 * Note that lock_ref_for_update() might append more updates
2986 * to the transaction.
2988 for (i = 0; i < transaction->nr; i++) {
2989 struct ref_update *update = transaction->updates[i];
2991 ret = lock_ref_for_update(refs, update, transaction,
2992 head_ref, &affected_refnames, err);
2999 string_list_clear(&affected_refnames, 0);
3002 files_transaction_cleanup(transaction);
3004 transaction->state = REF_TRANSACTION_PREPARED;
3009 static int files_transaction_finish(struct ref_store *ref_store,
3010 struct ref_transaction *transaction,
3013 struct files_ref_store *refs =
3014 files_downcast(ref_store, 0, "ref_transaction_finish");
3017 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3018 struct string_list_item *ref_to_delete;
3019 struct strbuf sb = STRBUF_INIT;
3023 if (!transaction->nr) {
3024 transaction->state = REF_TRANSACTION_CLOSED;
3028 /* Perform updates first so live commits remain referenced */
3029 for (i = 0; i < transaction->nr; i++) {
3030 struct ref_update *update = transaction->updates[i];
3031 struct ref_lock *lock = update->backend_data;
3033 if (update->flags & REF_NEEDS_COMMIT ||
3034 update->flags & REF_LOG_ONLY) {
3035 if (files_log_ref_write(refs,
3039 update->msg, update->flags,
3041 char *old_msg = strbuf_detach(err, NULL);
3043 strbuf_addf(err, "cannot update the ref '%s': %s",
3044 lock->ref_name, old_msg);
3047 update->backend_data = NULL;
3048 ret = TRANSACTION_GENERIC_ERROR;
3052 if (update->flags & REF_NEEDS_COMMIT) {
3053 clear_loose_ref_cache(refs);
3054 if (commit_ref(lock)) {
3055 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3057 update->backend_data = NULL;
3058 ret = TRANSACTION_GENERIC_ERROR;
3063 /* Perform deletes now that updates are safely completed */
3064 for (i = 0; i < transaction->nr; i++) {
3065 struct ref_update *update = transaction->updates[i];
3066 struct ref_lock *lock = update->backend_data;
3068 if (update->flags & REF_DELETING &&
3069 !(update->flags & REF_LOG_ONLY)) {
3070 if (!(update->type & REF_ISPACKED) ||
3071 update->type & REF_ISSYMREF) {
3072 /* It is a loose reference. */
3074 files_ref_path(refs, &sb, lock->ref_name);
3075 if (unlink_or_msg(sb.buf, err)) {
3076 ret = TRANSACTION_GENERIC_ERROR;
3079 update->flags |= REF_DELETED_LOOSE;
3082 if (!(update->flags & REF_ISPRUNING))
3083 string_list_append(&refs_to_delete,
3088 if (repack_without_refs(refs, &refs_to_delete, err)) {
3089 ret = TRANSACTION_GENERIC_ERROR;
3093 /* Delete the reflogs of any references that were deleted: */
3094 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3096 files_reflog_path(refs, &sb, ref_to_delete->string);
3097 if (!unlink_or_warn(sb.buf))
3098 try_remove_empty_parents(refs, ref_to_delete->string,
3099 REMOVE_EMPTY_PARENTS_REFLOG);
3102 clear_loose_ref_cache(refs);
3105 files_transaction_cleanup(transaction);
3107 for (i = 0; i < transaction->nr; i++) {
3108 struct ref_update *update = transaction->updates[i];
3110 if (update->flags & REF_DELETED_LOOSE) {
3112 * The loose reference was deleted. Delete any
3113 * empty parent directories. (Note that this
3114 * can only work because we have already
3115 * removed the lockfile.)
3117 try_remove_empty_parents(refs, update->refname,
3118 REMOVE_EMPTY_PARENTS_REF);
3122 strbuf_release(&sb);
3123 string_list_clear(&refs_to_delete, 0);
3127 static int files_transaction_abort(struct ref_store *ref_store,
3128 struct ref_transaction *transaction,
3131 files_transaction_cleanup(transaction);
3135 static int ref_present(const char *refname,
3136 const struct object_id *oid, int flags, void *cb_data)
3138 struct string_list *affected_refnames = cb_data;
3140 return string_list_has_string(affected_refnames, refname);
3143 static int files_initial_transaction_commit(struct ref_store *ref_store,
3144 struct ref_transaction *transaction,
3147 struct files_ref_store *refs =
3148 files_downcast(ref_store, REF_STORE_WRITE,
3149 "initial_ref_transaction_commit");
3152 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3156 if (transaction->state != REF_TRANSACTION_OPEN)
3157 die("BUG: commit called for transaction that is not open");
3159 /* Fail if a refname appears more than once in the transaction: */
3160 for (i = 0; i < transaction->nr; i++)
3161 string_list_append(&affected_refnames,
3162 transaction->updates[i]->refname);
3163 string_list_sort(&affected_refnames);
3164 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3165 ret = TRANSACTION_GENERIC_ERROR;
3170 * It's really undefined to call this function in an active
3171 * repository or when there are existing references: we are
3172 * only locking and changing packed-refs, so (1) any
3173 * simultaneous processes might try to change a reference at
3174 * the same time we do, and (2) any existing loose versions of
3175 * the references that we are setting would have precedence
3176 * over our values. But some remote helpers create the remote
3177 * "HEAD" and "master" branches before calling this function,
3178 * so here we really only check that none of the references
3179 * that we are creating already exists.
3181 if (refs_for_each_rawref(&refs->base, ref_present,
3182 &affected_refnames))
3183 die("BUG: initial ref transaction called with existing refs");
3185 for (i = 0; i < transaction->nr; i++) {
3186 struct ref_update *update = transaction->updates[i];
3188 if ((update->flags & REF_HAVE_OLD) &&
3189 !is_null_oid(&update->old_oid))
3190 die("BUG: initial ref transaction with old_sha1 set");
3191 if (refs_verify_refname_available(&refs->base, update->refname,
3192 &affected_refnames, NULL,
3194 ret = TRANSACTION_NAME_CONFLICT;
3199 if (lock_packed_refs(refs, 0)) {
3200 strbuf_addf(err, "unable to lock packed-refs file: %s",
3202 ret = TRANSACTION_GENERIC_ERROR;
3206 for (i = 0; i < transaction->nr; i++) {
3207 struct ref_update *update = transaction->updates[i];
3209 if ((update->flags & REF_HAVE_NEW) &&
3210 !is_null_oid(&update->new_oid))
3211 add_packed_ref(refs, update->refname,
3215 if (commit_packed_refs(refs)) {
3216 strbuf_addf(err, "unable to commit packed-refs file: %s",
3218 ret = TRANSACTION_GENERIC_ERROR;
3223 transaction->state = REF_TRANSACTION_CLOSED;
3224 string_list_clear(&affected_refnames, 0);
3228 struct expire_reflog_cb {
3230 reflog_expiry_should_prune_fn *should_prune_fn;
3233 struct object_id last_kept_oid;
3236 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3237 const char *email, timestamp_t timestamp, int tz,
3238 const char *message, void *cb_data)
3240 struct expire_reflog_cb *cb = cb_data;
3241 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3243 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3244 ooid = &cb->last_kept_oid;
3246 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3247 message, policy_cb)) {
3249 printf("would prune %s", message);
3250 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3251 printf("prune %s", message);
3254 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3255 oid_to_hex(ooid), oid_to_hex(noid),
3256 email, timestamp, tz, message);
3257 oidcpy(&cb->last_kept_oid, noid);
3259 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3260 printf("keep %s", message);
3265 static int files_reflog_expire(struct ref_store *ref_store,
3266 const char *refname, const unsigned char *sha1,
3268 reflog_expiry_prepare_fn prepare_fn,
3269 reflog_expiry_should_prune_fn should_prune_fn,
3270 reflog_expiry_cleanup_fn cleanup_fn,
3271 void *policy_cb_data)
3273 struct files_ref_store *refs =
3274 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3275 static struct lock_file reflog_lock;
3276 struct expire_reflog_cb cb;
3277 struct ref_lock *lock;
3278 struct strbuf log_file_sb = STRBUF_INIT;
3282 struct strbuf err = STRBUF_INIT;
3283 struct object_id oid;
3285 memset(&cb, 0, sizeof(cb));
3287 cb.policy_cb = policy_cb_data;
3288 cb.should_prune_fn = should_prune_fn;
3291 * The reflog file is locked by holding the lock on the
3292 * reference itself, plus we might need to update the
3293 * reference if --updateref was specified:
3295 lock = lock_ref_sha1_basic(refs, refname, sha1,
3296 NULL, NULL, REF_NODEREF,
3299 error("cannot lock ref '%s': %s", refname, err.buf);
3300 strbuf_release(&err);
3303 if (!refs_reflog_exists(ref_store, refname)) {
3308 files_reflog_path(refs, &log_file_sb, refname);
3309 log_file = strbuf_detach(&log_file_sb, NULL);
3310 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3312 * Even though holding $GIT_DIR/logs/$reflog.lock has
3313 * no locking implications, we use the lock_file
3314 * machinery here anyway because it does a lot of the
3315 * work we need, including cleaning up if the program
3316 * exits unexpectedly.
3318 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3319 struct strbuf err = STRBUF_INIT;
3320 unable_to_lock_message(log_file, errno, &err);
3321 error("%s", err.buf);
3322 strbuf_release(&err);
3325 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3327 error("cannot fdopen %s (%s)",
3328 get_lock_file_path(&reflog_lock), strerror(errno));
3333 hashcpy(oid.hash, sha1);
3335 (*prepare_fn)(refname, &oid, cb.policy_cb);
3336 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3337 (*cleanup_fn)(cb.policy_cb);
3339 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3341 * It doesn't make sense to adjust a reference pointed
3342 * to by a symbolic ref based on expiring entries in
3343 * the symbolic reference's reflog. Nor can we update
3344 * a reference if there are no remaining reflog
3347 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3348 !(type & REF_ISSYMREF) &&
3349 !is_null_oid(&cb.last_kept_oid);
3351 if (close_lock_file(&reflog_lock)) {
3352 status |= error("couldn't write %s: %s", log_file,
3354 } else if (update &&
3355 (write_in_full(get_lock_file_fd(lock->lk),
3356 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3357 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3358 close_ref(lock) < 0)) {
3359 status |= error("couldn't write %s",
3360 get_lock_file_path(lock->lk));
3361 rollback_lock_file(&reflog_lock);
3362 } else if (commit_lock_file(&reflog_lock)) {
3363 status |= error("unable to write reflog '%s' (%s)",
3364 log_file, strerror(errno));
3365 } else if (update && commit_ref(lock)) {
3366 status |= error("couldn't set %s", lock->ref_name);
3374 rollback_lock_file(&reflog_lock);
3380 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3382 struct files_ref_store *refs =
3383 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3384 struct strbuf sb = STRBUF_INIT;
3387 * Create .git/refs/{heads,tags}
3389 files_ref_path(refs, &sb, "refs/heads");
3390 safe_create_dir(sb.buf, 1);
3393 files_ref_path(refs, &sb, "refs/tags");
3394 safe_create_dir(sb.buf, 1);
3396 strbuf_release(&sb);
3400 struct ref_storage_be refs_be_files = {
3403 files_ref_store_create,
3405 files_transaction_prepare,
3406 files_transaction_finish,
3407 files_transaction_abort,
3408 files_initial_transaction_commit,
3412 files_create_symref,
3417 files_ref_iterator_begin,
3420 files_reflog_iterator_begin,
3421 files_for_each_reflog_ent,
3422 files_for_each_reflog_ent_reverse,
3423 files_reflog_exists,
3424 files_create_reflog,
3425 files_delete_reflog,