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 * Check that the packed refs cache (if any) still reflects the
374 * contents of the file. If not, clear the cache.
376 static void validate_packed_ref_cache(struct files_ref_store *refs)
379 !stat_validity_check(&refs->packed->validity,
380 files_packed_refs_path(refs)))
381 clear_packed_ref_cache(refs);
385 * Get the packed_ref_cache for the specified files_ref_store,
386 * creating and populating it if it hasn't been read before or if the
387 * file has been changed (according to its `validity` field) since it
388 * was last read. On the other hand, if we hold the lock, then assume
389 * that the file hasn't been changed out from under us, so skip the
390 * extra `stat()` call in `stat_validity_check()`.
392 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
394 const char *packed_refs_file = files_packed_refs_path(refs);
396 if (!is_lock_file_locked(&refs->packed_refs_lock))
397 validate_packed_ref_cache(refs);
400 refs->packed = read_packed_refs(packed_refs_file);
405 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
407 return get_ref_dir(packed_ref_cache->cache->root);
410 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
412 return get_packed_ref_dir(get_packed_ref_cache(refs));
416 * Add a reference to the in-memory packed reference cache. This may
417 * only be called while the packed-refs file is locked (see
418 * lock_packed_refs()). To actually write the packed-refs file, call
419 * commit_packed_refs().
421 static void add_packed_ref(struct files_ref_store *refs,
422 const char *refname, const struct object_id *oid)
424 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
426 if (!is_lock_file_locked(&refs->packed_refs_lock))
427 die("BUG: packed refs not locked");
429 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
430 die("Reference has invalid format: '%s'", refname);
432 add_ref_entry(get_packed_ref_dir(packed_ref_cache),
433 create_ref_entry(refname, oid, REF_ISPACKED));
437 * Read the loose references from the namespace dirname into dir
438 * (without recursing). dirname must end with '/'. dir must be the
439 * directory entry corresponding to dirname.
441 static void loose_fill_ref_dir(struct ref_store *ref_store,
442 struct ref_dir *dir, const char *dirname)
444 struct files_ref_store *refs =
445 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
448 int dirnamelen = strlen(dirname);
449 struct strbuf refname;
450 struct strbuf path = STRBUF_INIT;
453 files_ref_path(refs, &path, dirname);
454 path_baselen = path.len;
456 d = opendir(path.buf);
458 strbuf_release(&path);
462 strbuf_init(&refname, dirnamelen + 257);
463 strbuf_add(&refname, dirname, dirnamelen);
465 while ((de = readdir(d)) != NULL) {
466 struct object_id oid;
470 if (de->d_name[0] == '.')
472 if (ends_with(de->d_name, ".lock"))
474 strbuf_addstr(&refname, de->d_name);
475 strbuf_addstr(&path, de->d_name);
476 if (stat(path.buf, &st) < 0) {
477 ; /* silently ignore */
478 } else if (S_ISDIR(st.st_mode)) {
479 strbuf_addch(&refname, '/');
480 add_entry_to_dir(dir,
481 create_dir_entry(dir->cache, refname.buf,
484 if (!refs_resolve_ref_unsafe(&refs->base,
489 flag |= REF_ISBROKEN;
490 } else if (is_null_oid(&oid)) {
492 * It is so astronomically unlikely
493 * that NULL_SHA1 is the SHA-1 of an
494 * actual object that we consider its
495 * appearance in a loose reference
496 * file to be repo corruption
497 * (probably due to a software bug).
499 flag |= REF_ISBROKEN;
502 if (check_refname_format(refname.buf,
503 REFNAME_ALLOW_ONELEVEL)) {
504 if (!refname_is_safe(refname.buf))
505 die("loose refname is dangerous: %s", refname.buf);
507 flag |= REF_BAD_NAME | REF_ISBROKEN;
509 add_entry_to_dir(dir,
510 create_ref_entry(refname.buf, &oid, flag));
512 strbuf_setlen(&refname, dirnamelen);
513 strbuf_setlen(&path, path_baselen);
515 strbuf_release(&refname);
516 strbuf_release(&path);
520 * Manually add refs/bisect, which, being per-worktree, might
521 * not appear in the directory listing for refs/ in the main
524 if (!strcmp(dirname, "refs/")) {
525 int pos = search_ref_dir(dir, "refs/bisect/", 12);
528 struct ref_entry *child_entry = create_dir_entry(
529 dir->cache, "refs/bisect/", 12, 1);
530 add_entry_to_dir(dir, child_entry);
535 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
539 * Mark the top-level directory complete because we
540 * are about to read the only subdirectory that can
543 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
545 /* We're going to fill the top level ourselves: */
546 refs->loose->root->flag &= ~REF_INCOMPLETE;
549 * Add an incomplete entry for "refs/" (to be filled
552 add_entry_to_dir(get_ref_dir(refs->loose->root),
553 create_dir_entry(refs->loose, "refs/", 5, 1));
559 * Return the ref_entry for the given refname from the packed
560 * references. If it does not exist, return NULL.
562 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
565 return find_ref_entry(get_packed_refs(refs), refname);
569 * A loose ref file doesn't exist; check for a packed ref.
571 static int resolve_packed_ref(struct files_ref_store *refs,
573 unsigned char *sha1, unsigned int *flags)
575 struct ref_entry *entry;
578 * The loose reference file does not exist; check for a packed
581 entry = get_packed_ref(refs, refname);
583 hashcpy(sha1, entry->u.value.oid.hash);
584 *flags |= REF_ISPACKED;
587 /* refname is not a packed reference. */
591 static int files_read_raw_ref(struct ref_store *ref_store,
592 const char *refname, unsigned char *sha1,
593 struct strbuf *referent, unsigned int *type)
595 struct files_ref_store *refs =
596 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
597 struct strbuf sb_contents = STRBUF_INIT;
598 struct strbuf sb_path = STRBUF_INIT;
605 int remaining_retries = 3;
608 strbuf_reset(&sb_path);
610 files_ref_path(refs, &sb_path, refname);
616 * We might have to loop back here to avoid a race
617 * condition: first we lstat() the file, then we try
618 * to read it as a link or as a file. But if somebody
619 * changes the type of the file (file <-> directory
620 * <-> symlink) between the lstat() and reading, then
621 * we don't want to report that as an error but rather
622 * try again starting with the lstat().
624 * We'll keep a count of the retries, though, just to avoid
625 * any confusing situation sending us into an infinite loop.
628 if (remaining_retries-- <= 0)
631 if (lstat(path, &st) < 0) {
634 if (resolve_packed_ref(refs, refname, sha1, type)) {
642 /* Follow "normalized" - ie "refs/.." symlinks by hand */
643 if (S_ISLNK(st.st_mode)) {
644 strbuf_reset(&sb_contents);
645 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
646 if (errno == ENOENT || errno == EINVAL)
647 /* inconsistent with lstat; retry */
652 if (starts_with(sb_contents.buf, "refs/") &&
653 !check_refname_format(sb_contents.buf, 0)) {
654 strbuf_swap(&sb_contents, referent);
655 *type |= REF_ISSYMREF;
660 * It doesn't look like a refname; fall through to just
661 * treating it like a non-symlink, and reading whatever it
666 /* Is it a directory? */
667 if (S_ISDIR(st.st_mode)) {
669 * Even though there is a directory where the loose
670 * ref is supposed to be, there could still be a
673 if (resolve_packed_ref(refs, refname, sha1, type)) {
682 * Anything else, just open it and try to use it as
685 fd = open(path, O_RDONLY);
687 if (errno == ENOENT && !S_ISLNK(st.st_mode))
688 /* inconsistent with lstat; retry */
693 strbuf_reset(&sb_contents);
694 if (strbuf_read(&sb_contents, fd, 256) < 0) {
695 int save_errno = errno;
701 strbuf_rtrim(&sb_contents);
702 buf = sb_contents.buf;
703 if (starts_with(buf, "ref:")) {
705 while (isspace(*buf))
708 strbuf_reset(referent);
709 strbuf_addstr(referent, buf);
710 *type |= REF_ISSYMREF;
716 * Please note that FETCH_HEAD has additional
717 * data after the sha.
719 if (get_sha1_hex(buf, sha1) ||
720 (buf[40] != '\0' && !isspace(buf[40]))) {
721 *type |= REF_ISBROKEN;
730 strbuf_release(&sb_path);
731 strbuf_release(&sb_contents);
736 static void unlock_ref(struct ref_lock *lock)
738 /* Do not free lock->lk -- atexit() still looks at them */
740 rollback_lock_file(lock->lk);
741 free(lock->ref_name);
746 * Lock refname, without following symrefs, and set *lock_p to point
747 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
748 * and type similarly to read_raw_ref().
750 * The caller must verify that refname is a "safe" reference name (in
751 * the sense of refname_is_safe()) before calling this function.
753 * If the reference doesn't already exist, verify that refname doesn't
754 * have a D/F conflict with any existing references. extras and skip
755 * are passed to refs_verify_refname_available() for this check.
757 * If mustexist is not set and the reference is not found or is
758 * broken, lock the reference anyway but clear sha1.
760 * Return 0 on success. On failure, write an error message to err and
761 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
763 * Implementation note: This function is basically
768 * but it includes a lot more code to
769 * - Deal with possible races with other processes
770 * - Avoid calling refs_verify_refname_available() when it can be
771 * avoided, namely if we were successfully able to read the ref
772 * - Generate informative error messages in the case of failure
774 static int lock_raw_ref(struct files_ref_store *refs,
775 const char *refname, int mustexist,
776 const struct string_list *extras,
777 const struct string_list *skip,
778 struct ref_lock **lock_p,
779 struct strbuf *referent,
783 struct ref_lock *lock;
784 struct strbuf ref_file = STRBUF_INIT;
785 int attempts_remaining = 3;
786 int ret = TRANSACTION_GENERIC_ERROR;
789 files_assert_main_repository(refs, "lock_raw_ref");
793 /* First lock the file so it can't change out from under us. */
795 *lock_p = lock = xcalloc(1, sizeof(*lock));
797 lock->ref_name = xstrdup(refname);
798 files_ref_path(refs, &ref_file, refname);
801 switch (safe_create_leading_directories(ref_file.buf)) {
806 * Suppose refname is "refs/foo/bar". We just failed
807 * to create the containing directory, "refs/foo",
808 * because there was a non-directory in the way. This
809 * indicates a D/F conflict, probably because of
810 * another reference such as "refs/foo". There is no
811 * reason to expect this error to be transitory.
813 if (refs_verify_refname_available(&refs->base, refname,
814 extras, skip, err)) {
817 * To the user the relevant error is
818 * that the "mustexist" reference is
822 strbuf_addf(err, "unable to resolve reference '%s'",
826 * The error message set by
827 * refs_verify_refname_available() is
830 ret = TRANSACTION_NAME_CONFLICT;
834 * The file that is in the way isn't a loose
835 * reference. Report it as a low-level
838 strbuf_addf(err, "unable to create lock file %s.lock; "
839 "non-directory in the way",
844 /* Maybe another process was tidying up. Try again. */
845 if (--attempts_remaining > 0)
849 strbuf_addf(err, "unable to create directory for %s",
855 lock->lk = xcalloc(1, sizeof(struct lock_file));
857 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
858 if (errno == ENOENT && --attempts_remaining > 0) {
860 * Maybe somebody just deleted one of the
861 * directories leading to ref_file. Try
866 unable_to_lock_message(ref_file.buf, errno, err);
872 * Now we hold the lock and can read the reference without
873 * fear that its value will change.
876 if (files_read_raw_ref(&refs->base, refname,
877 lock->old_oid.hash, referent, type)) {
878 if (errno == ENOENT) {
880 /* Garden variety missing reference. */
881 strbuf_addf(err, "unable to resolve reference '%s'",
886 * Reference is missing, but that's OK. We
887 * know that there is not a conflict with
888 * another loose reference because
889 * (supposing that we are trying to lock
890 * reference "refs/foo/bar"):
892 * - We were successfully able to create
893 * the lockfile refs/foo/bar.lock, so we
894 * know there cannot be a loose reference
897 * - We got ENOENT and not EISDIR, so we
898 * know that there cannot be a loose
899 * reference named "refs/foo/bar/baz".
902 } else if (errno == EISDIR) {
904 * There is a directory in the way. It might have
905 * contained references that have been deleted. If
906 * we don't require that the reference already
907 * exists, try to remove the directory so that it
908 * doesn't cause trouble when we want to rename the
909 * lockfile into place later.
912 /* Garden variety missing reference. */
913 strbuf_addf(err, "unable to resolve reference '%s'",
916 } else if (remove_dir_recursively(&ref_file,
917 REMOVE_DIR_EMPTY_ONLY)) {
918 if (refs_verify_refname_available(
919 &refs->base, refname,
920 extras, skip, err)) {
922 * The error message set by
923 * verify_refname_available() is OK.
925 ret = TRANSACTION_NAME_CONFLICT;
929 * We can't delete the directory,
930 * but we also don't know of any
931 * references that it should
934 strbuf_addf(err, "there is a non-empty directory '%s' "
935 "blocking reference '%s'",
936 ref_file.buf, refname);
940 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
941 strbuf_addf(err, "unable to resolve reference '%s': "
942 "reference broken", refname);
945 strbuf_addf(err, "unable to resolve reference '%s': %s",
946 refname, strerror(errno));
951 * If the ref did not exist and we are creating it,
952 * make sure there is no existing ref that conflicts
955 if (refs_verify_refname_available(
956 &refs->base, refname,
969 strbuf_release(&ref_file);
973 static int files_peel_ref(struct ref_store *ref_store,
974 const char *refname, unsigned char *sha1)
976 struct files_ref_store *refs =
977 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
980 unsigned char base[20];
982 if (current_ref_iter && current_ref_iter->refname == refname) {
983 struct object_id peeled;
985 if (ref_iterator_peel(current_ref_iter, &peeled))
987 hashcpy(sha1, peeled.hash);
991 if (refs_read_ref_full(ref_store, refname,
992 RESOLVE_REF_READING, base, &flag))
996 * If the reference is packed, read its ref_entry from the
997 * cache in the hope that we already know its peeled value.
998 * We only try this optimization on packed references because
999 * (a) forcing the filling of the loose reference cache could
1000 * be expensive and (b) loose references anyway usually do not
1001 * have REF_KNOWS_PEELED.
1003 if (flag & REF_ISPACKED) {
1004 struct ref_entry *r = get_packed_ref(refs, refname);
1006 if (peel_entry(r, 0))
1008 hashcpy(sha1, r->u.value.peeled.hash);
1013 return peel_object(base, sha1);
1016 struct files_ref_iterator {
1017 struct ref_iterator base;
1019 struct packed_ref_cache *packed_ref_cache;
1020 struct ref_iterator *iter0;
1024 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1026 struct files_ref_iterator *iter =
1027 (struct files_ref_iterator *)ref_iterator;
1030 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1031 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1032 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1035 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1036 !ref_resolves_to_object(iter->iter0->refname,
1038 iter->iter0->flags))
1041 iter->base.refname = iter->iter0->refname;
1042 iter->base.oid = iter->iter0->oid;
1043 iter->base.flags = iter->iter0->flags;
1048 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1054 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1055 struct object_id *peeled)
1057 struct files_ref_iterator *iter =
1058 (struct files_ref_iterator *)ref_iterator;
1060 return ref_iterator_peel(iter->iter0, peeled);
1063 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1065 struct files_ref_iterator *iter =
1066 (struct files_ref_iterator *)ref_iterator;
1070 ok = ref_iterator_abort(iter->iter0);
1072 release_packed_ref_cache(iter->packed_ref_cache);
1073 base_ref_iterator_free(ref_iterator);
1077 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1078 files_ref_iterator_advance,
1079 files_ref_iterator_peel,
1080 files_ref_iterator_abort
1083 static struct ref_iterator *files_ref_iterator_begin(
1084 struct ref_store *ref_store,
1085 const char *prefix, unsigned int flags)
1087 struct files_ref_store *refs;
1088 struct ref_iterator *loose_iter, *packed_iter;
1089 struct files_ref_iterator *iter;
1090 struct ref_iterator *ref_iterator;
1091 unsigned int required_flags = REF_STORE_READ;
1093 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1094 required_flags |= REF_STORE_ODB;
1096 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1098 iter = xcalloc(1, sizeof(*iter));
1099 ref_iterator = &iter->base;
1100 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1103 * We must make sure that all loose refs are read before
1104 * accessing the packed-refs file; this avoids a race
1105 * condition if loose refs are migrated to the packed-refs
1106 * file by a simultaneous process, but our in-memory view is
1107 * from before the migration. We ensure this as follows:
1108 * First, we call start the loose refs iteration with its
1109 * `prime_ref` argument set to true. This causes the loose
1110 * references in the subtree to be pre-read into the cache.
1111 * (If they've already been read, that's OK; we only need to
1112 * guarantee that they're read before the packed refs, not
1113 * *how much* before.) After that, we call
1114 * get_packed_ref_cache(), which internally checks whether the
1115 * packed-ref cache is up to date with what is on disk, and
1116 * re-reads it if not.
1119 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1122 iter->packed_ref_cache = get_packed_ref_cache(refs);
1123 acquire_packed_ref_cache(iter->packed_ref_cache);
1124 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1127 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1128 iter->flags = flags;
1130 return ref_iterator;
1134 * Verify that the reference locked by lock has the value old_sha1.
1135 * Fail if the reference doesn't exist and mustexist is set. Return 0
1136 * on success. On error, write an error message to err, set errno, and
1137 * return a negative value.
1139 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1140 const unsigned char *old_sha1, int mustexist,
1145 if (refs_read_ref_full(ref_store, lock->ref_name,
1146 mustexist ? RESOLVE_REF_READING : 0,
1147 lock->old_oid.hash, NULL)) {
1149 int save_errno = errno;
1150 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1154 oidclr(&lock->old_oid);
1158 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1159 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1161 oid_to_hex(&lock->old_oid),
1162 sha1_to_hex(old_sha1));
1169 static int remove_empty_directories(struct strbuf *path)
1172 * we want to create a file but there is a directory there;
1173 * if that is an empty directory (or a directory that contains
1174 * only empty directories), remove them.
1176 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1179 static int create_reflock(const char *path, void *cb)
1181 struct lock_file *lk = cb;
1183 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1187 * Locks a ref returning the lock on success and NULL on failure.
1188 * On failure errno is set to something meaningful.
1190 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1191 const char *refname,
1192 const unsigned char *old_sha1,
1193 const struct string_list *extras,
1194 const struct string_list *skip,
1195 unsigned int flags, int *type,
1198 struct strbuf ref_file = STRBUF_INIT;
1199 struct ref_lock *lock;
1201 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1202 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1205 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1208 lock = xcalloc(1, sizeof(struct ref_lock));
1211 resolve_flags |= RESOLVE_REF_READING;
1212 if (flags & REF_DELETING)
1213 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1215 files_ref_path(refs, &ref_file, refname);
1216 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1217 refname, resolve_flags,
1218 lock->old_oid.hash, type);
1219 if (!resolved && errno == EISDIR) {
1221 * we are trying to lock foo but we used to
1222 * have foo/bar which now does not exist;
1223 * it is normal for the empty directory 'foo'
1226 if (remove_empty_directories(&ref_file)) {
1228 if (!refs_verify_refname_available(
1230 refname, extras, skip, err))
1231 strbuf_addf(err, "there are still refs under '%s'",
1235 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1236 refname, resolve_flags,
1237 lock->old_oid.hash, type);
1241 if (last_errno != ENOTDIR ||
1242 !refs_verify_refname_available(&refs->base, refname,
1244 strbuf_addf(err, "unable to resolve reference '%s': %s",
1245 refname, strerror(last_errno));
1251 * If the ref did not exist and we are creating it, make sure
1252 * there is no existing packed ref whose name begins with our
1253 * refname, nor a packed ref whose name is a proper prefix of
1256 if (is_null_oid(&lock->old_oid) &&
1257 refs_verify_refname_available(&refs->base, refname,
1258 extras, skip, err)) {
1259 last_errno = ENOTDIR;
1263 lock->lk = xcalloc(1, sizeof(struct lock_file));
1265 lock->ref_name = xstrdup(refname);
1267 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1269 unable_to_lock_message(ref_file.buf, errno, err);
1273 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1284 strbuf_release(&ref_file);
1290 * Write an entry to the packed-refs file for the specified refname.
1291 * If peeled is non-NULL, write it as the entry's peeled value.
1293 static void write_packed_entry(FILE *fh, const char *refname,
1294 const unsigned char *sha1,
1295 const unsigned char *peeled)
1297 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1299 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1303 * Lock the packed-refs file for writing. Flags is passed to
1304 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1305 * errno appropriately and return a nonzero value.
1307 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1309 static int timeout_configured = 0;
1310 static int timeout_value = 1000;
1311 struct packed_ref_cache *packed_ref_cache;
1313 files_assert_main_repository(refs, "lock_packed_refs");
1315 if (!timeout_configured) {
1316 git_config_get_int("core.packedrefstimeout", &timeout_value);
1317 timeout_configured = 1;
1320 if (hold_lock_file_for_update_timeout(
1321 &refs->packed_refs_lock, files_packed_refs_path(refs),
1322 flags, timeout_value) < 0)
1326 * Now that we hold the `packed-refs` lock, make sure that our
1327 * cache matches the current version of the file. Normally
1328 * `get_packed_ref_cache()` does that for us, but that
1329 * function assumes that when the file is locked, any existing
1330 * cache is still valid. We've just locked the file, but it
1331 * might have changed the moment *before* we locked it.
1333 validate_packed_ref_cache(refs);
1335 packed_ref_cache = get_packed_ref_cache(refs);
1336 /* Increment the reference count to prevent it from being freed: */
1337 acquire_packed_ref_cache(packed_ref_cache);
1342 * Write the current version of the packed refs cache from memory to
1343 * disk. The packed-refs file must already be locked for writing (see
1344 * lock_packed_refs()). Return zero on success. On errors, set errno
1345 * and return a nonzero value
1347 static int commit_packed_refs(struct files_ref_store *refs)
1349 struct packed_ref_cache *packed_ref_cache =
1350 get_packed_ref_cache(refs);
1354 struct ref_iterator *iter;
1356 files_assert_main_repository(refs, "commit_packed_refs");
1358 if (!is_lock_file_locked(&refs->packed_refs_lock))
1359 die("BUG: packed-refs not locked");
1361 out = fdopen_lock_file(&refs->packed_refs_lock, "w");
1363 die_errno("unable to fdopen packed-refs descriptor");
1365 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1367 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1368 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1369 struct object_id peeled;
1370 int peel_error = ref_iterator_peel(iter, &peeled);
1372 write_packed_entry(out, iter->refname, iter->oid->hash,
1373 peel_error ? NULL : peeled.hash);
1376 if (ok != ITER_DONE)
1377 die("error while iterating over references");
1379 if (commit_lock_file(&refs->packed_refs_lock)) {
1383 release_packed_ref_cache(packed_ref_cache);
1389 * Rollback the lockfile for the packed-refs file, and discard the
1390 * in-memory packed reference cache. (The packed-refs file will be
1391 * read anew if it is needed again after this function is called.)
1393 static void rollback_packed_refs(struct files_ref_store *refs)
1395 struct packed_ref_cache *packed_ref_cache =
1396 get_packed_ref_cache(refs);
1398 files_assert_main_repository(refs, "rollback_packed_refs");
1400 if (!is_lock_file_locked(&refs->packed_refs_lock))
1401 die("BUG: packed-refs not locked");
1402 rollback_lock_file(&refs->packed_refs_lock);
1403 release_packed_ref_cache(packed_ref_cache);
1404 clear_packed_ref_cache(refs);
1407 struct ref_to_prune {
1408 struct ref_to_prune *next;
1409 unsigned char sha1[20];
1410 char name[FLEX_ARRAY];
1414 REMOVE_EMPTY_PARENTS_REF = 0x01,
1415 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1419 * Remove empty parent directories associated with the specified
1420 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1421 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1422 * REMOVE_EMPTY_PARENTS_REFLOG.
1424 static void try_remove_empty_parents(struct files_ref_store *refs,
1425 const char *refname,
1428 struct strbuf buf = STRBUF_INIT;
1429 struct strbuf sb = STRBUF_INIT;
1433 strbuf_addstr(&buf, refname);
1435 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1436 while (*p && *p != '/')
1438 /* tolerate duplicate slashes; see check_refname_format() */
1442 q = buf.buf + buf.len;
1443 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1444 while (q > p && *q != '/')
1446 while (q > p && *(q-1) == '/')
1450 strbuf_setlen(&buf, q - buf.buf);
1453 files_ref_path(refs, &sb, buf.buf);
1454 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1455 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1458 files_reflog_path(refs, &sb, buf.buf);
1459 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1460 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1462 strbuf_release(&buf);
1463 strbuf_release(&sb);
1466 /* make sure nobody touched the ref, and unlink */
1467 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1469 struct ref_transaction *transaction;
1470 struct strbuf err = STRBUF_INIT;
1472 if (check_refname_format(r->name, 0))
1475 transaction = ref_store_transaction_begin(&refs->base, &err);
1477 ref_transaction_delete(transaction, r->name, r->sha1,
1478 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1479 ref_transaction_commit(transaction, &err)) {
1480 ref_transaction_free(transaction);
1481 error("%s", err.buf);
1482 strbuf_release(&err);
1485 ref_transaction_free(transaction);
1486 strbuf_release(&err);
1489 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1498 * Return true if the specified reference should be packed.
1500 static int should_pack_ref(const char *refname,
1501 const struct object_id *oid, unsigned int ref_flags,
1502 unsigned int pack_flags)
1504 /* Do not pack per-worktree refs: */
1505 if (ref_type(refname) != REF_TYPE_NORMAL)
1508 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1509 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1512 /* Do not pack symbolic refs: */
1513 if (ref_flags & REF_ISSYMREF)
1516 /* Do not pack broken refs: */
1517 if (!ref_resolves_to_object(refname, oid, ref_flags))
1523 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1525 struct files_ref_store *refs =
1526 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1528 struct ref_iterator *iter;
1529 struct ref_dir *packed_refs;
1531 struct ref_to_prune *refs_to_prune = NULL;
1533 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1534 packed_refs = get_packed_refs(refs);
1536 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1537 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1539 * If the loose reference can be packed, add an entry
1540 * in the packed ref cache. If the reference should be
1541 * pruned, also add it to refs_to_prune.
1543 struct ref_entry *packed_entry;
1545 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1550 * Create an entry in the packed-refs cache equivalent
1551 * to the one from the loose ref cache, except that
1552 * we don't copy the peeled status, because we want it
1555 packed_entry = find_ref_entry(packed_refs, iter->refname);
1557 /* Overwrite existing packed entry with info from loose entry */
1558 packed_entry->flag = REF_ISPACKED;
1559 oidcpy(&packed_entry->u.value.oid, iter->oid);
1561 packed_entry = create_ref_entry(iter->refname, iter->oid,
1563 add_ref_entry(packed_refs, packed_entry);
1565 oidclr(&packed_entry->u.value.peeled);
1567 /* Schedule the loose reference for pruning if requested. */
1568 if ((flags & PACK_REFS_PRUNE)) {
1569 struct ref_to_prune *n;
1570 FLEX_ALLOC_STR(n, name, iter->refname);
1571 hashcpy(n->sha1, iter->oid->hash);
1572 n->next = refs_to_prune;
1576 if (ok != ITER_DONE)
1577 die("error while iterating over references");
1579 if (commit_packed_refs(refs))
1580 die_errno("unable to overwrite old ref-pack file");
1582 prune_refs(refs, refs_to_prune);
1587 * Rewrite the packed-refs file, omitting any refs listed in
1588 * 'refnames'. On error, leave packed-refs unchanged, write an error
1589 * message to 'err', and return a nonzero value.
1591 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1593 static int repack_without_refs(struct files_ref_store *refs,
1594 struct string_list *refnames, struct strbuf *err)
1596 struct ref_dir *packed;
1597 struct string_list_item *refname;
1598 int ret, needs_repacking = 0, removed = 0;
1600 files_assert_main_repository(refs, "repack_without_refs");
1603 /* Look for a packed ref */
1604 for_each_string_list_item(refname, refnames) {
1605 if (get_packed_ref(refs, refname->string)) {
1606 needs_repacking = 1;
1611 /* Avoid locking if we have nothing to do */
1612 if (!needs_repacking)
1613 return 0; /* no refname exists in packed refs */
1615 if (lock_packed_refs(refs, 0)) {
1616 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1619 packed = get_packed_refs(refs);
1621 /* Remove refnames from the cache */
1622 for_each_string_list_item(refname, refnames)
1623 if (remove_entry_from_dir(packed, refname->string) != -1)
1627 * All packed entries disappeared while we were
1628 * acquiring the lock.
1630 rollback_packed_refs(refs);
1634 /* Write what remains */
1635 ret = commit_packed_refs(refs);
1637 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1642 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1643 struct string_list *refnames, unsigned int flags)
1645 struct files_ref_store *refs =
1646 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1647 struct strbuf err = STRBUF_INIT;
1653 result = repack_without_refs(refs, refnames, &err);
1656 * If we failed to rewrite the packed-refs file, then
1657 * it is unsafe to try to remove loose refs, because
1658 * doing so might expose an obsolete packed value for
1659 * a reference that might even point at an object that
1660 * has been garbage collected.
1662 if (refnames->nr == 1)
1663 error(_("could not delete reference %s: %s"),
1664 refnames->items[0].string, err.buf);
1666 error(_("could not delete references: %s"), err.buf);
1671 for (i = 0; i < refnames->nr; i++) {
1672 const char *refname = refnames->items[i].string;
1674 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1675 result |= error(_("could not remove reference %s"), refname);
1679 strbuf_release(&err);
1684 * People using contrib's git-new-workdir have .git/logs/refs ->
1685 * /some/other/path/.git/logs/refs, and that may live on another device.
1687 * IOW, to avoid cross device rename errors, the temporary renamed log must
1688 * live into logs/refs.
1690 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1693 const char *tmp_renamed_log;
1697 static int rename_tmp_log_callback(const char *path, void *cb_data)
1699 struct rename_cb *cb = cb_data;
1701 if (rename(cb->tmp_renamed_log, path)) {
1703 * rename(a, b) when b is an existing directory ought
1704 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1705 * Sheesh. Record the true errno for error reporting,
1706 * but report EISDIR to raceproof_create_file() so
1707 * that it knows to retry.
1709 cb->true_errno = errno;
1710 if (errno == ENOTDIR)
1718 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1720 struct strbuf path = STRBUF_INIT;
1721 struct strbuf tmp = STRBUF_INIT;
1722 struct rename_cb cb;
1725 files_reflog_path(refs, &path, newrefname);
1726 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1727 cb.tmp_renamed_log = tmp.buf;
1728 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1730 if (errno == EISDIR)
1731 error("directory not empty: %s", path.buf);
1733 error("unable to move logfile %s to %s: %s",
1735 strerror(cb.true_errno));
1738 strbuf_release(&path);
1739 strbuf_release(&tmp);
1743 static int write_ref_to_lockfile(struct ref_lock *lock,
1744 const struct object_id *oid, struct strbuf *err);
1745 static int commit_ref_update(struct files_ref_store *refs,
1746 struct ref_lock *lock,
1747 const struct object_id *oid, const char *logmsg,
1748 struct strbuf *err);
1750 static int files_rename_ref(struct ref_store *ref_store,
1751 const char *oldrefname, const char *newrefname,
1754 struct files_ref_store *refs =
1755 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1756 struct object_id oid, orig_oid;
1757 int flag = 0, logmoved = 0;
1758 struct ref_lock *lock;
1759 struct stat loginfo;
1760 struct strbuf sb_oldref = STRBUF_INIT;
1761 struct strbuf sb_newref = STRBUF_INIT;
1762 struct strbuf tmp_renamed_log = STRBUF_INIT;
1764 struct strbuf err = STRBUF_INIT;
1766 files_reflog_path(refs, &sb_oldref, oldrefname);
1767 files_reflog_path(refs, &sb_newref, newrefname);
1768 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1770 log = !lstat(sb_oldref.buf, &loginfo);
1771 if (log && S_ISLNK(loginfo.st_mode)) {
1772 ret = error("reflog for %s is a symlink", oldrefname);
1776 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1777 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1778 orig_oid.hash, &flag)) {
1779 ret = error("refname %s not found", oldrefname);
1783 if (flag & REF_ISSYMREF) {
1784 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1788 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1793 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1794 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1795 oldrefname, strerror(errno));
1799 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1800 orig_oid.hash, REF_NODEREF)) {
1801 error("unable to delete old %s", oldrefname);
1806 * Since we are doing a shallow lookup, oid is not the
1807 * correct value to pass to delete_ref as old_oid. But that
1808 * doesn't matter, because an old_oid check wouldn't add to
1809 * the safety anyway; we want to delete the reference whatever
1810 * its current value.
1812 if (!refs_read_ref_full(&refs->base, newrefname,
1813 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1815 refs_delete_ref(&refs->base, NULL, newrefname,
1816 NULL, REF_NODEREF)) {
1817 if (errno == EISDIR) {
1818 struct strbuf path = STRBUF_INIT;
1821 files_ref_path(refs, &path, newrefname);
1822 result = remove_empty_directories(&path);
1823 strbuf_release(&path);
1826 error("Directory not empty: %s", newrefname);
1830 error("unable to delete existing %s", newrefname);
1835 if (log && rename_tmp_log(refs, newrefname))
1840 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1841 REF_NODEREF, NULL, &err);
1843 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1844 strbuf_release(&err);
1847 oidcpy(&lock->old_oid, &orig_oid);
1849 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1850 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1851 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1852 strbuf_release(&err);
1860 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1861 REF_NODEREF, NULL, &err);
1863 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1864 strbuf_release(&err);
1868 flag = log_all_ref_updates;
1869 log_all_ref_updates = LOG_REFS_NONE;
1870 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1871 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1872 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1873 strbuf_release(&err);
1875 log_all_ref_updates = flag;
1878 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1879 error("unable to restore logfile %s from %s: %s",
1880 oldrefname, newrefname, strerror(errno));
1881 if (!logmoved && log &&
1882 rename(tmp_renamed_log.buf, sb_oldref.buf))
1883 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1884 oldrefname, strerror(errno));
1887 strbuf_release(&sb_newref);
1888 strbuf_release(&sb_oldref);
1889 strbuf_release(&tmp_renamed_log);
1894 static int close_ref(struct ref_lock *lock)
1896 if (close_lock_file(lock->lk))
1901 static int commit_ref(struct ref_lock *lock)
1903 char *path = get_locked_file_path(lock->lk);
1906 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1908 * There is a directory at the path we want to rename
1909 * the lockfile to. Hopefully it is empty; try to
1912 size_t len = strlen(path);
1913 struct strbuf sb_path = STRBUF_INIT;
1915 strbuf_attach(&sb_path, path, len, len);
1918 * If this fails, commit_lock_file() will also fail
1919 * and will report the problem.
1921 remove_empty_directories(&sb_path);
1922 strbuf_release(&sb_path);
1927 if (commit_lock_file(lock->lk))
1932 static int open_or_create_logfile(const char *path, void *cb)
1936 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1937 return (*fd < 0) ? -1 : 0;
1941 * Create a reflog for a ref. If force_create = 0, only create the
1942 * reflog for certain refs (those for which should_autocreate_reflog
1943 * returns non-zero). Otherwise, create it regardless of the reference
1944 * name. If the logfile already existed or was created, return 0 and
1945 * set *logfd to the file descriptor opened for appending to the file.
1946 * If no logfile exists and we decided not to create one, return 0 and
1947 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1950 static int log_ref_setup(struct files_ref_store *refs,
1951 const char *refname, int force_create,
1952 int *logfd, struct strbuf *err)
1954 struct strbuf logfile_sb = STRBUF_INIT;
1957 files_reflog_path(refs, &logfile_sb, refname);
1958 logfile = strbuf_detach(&logfile_sb, NULL);
1960 if (force_create || should_autocreate_reflog(refname)) {
1961 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1962 if (errno == ENOENT)
1963 strbuf_addf(err, "unable to create directory for '%s': "
1964 "%s", logfile, strerror(errno));
1965 else if (errno == EISDIR)
1966 strbuf_addf(err, "there are still logs under '%s'",
1969 strbuf_addf(err, "unable to append to '%s': %s",
1970 logfile, strerror(errno));
1975 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1977 if (errno == ENOENT || errno == EISDIR) {
1979 * The logfile doesn't already exist,
1980 * but that is not an error; it only
1981 * means that we won't write log
1986 strbuf_addf(err, "unable to append to '%s': %s",
1987 logfile, strerror(errno));
1994 adjust_shared_perm(logfile);
2004 static int files_create_reflog(struct ref_store *ref_store,
2005 const char *refname, int force_create,
2008 struct files_ref_store *refs =
2009 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2012 if (log_ref_setup(refs, refname, force_create, &fd, err))
2021 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2022 const struct object_id *new_oid,
2023 const char *committer, const char *msg)
2025 int msglen, written;
2026 unsigned maxlen, len;
2029 msglen = msg ? strlen(msg) : 0;
2030 maxlen = strlen(committer) + msglen + 100;
2031 logrec = xmalloc(maxlen);
2032 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2033 oid_to_hex(old_oid),
2034 oid_to_hex(new_oid),
2037 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2039 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2047 static int files_log_ref_write(struct files_ref_store *refs,
2048 const char *refname, const struct object_id *old_oid,
2049 const struct object_id *new_oid, const char *msg,
2050 int flags, struct strbuf *err)
2054 if (log_all_ref_updates == LOG_REFS_UNSET)
2055 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2057 result = log_ref_setup(refs, refname,
2058 flags & REF_FORCE_CREATE_REFLOG,
2066 result = log_ref_write_fd(logfd, old_oid, new_oid,
2067 git_committer_info(0), msg);
2069 struct strbuf sb = STRBUF_INIT;
2070 int save_errno = errno;
2072 files_reflog_path(refs, &sb, refname);
2073 strbuf_addf(err, "unable to append to '%s': %s",
2074 sb.buf, strerror(save_errno));
2075 strbuf_release(&sb);
2080 struct strbuf sb = STRBUF_INIT;
2081 int save_errno = errno;
2083 files_reflog_path(refs, &sb, refname);
2084 strbuf_addf(err, "unable to append to '%s': %s",
2085 sb.buf, strerror(save_errno));
2086 strbuf_release(&sb);
2093 * Write sha1 into the open lockfile, then close the lockfile. On
2094 * errors, rollback the lockfile, fill in *err and
2097 static int write_ref_to_lockfile(struct ref_lock *lock,
2098 const struct object_id *oid, struct strbuf *err)
2100 static char term = '\n';
2104 o = parse_object(oid);
2107 "trying to write ref '%s' with nonexistent object %s",
2108 lock->ref_name, oid_to_hex(oid));
2112 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2114 "trying to write non-commit object %s to branch '%s'",
2115 oid_to_hex(oid), lock->ref_name);
2119 fd = get_lock_file_fd(lock->lk);
2120 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2121 write_in_full(fd, &term, 1) != 1 ||
2122 close_ref(lock) < 0) {
2124 "couldn't write '%s'", get_lock_file_path(lock->lk));
2132 * Commit a change to a loose reference that has already been written
2133 * to the loose reference lockfile. Also update the reflogs if
2134 * necessary, using the specified lockmsg (which can be NULL).
2136 static int commit_ref_update(struct files_ref_store *refs,
2137 struct ref_lock *lock,
2138 const struct object_id *oid, const char *logmsg,
2141 files_assert_main_repository(refs, "commit_ref_update");
2143 clear_loose_ref_cache(refs);
2144 if (files_log_ref_write(refs, lock->ref_name,
2145 &lock->old_oid, oid,
2147 char *old_msg = strbuf_detach(err, NULL);
2148 strbuf_addf(err, "cannot update the ref '%s': %s",
2149 lock->ref_name, old_msg);
2155 if (strcmp(lock->ref_name, "HEAD") != 0) {
2157 * Special hack: If a branch is updated directly and HEAD
2158 * points to it (may happen on the remote side of a push
2159 * for example) then logically the HEAD reflog should be
2161 * A generic solution implies reverse symref information,
2162 * but finding all symrefs pointing to the given branch
2163 * would be rather costly for this rare event (the direct
2164 * update of a branch) to be worth it. So let's cheat and
2165 * check with HEAD only which should cover 99% of all usage
2166 * scenarios (even 100% of the default ones).
2168 struct object_id head_oid;
2170 const char *head_ref;
2172 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2173 RESOLVE_REF_READING,
2174 head_oid.hash, &head_flag);
2175 if (head_ref && (head_flag & REF_ISSYMREF) &&
2176 !strcmp(head_ref, lock->ref_name)) {
2177 struct strbuf log_err = STRBUF_INIT;
2178 if (files_log_ref_write(refs, "HEAD",
2179 &lock->old_oid, oid,
2180 logmsg, 0, &log_err)) {
2181 error("%s", log_err.buf);
2182 strbuf_release(&log_err);
2187 if (commit_ref(lock)) {
2188 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2197 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2200 #ifndef NO_SYMLINK_HEAD
2201 char *ref_path = get_locked_file_path(lock->lk);
2203 ret = symlink(target, ref_path);
2207 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2212 static void update_symref_reflog(struct files_ref_store *refs,
2213 struct ref_lock *lock, const char *refname,
2214 const char *target, const char *logmsg)
2216 struct strbuf err = STRBUF_INIT;
2217 struct object_id new_oid;
2219 !refs_read_ref_full(&refs->base, target,
2220 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2221 files_log_ref_write(refs, refname, &lock->old_oid,
2222 &new_oid, logmsg, 0, &err)) {
2223 error("%s", err.buf);
2224 strbuf_release(&err);
2228 static int create_symref_locked(struct files_ref_store *refs,
2229 struct ref_lock *lock, const char *refname,
2230 const char *target, const char *logmsg)
2232 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2233 update_symref_reflog(refs, lock, refname, target, logmsg);
2237 if (!fdopen_lock_file(lock->lk, "w"))
2238 return error("unable to fdopen %s: %s",
2239 lock->lk->tempfile.filename.buf, strerror(errno));
2241 update_symref_reflog(refs, lock, refname, target, logmsg);
2243 /* no error check; commit_ref will check ferror */
2244 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2245 if (commit_ref(lock) < 0)
2246 return error("unable to write symref for %s: %s", refname,
2251 static int files_create_symref(struct ref_store *ref_store,
2252 const char *refname, const char *target,
2255 struct files_ref_store *refs =
2256 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2257 struct strbuf err = STRBUF_INIT;
2258 struct ref_lock *lock;
2261 lock = lock_ref_sha1_basic(refs, refname, NULL,
2262 NULL, NULL, REF_NODEREF, NULL,
2265 error("%s", err.buf);
2266 strbuf_release(&err);
2270 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2275 static int files_reflog_exists(struct ref_store *ref_store,
2276 const char *refname)
2278 struct files_ref_store *refs =
2279 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2280 struct strbuf sb = STRBUF_INIT;
2284 files_reflog_path(refs, &sb, refname);
2285 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2286 strbuf_release(&sb);
2290 static int files_delete_reflog(struct ref_store *ref_store,
2291 const char *refname)
2293 struct files_ref_store *refs =
2294 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2295 struct strbuf sb = STRBUF_INIT;
2298 files_reflog_path(refs, &sb, refname);
2299 ret = remove_path(sb.buf);
2300 strbuf_release(&sb);
2304 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2306 struct object_id ooid, noid;
2307 char *email_end, *message;
2308 timestamp_t timestamp;
2310 const char *p = sb->buf;
2312 /* old SP new SP name <email> SP time TAB msg LF */
2313 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2314 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2315 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2316 !(email_end = strchr(p, '>')) ||
2317 email_end[1] != ' ' ||
2318 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2319 !message || message[0] != ' ' ||
2320 (message[1] != '+' && message[1] != '-') ||
2321 !isdigit(message[2]) || !isdigit(message[3]) ||
2322 !isdigit(message[4]) || !isdigit(message[5]))
2323 return 0; /* corrupt? */
2324 email_end[1] = '\0';
2325 tz = strtol(message + 1, NULL, 10);
2326 if (message[6] != '\t')
2330 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2333 static char *find_beginning_of_line(char *bob, char *scan)
2335 while (bob < scan && *(--scan) != '\n')
2336 ; /* keep scanning backwards */
2338 * Return either beginning of the buffer, or LF at the end of
2339 * the previous line.
2344 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2345 const char *refname,
2346 each_reflog_ent_fn fn,
2349 struct files_ref_store *refs =
2350 files_downcast(ref_store, REF_STORE_READ,
2351 "for_each_reflog_ent_reverse");
2352 struct strbuf sb = STRBUF_INIT;
2355 int ret = 0, at_tail = 1;
2357 files_reflog_path(refs, &sb, refname);
2358 logfp = fopen(sb.buf, "r");
2359 strbuf_release(&sb);
2363 /* Jump to the end */
2364 if (fseek(logfp, 0, SEEK_END) < 0)
2365 ret = error("cannot seek back reflog for %s: %s",
2366 refname, strerror(errno));
2368 while (!ret && 0 < pos) {
2374 /* Fill next block from the end */
2375 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2376 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2377 ret = error("cannot seek back reflog for %s: %s",
2378 refname, strerror(errno));
2381 nread = fread(buf, cnt, 1, logfp);
2383 ret = error("cannot read %d bytes from reflog for %s: %s",
2384 cnt, refname, strerror(errno));
2389 scanp = endp = buf + cnt;
2390 if (at_tail && scanp[-1] == '\n')
2391 /* Looking at the final LF at the end of the file */
2395 while (buf < scanp) {
2397 * terminating LF of the previous line, or the beginning
2402 bp = find_beginning_of_line(buf, scanp);
2406 * The newline is the end of the previous line,
2407 * so we know we have complete line starting
2408 * at (bp + 1). Prefix it onto any prior data
2409 * we collected for the line and process it.
2411 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2414 ret = show_one_reflog_ent(&sb, fn, cb_data);
2420 * We are at the start of the buffer, and the
2421 * start of the file; there is no previous
2422 * line, and we have everything for this one.
2423 * Process it, and we can end the loop.
2425 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2426 ret = show_one_reflog_ent(&sb, fn, cb_data);
2433 * We are at the start of the buffer, and there
2434 * is more file to read backwards. Which means
2435 * we are in the middle of a line. Note that we
2436 * may get here even if *bp was a newline; that
2437 * just means we are at the exact end of the
2438 * previous line, rather than some spot in the
2441 * Save away what we have to be combined with
2442 * the data from the next read.
2444 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2451 die("BUG: reverse reflog parser had leftover data");
2454 strbuf_release(&sb);
2458 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2459 const char *refname,
2460 each_reflog_ent_fn fn, void *cb_data)
2462 struct files_ref_store *refs =
2463 files_downcast(ref_store, REF_STORE_READ,
2464 "for_each_reflog_ent");
2466 struct strbuf sb = STRBUF_INIT;
2469 files_reflog_path(refs, &sb, refname);
2470 logfp = fopen(sb.buf, "r");
2471 strbuf_release(&sb);
2475 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2476 ret = show_one_reflog_ent(&sb, fn, cb_data);
2478 strbuf_release(&sb);
2482 struct files_reflog_iterator {
2483 struct ref_iterator base;
2485 struct ref_store *ref_store;
2486 struct dir_iterator *dir_iterator;
2487 struct object_id oid;
2490 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2492 struct files_reflog_iterator *iter =
2493 (struct files_reflog_iterator *)ref_iterator;
2494 struct dir_iterator *diter = iter->dir_iterator;
2497 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2500 if (!S_ISREG(diter->st.st_mode))
2502 if (diter->basename[0] == '.')
2504 if (ends_with(diter->basename, ".lock"))
2507 if (refs_read_ref_full(iter->ref_store,
2508 diter->relative_path, 0,
2509 iter->oid.hash, &flags)) {
2510 error("bad ref for %s", diter->path.buf);
2514 iter->base.refname = diter->relative_path;
2515 iter->base.oid = &iter->oid;
2516 iter->base.flags = flags;
2520 iter->dir_iterator = NULL;
2521 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2526 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2527 struct object_id *peeled)
2529 die("BUG: ref_iterator_peel() called for reflog_iterator");
2532 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2534 struct files_reflog_iterator *iter =
2535 (struct files_reflog_iterator *)ref_iterator;
2538 if (iter->dir_iterator)
2539 ok = dir_iterator_abort(iter->dir_iterator);
2541 base_ref_iterator_free(ref_iterator);
2545 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2546 files_reflog_iterator_advance,
2547 files_reflog_iterator_peel,
2548 files_reflog_iterator_abort
2551 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2553 struct files_ref_store *refs =
2554 files_downcast(ref_store, REF_STORE_READ,
2555 "reflog_iterator_begin");
2556 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2557 struct ref_iterator *ref_iterator = &iter->base;
2558 struct strbuf sb = STRBUF_INIT;
2560 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2561 files_reflog_path(refs, &sb, NULL);
2562 iter->dir_iterator = dir_iterator_begin(sb.buf);
2563 iter->ref_store = ref_store;
2564 strbuf_release(&sb);
2565 return ref_iterator;
2569 * If update is a direct update of head_ref (the reference pointed to
2570 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2572 static int split_head_update(struct ref_update *update,
2573 struct ref_transaction *transaction,
2574 const char *head_ref,
2575 struct string_list *affected_refnames,
2578 struct string_list_item *item;
2579 struct ref_update *new_update;
2581 if ((update->flags & REF_LOG_ONLY) ||
2582 (update->flags & REF_ISPRUNING) ||
2583 (update->flags & REF_UPDATE_VIA_HEAD))
2586 if (strcmp(update->refname, head_ref))
2590 * First make sure that HEAD is not already in the
2591 * transaction. This insertion is O(N) in the transaction
2592 * size, but it happens at most once per transaction.
2594 item = string_list_insert(affected_refnames, "HEAD");
2596 /* An entry already existed */
2598 "multiple updates for 'HEAD' (including one "
2599 "via its referent '%s') are not allowed",
2601 return TRANSACTION_NAME_CONFLICT;
2604 new_update = ref_transaction_add_update(
2605 transaction, "HEAD",
2606 update->flags | REF_LOG_ONLY | REF_NODEREF,
2607 update->new_oid.hash, update->old_oid.hash,
2610 item->util = new_update;
2616 * update is for a symref that points at referent and doesn't have
2617 * REF_NODEREF set. Split it into two updates:
2618 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2619 * - A new, separate update for the referent reference
2620 * Note that the new update will itself be subject to splitting when
2621 * the iteration gets to it.
2623 static int split_symref_update(struct files_ref_store *refs,
2624 struct ref_update *update,
2625 const char *referent,
2626 struct ref_transaction *transaction,
2627 struct string_list *affected_refnames,
2630 struct string_list_item *item;
2631 struct ref_update *new_update;
2632 unsigned int new_flags;
2635 * First make sure that referent is not already in the
2636 * transaction. This insertion is O(N) in the transaction
2637 * size, but it happens at most once per symref in a
2640 item = string_list_insert(affected_refnames, referent);
2642 /* An entry already existed */
2644 "multiple updates for '%s' (including one "
2645 "via symref '%s') are not allowed",
2646 referent, update->refname);
2647 return TRANSACTION_NAME_CONFLICT;
2650 new_flags = update->flags;
2651 if (!strcmp(update->refname, "HEAD")) {
2653 * Record that the new update came via HEAD, so that
2654 * when we process it, split_head_update() doesn't try
2655 * to add another reflog update for HEAD. Note that
2656 * this bit will be propagated if the new_update
2657 * itself needs to be split.
2659 new_flags |= REF_UPDATE_VIA_HEAD;
2662 new_update = ref_transaction_add_update(
2663 transaction, referent, new_flags,
2664 update->new_oid.hash, update->old_oid.hash,
2667 new_update->parent_update = update;
2670 * Change the symbolic ref update to log only. Also, it
2671 * doesn't need to check its old SHA-1 value, as that will be
2672 * done when new_update is processed.
2674 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2675 update->flags &= ~REF_HAVE_OLD;
2677 item->util = new_update;
2683 * Return the refname under which update was originally requested.
2685 static const char *original_update_refname(struct ref_update *update)
2687 while (update->parent_update)
2688 update = update->parent_update;
2690 return update->refname;
2694 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2695 * are consistent with oid, which is the reference's current value. If
2696 * everything is OK, return 0; otherwise, write an error message to
2697 * err and return -1.
2699 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2702 if (!(update->flags & REF_HAVE_OLD) ||
2703 !oidcmp(oid, &update->old_oid))
2706 if (is_null_oid(&update->old_oid))
2707 strbuf_addf(err, "cannot lock ref '%s': "
2708 "reference already exists",
2709 original_update_refname(update));
2710 else if (is_null_oid(oid))
2711 strbuf_addf(err, "cannot lock ref '%s': "
2712 "reference is missing but expected %s",
2713 original_update_refname(update),
2714 oid_to_hex(&update->old_oid));
2716 strbuf_addf(err, "cannot lock ref '%s': "
2717 "is at %s but expected %s",
2718 original_update_refname(update),
2720 oid_to_hex(&update->old_oid));
2726 * Prepare for carrying out update:
2727 * - Lock the reference referred to by update.
2728 * - Read the reference under lock.
2729 * - Check that its old SHA-1 value (if specified) is correct, and in
2730 * any case record it in update->lock->old_oid for later use when
2731 * writing the reflog.
2732 * - If it is a symref update without REF_NODEREF, split it up into a
2733 * REF_LOG_ONLY update of the symref and add a separate update for
2734 * the referent to transaction.
2735 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2738 static int lock_ref_for_update(struct files_ref_store *refs,
2739 struct ref_update *update,
2740 struct ref_transaction *transaction,
2741 const char *head_ref,
2742 struct string_list *affected_refnames,
2745 struct strbuf referent = STRBUF_INIT;
2746 int mustexist = (update->flags & REF_HAVE_OLD) &&
2747 !is_null_oid(&update->old_oid);
2749 struct ref_lock *lock;
2751 files_assert_main_repository(refs, "lock_ref_for_update");
2753 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2754 update->flags |= REF_DELETING;
2757 ret = split_head_update(update, transaction, head_ref,
2758 affected_refnames, err);
2763 ret = lock_raw_ref(refs, update->refname, mustexist,
2764 affected_refnames, NULL,
2766 &update->type, err);
2770 reason = strbuf_detach(err, NULL);
2771 strbuf_addf(err, "cannot lock ref '%s': %s",
2772 original_update_refname(update), reason);
2777 update->backend_data = lock;
2779 if (update->type & REF_ISSYMREF) {
2780 if (update->flags & REF_NODEREF) {
2782 * We won't be reading the referent as part of
2783 * the transaction, so we have to read it here
2784 * to record and possibly check old_sha1:
2786 if (refs_read_ref_full(&refs->base,
2788 lock->old_oid.hash, NULL)) {
2789 if (update->flags & REF_HAVE_OLD) {
2790 strbuf_addf(err, "cannot lock ref '%s': "
2791 "error reading reference",
2792 original_update_refname(update));
2795 } else if (check_old_oid(update, &lock->old_oid, err)) {
2796 return TRANSACTION_GENERIC_ERROR;
2800 * Create a new update for the reference this
2801 * symref is pointing at. Also, we will record
2802 * and verify old_sha1 for this update as part
2803 * of processing the split-off update, so we
2804 * don't have to do it here.
2806 ret = split_symref_update(refs, update,
2807 referent.buf, transaction,
2808 affected_refnames, err);
2813 struct ref_update *parent_update;
2815 if (check_old_oid(update, &lock->old_oid, err))
2816 return TRANSACTION_GENERIC_ERROR;
2819 * If this update is happening indirectly because of a
2820 * symref update, record the old SHA-1 in the parent
2823 for (parent_update = update->parent_update;
2825 parent_update = parent_update->parent_update) {
2826 struct ref_lock *parent_lock = parent_update->backend_data;
2827 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2831 if ((update->flags & REF_HAVE_NEW) &&
2832 !(update->flags & REF_DELETING) &&
2833 !(update->flags & REF_LOG_ONLY)) {
2834 if (!(update->type & REF_ISSYMREF) &&
2835 !oidcmp(&lock->old_oid, &update->new_oid)) {
2837 * The reference already has the desired
2838 * value, so we don't need to write it.
2840 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2842 char *write_err = strbuf_detach(err, NULL);
2845 * The lock was freed upon failure of
2846 * write_ref_to_lockfile():
2848 update->backend_data = NULL;
2850 "cannot update ref '%s': %s",
2851 update->refname, write_err);
2853 return TRANSACTION_GENERIC_ERROR;
2855 update->flags |= REF_NEEDS_COMMIT;
2858 if (!(update->flags & REF_NEEDS_COMMIT)) {
2860 * We didn't call write_ref_to_lockfile(), so
2861 * the lockfile is still open. Close it to
2862 * free up the file descriptor:
2864 if (close_ref(lock)) {
2865 strbuf_addf(err, "couldn't close '%s.lock'",
2867 return TRANSACTION_GENERIC_ERROR;
2874 * Unlock any references in `transaction` that are still locked, and
2875 * mark the transaction closed.
2877 static void files_transaction_cleanup(struct ref_transaction *transaction)
2881 for (i = 0; i < transaction->nr; i++) {
2882 struct ref_update *update = transaction->updates[i];
2883 struct ref_lock *lock = update->backend_data;
2887 update->backend_data = NULL;
2891 transaction->state = REF_TRANSACTION_CLOSED;
2894 static int files_transaction_prepare(struct ref_store *ref_store,
2895 struct ref_transaction *transaction,
2898 struct files_ref_store *refs =
2899 files_downcast(ref_store, REF_STORE_WRITE,
2900 "ref_transaction_prepare");
2903 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2904 char *head_ref = NULL;
2906 struct object_id head_oid;
2910 if (!transaction->nr)
2914 * Fail if a refname appears more than once in the
2915 * transaction. (If we end up splitting up any updates using
2916 * split_symref_update() or split_head_update(), those
2917 * functions will check that the new updates don't have the
2918 * same refname as any existing ones.)
2920 for (i = 0; i < transaction->nr; i++) {
2921 struct ref_update *update = transaction->updates[i];
2922 struct string_list_item *item =
2923 string_list_append(&affected_refnames, update->refname);
2926 * We store a pointer to update in item->util, but at
2927 * the moment we never use the value of this field
2928 * except to check whether it is non-NULL.
2930 item->util = update;
2932 string_list_sort(&affected_refnames);
2933 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2934 ret = TRANSACTION_GENERIC_ERROR;
2939 * Special hack: If a branch is updated directly and HEAD
2940 * points to it (may happen on the remote side of a push
2941 * for example) then logically the HEAD reflog should be
2944 * A generic solution would require reverse symref lookups,
2945 * but finding all symrefs pointing to a given branch would be
2946 * rather costly for this rare event (the direct update of a
2947 * branch) to be worth it. So let's cheat and check with HEAD
2948 * only, which should cover 99% of all usage scenarios (even
2949 * 100% of the default ones).
2951 * So if HEAD is a symbolic reference, then record the name of
2952 * the reference that it points to. If we see an update of
2953 * head_ref within the transaction, then split_head_update()
2954 * arranges for the reflog of HEAD to be updated, too.
2956 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2957 RESOLVE_REF_NO_RECURSE,
2958 head_oid.hash, &head_type);
2960 if (head_ref && !(head_type & REF_ISSYMREF)) {
2966 * Acquire all locks, verify old values if provided, check
2967 * that new values are valid, and write new values to the
2968 * lockfiles, ready to be activated. Only keep one lockfile
2969 * open at a time to avoid running out of file descriptors.
2970 * Note that lock_ref_for_update() might append more updates
2971 * to the transaction.
2973 for (i = 0; i < transaction->nr; i++) {
2974 struct ref_update *update = transaction->updates[i];
2976 ret = lock_ref_for_update(refs, update, transaction,
2977 head_ref, &affected_refnames, err);
2984 string_list_clear(&affected_refnames, 0);
2987 files_transaction_cleanup(transaction);
2989 transaction->state = REF_TRANSACTION_PREPARED;
2994 static int files_transaction_finish(struct ref_store *ref_store,
2995 struct ref_transaction *transaction,
2998 struct files_ref_store *refs =
2999 files_downcast(ref_store, 0, "ref_transaction_finish");
3002 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3003 struct string_list_item *ref_to_delete;
3004 struct strbuf sb = STRBUF_INIT;
3008 if (!transaction->nr) {
3009 transaction->state = REF_TRANSACTION_CLOSED;
3013 /* Perform updates first so live commits remain referenced */
3014 for (i = 0; i < transaction->nr; i++) {
3015 struct ref_update *update = transaction->updates[i];
3016 struct ref_lock *lock = update->backend_data;
3018 if (update->flags & REF_NEEDS_COMMIT ||
3019 update->flags & REF_LOG_ONLY) {
3020 if (files_log_ref_write(refs,
3024 update->msg, update->flags,
3026 char *old_msg = strbuf_detach(err, NULL);
3028 strbuf_addf(err, "cannot update the ref '%s': %s",
3029 lock->ref_name, old_msg);
3032 update->backend_data = NULL;
3033 ret = TRANSACTION_GENERIC_ERROR;
3037 if (update->flags & REF_NEEDS_COMMIT) {
3038 clear_loose_ref_cache(refs);
3039 if (commit_ref(lock)) {
3040 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3042 update->backend_data = NULL;
3043 ret = TRANSACTION_GENERIC_ERROR;
3048 /* Perform deletes now that updates are safely completed */
3049 for (i = 0; i < transaction->nr; i++) {
3050 struct ref_update *update = transaction->updates[i];
3051 struct ref_lock *lock = update->backend_data;
3053 if (update->flags & REF_DELETING &&
3054 !(update->flags & REF_LOG_ONLY)) {
3055 if (!(update->type & REF_ISPACKED) ||
3056 update->type & REF_ISSYMREF) {
3057 /* It is a loose reference. */
3059 files_ref_path(refs, &sb, lock->ref_name);
3060 if (unlink_or_msg(sb.buf, err)) {
3061 ret = TRANSACTION_GENERIC_ERROR;
3064 update->flags |= REF_DELETED_LOOSE;
3067 if (!(update->flags & REF_ISPRUNING))
3068 string_list_append(&refs_to_delete,
3073 if (repack_without_refs(refs, &refs_to_delete, err)) {
3074 ret = TRANSACTION_GENERIC_ERROR;
3078 /* Delete the reflogs of any references that were deleted: */
3079 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3081 files_reflog_path(refs, &sb, ref_to_delete->string);
3082 if (!unlink_or_warn(sb.buf))
3083 try_remove_empty_parents(refs, ref_to_delete->string,
3084 REMOVE_EMPTY_PARENTS_REFLOG);
3087 clear_loose_ref_cache(refs);
3090 files_transaction_cleanup(transaction);
3092 for (i = 0; i < transaction->nr; i++) {
3093 struct ref_update *update = transaction->updates[i];
3095 if (update->flags & REF_DELETED_LOOSE) {
3097 * The loose reference was deleted. Delete any
3098 * empty parent directories. (Note that this
3099 * can only work because we have already
3100 * removed the lockfile.)
3102 try_remove_empty_parents(refs, update->refname,
3103 REMOVE_EMPTY_PARENTS_REF);
3107 strbuf_release(&sb);
3108 string_list_clear(&refs_to_delete, 0);
3112 static int files_transaction_abort(struct ref_store *ref_store,
3113 struct ref_transaction *transaction,
3116 files_transaction_cleanup(transaction);
3120 static int ref_present(const char *refname,
3121 const struct object_id *oid, int flags, void *cb_data)
3123 struct string_list *affected_refnames = cb_data;
3125 return string_list_has_string(affected_refnames, refname);
3128 static int files_initial_transaction_commit(struct ref_store *ref_store,
3129 struct ref_transaction *transaction,
3132 struct files_ref_store *refs =
3133 files_downcast(ref_store, REF_STORE_WRITE,
3134 "initial_ref_transaction_commit");
3137 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3141 if (transaction->state != REF_TRANSACTION_OPEN)
3142 die("BUG: commit called for transaction that is not open");
3144 /* Fail if a refname appears more than once in the transaction: */
3145 for (i = 0; i < transaction->nr; i++)
3146 string_list_append(&affected_refnames,
3147 transaction->updates[i]->refname);
3148 string_list_sort(&affected_refnames);
3149 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3150 ret = TRANSACTION_GENERIC_ERROR;
3155 * It's really undefined to call this function in an active
3156 * repository or when there are existing references: we are
3157 * only locking and changing packed-refs, so (1) any
3158 * simultaneous processes might try to change a reference at
3159 * the same time we do, and (2) any existing loose versions of
3160 * the references that we are setting would have precedence
3161 * over our values. But some remote helpers create the remote
3162 * "HEAD" and "master" branches before calling this function,
3163 * so here we really only check that none of the references
3164 * that we are creating already exists.
3166 if (refs_for_each_rawref(&refs->base, ref_present,
3167 &affected_refnames))
3168 die("BUG: initial ref transaction called with existing refs");
3170 for (i = 0; i < transaction->nr; i++) {
3171 struct ref_update *update = transaction->updates[i];
3173 if ((update->flags & REF_HAVE_OLD) &&
3174 !is_null_oid(&update->old_oid))
3175 die("BUG: initial ref transaction with old_sha1 set");
3176 if (refs_verify_refname_available(&refs->base, update->refname,
3177 &affected_refnames, NULL,
3179 ret = TRANSACTION_NAME_CONFLICT;
3184 if (lock_packed_refs(refs, 0)) {
3185 strbuf_addf(err, "unable to lock packed-refs file: %s",
3187 ret = TRANSACTION_GENERIC_ERROR;
3191 for (i = 0; i < transaction->nr; i++) {
3192 struct ref_update *update = transaction->updates[i];
3194 if ((update->flags & REF_HAVE_NEW) &&
3195 !is_null_oid(&update->new_oid))
3196 add_packed_ref(refs, update->refname,
3200 if (commit_packed_refs(refs)) {
3201 strbuf_addf(err, "unable to commit packed-refs file: %s",
3203 ret = TRANSACTION_GENERIC_ERROR;
3208 transaction->state = REF_TRANSACTION_CLOSED;
3209 string_list_clear(&affected_refnames, 0);
3213 struct expire_reflog_cb {
3215 reflog_expiry_should_prune_fn *should_prune_fn;
3218 struct object_id last_kept_oid;
3221 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3222 const char *email, timestamp_t timestamp, int tz,
3223 const char *message, void *cb_data)
3225 struct expire_reflog_cb *cb = cb_data;
3226 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3228 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3229 ooid = &cb->last_kept_oid;
3231 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3232 message, policy_cb)) {
3234 printf("would prune %s", message);
3235 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3236 printf("prune %s", message);
3239 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3240 oid_to_hex(ooid), oid_to_hex(noid),
3241 email, timestamp, tz, message);
3242 oidcpy(&cb->last_kept_oid, noid);
3244 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3245 printf("keep %s", message);
3250 static int files_reflog_expire(struct ref_store *ref_store,
3251 const char *refname, const unsigned char *sha1,
3253 reflog_expiry_prepare_fn prepare_fn,
3254 reflog_expiry_should_prune_fn should_prune_fn,
3255 reflog_expiry_cleanup_fn cleanup_fn,
3256 void *policy_cb_data)
3258 struct files_ref_store *refs =
3259 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3260 static struct lock_file reflog_lock;
3261 struct expire_reflog_cb cb;
3262 struct ref_lock *lock;
3263 struct strbuf log_file_sb = STRBUF_INIT;
3267 struct strbuf err = STRBUF_INIT;
3268 struct object_id oid;
3270 memset(&cb, 0, sizeof(cb));
3272 cb.policy_cb = policy_cb_data;
3273 cb.should_prune_fn = should_prune_fn;
3276 * The reflog file is locked by holding the lock on the
3277 * reference itself, plus we might need to update the
3278 * reference if --updateref was specified:
3280 lock = lock_ref_sha1_basic(refs, refname, sha1,
3281 NULL, NULL, REF_NODEREF,
3284 error("cannot lock ref '%s': %s", refname, err.buf);
3285 strbuf_release(&err);
3288 if (!refs_reflog_exists(ref_store, refname)) {
3293 files_reflog_path(refs, &log_file_sb, refname);
3294 log_file = strbuf_detach(&log_file_sb, NULL);
3295 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3297 * Even though holding $GIT_DIR/logs/$reflog.lock has
3298 * no locking implications, we use the lock_file
3299 * machinery here anyway because it does a lot of the
3300 * work we need, including cleaning up if the program
3301 * exits unexpectedly.
3303 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3304 struct strbuf err = STRBUF_INIT;
3305 unable_to_lock_message(log_file, errno, &err);
3306 error("%s", err.buf);
3307 strbuf_release(&err);
3310 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3312 error("cannot fdopen %s (%s)",
3313 get_lock_file_path(&reflog_lock), strerror(errno));
3318 hashcpy(oid.hash, sha1);
3320 (*prepare_fn)(refname, &oid, cb.policy_cb);
3321 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3322 (*cleanup_fn)(cb.policy_cb);
3324 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3326 * It doesn't make sense to adjust a reference pointed
3327 * to by a symbolic ref based on expiring entries in
3328 * the symbolic reference's reflog. Nor can we update
3329 * a reference if there are no remaining reflog
3332 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3333 !(type & REF_ISSYMREF) &&
3334 !is_null_oid(&cb.last_kept_oid);
3336 if (close_lock_file(&reflog_lock)) {
3337 status |= error("couldn't write %s: %s", log_file,
3339 } else if (update &&
3340 (write_in_full(get_lock_file_fd(lock->lk),
3341 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3342 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3343 close_ref(lock) < 0)) {
3344 status |= error("couldn't write %s",
3345 get_lock_file_path(lock->lk));
3346 rollback_lock_file(&reflog_lock);
3347 } else if (commit_lock_file(&reflog_lock)) {
3348 status |= error("unable to write reflog '%s' (%s)",
3349 log_file, strerror(errno));
3350 } else if (update && commit_ref(lock)) {
3351 status |= error("couldn't set %s", lock->ref_name);
3359 rollback_lock_file(&reflog_lock);
3365 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3367 struct files_ref_store *refs =
3368 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3369 struct strbuf sb = STRBUF_INIT;
3372 * Create .git/refs/{heads,tags}
3374 files_ref_path(refs, &sb, "refs/heads");
3375 safe_create_dir(sb.buf, 1);
3378 files_ref_path(refs, &sb, "refs/tags");
3379 safe_create_dir(sb.buf, 1);
3381 strbuf_release(&sb);
3385 struct ref_storage_be refs_be_files = {
3388 files_ref_store_create,
3390 files_transaction_prepare,
3391 files_transaction_finish,
3392 files_transaction_abort,
3393 files_initial_transaction_commit,
3397 files_create_symref,
3401 files_ref_iterator_begin,
3404 files_reflog_iterator_begin,
3405 files_for_each_reflog_ent,
3406 files_for_each_reflog_ent_reverse,
3407 files_reflog_exists,
3408 files_create_reflog,
3409 files_delete_reflog,