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 or overwrite a reference in the in-memory packed reference
417 * cache. This may only be called while the packed-refs file is locked
418 * (see lock_packed_refs()). To actually write the packed-refs file,
419 * call 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 ref_dir *packed_refs;
425 struct ref_entry *packed_entry;
427 if (!is_lock_file_locked(&refs->packed_refs_lock))
428 die("BUG: packed refs not locked");
430 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
431 die("Reference has invalid format: '%s'", refname);
433 packed_refs = get_packed_refs(refs);
434 packed_entry = find_ref_entry(packed_refs, refname);
436 /* Overwrite the existing entry: */
437 oidcpy(&packed_entry->u.value.oid, oid);
438 packed_entry->flag = REF_ISPACKED;
439 oidclr(&packed_entry->u.value.peeled);
441 packed_entry = create_ref_entry(refname, oid, REF_ISPACKED);
442 add_ref_entry(packed_refs, packed_entry);
447 * Read the loose references from the namespace dirname into dir
448 * (without recursing). dirname must end with '/'. dir must be the
449 * directory entry corresponding to dirname.
451 static void loose_fill_ref_dir(struct ref_store *ref_store,
452 struct ref_dir *dir, const char *dirname)
454 struct files_ref_store *refs =
455 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
458 int dirnamelen = strlen(dirname);
459 struct strbuf refname;
460 struct strbuf path = STRBUF_INIT;
463 files_ref_path(refs, &path, dirname);
464 path_baselen = path.len;
466 d = opendir(path.buf);
468 strbuf_release(&path);
472 strbuf_init(&refname, dirnamelen + 257);
473 strbuf_add(&refname, dirname, dirnamelen);
475 while ((de = readdir(d)) != NULL) {
476 struct object_id oid;
480 if (de->d_name[0] == '.')
482 if (ends_with(de->d_name, ".lock"))
484 strbuf_addstr(&refname, de->d_name);
485 strbuf_addstr(&path, de->d_name);
486 if (stat(path.buf, &st) < 0) {
487 ; /* silently ignore */
488 } else if (S_ISDIR(st.st_mode)) {
489 strbuf_addch(&refname, '/');
490 add_entry_to_dir(dir,
491 create_dir_entry(dir->cache, refname.buf,
494 if (!refs_resolve_ref_unsafe(&refs->base,
499 flag |= REF_ISBROKEN;
500 } else if (is_null_oid(&oid)) {
502 * It is so astronomically unlikely
503 * that NULL_SHA1 is the SHA-1 of an
504 * actual object that we consider its
505 * appearance in a loose reference
506 * file to be repo corruption
507 * (probably due to a software bug).
509 flag |= REF_ISBROKEN;
512 if (check_refname_format(refname.buf,
513 REFNAME_ALLOW_ONELEVEL)) {
514 if (!refname_is_safe(refname.buf))
515 die("loose refname is dangerous: %s", refname.buf);
517 flag |= REF_BAD_NAME | REF_ISBROKEN;
519 add_entry_to_dir(dir,
520 create_ref_entry(refname.buf, &oid, flag));
522 strbuf_setlen(&refname, dirnamelen);
523 strbuf_setlen(&path, path_baselen);
525 strbuf_release(&refname);
526 strbuf_release(&path);
530 * Manually add refs/bisect, which, being per-worktree, might
531 * not appear in the directory listing for refs/ in the main
534 if (!strcmp(dirname, "refs/")) {
535 int pos = search_ref_dir(dir, "refs/bisect/", 12);
538 struct ref_entry *child_entry = create_dir_entry(
539 dir->cache, "refs/bisect/", 12, 1);
540 add_entry_to_dir(dir, child_entry);
545 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
549 * Mark the top-level directory complete because we
550 * are about to read the only subdirectory that can
553 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
555 /* We're going to fill the top level ourselves: */
556 refs->loose->root->flag &= ~REF_INCOMPLETE;
559 * Add an incomplete entry for "refs/" (to be filled
562 add_entry_to_dir(get_ref_dir(refs->loose->root),
563 create_dir_entry(refs->loose, "refs/", 5, 1));
569 * Return the ref_entry for the given refname from the packed
570 * references. If it does not exist, return NULL.
572 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
575 return find_ref_entry(get_packed_refs(refs), refname);
579 * A loose ref file doesn't exist; check for a packed ref.
581 static int resolve_packed_ref(struct files_ref_store *refs,
583 unsigned char *sha1, unsigned int *flags)
585 struct ref_entry *entry;
588 * The loose reference file does not exist; check for a packed
591 entry = get_packed_ref(refs, refname);
593 hashcpy(sha1, entry->u.value.oid.hash);
594 *flags |= REF_ISPACKED;
597 /* refname is not a packed reference. */
601 static int files_read_raw_ref(struct ref_store *ref_store,
602 const char *refname, unsigned char *sha1,
603 struct strbuf *referent, unsigned int *type)
605 struct files_ref_store *refs =
606 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
607 struct strbuf sb_contents = STRBUF_INIT;
608 struct strbuf sb_path = STRBUF_INIT;
615 int remaining_retries = 3;
618 strbuf_reset(&sb_path);
620 files_ref_path(refs, &sb_path, refname);
626 * We might have to loop back here to avoid a race
627 * condition: first we lstat() the file, then we try
628 * to read it as a link or as a file. But if somebody
629 * changes the type of the file (file <-> directory
630 * <-> symlink) between the lstat() and reading, then
631 * we don't want to report that as an error but rather
632 * try again starting with the lstat().
634 * We'll keep a count of the retries, though, just to avoid
635 * any confusing situation sending us into an infinite loop.
638 if (remaining_retries-- <= 0)
641 if (lstat(path, &st) < 0) {
644 if (resolve_packed_ref(refs, refname, sha1, type)) {
652 /* Follow "normalized" - ie "refs/.." symlinks by hand */
653 if (S_ISLNK(st.st_mode)) {
654 strbuf_reset(&sb_contents);
655 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
656 if (errno == ENOENT || errno == EINVAL)
657 /* inconsistent with lstat; retry */
662 if (starts_with(sb_contents.buf, "refs/") &&
663 !check_refname_format(sb_contents.buf, 0)) {
664 strbuf_swap(&sb_contents, referent);
665 *type |= REF_ISSYMREF;
670 * It doesn't look like a refname; fall through to just
671 * treating it like a non-symlink, and reading whatever it
676 /* Is it a directory? */
677 if (S_ISDIR(st.st_mode)) {
679 * Even though there is a directory where the loose
680 * ref is supposed to be, there could still be a
683 if (resolve_packed_ref(refs, refname, sha1, type)) {
692 * Anything else, just open it and try to use it as
695 fd = open(path, O_RDONLY);
697 if (errno == ENOENT && !S_ISLNK(st.st_mode))
698 /* inconsistent with lstat; retry */
703 strbuf_reset(&sb_contents);
704 if (strbuf_read(&sb_contents, fd, 256) < 0) {
705 int save_errno = errno;
711 strbuf_rtrim(&sb_contents);
712 buf = sb_contents.buf;
713 if (starts_with(buf, "ref:")) {
715 while (isspace(*buf))
718 strbuf_reset(referent);
719 strbuf_addstr(referent, buf);
720 *type |= REF_ISSYMREF;
726 * Please note that FETCH_HEAD has additional
727 * data after the sha.
729 if (get_sha1_hex(buf, sha1) ||
730 (buf[40] != '\0' && !isspace(buf[40]))) {
731 *type |= REF_ISBROKEN;
740 strbuf_release(&sb_path);
741 strbuf_release(&sb_contents);
746 static void unlock_ref(struct ref_lock *lock)
748 /* Do not free lock->lk -- atexit() still looks at them */
750 rollback_lock_file(lock->lk);
751 free(lock->ref_name);
756 * Lock refname, without following symrefs, and set *lock_p to point
757 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
758 * and type similarly to read_raw_ref().
760 * The caller must verify that refname is a "safe" reference name (in
761 * the sense of refname_is_safe()) before calling this function.
763 * If the reference doesn't already exist, verify that refname doesn't
764 * have a D/F conflict with any existing references. extras and skip
765 * are passed to refs_verify_refname_available() for this check.
767 * If mustexist is not set and the reference is not found or is
768 * broken, lock the reference anyway but clear sha1.
770 * Return 0 on success. On failure, write an error message to err and
771 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
773 * Implementation note: This function is basically
778 * but it includes a lot more code to
779 * - Deal with possible races with other processes
780 * - Avoid calling refs_verify_refname_available() when it can be
781 * avoided, namely if we were successfully able to read the ref
782 * - Generate informative error messages in the case of failure
784 static int lock_raw_ref(struct files_ref_store *refs,
785 const char *refname, int mustexist,
786 const struct string_list *extras,
787 const struct string_list *skip,
788 struct ref_lock **lock_p,
789 struct strbuf *referent,
793 struct ref_lock *lock;
794 struct strbuf ref_file = STRBUF_INIT;
795 int attempts_remaining = 3;
796 int ret = TRANSACTION_GENERIC_ERROR;
799 files_assert_main_repository(refs, "lock_raw_ref");
803 /* First lock the file so it can't change out from under us. */
805 *lock_p = lock = xcalloc(1, sizeof(*lock));
807 lock->ref_name = xstrdup(refname);
808 files_ref_path(refs, &ref_file, refname);
811 switch (safe_create_leading_directories(ref_file.buf)) {
816 * Suppose refname is "refs/foo/bar". We just failed
817 * to create the containing directory, "refs/foo",
818 * because there was a non-directory in the way. This
819 * indicates a D/F conflict, probably because of
820 * another reference such as "refs/foo". There is no
821 * reason to expect this error to be transitory.
823 if (refs_verify_refname_available(&refs->base, refname,
824 extras, skip, err)) {
827 * To the user the relevant error is
828 * that the "mustexist" reference is
832 strbuf_addf(err, "unable to resolve reference '%s'",
836 * The error message set by
837 * refs_verify_refname_available() is
840 ret = TRANSACTION_NAME_CONFLICT;
844 * The file that is in the way isn't a loose
845 * reference. Report it as a low-level
848 strbuf_addf(err, "unable to create lock file %s.lock; "
849 "non-directory in the way",
854 /* Maybe another process was tidying up. Try again. */
855 if (--attempts_remaining > 0)
859 strbuf_addf(err, "unable to create directory for %s",
865 lock->lk = xcalloc(1, sizeof(struct lock_file));
867 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
868 if (errno == ENOENT && --attempts_remaining > 0) {
870 * Maybe somebody just deleted one of the
871 * directories leading to ref_file. Try
876 unable_to_lock_message(ref_file.buf, errno, err);
882 * Now we hold the lock and can read the reference without
883 * fear that its value will change.
886 if (files_read_raw_ref(&refs->base, refname,
887 lock->old_oid.hash, referent, type)) {
888 if (errno == ENOENT) {
890 /* Garden variety missing reference. */
891 strbuf_addf(err, "unable to resolve reference '%s'",
896 * Reference is missing, but that's OK. We
897 * know that there is not a conflict with
898 * another loose reference because
899 * (supposing that we are trying to lock
900 * reference "refs/foo/bar"):
902 * - We were successfully able to create
903 * the lockfile refs/foo/bar.lock, so we
904 * know there cannot be a loose reference
907 * - We got ENOENT and not EISDIR, so we
908 * know that there cannot be a loose
909 * reference named "refs/foo/bar/baz".
912 } else if (errno == EISDIR) {
914 * There is a directory in the way. It might have
915 * contained references that have been deleted. If
916 * we don't require that the reference already
917 * exists, try to remove the directory so that it
918 * doesn't cause trouble when we want to rename the
919 * lockfile into place later.
922 /* Garden variety missing reference. */
923 strbuf_addf(err, "unable to resolve reference '%s'",
926 } else if (remove_dir_recursively(&ref_file,
927 REMOVE_DIR_EMPTY_ONLY)) {
928 if (refs_verify_refname_available(
929 &refs->base, refname,
930 extras, skip, err)) {
932 * The error message set by
933 * verify_refname_available() is OK.
935 ret = TRANSACTION_NAME_CONFLICT;
939 * We can't delete the directory,
940 * but we also don't know of any
941 * references that it should
944 strbuf_addf(err, "there is a non-empty directory '%s' "
945 "blocking reference '%s'",
946 ref_file.buf, refname);
950 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
951 strbuf_addf(err, "unable to resolve reference '%s': "
952 "reference broken", refname);
955 strbuf_addf(err, "unable to resolve reference '%s': %s",
956 refname, strerror(errno));
961 * If the ref did not exist and we are creating it,
962 * make sure there is no existing ref that conflicts
965 if (refs_verify_refname_available(
966 &refs->base, refname,
979 strbuf_release(&ref_file);
983 static int files_peel_ref(struct ref_store *ref_store,
984 const char *refname, unsigned char *sha1)
986 struct files_ref_store *refs =
987 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
990 unsigned char base[20];
992 if (current_ref_iter && current_ref_iter->refname == refname) {
993 struct object_id peeled;
995 if (ref_iterator_peel(current_ref_iter, &peeled))
997 hashcpy(sha1, peeled.hash);
1001 if (refs_read_ref_full(ref_store, refname,
1002 RESOLVE_REF_READING, base, &flag))
1006 * If the reference is packed, read its ref_entry from the
1007 * cache in the hope that we already know its peeled value.
1008 * We only try this optimization on packed references because
1009 * (a) forcing the filling of the loose reference cache could
1010 * be expensive and (b) loose references anyway usually do not
1011 * have REF_KNOWS_PEELED.
1013 if (flag & REF_ISPACKED) {
1014 struct ref_entry *r = get_packed_ref(refs, refname);
1016 if (peel_entry(r, 0))
1018 hashcpy(sha1, r->u.value.peeled.hash);
1023 return peel_object(base, sha1);
1026 struct files_ref_iterator {
1027 struct ref_iterator base;
1029 struct packed_ref_cache *packed_ref_cache;
1030 struct ref_iterator *iter0;
1034 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1036 struct files_ref_iterator *iter =
1037 (struct files_ref_iterator *)ref_iterator;
1040 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1041 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1042 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1045 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1046 !ref_resolves_to_object(iter->iter0->refname,
1048 iter->iter0->flags))
1051 iter->base.refname = iter->iter0->refname;
1052 iter->base.oid = iter->iter0->oid;
1053 iter->base.flags = iter->iter0->flags;
1058 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1064 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1065 struct object_id *peeled)
1067 struct files_ref_iterator *iter =
1068 (struct files_ref_iterator *)ref_iterator;
1070 return ref_iterator_peel(iter->iter0, peeled);
1073 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1075 struct files_ref_iterator *iter =
1076 (struct files_ref_iterator *)ref_iterator;
1080 ok = ref_iterator_abort(iter->iter0);
1082 release_packed_ref_cache(iter->packed_ref_cache);
1083 base_ref_iterator_free(ref_iterator);
1087 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1088 files_ref_iterator_advance,
1089 files_ref_iterator_peel,
1090 files_ref_iterator_abort
1093 static struct ref_iterator *files_ref_iterator_begin(
1094 struct ref_store *ref_store,
1095 const char *prefix, unsigned int flags)
1097 struct files_ref_store *refs;
1098 struct ref_iterator *loose_iter, *packed_iter;
1099 struct files_ref_iterator *iter;
1100 struct ref_iterator *ref_iterator;
1101 unsigned int required_flags = REF_STORE_READ;
1103 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1104 required_flags |= REF_STORE_ODB;
1106 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1108 iter = xcalloc(1, sizeof(*iter));
1109 ref_iterator = &iter->base;
1110 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1113 * We must make sure that all loose refs are read before
1114 * accessing the packed-refs file; this avoids a race
1115 * condition if loose refs are migrated to the packed-refs
1116 * file by a simultaneous process, but our in-memory view is
1117 * from before the migration. We ensure this as follows:
1118 * First, we call start the loose refs iteration with its
1119 * `prime_ref` argument set to true. This causes the loose
1120 * references in the subtree to be pre-read into the cache.
1121 * (If they've already been read, that's OK; we only need to
1122 * guarantee that they're read before the packed refs, not
1123 * *how much* before.) After that, we call
1124 * get_packed_ref_cache(), which internally checks whether the
1125 * packed-ref cache is up to date with what is on disk, and
1126 * re-reads it if not.
1129 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1132 iter->packed_ref_cache = get_packed_ref_cache(refs);
1133 acquire_packed_ref_cache(iter->packed_ref_cache);
1134 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1137 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1138 iter->flags = flags;
1140 return ref_iterator;
1144 * Verify that the reference locked by lock has the value old_sha1.
1145 * Fail if the reference doesn't exist and mustexist is set. Return 0
1146 * on success. On error, write an error message to err, set errno, and
1147 * return a negative value.
1149 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1150 const unsigned char *old_sha1, int mustexist,
1155 if (refs_read_ref_full(ref_store, lock->ref_name,
1156 mustexist ? RESOLVE_REF_READING : 0,
1157 lock->old_oid.hash, NULL)) {
1159 int save_errno = errno;
1160 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1164 oidclr(&lock->old_oid);
1168 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1169 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1171 oid_to_hex(&lock->old_oid),
1172 sha1_to_hex(old_sha1));
1179 static int remove_empty_directories(struct strbuf *path)
1182 * we want to create a file but there is a directory there;
1183 * if that is an empty directory (or a directory that contains
1184 * only empty directories), remove them.
1186 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1189 static int create_reflock(const char *path, void *cb)
1191 struct lock_file *lk = cb;
1193 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1197 * Locks a ref returning the lock on success and NULL on failure.
1198 * On failure errno is set to something meaningful.
1200 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1201 const char *refname,
1202 const unsigned char *old_sha1,
1203 const struct string_list *extras,
1204 const struct string_list *skip,
1205 unsigned int flags, int *type,
1208 struct strbuf ref_file = STRBUF_INIT;
1209 struct ref_lock *lock;
1211 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1212 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1215 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1218 lock = xcalloc(1, sizeof(struct ref_lock));
1221 resolve_flags |= RESOLVE_REF_READING;
1222 if (flags & REF_DELETING)
1223 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1225 files_ref_path(refs, &ref_file, refname);
1226 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1227 refname, resolve_flags,
1228 lock->old_oid.hash, type);
1229 if (!resolved && errno == EISDIR) {
1231 * we are trying to lock foo but we used to
1232 * have foo/bar which now does not exist;
1233 * it is normal for the empty directory 'foo'
1236 if (remove_empty_directories(&ref_file)) {
1238 if (!refs_verify_refname_available(
1240 refname, extras, skip, err))
1241 strbuf_addf(err, "there are still refs under '%s'",
1245 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1246 refname, resolve_flags,
1247 lock->old_oid.hash, type);
1251 if (last_errno != ENOTDIR ||
1252 !refs_verify_refname_available(&refs->base, refname,
1254 strbuf_addf(err, "unable to resolve reference '%s': %s",
1255 refname, strerror(last_errno));
1261 * If the ref did not exist and we are creating it, make sure
1262 * there is no existing packed ref whose name begins with our
1263 * refname, nor a packed ref whose name is a proper prefix of
1266 if (is_null_oid(&lock->old_oid) &&
1267 refs_verify_refname_available(&refs->base, refname,
1268 extras, skip, err)) {
1269 last_errno = ENOTDIR;
1273 lock->lk = xcalloc(1, sizeof(struct lock_file));
1275 lock->ref_name = xstrdup(refname);
1277 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1279 unable_to_lock_message(ref_file.buf, errno, err);
1283 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1294 strbuf_release(&ref_file);
1300 * Write an entry to the packed-refs file for the specified refname.
1301 * If peeled is non-NULL, write it as the entry's peeled value.
1303 static void write_packed_entry(FILE *fh, const char *refname,
1304 const unsigned char *sha1,
1305 const unsigned char *peeled)
1307 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1309 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1313 * Lock the packed-refs file for writing. Flags is passed to
1314 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1315 * errno appropriately and return a nonzero value.
1317 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1319 static int timeout_configured = 0;
1320 static int timeout_value = 1000;
1321 struct packed_ref_cache *packed_ref_cache;
1323 files_assert_main_repository(refs, "lock_packed_refs");
1325 if (!timeout_configured) {
1326 git_config_get_int("core.packedrefstimeout", &timeout_value);
1327 timeout_configured = 1;
1330 if (hold_lock_file_for_update_timeout(
1331 &refs->packed_refs_lock, files_packed_refs_path(refs),
1332 flags, timeout_value) < 0)
1336 * Now that we hold the `packed-refs` lock, make sure that our
1337 * cache matches the current version of the file. Normally
1338 * `get_packed_ref_cache()` does that for us, but that
1339 * function assumes that when the file is locked, any existing
1340 * cache is still valid. We've just locked the file, but it
1341 * might have changed the moment *before* we locked it.
1343 validate_packed_ref_cache(refs);
1345 packed_ref_cache = get_packed_ref_cache(refs);
1346 /* Increment the reference count to prevent it from being freed: */
1347 acquire_packed_ref_cache(packed_ref_cache);
1352 * Write the current version of the packed refs cache from memory to
1353 * disk. The packed-refs file must already be locked for writing (see
1354 * lock_packed_refs()). Return zero on success. On errors, set errno
1355 * and return a nonzero value
1357 static int commit_packed_refs(struct files_ref_store *refs)
1359 struct packed_ref_cache *packed_ref_cache =
1360 get_packed_ref_cache(refs);
1364 struct ref_iterator *iter;
1366 files_assert_main_repository(refs, "commit_packed_refs");
1368 if (!is_lock_file_locked(&refs->packed_refs_lock))
1369 die("BUG: packed-refs not locked");
1371 out = fdopen_lock_file(&refs->packed_refs_lock, "w");
1373 die_errno("unable to fdopen packed-refs descriptor");
1375 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1377 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1378 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1379 struct object_id peeled;
1380 int peel_error = ref_iterator_peel(iter, &peeled);
1382 write_packed_entry(out, iter->refname, iter->oid->hash,
1383 peel_error ? NULL : peeled.hash);
1386 if (ok != ITER_DONE)
1387 die("error while iterating over references");
1389 if (commit_lock_file(&refs->packed_refs_lock)) {
1393 release_packed_ref_cache(packed_ref_cache);
1399 * Rollback the lockfile for the packed-refs file, and discard the
1400 * in-memory packed reference cache. (The packed-refs file will be
1401 * read anew if it is needed again after this function is called.)
1403 static void rollback_packed_refs(struct files_ref_store *refs)
1405 struct packed_ref_cache *packed_ref_cache =
1406 get_packed_ref_cache(refs);
1408 files_assert_main_repository(refs, "rollback_packed_refs");
1410 if (!is_lock_file_locked(&refs->packed_refs_lock))
1411 die("BUG: packed-refs not locked");
1412 rollback_lock_file(&refs->packed_refs_lock);
1413 release_packed_ref_cache(packed_ref_cache);
1414 clear_packed_ref_cache(refs);
1417 struct ref_to_prune {
1418 struct ref_to_prune *next;
1419 unsigned char sha1[20];
1420 char name[FLEX_ARRAY];
1424 REMOVE_EMPTY_PARENTS_REF = 0x01,
1425 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1429 * Remove empty parent directories associated with the specified
1430 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1431 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1432 * REMOVE_EMPTY_PARENTS_REFLOG.
1434 static void try_remove_empty_parents(struct files_ref_store *refs,
1435 const char *refname,
1438 struct strbuf buf = STRBUF_INIT;
1439 struct strbuf sb = STRBUF_INIT;
1443 strbuf_addstr(&buf, refname);
1445 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1446 while (*p && *p != '/')
1448 /* tolerate duplicate slashes; see check_refname_format() */
1452 q = buf.buf + buf.len;
1453 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1454 while (q > p && *q != '/')
1456 while (q > p && *(q-1) == '/')
1460 strbuf_setlen(&buf, q - buf.buf);
1463 files_ref_path(refs, &sb, buf.buf);
1464 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1465 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1468 files_reflog_path(refs, &sb, buf.buf);
1469 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1470 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1472 strbuf_release(&buf);
1473 strbuf_release(&sb);
1476 /* make sure nobody touched the ref, and unlink */
1477 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1479 struct ref_transaction *transaction;
1480 struct strbuf err = STRBUF_INIT;
1482 if (check_refname_format(r->name, 0))
1485 transaction = ref_store_transaction_begin(&refs->base, &err);
1487 ref_transaction_delete(transaction, r->name, r->sha1,
1488 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1489 ref_transaction_commit(transaction, &err)) {
1490 ref_transaction_free(transaction);
1491 error("%s", err.buf);
1492 strbuf_release(&err);
1495 ref_transaction_free(transaction);
1496 strbuf_release(&err);
1499 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1508 * Return true if the specified reference should be packed.
1510 static int should_pack_ref(const char *refname,
1511 const struct object_id *oid, unsigned int ref_flags,
1512 unsigned int pack_flags)
1514 /* Do not pack per-worktree refs: */
1515 if (ref_type(refname) != REF_TYPE_NORMAL)
1518 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1519 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1522 /* Do not pack symbolic refs: */
1523 if (ref_flags & REF_ISSYMREF)
1526 /* Do not pack broken refs: */
1527 if (!ref_resolves_to_object(refname, oid, ref_flags))
1533 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1535 struct files_ref_store *refs =
1536 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1538 struct ref_iterator *iter;
1540 struct ref_to_prune *refs_to_prune = NULL;
1542 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1544 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1545 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1547 * If the loose reference can be packed, add an entry
1548 * in the packed ref cache. If the reference should be
1549 * pruned, also add it to refs_to_prune.
1551 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1556 * Create an entry in the packed-refs cache equivalent
1557 * to the one from the loose ref cache, except that
1558 * we don't copy the peeled status, because we want it
1561 add_packed_ref(refs, iter->refname, iter->oid);
1563 /* Schedule the loose reference for pruning if requested. */
1564 if ((flags & PACK_REFS_PRUNE)) {
1565 struct ref_to_prune *n;
1566 FLEX_ALLOC_STR(n, name, iter->refname);
1567 hashcpy(n->sha1, iter->oid->hash);
1568 n->next = refs_to_prune;
1572 if (ok != ITER_DONE)
1573 die("error while iterating over references");
1575 if (commit_packed_refs(refs))
1576 die_errno("unable to overwrite old ref-pack file");
1578 prune_refs(refs, refs_to_prune);
1583 * Rewrite the packed-refs file, omitting any refs listed in
1584 * 'refnames'. On error, leave packed-refs unchanged, write an error
1585 * message to 'err', and return a nonzero value.
1587 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1589 static int repack_without_refs(struct files_ref_store *refs,
1590 struct string_list *refnames, struct strbuf *err)
1592 struct ref_dir *packed;
1593 struct string_list_item *refname;
1594 int ret, needs_repacking = 0, removed = 0;
1596 files_assert_main_repository(refs, "repack_without_refs");
1599 /* Look for a packed ref */
1600 for_each_string_list_item(refname, refnames) {
1601 if (get_packed_ref(refs, refname->string)) {
1602 needs_repacking = 1;
1607 /* Avoid locking if we have nothing to do */
1608 if (!needs_repacking)
1609 return 0; /* no refname exists in packed refs */
1611 if (lock_packed_refs(refs, 0)) {
1612 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1615 packed = get_packed_refs(refs);
1617 /* Remove refnames from the cache */
1618 for_each_string_list_item(refname, refnames)
1619 if (remove_entry_from_dir(packed, refname->string) != -1)
1623 * All packed entries disappeared while we were
1624 * acquiring the lock.
1626 rollback_packed_refs(refs);
1630 /* Write what remains */
1631 ret = commit_packed_refs(refs);
1633 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1638 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1639 struct string_list *refnames, unsigned int flags)
1641 struct files_ref_store *refs =
1642 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1643 struct strbuf err = STRBUF_INIT;
1649 result = repack_without_refs(refs, refnames, &err);
1652 * If we failed to rewrite the packed-refs file, then
1653 * it is unsafe to try to remove loose refs, because
1654 * doing so might expose an obsolete packed value for
1655 * a reference that might even point at an object that
1656 * has been garbage collected.
1658 if (refnames->nr == 1)
1659 error(_("could not delete reference %s: %s"),
1660 refnames->items[0].string, err.buf);
1662 error(_("could not delete references: %s"), err.buf);
1667 for (i = 0; i < refnames->nr; i++) {
1668 const char *refname = refnames->items[i].string;
1670 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1671 result |= error(_("could not remove reference %s"), refname);
1675 strbuf_release(&err);
1680 * People using contrib's git-new-workdir have .git/logs/refs ->
1681 * /some/other/path/.git/logs/refs, and that may live on another device.
1683 * IOW, to avoid cross device rename errors, the temporary renamed log must
1684 * live into logs/refs.
1686 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1689 const char *tmp_renamed_log;
1693 static int rename_tmp_log_callback(const char *path, void *cb_data)
1695 struct rename_cb *cb = cb_data;
1697 if (rename(cb->tmp_renamed_log, path)) {
1699 * rename(a, b) when b is an existing directory ought
1700 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1701 * Sheesh. Record the true errno for error reporting,
1702 * but report EISDIR to raceproof_create_file() so
1703 * that it knows to retry.
1705 cb->true_errno = errno;
1706 if (errno == ENOTDIR)
1714 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1716 struct strbuf path = STRBUF_INIT;
1717 struct strbuf tmp = STRBUF_INIT;
1718 struct rename_cb cb;
1721 files_reflog_path(refs, &path, newrefname);
1722 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1723 cb.tmp_renamed_log = tmp.buf;
1724 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1726 if (errno == EISDIR)
1727 error("directory not empty: %s", path.buf);
1729 error("unable to move logfile %s to %s: %s",
1731 strerror(cb.true_errno));
1734 strbuf_release(&path);
1735 strbuf_release(&tmp);
1739 static int write_ref_to_lockfile(struct ref_lock *lock,
1740 const struct object_id *oid, struct strbuf *err);
1741 static int commit_ref_update(struct files_ref_store *refs,
1742 struct ref_lock *lock,
1743 const struct object_id *oid, const char *logmsg,
1744 struct strbuf *err);
1746 static int files_rename_ref(struct ref_store *ref_store,
1747 const char *oldrefname, const char *newrefname,
1750 struct files_ref_store *refs =
1751 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1752 struct object_id oid, orig_oid;
1753 int flag = 0, logmoved = 0;
1754 struct ref_lock *lock;
1755 struct stat loginfo;
1756 struct strbuf sb_oldref = STRBUF_INIT;
1757 struct strbuf sb_newref = STRBUF_INIT;
1758 struct strbuf tmp_renamed_log = STRBUF_INIT;
1760 struct strbuf err = STRBUF_INIT;
1762 files_reflog_path(refs, &sb_oldref, oldrefname);
1763 files_reflog_path(refs, &sb_newref, newrefname);
1764 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1766 log = !lstat(sb_oldref.buf, &loginfo);
1767 if (log && S_ISLNK(loginfo.st_mode)) {
1768 ret = error("reflog for %s is a symlink", oldrefname);
1772 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1773 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1774 orig_oid.hash, &flag)) {
1775 ret = error("refname %s not found", oldrefname);
1779 if (flag & REF_ISSYMREF) {
1780 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1784 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1789 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1790 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1791 oldrefname, strerror(errno));
1795 if (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 (!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);
1839 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1840 strbuf_release(&err);
1843 oidcpy(&lock->old_oid, &orig_oid);
1845 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1846 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1847 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1848 strbuf_release(&err);
1856 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1857 REF_NODEREF, NULL, &err);
1859 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1860 strbuf_release(&err);
1864 flag = log_all_ref_updates;
1865 log_all_ref_updates = LOG_REFS_NONE;
1866 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1867 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1868 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1869 strbuf_release(&err);
1871 log_all_ref_updates = flag;
1874 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1875 error("unable to restore logfile %s from %s: %s",
1876 oldrefname, newrefname, strerror(errno));
1877 if (!logmoved && log &&
1878 rename(tmp_renamed_log.buf, sb_oldref.buf))
1879 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1880 oldrefname, strerror(errno));
1883 strbuf_release(&sb_newref);
1884 strbuf_release(&sb_oldref);
1885 strbuf_release(&tmp_renamed_log);
1890 static int close_ref(struct ref_lock *lock)
1892 if (close_lock_file(lock->lk))
1897 static int commit_ref(struct ref_lock *lock)
1899 char *path = get_locked_file_path(lock->lk);
1902 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1904 * There is a directory at the path we want to rename
1905 * the lockfile to. Hopefully it is empty; try to
1908 size_t len = strlen(path);
1909 struct strbuf sb_path = STRBUF_INIT;
1911 strbuf_attach(&sb_path, path, len, len);
1914 * If this fails, commit_lock_file() will also fail
1915 * and will report the problem.
1917 remove_empty_directories(&sb_path);
1918 strbuf_release(&sb_path);
1923 if (commit_lock_file(lock->lk))
1928 static int open_or_create_logfile(const char *path, void *cb)
1932 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1933 return (*fd < 0) ? -1 : 0;
1937 * Create a reflog for a ref. If force_create = 0, only create the
1938 * reflog for certain refs (those for which should_autocreate_reflog
1939 * returns non-zero). Otherwise, create it regardless of the reference
1940 * name. If the logfile already existed or was created, return 0 and
1941 * set *logfd to the file descriptor opened for appending to the file.
1942 * If no logfile exists and we decided not to create one, return 0 and
1943 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1946 static int log_ref_setup(struct files_ref_store *refs,
1947 const char *refname, int force_create,
1948 int *logfd, struct strbuf *err)
1950 struct strbuf logfile_sb = STRBUF_INIT;
1953 files_reflog_path(refs, &logfile_sb, refname);
1954 logfile = strbuf_detach(&logfile_sb, NULL);
1956 if (force_create || should_autocreate_reflog(refname)) {
1957 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1958 if (errno == ENOENT)
1959 strbuf_addf(err, "unable to create directory for '%s': "
1960 "%s", logfile, strerror(errno));
1961 else if (errno == EISDIR)
1962 strbuf_addf(err, "there are still logs under '%s'",
1965 strbuf_addf(err, "unable to append to '%s': %s",
1966 logfile, strerror(errno));
1971 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1973 if (errno == ENOENT || errno == EISDIR) {
1975 * The logfile doesn't already exist,
1976 * but that is not an error; it only
1977 * means that we won't write log
1982 strbuf_addf(err, "unable to append to '%s': %s",
1983 logfile, strerror(errno));
1990 adjust_shared_perm(logfile);
2000 static int files_create_reflog(struct ref_store *ref_store,
2001 const char *refname, int force_create,
2004 struct files_ref_store *refs =
2005 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2008 if (log_ref_setup(refs, refname, force_create, &fd, err))
2017 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2018 const struct object_id *new_oid,
2019 const char *committer, const char *msg)
2021 int msglen, written;
2022 unsigned maxlen, len;
2025 msglen = msg ? strlen(msg) : 0;
2026 maxlen = strlen(committer) + msglen + 100;
2027 logrec = xmalloc(maxlen);
2028 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2029 oid_to_hex(old_oid),
2030 oid_to_hex(new_oid),
2033 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2035 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2043 static int files_log_ref_write(struct files_ref_store *refs,
2044 const char *refname, const struct object_id *old_oid,
2045 const struct object_id *new_oid, const char *msg,
2046 int flags, struct strbuf *err)
2050 if (log_all_ref_updates == LOG_REFS_UNSET)
2051 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2053 result = log_ref_setup(refs, refname,
2054 flags & REF_FORCE_CREATE_REFLOG,
2062 result = log_ref_write_fd(logfd, old_oid, new_oid,
2063 git_committer_info(0), msg);
2065 struct strbuf sb = STRBUF_INIT;
2066 int save_errno = errno;
2068 files_reflog_path(refs, &sb, refname);
2069 strbuf_addf(err, "unable to append to '%s': %s",
2070 sb.buf, strerror(save_errno));
2071 strbuf_release(&sb);
2076 struct strbuf sb = STRBUF_INIT;
2077 int save_errno = errno;
2079 files_reflog_path(refs, &sb, refname);
2080 strbuf_addf(err, "unable to append to '%s': %s",
2081 sb.buf, strerror(save_errno));
2082 strbuf_release(&sb);
2089 * Write sha1 into the open lockfile, then close the lockfile. On
2090 * errors, rollback the lockfile, fill in *err and
2093 static int write_ref_to_lockfile(struct ref_lock *lock,
2094 const struct object_id *oid, struct strbuf *err)
2096 static char term = '\n';
2100 o = parse_object(oid);
2103 "trying to write ref '%s' with nonexistent object %s",
2104 lock->ref_name, oid_to_hex(oid));
2108 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2110 "trying to write non-commit object %s to branch '%s'",
2111 oid_to_hex(oid), lock->ref_name);
2115 fd = get_lock_file_fd(lock->lk);
2116 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2117 write_in_full(fd, &term, 1) != 1 ||
2118 close_ref(lock) < 0) {
2120 "couldn't write '%s'", get_lock_file_path(lock->lk));
2128 * Commit a change to a loose reference that has already been written
2129 * to the loose reference lockfile. Also update the reflogs if
2130 * necessary, using the specified lockmsg (which can be NULL).
2132 static int commit_ref_update(struct files_ref_store *refs,
2133 struct ref_lock *lock,
2134 const struct object_id *oid, const char *logmsg,
2137 files_assert_main_repository(refs, "commit_ref_update");
2139 clear_loose_ref_cache(refs);
2140 if (files_log_ref_write(refs, lock->ref_name,
2141 &lock->old_oid, oid,
2143 char *old_msg = strbuf_detach(err, NULL);
2144 strbuf_addf(err, "cannot update the ref '%s': %s",
2145 lock->ref_name, old_msg);
2151 if (strcmp(lock->ref_name, "HEAD") != 0) {
2153 * Special hack: If a branch is updated directly and HEAD
2154 * points to it (may happen on the remote side of a push
2155 * for example) then logically the HEAD reflog should be
2157 * A generic solution implies reverse symref information,
2158 * but finding all symrefs pointing to the given branch
2159 * would be rather costly for this rare event (the direct
2160 * update of a branch) to be worth it. So let's cheat and
2161 * check with HEAD only which should cover 99% of all usage
2162 * scenarios (even 100% of the default ones).
2164 struct object_id head_oid;
2166 const char *head_ref;
2168 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2169 RESOLVE_REF_READING,
2170 head_oid.hash, &head_flag);
2171 if (head_ref && (head_flag & REF_ISSYMREF) &&
2172 !strcmp(head_ref, lock->ref_name)) {
2173 struct strbuf log_err = STRBUF_INIT;
2174 if (files_log_ref_write(refs, "HEAD",
2175 &lock->old_oid, oid,
2176 logmsg, 0, &log_err)) {
2177 error("%s", log_err.buf);
2178 strbuf_release(&log_err);
2183 if (commit_ref(lock)) {
2184 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2193 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2196 #ifndef NO_SYMLINK_HEAD
2197 char *ref_path = get_locked_file_path(lock->lk);
2199 ret = symlink(target, ref_path);
2203 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2208 static void update_symref_reflog(struct files_ref_store *refs,
2209 struct ref_lock *lock, const char *refname,
2210 const char *target, const char *logmsg)
2212 struct strbuf err = STRBUF_INIT;
2213 struct object_id new_oid;
2215 !refs_read_ref_full(&refs->base, target,
2216 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2217 files_log_ref_write(refs, refname, &lock->old_oid,
2218 &new_oid, logmsg, 0, &err)) {
2219 error("%s", err.buf);
2220 strbuf_release(&err);
2224 static int create_symref_locked(struct files_ref_store *refs,
2225 struct ref_lock *lock, const char *refname,
2226 const char *target, const char *logmsg)
2228 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2229 update_symref_reflog(refs, lock, refname, target, logmsg);
2233 if (!fdopen_lock_file(lock->lk, "w"))
2234 return error("unable to fdopen %s: %s",
2235 lock->lk->tempfile.filename.buf, strerror(errno));
2237 update_symref_reflog(refs, lock, refname, target, logmsg);
2239 /* no error check; commit_ref will check ferror */
2240 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2241 if (commit_ref(lock) < 0)
2242 return error("unable to write symref for %s: %s", refname,
2247 static int files_create_symref(struct ref_store *ref_store,
2248 const char *refname, const char *target,
2251 struct files_ref_store *refs =
2252 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2253 struct strbuf err = STRBUF_INIT;
2254 struct ref_lock *lock;
2257 lock = lock_ref_sha1_basic(refs, refname, NULL,
2258 NULL, NULL, REF_NODEREF, NULL,
2261 error("%s", err.buf);
2262 strbuf_release(&err);
2266 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2271 static int files_reflog_exists(struct ref_store *ref_store,
2272 const char *refname)
2274 struct files_ref_store *refs =
2275 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2276 struct strbuf sb = STRBUF_INIT;
2280 files_reflog_path(refs, &sb, refname);
2281 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2282 strbuf_release(&sb);
2286 static int files_delete_reflog(struct ref_store *ref_store,
2287 const char *refname)
2289 struct files_ref_store *refs =
2290 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2291 struct strbuf sb = STRBUF_INIT;
2294 files_reflog_path(refs, &sb, refname);
2295 ret = remove_path(sb.buf);
2296 strbuf_release(&sb);
2300 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2302 struct object_id ooid, noid;
2303 char *email_end, *message;
2304 timestamp_t timestamp;
2306 const char *p = sb->buf;
2308 /* old SP new SP name <email> SP time TAB msg LF */
2309 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2310 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2311 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2312 !(email_end = strchr(p, '>')) ||
2313 email_end[1] != ' ' ||
2314 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2315 !message || message[0] != ' ' ||
2316 (message[1] != '+' && message[1] != '-') ||
2317 !isdigit(message[2]) || !isdigit(message[3]) ||
2318 !isdigit(message[4]) || !isdigit(message[5]))
2319 return 0; /* corrupt? */
2320 email_end[1] = '\0';
2321 tz = strtol(message + 1, NULL, 10);
2322 if (message[6] != '\t')
2326 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2329 static char *find_beginning_of_line(char *bob, char *scan)
2331 while (bob < scan && *(--scan) != '\n')
2332 ; /* keep scanning backwards */
2334 * Return either beginning of the buffer, or LF at the end of
2335 * the previous line.
2340 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2341 const char *refname,
2342 each_reflog_ent_fn fn,
2345 struct files_ref_store *refs =
2346 files_downcast(ref_store, REF_STORE_READ,
2347 "for_each_reflog_ent_reverse");
2348 struct strbuf sb = STRBUF_INIT;
2351 int ret = 0, at_tail = 1;
2353 files_reflog_path(refs, &sb, refname);
2354 logfp = fopen(sb.buf, "r");
2355 strbuf_release(&sb);
2359 /* Jump to the end */
2360 if (fseek(logfp, 0, SEEK_END) < 0)
2361 ret = error("cannot seek back reflog for %s: %s",
2362 refname, strerror(errno));
2364 while (!ret && 0 < pos) {
2370 /* Fill next block from the end */
2371 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2372 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2373 ret = error("cannot seek back reflog for %s: %s",
2374 refname, strerror(errno));
2377 nread = fread(buf, cnt, 1, logfp);
2379 ret = error("cannot read %d bytes from reflog for %s: %s",
2380 cnt, refname, strerror(errno));
2385 scanp = endp = buf + cnt;
2386 if (at_tail && scanp[-1] == '\n')
2387 /* Looking at the final LF at the end of the file */
2391 while (buf < scanp) {
2393 * terminating LF of the previous line, or the beginning
2398 bp = find_beginning_of_line(buf, scanp);
2402 * The newline is the end of the previous line,
2403 * so we know we have complete line starting
2404 * at (bp + 1). Prefix it onto any prior data
2405 * we collected for the line and process it.
2407 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2410 ret = show_one_reflog_ent(&sb, fn, cb_data);
2416 * We are at the start of the buffer, and the
2417 * start of the file; there is no previous
2418 * line, and we have everything for this one.
2419 * Process it, and we can end the loop.
2421 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2422 ret = show_one_reflog_ent(&sb, fn, cb_data);
2429 * We are at the start of the buffer, and there
2430 * is more file to read backwards. Which means
2431 * we are in the middle of a line. Note that we
2432 * may get here even if *bp was a newline; that
2433 * just means we are at the exact end of the
2434 * previous line, rather than some spot in the
2437 * Save away what we have to be combined with
2438 * the data from the next read.
2440 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2447 die("BUG: reverse reflog parser had leftover data");
2450 strbuf_release(&sb);
2454 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2455 const char *refname,
2456 each_reflog_ent_fn fn, void *cb_data)
2458 struct files_ref_store *refs =
2459 files_downcast(ref_store, REF_STORE_READ,
2460 "for_each_reflog_ent");
2462 struct strbuf sb = STRBUF_INIT;
2465 files_reflog_path(refs, &sb, refname);
2466 logfp = fopen(sb.buf, "r");
2467 strbuf_release(&sb);
2471 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2472 ret = show_one_reflog_ent(&sb, fn, cb_data);
2474 strbuf_release(&sb);
2478 struct files_reflog_iterator {
2479 struct ref_iterator base;
2481 struct ref_store *ref_store;
2482 struct dir_iterator *dir_iterator;
2483 struct object_id oid;
2486 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2488 struct files_reflog_iterator *iter =
2489 (struct files_reflog_iterator *)ref_iterator;
2490 struct dir_iterator *diter = iter->dir_iterator;
2493 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2496 if (!S_ISREG(diter->st.st_mode))
2498 if (diter->basename[0] == '.')
2500 if (ends_with(diter->basename, ".lock"))
2503 if (refs_read_ref_full(iter->ref_store,
2504 diter->relative_path, 0,
2505 iter->oid.hash, &flags)) {
2506 error("bad ref for %s", diter->path.buf);
2510 iter->base.refname = diter->relative_path;
2511 iter->base.oid = &iter->oid;
2512 iter->base.flags = flags;
2516 iter->dir_iterator = NULL;
2517 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2522 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2523 struct object_id *peeled)
2525 die("BUG: ref_iterator_peel() called for reflog_iterator");
2528 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2530 struct files_reflog_iterator *iter =
2531 (struct files_reflog_iterator *)ref_iterator;
2534 if (iter->dir_iterator)
2535 ok = dir_iterator_abort(iter->dir_iterator);
2537 base_ref_iterator_free(ref_iterator);
2541 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2542 files_reflog_iterator_advance,
2543 files_reflog_iterator_peel,
2544 files_reflog_iterator_abort
2547 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2549 struct files_ref_store *refs =
2550 files_downcast(ref_store, REF_STORE_READ,
2551 "reflog_iterator_begin");
2552 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2553 struct ref_iterator *ref_iterator = &iter->base;
2554 struct strbuf sb = STRBUF_INIT;
2556 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2557 files_reflog_path(refs, &sb, NULL);
2558 iter->dir_iterator = dir_iterator_begin(sb.buf);
2559 iter->ref_store = ref_store;
2560 strbuf_release(&sb);
2561 return ref_iterator;
2565 * If update is a direct update of head_ref (the reference pointed to
2566 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2568 static int split_head_update(struct ref_update *update,
2569 struct ref_transaction *transaction,
2570 const char *head_ref,
2571 struct string_list *affected_refnames,
2574 struct string_list_item *item;
2575 struct ref_update *new_update;
2577 if ((update->flags & REF_LOG_ONLY) ||
2578 (update->flags & REF_ISPRUNING) ||
2579 (update->flags & REF_UPDATE_VIA_HEAD))
2582 if (strcmp(update->refname, head_ref))
2586 * First make sure that HEAD is not already in the
2587 * transaction. This insertion is O(N) in the transaction
2588 * size, but it happens at most once per transaction.
2590 item = string_list_insert(affected_refnames, "HEAD");
2592 /* An entry already existed */
2594 "multiple updates for 'HEAD' (including one "
2595 "via its referent '%s') are not allowed",
2597 return TRANSACTION_NAME_CONFLICT;
2600 new_update = ref_transaction_add_update(
2601 transaction, "HEAD",
2602 update->flags | REF_LOG_ONLY | REF_NODEREF,
2603 update->new_oid.hash, update->old_oid.hash,
2606 item->util = new_update;
2612 * update is for a symref that points at referent and doesn't have
2613 * REF_NODEREF set. Split it into two updates:
2614 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2615 * - A new, separate update for the referent reference
2616 * Note that the new update will itself be subject to splitting when
2617 * the iteration gets to it.
2619 static int split_symref_update(struct files_ref_store *refs,
2620 struct ref_update *update,
2621 const char *referent,
2622 struct ref_transaction *transaction,
2623 struct string_list *affected_refnames,
2626 struct string_list_item *item;
2627 struct ref_update *new_update;
2628 unsigned int new_flags;
2631 * First make sure that referent is not already in the
2632 * transaction. This insertion is O(N) in the transaction
2633 * size, but it happens at most once per symref in a
2636 item = string_list_insert(affected_refnames, referent);
2638 /* An entry already existed */
2640 "multiple updates for '%s' (including one "
2641 "via symref '%s') are not allowed",
2642 referent, update->refname);
2643 return TRANSACTION_NAME_CONFLICT;
2646 new_flags = update->flags;
2647 if (!strcmp(update->refname, "HEAD")) {
2649 * Record that the new update came via HEAD, so that
2650 * when we process it, split_head_update() doesn't try
2651 * to add another reflog update for HEAD. Note that
2652 * this bit will be propagated if the new_update
2653 * itself needs to be split.
2655 new_flags |= REF_UPDATE_VIA_HEAD;
2658 new_update = ref_transaction_add_update(
2659 transaction, referent, new_flags,
2660 update->new_oid.hash, update->old_oid.hash,
2663 new_update->parent_update = update;
2666 * Change the symbolic ref update to log only. Also, it
2667 * doesn't need to check its old SHA-1 value, as that will be
2668 * done when new_update is processed.
2670 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2671 update->flags &= ~REF_HAVE_OLD;
2673 item->util = new_update;
2679 * Return the refname under which update was originally requested.
2681 static const char *original_update_refname(struct ref_update *update)
2683 while (update->parent_update)
2684 update = update->parent_update;
2686 return update->refname;
2690 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2691 * are consistent with oid, which is the reference's current value. If
2692 * everything is OK, return 0; otherwise, write an error message to
2693 * err and return -1.
2695 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2698 if (!(update->flags & REF_HAVE_OLD) ||
2699 !oidcmp(oid, &update->old_oid))
2702 if (is_null_oid(&update->old_oid))
2703 strbuf_addf(err, "cannot lock ref '%s': "
2704 "reference already exists",
2705 original_update_refname(update));
2706 else if (is_null_oid(oid))
2707 strbuf_addf(err, "cannot lock ref '%s': "
2708 "reference is missing but expected %s",
2709 original_update_refname(update),
2710 oid_to_hex(&update->old_oid));
2712 strbuf_addf(err, "cannot lock ref '%s': "
2713 "is at %s but expected %s",
2714 original_update_refname(update),
2716 oid_to_hex(&update->old_oid));
2722 * Prepare for carrying out update:
2723 * - Lock the reference referred to by update.
2724 * - Read the reference under lock.
2725 * - Check that its old SHA-1 value (if specified) is correct, and in
2726 * any case record it in update->lock->old_oid for later use when
2727 * writing the reflog.
2728 * - If it is a symref update without REF_NODEREF, split it up into a
2729 * REF_LOG_ONLY update of the symref and add a separate update for
2730 * the referent to transaction.
2731 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2734 static int lock_ref_for_update(struct files_ref_store *refs,
2735 struct ref_update *update,
2736 struct ref_transaction *transaction,
2737 const char *head_ref,
2738 struct string_list *affected_refnames,
2741 struct strbuf referent = STRBUF_INIT;
2742 int mustexist = (update->flags & REF_HAVE_OLD) &&
2743 !is_null_oid(&update->old_oid);
2745 struct ref_lock *lock;
2747 files_assert_main_repository(refs, "lock_ref_for_update");
2749 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2750 update->flags |= REF_DELETING;
2753 ret = split_head_update(update, transaction, head_ref,
2754 affected_refnames, err);
2759 ret = lock_raw_ref(refs, update->refname, mustexist,
2760 affected_refnames, NULL,
2762 &update->type, err);
2766 reason = strbuf_detach(err, NULL);
2767 strbuf_addf(err, "cannot lock ref '%s': %s",
2768 original_update_refname(update), reason);
2773 update->backend_data = lock;
2775 if (update->type & REF_ISSYMREF) {
2776 if (update->flags & REF_NODEREF) {
2778 * We won't be reading the referent as part of
2779 * the transaction, so we have to read it here
2780 * to record and possibly check old_sha1:
2782 if (refs_read_ref_full(&refs->base,
2784 lock->old_oid.hash, NULL)) {
2785 if (update->flags & REF_HAVE_OLD) {
2786 strbuf_addf(err, "cannot lock ref '%s': "
2787 "error reading reference",
2788 original_update_refname(update));
2791 } else if (check_old_oid(update, &lock->old_oid, err)) {
2792 return TRANSACTION_GENERIC_ERROR;
2796 * Create a new update for the reference this
2797 * symref is pointing at. Also, we will record
2798 * and verify old_sha1 for this update as part
2799 * of processing the split-off update, so we
2800 * don't have to do it here.
2802 ret = split_symref_update(refs, update,
2803 referent.buf, transaction,
2804 affected_refnames, err);
2809 struct ref_update *parent_update;
2811 if (check_old_oid(update, &lock->old_oid, err))
2812 return TRANSACTION_GENERIC_ERROR;
2815 * If this update is happening indirectly because of a
2816 * symref update, record the old SHA-1 in the parent
2819 for (parent_update = update->parent_update;
2821 parent_update = parent_update->parent_update) {
2822 struct ref_lock *parent_lock = parent_update->backend_data;
2823 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2827 if ((update->flags & REF_HAVE_NEW) &&
2828 !(update->flags & REF_DELETING) &&
2829 !(update->flags & REF_LOG_ONLY)) {
2830 if (!(update->type & REF_ISSYMREF) &&
2831 !oidcmp(&lock->old_oid, &update->new_oid)) {
2833 * The reference already has the desired
2834 * value, so we don't need to write it.
2836 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2838 char *write_err = strbuf_detach(err, NULL);
2841 * The lock was freed upon failure of
2842 * write_ref_to_lockfile():
2844 update->backend_data = NULL;
2846 "cannot update ref '%s': %s",
2847 update->refname, write_err);
2849 return TRANSACTION_GENERIC_ERROR;
2851 update->flags |= REF_NEEDS_COMMIT;
2854 if (!(update->flags & REF_NEEDS_COMMIT)) {
2856 * We didn't call write_ref_to_lockfile(), so
2857 * the lockfile is still open. Close it to
2858 * free up the file descriptor:
2860 if (close_ref(lock)) {
2861 strbuf_addf(err, "couldn't close '%s.lock'",
2863 return TRANSACTION_GENERIC_ERROR;
2870 * Unlock any references in `transaction` that are still locked, and
2871 * mark the transaction closed.
2873 static void files_transaction_cleanup(struct ref_transaction *transaction)
2877 for (i = 0; i < transaction->nr; i++) {
2878 struct ref_update *update = transaction->updates[i];
2879 struct ref_lock *lock = update->backend_data;
2883 update->backend_data = NULL;
2887 transaction->state = REF_TRANSACTION_CLOSED;
2890 static int files_transaction_prepare(struct ref_store *ref_store,
2891 struct ref_transaction *transaction,
2894 struct files_ref_store *refs =
2895 files_downcast(ref_store, REF_STORE_WRITE,
2896 "ref_transaction_prepare");
2899 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2900 char *head_ref = NULL;
2902 struct object_id head_oid;
2906 if (!transaction->nr)
2910 * Fail if a refname appears more than once in the
2911 * transaction. (If we end up splitting up any updates using
2912 * split_symref_update() or split_head_update(), those
2913 * functions will check that the new updates don't have the
2914 * same refname as any existing ones.)
2916 for (i = 0; i < transaction->nr; i++) {
2917 struct ref_update *update = transaction->updates[i];
2918 struct string_list_item *item =
2919 string_list_append(&affected_refnames, update->refname);
2922 * We store a pointer to update in item->util, but at
2923 * the moment we never use the value of this field
2924 * except to check whether it is non-NULL.
2926 item->util = update;
2928 string_list_sort(&affected_refnames);
2929 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2930 ret = TRANSACTION_GENERIC_ERROR;
2935 * Special hack: If a branch is updated directly and HEAD
2936 * points to it (may happen on the remote side of a push
2937 * for example) then logically the HEAD reflog should be
2940 * A generic solution would require reverse symref lookups,
2941 * but finding all symrefs pointing to a given branch would be
2942 * rather costly for this rare event (the direct update of a
2943 * branch) to be worth it. So let's cheat and check with HEAD
2944 * only, which should cover 99% of all usage scenarios (even
2945 * 100% of the default ones).
2947 * So if HEAD is a symbolic reference, then record the name of
2948 * the reference that it points to. If we see an update of
2949 * head_ref within the transaction, then split_head_update()
2950 * arranges for the reflog of HEAD to be updated, too.
2952 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2953 RESOLVE_REF_NO_RECURSE,
2954 head_oid.hash, &head_type);
2956 if (head_ref && !(head_type & REF_ISSYMREF)) {
2962 * Acquire all locks, verify old values if provided, check
2963 * that new values are valid, and write new values to the
2964 * lockfiles, ready to be activated. Only keep one lockfile
2965 * open at a time to avoid running out of file descriptors.
2966 * Note that lock_ref_for_update() might append more updates
2967 * to the transaction.
2969 for (i = 0; i < transaction->nr; i++) {
2970 struct ref_update *update = transaction->updates[i];
2972 ret = lock_ref_for_update(refs, update, transaction,
2973 head_ref, &affected_refnames, err);
2980 string_list_clear(&affected_refnames, 0);
2983 files_transaction_cleanup(transaction);
2985 transaction->state = REF_TRANSACTION_PREPARED;
2990 static int files_transaction_finish(struct ref_store *ref_store,
2991 struct ref_transaction *transaction,
2994 struct files_ref_store *refs =
2995 files_downcast(ref_store, 0, "ref_transaction_finish");
2998 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2999 struct string_list_item *ref_to_delete;
3000 struct strbuf sb = STRBUF_INIT;
3004 if (!transaction->nr) {
3005 transaction->state = REF_TRANSACTION_CLOSED;
3009 /* Perform updates first so live commits remain referenced */
3010 for (i = 0; i < transaction->nr; i++) {
3011 struct ref_update *update = transaction->updates[i];
3012 struct ref_lock *lock = update->backend_data;
3014 if (update->flags & REF_NEEDS_COMMIT ||
3015 update->flags & REF_LOG_ONLY) {
3016 if (files_log_ref_write(refs,
3020 update->msg, update->flags,
3022 char *old_msg = strbuf_detach(err, NULL);
3024 strbuf_addf(err, "cannot update the ref '%s': %s",
3025 lock->ref_name, old_msg);
3028 update->backend_data = NULL;
3029 ret = TRANSACTION_GENERIC_ERROR;
3033 if (update->flags & REF_NEEDS_COMMIT) {
3034 clear_loose_ref_cache(refs);
3035 if (commit_ref(lock)) {
3036 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3038 update->backend_data = NULL;
3039 ret = TRANSACTION_GENERIC_ERROR;
3044 /* Perform deletes now that updates are safely completed */
3045 for (i = 0; i < transaction->nr; i++) {
3046 struct ref_update *update = transaction->updates[i];
3047 struct ref_lock *lock = update->backend_data;
3049 if (update->flags & REF_DELETING &&
3050 !(update->flags & REF_LOG_ONLY)) {
3051 if (!(update->type & REF_ISPACKED) ||
3052 update->type & REF_ISSYMREF) {
3053 /* It is a loose reference. */
3055 files_ref_path(refs, &sb, lock->ref_name);
3056 if (unlink_or_msg(sb.buf, err)) {
3057 ret = TRANSACTION_GENERIC_ERROR;
3060 update->flags |= REF_DELETED_LOOSE;
3063 if (!(update->flags & REF_ISPRUNING))
3064 string_list_append(&refs_to_delete,
3069 if (repack_without_refs(refs, &refs_to_delete, err)) {
3070 ret = TRANSACTION_GENERIC_ERROR;
3074 /* Delete the reflogs of any references that were deleted: */
3075 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3077 files_reflog_path(refs, &sb, ref_to_delete->string);
3078 if (!unlink_or_warn(sb.buf))
3079 try_remove_empty_parents(refs, ref_to_delete->string,
3080 REMOVE_EMPTY_PARENTS_REFLOG);
3083 clear_loose_ref_cache(refs);
3086 files_transaction_cleanup(transaction);
3088 for (i = 0; i < transaction->nr; i++) {
3089 struct ref_update *update = transaction->updates[i];
3091 if (update->flags & REF_DELETED_LOOSE) {
3093 * The loose reference was deleted. Delete any
3094 * empty parent directories. (Note that this
3095 * can only work because we have already
3096 * removed the lockfile.)
3098 try_remove_empty_parents(refs, update->refname,
3099 REMOVE_EMPTY_PARENTS_REF);
3103 strbuf_release(&sb);
3104 string_list_clear(&refs_to_delete, 0);
3108 static int files_transaction_abort(struct ref_store *ref_store,
3109 struct ref_transaction *transaction,
3112 files_transaction_cleanup(transaction);
3116 static int ref_present(const char *refname,
3117 const struct object_id *oid, int flags, void *cb_data)
3119 struct string_list *affected_refnames = cb_data;
3121 return string_list_has_string(affected_refnames, refname);
3124 static int files_initial_transaction_commit(struct ref_store *ref_store,
3125 struct ref_transaction *transaction,
3128 struct files_ref_store *refs =
3129 files_downcast(ref_store, REF_STORE_WRITE,
3130 "initial_ref_transaction_commit");
3133 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3137 if (transaction->state != REF_TRANSACTION_OPEN)
3138 die("BUG: commit called for transaction that is not open");
3140 /* Fail if a refname appears more than once in the transaction: */
3141 for (i = 0; i < transaction->nr; i++)
3142 string_list_append(&affected_refnames,
3143 transaction->updates[i]->refname);
3144 string_list_sort(&affected_refnames);
3145 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3146 ret = TRANSACTION_GENERIC_ERROR;
3151 * It's really undefined to call this function in an active
3152 * repository or when there are existing references: we are
3153 * only locking and changing packed-refs, so (1) any
3154 * simultaneous processes might try to change a reference at
3155 * the same time we do, and (2) any existing loose versions of
3156 * the references that we are setting would have precedence
3157 * over our values. But some remote helpers create the remote
3158 * "HEAD" and "master" branches before calling this function,
3159 * so here we really only check that none of the references
3160 * that we are creating already exists.
3162 if (refs_for_each_rawref(&refs->base, ref_present,
3163 &affected_refnames))
3164 die("BUG: initial ref transaction called with existing refs");
3166 for (i = 0; i < transaction->nr; i++) {
3167 struct ref_update *update = transaction->updates[i];
3169 if ((update->flags & REF_HAVE_OLD) &&
3170 !is_null_oid(&update->old_oid))
3171 die("BUG: initial ref transaction with old_sha1 set");
3172 if (refs_verify_refname_available(&refs->base, update->refname,
3173 &affected_refnames, NULL,
3175 ret = TRANSACTION_NAME_CONFLICT;
3180 if (lock_packed_refs(refs, 0)) {
3181 strbuf_addf(err, "unable to lock packed-refs file: %s",
3183 ret = TRANSACTION_GENERIC_ERROR;
3187 for (i = 0; i < transaction->nr; i++) {
3188 struct ref_update *update = transaction->updates[i];
3190 if ((update->flags & REF_HAVE_NEW) &&
3191 !is_null_oid(&update->new_oid))
3192 add_packed_ref(refs, update->refname,
3196 if (commit_packed_refs(refs)) {
3197 strbuf_addf(err, "unable to commit packed-refs file: %s",
3199 ret = TRANSACTION_GENERIC_ERROR;
3204 transaction->state = REF_TRANSACTION_CLOSED;
3205 string_list_clear(&affected_refnames, 0);
3209 struct expire_reflog_cb {
3211 reflog_expiry_should_prune_fn *should_prune_fn;
3214 struct object_id last_kept_oid;
3217 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3218 const char *email, timestamp_t timestamp, int tz,
3219 const char *message, void *cb_data)
3221 struct expire_reflog_cb *cb = cb_data;
3222 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3224 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3225 ooid = &cb->last_kept_oid;
3227 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3228 message, policy_cb)) {
3230 printf("would prune %s", message);
3231 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3232 printf("prune %s", message);
3235 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3236 oid_to_hex(ooid), oid_to_hex(noid),
3237 email, timestamp, tz, message);
3238 oidcpy(&cb->last_kept_oid, noid);
3240 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3241 printf("keep %s", message);
3246 static int files_reflog_expire(struct ref_store *ref_store,
3247 const char *refname, const unsigned char *sha1,
3249 reflog_expiry_prepare_fn prepare_fn,
3250 reflog_expiry_should_prune_fn should_prune_fn,
3251 reflog_expiry_cleanup_fn cleanup_fn,
3252 void *policy_cb_data)
3254 struct files_ref_store *refs =
3255 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3256 static struct lock_file reflog_lock;
3257 struct expire_reflog_cb cb;
3258 struct ref_lock *lock;
3259 struct strbuf log_file_sb = STRBUF_INIT;
3263 struct strbuf err = STRBUF_INIT;
3264 struct object_id oid;
3266 memset(&cb, 0, sizeof(cb));
3268 cb.policy_cb = policy_cb_data;
3269 cb.should_prune_fn = should_prune_fn;
3272 * The reflog file is locked by holding the lock on the
3273 * reference itself, plus we might need to update the
3274 * reference if --updateref was specified:
3276 lock = lock_ref_sha1_basic(refs, refname, sha1,
3277 NULL, NULL, REF_NODEREF,
3280 error("cannot lock ref '%s': %s", refname, err.buf);
3281 strbuf_release(&err);
3284 if (!refs_reflog_exists(ref_store, refname)) {
3289 files_reflog_path(refs, &log_file_sb, refname);
3290 log_file = strbuf_detach(&log_file_sb, NULL);
3291 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3293 * Even though holding $GIT_DIR/logs/$reflog.lock has
3294 * no locking implications, we use the lock_file
3295 * machinery here anyway because it does a lot of the
3296 * work we need, including cleaning up if the program
3297 * exits unexpectedly.
3299 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3300 struct strbuf err = STRBUF_INIT;
3301 unable_to_lock_message(log_file, errno, &err);
3302 error("%s", err.buf);
3303 strbuf_release(&err);
3306 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3308 error("cannot fdopen %s (%s)",
3309 get_lock_file_path(&reflog_lock), strerror(errno));
3314 hashcpy(oid.hash, sha1);
3316 (*prepare_fn)(refname, &oid, cb.policy_cb);
3317 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3318 (*cleanup_fn)(cb.policy_cb);
3320 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3322 * It doesn't make sense to adjust a reference pointed
3323 * to by a symbolic ref based on expiring entries in
3324 * the symbolic reference's reflog. Nor can we update
3325 * a reference if there are no remaining reflog
3328 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3329 !(type & REF_ISSYMREF) &&
3330 !is_null_oid(&cb.last_kept_oid);
3332 if (close_lock_file(&reflog_lock)) {
3333 status |= error("couldn't write %s: %s", log_file,
3335 } else if (update &&
3336 (write_in_full(get_lock_file_fd(lock->lk),
3337 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3338 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3339 close_ref(lock) < 0)) {
3340 status |= error("couldn't write %s",
3341 get_lock_file_path(lock->lk));
3342 rollback_lock_file(&reflog_lock);
3343 } else if (commit_lock_file(&reflog_lock)) {
3344 status |= error("unable to write reflog '%s' (%s)",
3345 log_file, strerror(errno));
3346 } else if (update && commit_ref(lock)) {
3347 status |= error("couldn't set %s", lock->ref_name);
3355 rollback_lock_file(&reflog_lock);
3361 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3363 struct files_ref_store *refs =
3364 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3365 struct strbuf sb = STRBUF_INIT;
3368 * Create .git/refs/{heads,tags}
3370 files_ref_path(refs, &sb, "refs/heads");
3371 safe_create_dir(sb.buf, 1);
3374 files_ref_path(refs, &sb, "refs/tags");
3375 safe_create_dir(sb.buf, 1);
3377 strbuf_release(&sb);
3381 struct ref_storage_be refs_be_files = {
3384 files_ref_store_create,
3386 files_transaction_prepare,
3387 files_transaction_finish,
3388 files_transaction_abort,
3389 files_initial_transaction_commit,
3393 files_create_symref,
3397 files_ref_iterator_begin,
3400 files_reflog_iterator_begin,
3401 files_for_each_reflog_ent,
3402 files_for_each_reflog_ent_reverse,
3403 files_reflog_exists,
3404 files_create_reflog,
3405 files_delete_reflog,