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 * A container for `packed-refs`-related data. It is not (yet) a
54 struct packed_ref_store {
55 unsigned int store_flags;
57 /* The path of the "packed-refs" file: */
61 * A cache of the values read from the `packed-refs` file, if
62 * it might still be current; otherwise, NULL.
64 struct packed_ref_cache *cache;
67 * Lock used for the "packed-refs" file. Note that this (and
68 * thus the enclosing `packed_ref_store`) must not be freed.
70 struct lock_file lock;
73 static struct packed_ref_store *packed_ref_store_create(
74 const char *path, unsigned int store_flags)
76 struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
78 refs->store_flags = store_flags;
79 refs->path = xstrdup(path);
84 * Die if refs is not the main ref store. caller is used in any
85 * necessary error messages.
87 static void packed_assert_main_repository(struct packed_ref_store *refs,
90 if (refs->store_flags & REF_STORE_MAIN)
93 die("BUG: operation %s only allowed for main ref store", caller);
97 * Future: need to be in "struct repository"
98 * when doing a full libification.
100 struct files_ref_store {
101 struct ref_store base;
102 unsigned int store_flags;
107 struct ref_cache *loose;
109 struct packed_ref_store *packed_ref_store;
113 * Increment the reference count of *packed_refs.
115 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
117 packed_refs->referrers++;
121 * Decrease the reference count of *packed_refs. If it goes to zero,
122 * free *packed_refs and return true; otherwise return false.
124 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
126 if (!--packed_refs->referrers) {
127 free_ref_cache(packed_refs->cache);
128 stat_validity_clear(&packed_refs->validity);
136 static void clear_packed_ref_cache(struct packed_ref_store *refs)
139 struct packed_ref_cache *cache = refs->cache;
141 if (is_lock_file_locked(&refs->lock))
142 die("BUG: packed-ref cache cleared while locked");
144 release_packed_ref_cache(cache);
148 static void clear_loose_ref_cache(struct files_ref_store *refs)
151 free_ref_cache(refs->loose);
157 * Create a new submodule ref cache and add it to the internal
160 static struct ref_store *files_ref_store_create(const char *gitdir,
163 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
164 struct ref_store *ref_store = (struct ref_store *)refs;
165 struct strbuf sb = STRBUF_INIT;
167 base_ref_store_init(ref_store, &refs_be_files);
168 refs->store_flags = flags;
170 refs->gitdir = xstrdup(gitdir);
171 get_common_dir_noenv(&sb, gitdir);
172 refs->gitcommondir = strbuf_detach(&sb, NULL);
173 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
174 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
181 * Die if refs is not the main ref store. caller is used in any
182 * necessary error messages.
184 static void files_assert_main_repository(struct files_ref_store *refs,
187 if (refs->store_flags & REF_STORE_MAIN)
190 die("BUG: operation %s only allowed for main ref store", caller);
194 * Downcast ref_store to files_ref_store. Die if ref_store is not a
195 * files_ref_store. required_flags is compared with ref_store's
196 * store_flags to ensure the ref_store has all required capabilities.
197 * "caller" is used in any necessary error messages.
199 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
200 unsigned int required_flags,
203 struct files_ref_store *refs;
205 if (ref_store->be != &refs_be_files)
206 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
207 ref_store->be->name, caller);
209 refs = (struct files_ref_store *)ref_store;
211 if ((refs->store_flags & required_flags) != required_flags)
212 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
213 caller, required_flags, refs->store_flags);
218 /* The length of a peeled reference line in packed-refs, including EOL: */
219 #define PEELED_LINE_LENGTH 42
222 * The packed-refs header line that we write out. Perhaps other
223 * traits will be added later. The trailing space is required.
225 static const char PACKED_REFS_HEADER[] =
226 "# pack-refs with: peeled fully-peeled \n";
229 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
230 * Return a pointer to the refname within the line (null-terminated),
231 * or NULL if there was a problem.
233 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
237 if (parse_oid_hex(line->buf, oid, &ref) < 0)
239 if (!isspace(*ref++))
245 if (line->buf[line->len - 1] != '\n')
247 line->buf[--line->len] = 0;
253 * Read from `packed_refs_file` into a newly-allocated
254 * `packed_ref_cache` and return it. The return value will already
255 * have its reference count incremented.
257 * A comment line of the form "# pack-refs with: " may contain zero or
258 * more traits. We interpret the traits as follows:
262 * Probably no references are peeled. But if the file contains a
263 * peeled value for a reference, we will use it.
267 * References under "refs/tags/", if they *can* be peeled, *are*
268 * peeled in this file. References outside of "refs/tags/" are
269 * probably not peeled even if they could have been, but if we find
270 * a peeled value for such a reference we will use it.
274 * All references in the file that can be peeled are peeled.
275 * Inversely (and this is more important), any references in the
276 * file for which no peeled value is recorded is not peelable. This
277 * trait should typically be written alongside "peeled" for
278 * compatibility with older clients, but we do not require it
279 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
281 static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
284 struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
285 struct ref_entry *last = NULL;
286 struct strbuf line = STRBUF_INIT;
287 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
290 acquire_packed_ref_cache(packed_refs);
291 packed_refs->cache = create_ref_cache(NULL, NULL);
292 packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
294 f = fopen(packed_refs_file, "r");
296 if (errno == ENOENT) {
298 * This is OK; it just means that no
299 * "packed-refs" file has been written yet,
300 * which is equivalent to it being empty.
304 die_errno("couldn't read %s", packed_refs_file);
308 stat_validity_update(&packed_refs->validity, fileno(f));
310 dir = get_ref_dir(packed_refs->cache->root);
311 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
312 struct object_id oid;
316 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
317 if (strstr(traits, " fully-peeled "))
318 peeled = PEELED_FULLY;
319 else if (strstr(traits, " peeled "))
320 peeled = PEELED_TAGS;
321 /* perhaps other traits later as well */
325 refname = parse_ref_line(&line, &oid);
327 int flag = REF_ISPACKED;
329 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
330 if (!refname_is_safe(refname))
331 die("packed refname is dangerous: %s", refname);
333 flag |= REF_BAD_NAME | REF_ISBROKEN;
335 last = create_ref_entry(refname, &oid, flag);
336 if (peeled == PEELED_FULLY ||
337 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
338 last->flag |= REF_KNOWS_PEELED;
339 add_ref_entry(dir, last);
343 line.buf[0] == '^' &&
344 line.len == PEELED_LINE_LENGTH &&
345 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
346 !get_oid_hex(line.buf + 1, &oid)) {
347 oidcpy(&last->u.value.peeled, &oid);
349 * Regardless of what the file header said,
350 * we definitely know the value of *this*
353 last->flag |= REF_KNOWS_PEELED;
358 strbuf_release(&line);
363 static void files_reflog_path(struct files_ref_store *refs,
369 * FIXME: of course this is wrong in multi worktree
370 * setting. To be fixed real soon.
372 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
376 switch (ref_type(refname)) {
377 case REF_TYPE_PER_WORKTREE:
378 case REF_TYPE_PSEUDOREF:
379 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
381 case REF_TYPE_NORMAL:
382 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
385 die("BUG: unknown ref type %d of ref %s",
386 ref_type(refname), refname);
390 static void files_ref_path(struct files_ref_store *refs,
394 switch (ref_type(refname)) {
395 case REF_TYPE_PER_WORKTREE:
396 case REF_TYPE_PSEUDOREF:
397 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
399 case REF_TYPE_NORMAL:
400 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
403 die("BUG: unknown ref type %d of ref %s",
404 ref_type(refname), refname);
409 * Check that the packed refs cache (if any) still reflects the
410 * contents of the file. If not, clear the cache.
412 static void validate_packed_ref_cache(struct packed_ref_store *refs)
415 !stat_validity_check(&refs->cache->validity, refs->path))
416 clear_packed_ref_cache(refs);
420 * Get the packed_ref_cache for the specified packed_ref_store,
421 * creating and populating it if it hasn't been read before or if the
422 * file has been changed (according to its `validity` field) since it
423 * was last read. On the other hand, if we hold the lock, then assume
424 * that the file hasn't been changed out from under us, so skip the
425 * extra `stat()` call in `stat_validity_check()`.
427 static struct packed_ref_cache *get_packed_ref_cache(struct packed_ref_store *refs)
429 if (!is_lock_file_locked(&refs->lock))
430 validate_packed_ref_cache(refs);
433 refs->cache = read_packed_refs(refs->path);
438 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
440 return get_ref_dir(packed_ref_cache->cache->root);
443 static struct ref_dir *get_packed_refs(struct packed_ref_store *refs)
445 return get_packed_ref_dir(get_packed_ref_cache(refs));
449 * Add or overwrite a reference in the in-memory packed reference
450 * cache. This may only be called while the packed-refs file is locked
451 * (see lock_packed_refs()). To actually write the packed-refs file,
452 * call commit_packed_refs().
454 static void add_packed_ref(struct packed_ref_store *refs,
455 const char *refname, const struct object_id *oid)
457 struct ref_dir *packed_refs;
458 struct ref_entry *packed_entry;
460 if (!is_lock_file_locked(&refs->lock))
461 die("BUG: packed refs not locked");
463 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
464 die("Reference has invalid format: '%s'", refname);
466 packed_refs = get_packed_refs(refs);
467 packed_entry = find_ref_entry(packed_refs, refname);
469 /* Overwrite the existing entry: */
470 oidcpy(&packed_entry->u.value.oid, oid);
471 packed_entry->flag = REF_ISPACKED;
472 oidclr(&packed_entry->u.value.peeled);
474 packed_entry = create_ref_entry(refname, oid, REF_ISPACKED);
475 add_ref_entry(packed_refs, packed_entry);
480 * Read the loose references from the namespace dirname into dir
481 * (without recursing). dirname must end with '/'. dir must be the
482 * directory entry corresponding to dirname.
484 static void loose_fill_ref_dir(struct ref_store *ref_store,
485 struct ref_dir *dir, const char *dirname)
487 struct files_ref_store *refs =
488 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
491 int dirnamelen = strlen(dirname);
492 struct strbuf refname;
493 struct strbuf path = STRBUF_INIT;
496 files_ref_path(refs, &path, dirname);
497 path_baselen = path.len;
499 d = opendir(path.buf);
501 strbuf_release(&path);
505 strbuf_init(&refname, dirnamelen + 257);
506 strbuf_add(&refname, dirname, dirnamelen);
508 while ((de = readdir(d)) != NULL) {
509 struct object_id oid;
513 if (de->d_name[0] == '.')
515 if (ends_with(de->d_name, ".lock"))
517 strbuf_addstr(&refname, de->d_name);
518 strbuf_addstr(&path, de->d_name);
519 if (stat(path.buf, &st) < 0) {
520 ; /* silently ignore */
521 } else if (S_ISDIR(st.st_mode)) {
522 strbuf_addch(&refname, '/');
523 add_entry_to_dir(dir,
524 create_dir_entry(dir->cache, refname.buf,
527 if (!refs_resolve_ref_unsafe(&refs->base,
532 flag |= REF_ISBROKEN;
533 } else if (is_null_oid(&oid)) {
535 * It is so astronomically unlikely
536 * that NULL_SHA1 is the SHA-1 of an
537 * actual object that we consider its
538 * appearance in a loose reference
539 * file to be repo corruption
540 * (probably due to a software bug).
542 flag |= REF_ISBROKEN;
545 if (check_refname_format(refname.buf,
546 REFNAME_ALLOW_ONELEVEL)) {
547 if (!refname_is_safe(refname.buf))
548 die("loose refname is dangerous: %s", refname.buf);
550 flag |= REF_BAD_NAME | REF_ISBROKEN;
552 add_entry_to_dir(dir,
553 create_ref_entry(refname.buf, &oid, flag));
555 strbuf_setlen(&refname, dirnamelen);
556 strbuf_setlen(&path, path_baselen);
558 strbuf_release(&refname);
559 strbuf_release(&path);
563 * Manually add refs/bisect, which, being per-worktree, might
564 * not appear in the directory listing for refs/ in the main
567 if (!strcmp(dirname, "refs/")) {
568 int pos = search_ref_dir(dir, "refs/bisect/", 12);
571 struct ref_entry *child_entry = create_dir_entry(
572 dir->cache, "refs/bisect/", 12, 1);
573 add_entry_to_dir(dir, child_entry);
578 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
582 * Mark the top-level directory complete because we
583 * are about to read the only subdirectory that can
586 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
588 /* We're going to fill the top level ourselves: */
589 refs->loose->root->flag &= ~REF_INCOMPLETE;
592 * Add an incomplete entry for "refs/" (to be filled
595 add_entry_to_dir(get_ref_dir(refs->loose->root),
596 create_dir_entry(refs->loose, "refs/", 5, 1));
602 * Return the ref_entry for the given refname from the packed
603 * references. If it does not exist, return NULL.
605 static struct ref_entry *get_packed_ref(struct packed_ref_store *refs,
608 return find_ref_entry(get_packed_refs(refs), refname);
612 * A loose ref file doesn't exist; check for a packed ref.
614 static int resolve_packed_ref(struct files_ref_store *refs,
616 unsigned char *sha1, unsigned int *flags)
618 struct ref_entry *entry;
621 * The loose reference file does not exist; check for a packed
624 entry = get_packed_ref(refs->packed_ref_store, refname);
626 hashcpy(sha1, entry->u.value.oid.hash);
627 *flags |= REF_ISPACKED;
630 /* refname is not a packed reference. */
634 static int files_read_raw_ref(struct ref_store *ref_store,
635 const char *refname, unsigned char *sha1,
636 struct strbuf *referent, unsigned int *type)
638 struct files_ref_store *refs =
639 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
640 struct strbuf sb_contents = STRBUF_INIT;
641 struct strbuf sb_path = STRBUF_INIT;
648 int remaining_retries = 3;
651 strbuf_reset(&sb_path);
653 files_ref_path(refs, &sb_path, refname);
659 * We might have to loop back here to avoid a race
660 * condition: first we lstat() the file, then we try
661 * to read it as a link or as a file. But if somebody
662 * changes the type of the file (file <-> directory
663 * <-> symlink) between the lstat() and reading, then
664 * we don't want to report that as an error but rather
665 * try again starting with the lstat().
667 * We'll keep a count of the retries, though, just to avoid
668 * any confusing situation sending us into an infinite loop.
671 if (remaining_retries-- <= 0)
674 if (lstat(path, &st) < 0) {
677 if (resolve_packed_ref(refs, refname, sha1, type)) {
685 /* Follow "normalized" - ie "refs/.." symlinks by hand */
686 if (S_ISLNK(st.st_mode)) {
687 strbuf_reset(&sb_contents);
688 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
689 if (errno == ENOENT || errno == EINVAL)
690 /* inconsistent with lstat; retry */
695 if (starts_with(sb_contents.buf, "refs/") &&
696 !check_refname_format(sb_contents.buf, 0)) {
697 strbuf_swap(&sb_contents, referent);
698 *type |= REF_ISSYMREF;
703 * It doesn't look like a refname; fall through to just
704 * treating it like a non-symlink, and reading whatever it
709 /* Is it a directory? */
710 if (S_ISDIR(st.st_mode)) {
712 * Even though there is a directory where the loose
713 * ref is supposed to be, there could still be a
716 if (resolve_packed_ref(refs, refname, sha1, type)) {
725 * Anything else, just open it and try to use it as
728 fd = open(path, O_RDONLY);
730 if (errno == ENOENT && !S_ISLNK(st.st_mode))
731 /* inconsistent with lstat; retry */
736 strbuf_reset(&sb_contents);
737 if (strbuf_read(&sb_contents, fd, 256) < 0) {
738 int save_errno = errno;
744 strbuf_rtrim(&sb_contents);
745 buf = sb_contents.buf;
746 if (starts_with(buf, "ref:")) {
748 while (isspace(*buf))
751 strbuf_reset(referent);
752 strbuf_addstr(referent, buf);
753 *type |= REF_ISSYMREF;
759 * Please note that FETCH_HEAD has additional
760 * data after the sha.
762 if (get_sha1_hex(buf, sha1) ||
763 (buf[40] != '\0' && !isspace(buf[40]))) {
764 *type |= REF_ISBROKEN;
773 strbuf_release(&sb_path);
774 strbuf_release(&sb_contents);
779 static void unlock_ref(struct ref_lock *lock)
781 /* Do not free lock->lk -- atexit() still looks at them */
783 rollback_lock_file(lock->lk);
784 free(lock->ref_name);
789 * Lock refname, without following symrefs, and set *lock_p to point
790 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
791 * and type similarly to read_raw_ref().
793 * The caller must verify that refname is a "safe" reference name (in
794 * the sense of refname_is_safe()) before calling this function.
796 * If the reference doesn't already exist, verify that refname doesn't
797 * have a D/F conflict with any existing references. extras and skip
798 * are passed to refs_verify_refname_available() for this check.
800 * If mustexist is not set and the reference is not found or is
801 * broken, lock the reference anyway but clear sha1.
803 * Return 0 on success. On failure, write an error message to err and
804 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
806 * Implementation note: This function is basically
811 * but it includes a lot more code to
812 * - Deal with possible races with other processes
813 * - Avoid calling refs_verify_refname_available() when it can be
814 * avoided, namely if we were successfully able to read the ref
815 * - Generate informative error messages in the case of failure
817 static int lock_raw_ref(struct files_ref_store *refs,
818 const char *refname, int mustexist,
819 const struct string_list *extras,
820 const struct string_list *skip,
821 struct ref_lock **lock_p,
822 struct strbuf *referent,
826 struct ref_lock *lock;
827 struct strbuf ref_file = STRBUF_INIT;
828 int attempts_remaining = 3;
829 int ret = TRANSACTION_GENERIC_ERROR;
832 files_assert_main_repository(refs, "lock_raw_ref");
836 /* First lock the file so it can't change out from under us. */
838 *lock_p = lock = xcalloc(1, sizeof(*lock));
840 lock->ref_name = xstrdup(refname);
841 files_ref_path(refs, &ref_file, refname);
844 switch (safe_create_leading_directories(ref_file.buf)) {
849 * Suppose refname is "refs/foo/bar". We just failed
850 * to create the containing directory, "refs/foo",
851 * because there was a non-directory in the way. This
852 * indicates a D/F conflict, probably because of
853 * another reference such as "refs/foo". There is no
854 * reason to expect this error to be transitory.
856 if (refs_verify_refname_available(&refs->base, refname,
857 extras, skip, err)) {
860 * To the user the relevant error is
861 * that the "mustexist" reference is
865 strbuf_addf(err, "unable to resolve reference '%s'",
869 * The error message set by
870 * refs_verify_refname_available() is
873 ret = TRANSACTION_NAME_CONFLICT;
877 * The file that is in the way isn't a loose
878 * reference. Report it as a low-level
881 strbuf_addf(err, "unable to create lock file %s.lock; "
882 "non-directory in the way",
887 /* Maybe another process was tidying up. Try again. */
888 if (--attempts_remaining > 0)
892 strbuf_addf(err, "unable to create directory for %s",
898 lock->lk = xcalloc(1, sizeof(struct lock_file));
900 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
901 if (errno == ENOENT && --attempts_remaining > 0) {
903 * Maybe somebody just deleted one of the
904 * directories leading to ref_file. Try
909 unable_to_lock_message(ref_file.buf, errno, err);
915 * Now we hold the lock and can read the reference without
916 * fear that its value will change.
919 if (files_read_raw_ref(&refs->base, refname,
920 lock->old_oid.hash, referent, type)) {
921 if (errno == ENOENT) {
923 /* Garden variety missing reference. */
924 strbuf_addf(err, "unable to resolve reference '%s'",
929 * Reference is missing, but that's OK. We
930 * know that there is not a conflict with
931 * another loose reference because
932 * (supposing that we are trying to lock
933 * reference "refs/foo/bar"):
935 * - We were successfully able to create
936 * the lockfile refs/foo/bar.lock, so we
937 * know there cannot be a loose reference
940 * - We got ENOENT and not EISDIR, so we
941 * know that there cannot be a loose
942 * reference named "refs/foo/bar/baz".
945 } else if (errno == EISDIR) {
947 * There is a directory in the way. It might have
948 * contained references that have been deleted. If
949 * we don't require that the reference already
950 * exists, try to remove the directory so that it
951 * doesn't cause trouble when we want to rename the
952 * lockfile into place later.
955 /* Garden variety missing reference. */
956 strbuf_addf(err, "unable to resolve reference '%s'",
959 } else if (remove_dir_recursively(&ref_file,
960 REMOVE_DIR_EMPTY_ONLY)) {
961 if (refs_verify_refname_available(
962 &refs->base, refname,
963 extras, skip, err)) {
965 * The error message set by
966 * verify_refname_available() is OK.
968 ret = TRANSACTION_NAME_CONFLICT;
972 * We can't delete the directory,
973 * but we also don't know of any
974 * references that it should
977 strbuf_addf(err, "there is a non-empty directory '%s' "
978 "blocking reference '%s'",
979 ref_file.buf, refname);
983 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
984 strbuf_addf(err, "unable to resolve reference '%s': "
985 "reference broken", refname);
988 strbuf_addf(err, "unable to resolve reference '%s': %s",
989 refname, strerror(errno));
994 * If the ref did not exist and we are creating it,
995 * make sure there is no existing ref that conflicts
998 if (refs_verify_refname_available(
999 &refs->base, refname,
1012 strbuf_release(&ref_file);
1016 static int files_peel_ref(struct ref_store *ref_store,
1017 const char *refname, unsigned char *sha1)
1019 struct files_ref_store *refs =
1020 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
1023 unsigned char base[20];
1025 if (current_ref_iter && current_ref_iter->refname == refname) {
1026 struct object_id peeled;
1028 if (ref_iterator_peel(current_ref_iter, &peeled))
1030 hashcpy(sha1, peeled.hash);
1034 if (refs_read_ref_full(ref_store, refname,
1035 RESOLVE_REF_READING, base, &flag))
1039 * If the reference is packed, read its ref_entry from the
1040 * cache in the hope that we already know its peeled value.
1041 * We only try this optimization on packed references because
1042 * (a) forcing the filling of the loose reference cache could
1043 * be expensive and (b) loose references anyway usually do not
1044 * have REF_KNOWS_PEELED.
1046 if (flag & REF_ISPACKED) {
1047 struct ref_entry *r =
1048 get_packed_ref(refs->packed_ref_store, refname);
1051 if (peel_entry(r, 0))
1053 hashcpy(sha1, r->u.value.peeled.hash);
1058 return peel_object(base, sha1);
1061 struct files_ref_iterator {
1062 struct ref_iterator base;
1064 struct packed_ref_cache *packed_ref_cache;
1065 struct ref_iterator *iter0;
1069 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1071 struct files_ref_iterator *iter =
1072 (struct files_ref_iterator *)ref_iterator;
1075 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1076 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1077 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1080 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1081 !ref_resolves_to_object(iter->iter0->refname,
1083 iter->iter0->flags))
1086 iter->base.refname = iter->iter0->refname;
1087 iter->base.oid = iter->iter0->oid;
1088 iter->base.flags = iter->iter0->flags;
1093 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1099 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1100 struct object_id *peeled)
1102 struct files_ref_iterator *iter =
1103 (struct files_ref_iterator *)ref_iterator;
1105 return ref_iterator_peel(iter->iter0, peeled);
1108 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1110 struct files_ref_iterator *iter =
1111 (struct files_ref_iterator *)ref_iterator;
1115 ok = ref_iterator_abort(iter->iter0);
1117 release_packed_ref_cache(iter->packed_ref_cache);
1118 base_ref_iterator_free(ref_iterator);
1122 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1123 files_ref_iterator_advance,
1124 files_ref_iterator_peel,
1125 files_ref_iterator_abort
1128 static struct ref_iterator *files_ref_iterator_begin(
1129 struct ref_store *ref_store,
1130 const char *prefix, unsigned int flags)
1132 struct files_ref_store *refs;
1133 struct ref_iterator *loose_iter, *packed_iter;
1134 struct files_ref_iterator *iter;
1135 struct ref_iterator *ref_iterator;
1136 unsigned int required_flags = REF_STORE_READ;
1138 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1139 required_flags |= REF_STORE_ODB;
1141 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1143 iter = xcalloc(1, sizeof(*iter));
1144 ref_iterator = &iter->base;
1145 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1148 * We must make sure that all loose refs are read before
1149 * accessing the packed-refs file; this avoids a race
1150 * condition if loose refs are migrated to the packed-refs
1151 * file by a simultaneous process, but our in-memory view is
1152 * from before the migration. We ensure this as follows:
1153 * First, we call start the loose refs iteration with its
1154 * `prime_ref` argument set to true. This causes the loose
1155 * references in the subtree to be pre-read into the cache.
1156 * (If they've already been read, that's OK; we only need to
1157 * guarantee that they're read before the packed refs, not
1158 * *how much* before.) After that, we call
1159 * get_packed_ref_cache(), which internally checks whether the
1160 * packed-ref cache is up to date with what is on disk, and
1161 * re-reads it if not.
1164 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1167 iter->packed_ref_cache = get_packed_ref_cache(refs->packed_ref_store);
1168 acquire_packed_ref_cache(iter->packed_ref_cache);
1169 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1172 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1173 iter->flags = flags;
1175 return ref_iterator;
1179 * Verify that the reference locked by lock has the value old_sha1.
1180 * Fail if the reference doesn't exist and mustexist is set. Return 0
1181 * on success. On error, write an error message to err, set errno, and
1182 * return a negative value.
1184 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1185 const unsigned char *old_sha1, int mustexist,
1190 if (refs_read_ref_full(ref_store, lock->ref_name,
1191 mustexist ? RESOLVE_REF_READING : 0,
1192 lock->old_oid.hash, NULL)) {
1194 int save_errno = errno;
1195 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1199 oidclr(&lock->old_oid);
1203 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1204 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1206 oid_to_hex(&lock->old_oid),
1207 sha1_to_hex(old_sha1));
1214 static int remove_empty_directories(struct strbuf *path)
1217 * we want to create a file but there is a directory there;
1218 * if that is an empty directory (or a directory that contains
1219 * only empty directories), remove them.
1221 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1224 static int create_reflock(const char *path, void *cb)
1226 struct lock_file *lk = cb;
1228 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1232 * Locks a ref returning the lock on success and NULL on failure.
1233 * On failure errno is set to something meaningful.
1235 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1236 const char *refname,
1237 const unsigned char *old_sha1,
1238 const struct string_list *extras,
1239 const struct string_list *skip,
1240 unsigned int flags, int *type,
1243 struct strbuf ref_file = STRBUF_INIT;
1244 struct ref_lock *lock;
1246 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1247 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1250 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1253 lock = xcalloc(1, sizeof(struct ref_lock));
1256 resolve_flags |= RESOLVE_REF_READING;
1257 if (flags & REF_DELETING)
1258 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1260 files_ref_path(refs, &ref_file, refname);
1261 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1262 refname, resolve_flags,
1263 lock->old_oid.hash, type);
1264 if (!resolved && errno == EISDIR) {
1266 * we are trying to lock foo but we used to
1267 * have foo/bar which now does not exist;
1268 * it is normal for the empty directory 'foo'
1271 if (remove_empty_directories(&ref_file)) {
1273 if (!refs_verify_refname_available(
1275 refname, extras, skip, err))
1276 strbuf_addf(err, "there are still refs under '%s'",
1280 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1281 refname, resolve_flags,
1282 lock->old_oid.hash, type);
1286 if (last_errno != ENOTDIR ||
1287 !refs_verify_refname_available(&refs->base, refname,
1289 strbuf_addf(err, "unable to resolve reference '%s': %s",
1290 refname, strerror(last_errno));
1296 * If the ref did not exist and we are creating it, make sure
1297 * there is no existing packed ref whose name begins with our
1298 * refname, nor a packed ref whose name is a proper prefix of
1301 if (is_null_oid(&lock->old_oid) &&
1302 refs_verify_refname_available(&refs->base, refname,
1303 extras, skip, err)) {
1304 last_errno = ENOTDIR;
1308 lock->lk = xcalloc(1, sizeof(struct lock_file));
1310 lock->ref_name = xstrdup(refname);
1312 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1314 unable_to_lock_message(ref_file.buf, errno, err);
1318 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1329 strbuf_release(&ref_file);
1335 * Write an entry to the packed-refs file for the specified refname.
1336 * If peeled is non-NULL, write it as the entry's peeled value.
1338 static void write_packed_entry(FILE *fh, const char *refname,
1339 const unsigned char *sha1,
1340 const unsigned char *peeled)
1342 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1344 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1348 * Lock the packed-refs file for writing. Flags is passed to
1349 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1350 * errno appropriately and return a nonzero value.
1352 static int lock_packed_refs(struct packed_ref_store *refs, int flags)
1354 static int timeout_configured = 0;
1355 static int timeout_value = 1000;
1356 struct packed_ref_cache *packed_ref_cache;
1358 packed_assert_main_repository(refs, "lock_packed_refs");
1360 if (!timeout_configured) {
1361 git_config_get_int("core.packedrefstimeout", &timeout_value);
1362 timeout_configured = 1;
1365 if (hold_lock_file_for_update_timeout(
1368 flags, timeout_value) < 0)
1372 * Now that we hold the `packed-refs` lock, make sure that our
1373 * cache matches the current version of the file. Normally
1374 * `get_packed_ref_cache()` does that for us, but that
1375 * function assumes that when the file is locked, any existing
1376 * cache is still valid. We've just locked the file, but it
1377 * might have changed the moment *before* we locked it.
1379 validate_packed_ref_cache(refs);
1381 packed_ref_cache = get_packed_ref_cache(refs);
1382 /* Increment the reference count to prevent it from being freed: */
1383 acquire_packed_ref_cache(packed_ref_cache);
1388 * Write the current version of the packed refs cache from memory to
1389 * disk. The packed-refs file must already be locked for writing (see
1390 * lock_packed_refs()). Return zero on success. On errors, set errno
1391 * and return a nonzero value
1393 static int commit_packed_refs(struct packed_ref_store *refs)
1395 struct packed_ref_cache *packed_ref_cache =
1396 get_packed_ref_cache(refs);
1400 struct ref_iterator *iter;
1402 packed_assert_main_repository(refs, "commit_packed_refs");
1404 if (!is_lock_file_locked(&refs->lock))
1405 die("BUG: packed-refs not locked");
1407 out = fdopen_lock_file(&refs->lock, "w");
1409 die_errno("unable to fdopen packed-refs descriptor");
1411 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1413 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1414 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1415 struct object_id peeled;
1416 int peel_error = ref_iterator_peel(iter, &peeled);
1418 write_packed_entry(out, iter->refname, iter->oid->hash,
1419 peel_error ? NULL : peeled.hash);
1422 if (ok != ITER_DONE)
1423 die("error while iterating over references");
1425 if (commit_lock_file(&refs->lock)) {
1429 release_packed_ref_cache(packed_ref_cache);
1435 * Rollback the lockfile for the packed-refs file, and discard the
1436 * in-memory packed reference cache. (The packed-refs file will be
1437 * read anew if it is needed again after this function is called.)
1439 static void rollback_packed_refs(struct packed_ref_store *refs)
1441 struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
1443 packed_assert_main_repository(refs, "rollback_packed_refs");
1445 if (!is_lock_file_locked(&refs->lock))
1446 die("BUG: packed-refs not locked");
1447 rollback_lock_file(&refs->lock);
1448 release_packed_ref_cache(packed_ref_cache);
1449 clear_packed_ref_cache(refs);
1452 struct ref_to_prune {
1453 struct ref_to_prune *next;
1454 unsigned char sha1[20];
1455 char name[FLEX_ARRAY];
1459 REMOVE_EMPTY_PARENTS_REF = 0x01,
1460 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1464 * Remove empty parent directories associated with the specified
1465 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1466 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1467 * REMOVE_EMPTY_PARENTS_REFLOG.
1469 static void try_remove_empty_parents(struct files_ref_store *refs,
1470 const char *refname,
1473 struct strbuf buf = STRBUF_INIT;
1474 struct strbuf sb = STRBUF_INIT;
1478 strbuf_addstr(&buf, refname);
1480 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1481 while (*p && *p != '/')
1483 /* tolerate duplicate slashes; see check_refname_format() */
1487 q = buf.buf + buf.len;
1488 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1489 while (q > p && *q != '/')
1491 while (q > p && *(q-1) == '/')
1495 strbuf_setlen(&buf, q - buf.buf);
1498 files_ref_path(refs, &sb, buf.buf);
1499 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1500 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1503 files_reflog_path(refs, &sb, buf.buf);
1504 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1505 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1507 strbuf_release(&buf);
1508 strbuf_release(&sb);
1511 /* make sure nobody touched the ref, and unlink */
1512 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1514 struct ref_transaction *transaction;
1515 struct strbuf err = STRBUF_INIT;
1517 if (check_refname_format(r->name, 0))
1520 transaction = ref_store_transaction_begin(&refs->base, &err);
1522 ref_transaction_delete(transaction, r->name, r->sha1,
1523 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1524 ref_transaction_commit(transaction, &err)) {
1525 ref_transaction_free(transaction);
1526 error("%s", err.buf);
1527 strbuf_release(&err);
1530 ref_transaction_free(transaction);
1531 strbuf_release(&err);
1534 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1543 * Return true if the specified reference should be packed.
1545 static int should_pack_ref(const char *refname,
1546 const struct object_id *oid, unsigned int ref_flags,
1547 unsigned int pack_flags)
1549 /* Do not pack per-worktree refs: */
1550 if (ref_type(refname) != REF_TYPE_NORMAL)
1553 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1554 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1557 /* Do not pack symbolic refs: */
1558 if (ref_flags & REF_ISSYMREF)
1561 /* Do not pack broken refs: */
1562 if (!ref_resolves_to_object(refname, oid, ref_flags))
1568 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1570 struct files_ref_store *refs =
1571 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1573 struct ref_iterator *iter;
1575 struct ref_to_prune *refs_to_prune = NULL;
1577 lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);
1579 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1580 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1582 * If the loose reference can be packed, add an entry
1583 * in the packed ref cache. If the reference should be
1584 * pruned, also add it to refs_to_prune.
1586 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1591 * Create an entry in the packed-refs cache equivalent
1592 * to the one from the loose ref cache, except that
1593 * we don't copy the peeled status, because we want it
1596 add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);
1598 /* Schedule the loose reference for pruning if requested. */
1599 if ((flags & PACK_REFS_PRUNE)) {
1600 struct ref_to_prune *n;
1601 FLEX_ALLOC_STR(n, name, iter->refname);
1602 hashcpy(n->sha1, iter->oid->hash);
1603 n->next = refs_to_prune;
1607 if (ok != ITER_DONE)
1608 die("error while iterating over references");
1610 if (commit_packed_refs(refs->packed_ref_store))
1611 die_errno("unable to overwrite old ref-pack file");
1613 prune_refs(refs, refs_to_prune);
1618 * Rewrite the packed-refs file, omitting any refs listed in
1619 * 'refnames'. On error, leave packed-refs unchanged, write an error
1620 * message to 'err', and return a nonzero value.
1622 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1624 static int repack_without_refs(struct packed_ref_store *refs,
1625 struct string_list *refnames, struct strbuf *err)
1627 struct ref_dir *packed;
1628 struct string_list_item *refname;
1629 int ret, needs_repacking = 0, removed = 0;
1631 packed_assert_main_repository(refs, "repack_without_refs");
1634 /* Look for a packed ref */
1635 for_each_string_list_item(refname, refnames) {
1636 if (get_packed_ref(refs, refname->string)) {
1637 needs_repacking = 1;
1642 /* Avoid locking if we have nothing to do */
1643 if (!needs_repacking)
1644 return 0; /* no refname exists in packed refs */
1646 if (lock_packed_refs(refs, 0)) {
1647 unable_to_lock_message(refs->path, errno, err);
1650 packed = get_packed_refs(refs);
1652 /* Remove refnames from the cache */
1653 for_each_string_list_item(refname, refnames)
1654 if (remove_entry_from_dir(packed, refname->string) != -1)
1658 * All packed entries disappeared while we were
1659 * acquiring the lock.
1661 rollback_packed_refs(refs);
1665 /* Write what remains */
1666 ret = commit_packed_refs(refs);
1668 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1673 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1674 struct string_list *refnames, unsigned int flags)
1676 struct files_ref_store *refs =
1677 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1678 struct strbuf err = STRBUF_INIT;
1684 result = repack_without_refs(refs->packed_ref_store, refnames, &err);
1687 * If we failed to rewrite the packed-refs file, then
1688 * it is unsafe to try to remove loose refs, because
1689 * doing so might expose an obsolete packed value for
1690 * a reference that might even point at an object that
1691 * has been garbage collected.
1693 if (refnames->nr == 1)
1694 error(_("could not delete reference %s: %s"),
1695 refnames->items[0].string, err.buf);
1697 error(_("could not delete references: %s"), err.buf);
1702 for (i = 0; i < refnames->nr; i++) {
1703 const char *refname = refnames->items[i].string;
1705 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1706 result |= error(_("could not remove reference %s"), refname);
1710 strbuf_release(&err);
1715 * People using contrib's git-new-workdir have .git/logs/refs ->
1716 * /some/other/path/.git/logs/refs, and that may live on another device.
1718 * IOW, to avoid cross device rename errors, the temporary renamed log must
1719 * live into logs/refs.
1721 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1724 const char *tmp_renamed_log;
1728 static int rename_tmp_log_callback(const char *path, void *cb_data)
1730 struct rename_cb *cb = cb_data;
1732 if (rename(cb->tmp_renamed_log, path)) {
1734 * rename(a, b) when b is an existing directory ought
1735 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1736 * Sheesh. Record the true errno for error reporting,
1737 * but report EISDIR to raceproof_create_file() so
1738 * that it knows to retry.
1740 cb->true_errno = errno;
1741 if (errno == ENOTDIR)
1749 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1751 struct strbuf path = STRBUF_INIT;
1752 struct strbuf tmp = STRBUF_INIT;
1753 struct rename_cb cb;
1756 files_reflog_path(refs, &path, newrefname);
1757 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1758 cb.tmp_renamed_log = tmp.buf;
1759 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1761 if (errno == EISDIR)
1762 error("directory not empty: %s", path.buf);
1764 error("unable to move logfile %s to %s: %s",
1766 strerror(cb.true_errno));
1769 strbuf_release(&path);
1770 strbuf_release(&tmp);
1774 static int write_ref_to_lockfile(struct ref_lock *lock,
1775 const struct object_id *oid, struct strbuf *err);
1776 static int commit_ref_update(struct files_ref_store *refs,
1777 struct ref_lock *lock,
1778 const struct object_id *oid, const char *logmsg,
1779 struct strbuf *err);
1781 static int files_rename_ref(struct ref_store *ref_store,
1782 const char *oldrefname, const char *newrefname,
1785 struct files_ref_store *refs =
1786 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1787 struct object_id oid, orig_oid;
1788 int flag = 0, logmoved = 0;
1789 struct ref_lock *lock;
1790 struct stat loginfo;
1791 struct strbuf sb_oldref = STRBUF_INIT;
1792 struct strbuf sb_newref = STRBUF_INIT;
1793 struct strbuf tmp_renamed_log = STRBUF_INIT;
1795 struct strbuf err = STRBUF_INIT;
1797 files_reflog_path(refs, &sb_oldref, oldrefname);
1798 files_reflog_path(refs, &sb_newref, newrefname);
1799 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1801 log = !lstat(sb_oldref.buf, &loginfo);
1802 if (log && S_ISLNK(loginfo.st_mode)) {
1803 ret = error("reflog for %s is a symlink", oldrefname);
1807 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1808 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1809 orig_oid.hash, &flag)) {
1810 ret = error("refname %s not found", oldrefname);
1814 if (flag & REF_ISSYMREF) {
1815 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1819 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1824 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1825 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1826 oldrefname, strerror(errno));
1830 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1831 orig_oid.hash, REF_NODEREF)) {
1832 error("unable to delete old %s", oldrefname);
1837 * Since we are doing a shallow lookup, oid is not the
1838 * correct value to pass to delete_ref as old_oid. But that
1839 * doesn't matter, because an old_oid check wouldn't add to
1840 * the safety anyway; we want to delete the reference whatever
1841 * its current value.
1843 if (!refs_read_ref_full(&refs->base, newrefname,
1844 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1846 refs_delete_ref(&refs->base, NULL, newrefname,
1847 NULL, REF_NODEREF)) {
1848 if (errno == EISDIR) {
1849 struct strbuf path = STRBUF_INIT;
1852 files_ref_path(refs, &path, newrefname);
1853 result = remove_empty_directories(&path);
1854 strbuf_release(&path);
1857 error("Directory not empty: %s", newrefname);
1861 error("unable to delete existing %s", newrefname);
1866 if (log && rename_tmp_log(refs, newrefname))
1871 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1872 REF_NODEREF, NULL, &err);
1874 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1875 strbuf_release(&err);
1878 oidcpy(&lock->old_oid, &orig_oid);
1880 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1881 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1882 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1883 strbuf_release(&err);
1891 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1892 REF_NODEREF, NULL, &err);
1894 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1895 strbuf_release(&err);
1899 flag = log_all_ref_updates;
1900 log_all_ref_updates = LOG_REFS_NONE;
1901 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1902 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1903 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1904 strbuf_release(&err);
1906 log_all_ref_updates = flag;
1909 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1910 error("unable to restore logfile %s from %s: %s",
1911 oldrefname, newrefname, strerror(errno));
1912 if (!logmoved && log &&
1913 rename(tmp_renamed_log.buf, sb_oldref.buf))
1914 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1915 oldrefname, strerror(errno));
1918 strbuf_release(&sb_newref);
1919 strbuf_release(&sb_oldref);
1920 strbuf_release(&tmp_renamed_log);
1925 static int close_ref(struct ref_lock *lock)
1927 if (close_lock_file(lock->lk))
1932 static int commit_ref(struct ref_lock *lock)
1934 char *path = get_locked_file_path(lock->lk);
1937 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1939 * There is a directory at the path we want to rename
1940 * the lockfile to. Hopefully it is empty; try to
1943 size_t len = strlen(path);
1944 struct strbuf sb_path = STRBUF_INIT;
1946 strbuf_attach(&sb_path, path, len, len);
1949 * If this fails, commit_lock_file() will also fail
1950 * and will report the problem.
1952 remove_empty_directories(&sb_path);
1953 strbuf_release(&sb_path);
1958 if (commit_lock_file(lock->lk))
1963 static int open_or_create_logfile(const char *path, void *cb)
1967 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1968 return (*fd < 0) ? -1 : 0;
1972 * Create a reflog for a ref. If force_create = 0, only create the
1973 * reflog for certain refs (those for which should_autocreate_reflog
1974 * returns non-zero). Otherwise, create it regardless of the reference
1975 * name. If the logfile already existed or was created, return 0 and
1976 * set *logfd to the file descriptor opened for appending to the file.
1977 * If no logfile exists and we decided not to create one, return 0 and
1978 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1981 static int log_ref_setup(struct files_ref_store *refs,
1982 const char *refname, int force_create,
1983 int *logfd, struct strbuf *err)
1985 struct strbuf logfile_sb = STRBUF_INIT;
1988 files_reflog_path(refs, &logfile_sb, refname);
1989 logfile = strbuf_detach(&logfile_sb, NULL);
1991 if (force_create || should_autocreate_reflog(refname)) {
1992 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1993 if (errno == ENOENT)
1994 strbuf_addf(err, "unable to create directory for '%s': "
1995 "%s", logfile, strerror(errno));
1996 else if (errno == EISDIR)
1997 strbuf_addf(err, "there are still logs under '%s'",
2000 strbuf_addf(err, "unable to append to '%s': %s",
2001 logfile, strerror(errno));
2006 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
2008 if (errno == ENOENT || errno == EISDIR) {
2010 * The logfile doesn't already exist,
2011 * but that is not an error; it only
2012 * means that we won't write log
2017 strbuf_addf(err, "unable to append to '%s': %s",
2018 logfile, strerror(errno));
2025 adjust_shared_perm(logfile);
2035 static int files_create_reflog(struct ref_store *ref_store,
2036 const char *refname, int force_create,
2039 struct files_ref_store *refs =
2040 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2043 if (log_ref_setup(refs, refname, force_create, &fd, err))
2052 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2053 const struct object_id *new_oid,
2054 const char *committer, const char *msg)
2056 int msglen, written;
2057 unsigned maxlen, len;
2060 msglen = msg ? strlen(msg) : 0;
2061 maxlen = strlen(committer) + msglen + 100;
2062 logrec = xmalloc(maxlen);
2063 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2064 oid_to_hex(old_oid),
2065 oid_to_hex(new_oid),
2068 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2070 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2078 static int files_log_ref_write(struct files_ref_store *refs,
2079 const char *refname, const struct object_id *old_oid,
2080 const struct object_id *new_oid, const char *msg,
2081 int flags, struct strbuf *err)
2085 if (log_all_ref_updates == LOG_REFS_UNSET)
2086 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2088 result = log_ref_setup(refs, refname,
2089 flags & REF_FORCE_CREATE_REFLOG,
2097 result = log_ref_write_fd(logfd, old_oid, new_oid,
2098 git_committer_info(0), msg);
2100 struct strbuf sb = STRBUF_INIT;
2101 int save_errno = errno;
2103 files_reflog_path(refs, &sb, refname);
2104 strbuf_addf(err, "unable to append to '%s': %s",
2105 sb.buf, strerror(save_errno));
2106 strbuf_release(&sb);
2111 struct strbuf sb = STRBUF_INIT;
2112 int save_errno = errno;
2114 files_reflog_path(refs, &sb, refname);
2115 strbuf_addf(err, "unable to append to '%s': %s",
2116 sb.buf, strerror(save_errno));
2117 strbuf_release(&sb);
2124 * Write sha1 into the open lockfile, then close the lockfile. On
2125 * errors, rollback the lockfile, fill in *err and
2128 static int write_ref_to_lockfile(struct ref_lock *lock,
2129 const struct object_id *oid, struct strbuf *err)
2131 static char term = '\n';
2135 o = parse_object(oid);
2138 "trying to write ref '%s' with nonexistent object %s",
2139 lock->ref_name, oid_to_hex(oid));
2143 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2145 "trying to write non-commit object %s to branch '%s'",
2146 oid_to_hex(oid), lock->ref_name);
2150 fd = get_lock_file_fd(lock->lk);
2151 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2152 write_in_full(fd, &term, 1) != 1 ||
2153 close_ref(lock) < 0) {
2155 "couldn't write '%s'", get_lock_file_path(lock->lk));
2163 * Commit a change to a loose reference that has already been written
2164 * to the loose reference lockfile. Also update the reflogs if
2165 * necessary, using the specified lockmsg (which can be NULL).
2167 static int commit_ref_update(struct files_ref_store *refs,
2168 struct ref_lock *lock,
2169 const struct object_id *oid, const char *logmsg,
2172 files_assert_main_repository(refs, "commit_ref_update");
2174 clear_loose_ref_cache(refs);
2175 if (files_log_ref_write(refs, lock->ref_name,
2176 &lock->old_oid, oid,
2178 char *old_msg = strbuf_detach(err, NULL);
2179 strbuf_addf(err, "cannot update the ref '%s': %s",
2180 lock->ref_name, old_msg);
2186 if (strcmp(lock->ref_name, "HEAD") != 0) {
2188 * Special hack: If a branch is updated directly and HEAD
2189 * points to it (may happen on the remote side of a push
2190 * for example) then logically the HEAD reflog should be
2192 * A generic solution implies reverse symref information,
2193 * but finding all symrefs pointing to the given branch
2194 * would be rather costly for this rare event (the direct
2195 * update of a branch) to be worth it. So let's cheat and
2196 * check with HEAD only which should cover 99% of all usage
2197 * scenarios (even 100% of the default ones).
2199 struct object_id head_oid;
2201 const char *head_ref;
2203 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2204 RESOLVE_REF_READING,
2205 head_oid.hash, &head_flag);
2206 if (head_ref && (head_flag & REF_ISSYMREF) &&
2207 !strcmp(head_ref, lock->ref_name)) {
2208 struct strbuf log_err = STRBUF_INIT;
2209 if (files_log_ref_write(refs, "HEAD",
2210 &lock->old_oid, oid,
2211 logmsg, 0, &log_err)) {
2212 error("%s", log_err.buf);
2213 strbuf_release(&log_err);
2218 if (commit_ref(lock)) {
2219 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2228 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2231 #ifndef NO_SYMLINK_HEAD
2232 char *ref_path = get_locked_file_path(lock->lk);
2234 ret = symlink(target, ref_path);
2238 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2243 static void update_symref_reflog(struct files_ref_store *refs,
2244 struct ref_lock *lock, const char *refname,
2245 const char *target, const char *logmsg)
2247 struct strbuf err = STRBUF_INIT;
2248 struct object_id new_oid;
2250 !refs_read_ref_full(&refs->base, target,
2251 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2252 files_log_ref_write(refs, refname, &lock->old_oid,
2253 &new_oid, logmsg, 0, &err)) {
2254 error("%s", err.buf);
2255 strbuf_release(&err);
2259 static int create_symref_locked(struct files_ref_store *refs,
2260 struct ref_lock *lock, const char *refname,
2261 const char *target, const char *logmsg)
2263 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2264 update_symref_reflog(refs, lock, refname, target, logmsg);
2268 if (!fdopen_lock_file(lock->lk, "w"))
2269 return error("unable to fdopen %s: %s",
2270 lock->lk->tempfile.filename.buf, strerror(errno));
2272 update_symref_reflog(refs, lock, refname, target, logmsg);
2274 /* no error check; commit_ref will check ferror */
2275 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2276 if (commit_ref(lock) < 0)
2277 return error("unable to write symref for %s: %s", refname,
2282 static int files_create_symref(struct ref_store *ref_store,
2283 const char *refname, const char *target,
2286 struct files_ref_store *refs =
2287 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2288 struct strbuf err = STRBUF_INIT;
2289 struct ref_lock *lock;
2292 lock = lock_ref_sha1_basic(refs, refname, NULL,
2293 NULL, NULL, REF_NODEREF, NULL,
2296 error("%s", err.buf);
2297 strbuf_release(&err);
2301 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2306 static int files_reflog_exists(struct ref_store *ref_store,
2307 const char *refname)
2309 struct files_ref_store *refs =
2310 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2311 struct strbuf sb = STRBUF_INIT;
2315 files_reflog_path(refs, &sb, refname);
2316 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2317 strbuf_release(&sb);
2321 static int files_delete_reflog(struct ref_store *ref_store,
2322 const char *refname)
2324 struct files_ref_store *refs =
2325 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2326 struct strbuf sb = STRBUF_INIT;
2329 files_reflog_path(refs, &sb, refname);
2330 ret = remove_path(sb.buf);
2331 strbuf_release(&sb);
2335 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2337 struct object_id ooid, noid;
2338 char *email_end, *message;
2339 timestamp_t timestamp;
2341 const char *p = sb->buf;
2343 /* old SP new SP name <email> SP time TAB msg LF */
2344 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2345 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2346 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2347 !(email_end = strchr(p, '>')) ||
2348 email_end[1] != ' ' ||
2349 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2350 !message || message[0] != ' ' ||
2351 (message[1] != '+' && message[1] != '-') ||
2352 !isdigit(message[2]) || !isdigit(message[3]) ||
2353 !isdigit(message[4]) || !isdigit(message[5]))
2354 return 0; /* corrupt? */
2355 email_end[1] = '\0';
2356 tz = strtol(message + 1, NULL, 10);
2357 if (message[6] != '\t')
2361 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2364 static char *find_beginning_of_line(char *bob, char *scan)
2366 while (bob < scan && *(--scan) != '\n')
2367 ; /* keep scanning backwards */
2369 * Return either beginning of the buffer, or LF at the end of
2370 * the previous line.
2375 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2376 const char *refname,
2377 each_reflog_ent_fn fn,
2380 struct files_ref_store *refs =
2381 files_downcast(ref_store, REF_STORE_READ,
2382 "for_each_reflog_ent_reverse");
2383 struct strbuf sb = STRBUF_INIT;
2386 int ret = 0, at_tail = 1;
2388 files_reflog_path(refs, &sb, refname);
2389 logfp = fopen(sb.buf, "r");
2390 strbuf_release(&sb);
2394 /* Jump to the end */
2395 if (fseek(logfp, 0, SEEK_END) < 0)
2396 ret = error("cannot seek back reflog for %s: %s",
2397 refname, strerror(errno));
2399 while (!ret && 0 < pos) {
2405 /* Fill next block from the end */
2406 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2407 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2408 ret = error("cannot seek back reflog for %s: %s",
2409 refname, strerror(errno));
2412 nread = fread(buf, cnt, 1, logfp);
2414 ret = error("cannot read %d bytes from reflog for %s: %s",
2415 cnt, refname, strerror(errno));
2420 scanp = endp = buf + cnt;
2421 if (at_tail && scanp[-1] == '\n')
2422 /* Looking at the final LF at the end of the file */
2426 while (buf < scanp) {
2428 * terminating LF of the previous line, or the beginning
2433 bp = find_beginning_of_line(buf, scanp);
2437 * The newline is the end of the previous line,
2438 * so we know we have complete line starting
2439 * at (bp + 1). Prefix it onto any prior data
2440 * we collected for the line and process it.
2442 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2445 ret = show_one_reflog_ent(&sb, fn, cb_data);
2451 * We are at the start of the buffer, and the
2452 * start of the file; there is no previous
2453 * line, and we have everything for this one.
2454 * Process it, and we can end the loop.
2456 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2457 ret = show_one_reflog_ent(&sb, fn, cb_data);
2464 * We are at the start of the buffer, and there
2465 * is more file to read backwards. Which means
2466 * we are in the middle of a line. Note that we
2467 * may get here even if *bp was a newline; that
2468 * just means we are at the exact end of the
2469 * previous line, rather than some spot in the
2472 * Save away what we have to be combined with
2473 * the data from the next read.
2475 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2482 die("BUG: reverse reflog parser had leftover data");
2485 strbuf_release(&sb);
2489 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2490 const char *refname,
2491 each_reflog_ent_fn fn, void *cb_data)
2493 struct files_ref_store *refs =
2494 files_downcast(ref_store, REF_STORE_READ,
2495 "for_each_reflog_ent");
2497 struct strbuf sb = STRBUF_INIT;
2500 files_reflog_path(refs, &sb, refname);
2501 logfp = fopen(sb.buf, "r");
2502 strbuf_release(&sb);
2506 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2507 ret = show_one_reflog_ent(&sb, fn, cb_data);
2509 strbuf_release(&sb);
2513 struct files_reflog_iterator {
2514 struct ref_iterator base;
2516 struct ref_store *ref_store;
2517 struct dir_iterator *dir_iterator;
2518 struct object_id oid;
2521 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2523 struct files_reflog_iterator *iter =
2524 (struct files_reflog_iterator *)ref_iterator;
2525 struct dir_iterator *diter = iter->dir_iterator;
2528 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2531 if (!S_ISREG(diter->st.st_mode))
2533 if (diter->basename[0] == '.')
2535 if (ends_with(diter->basename, ".lock"))
2538 if (refs_read_ref_full(iter->ref_store,
2539 diter->relative_path, 0,
2540 iter->oid.hash, &flags)) {
2541 error("bad ref for %s", diter->path.buf);
2545 iter->base.refname = diter->relative_path;
2546 iter->base.oid = &iter->oid;
2547 iter->base.flags = flags;
2551 iter->dir_iterator = NULL;
2552 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2557 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2558 struct object_id *peeled)
2560 die("BUG: ref_iterator_peel() called for reflog_iterator");
2563 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2565 struct files_reflog_iterator *iter =
2566 (struct files_reflog_iterator *)ref_iterator;
2569 if (iter->dir_iterator)
2570 ok = dir_iterator_abort(iter->dir_iterator);
2572 base_ref_iterator_free(ref_iterator);
2576 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2577 files_reflog_iterator_advance,
2578 files_reflog_iterator_peel,
2579 files_reflog_iterator_abort
2582 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2584 struct files_ref_store *refs =
2585 files_downcast(ref_store, REF_STORE_READ,
2586 "reflog_iterator_begin");
2587 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2588 struct ref_iterator *ref_iterator = &iter->base;
2589 struct strbuf sb = STRBUF_INIT;
2591 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2592 files_reflog_path(refs, &sb, NULL);
2593 iter->dir_iterator = dir_iterator_begin(sb.buf);
2594 iter->ref_store = ref_store;
2595 strbuf_release(&sb);
2596 return ref_iterator;
2600 * If update is a direct update of head_ref (the reference pointed to
2601 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2603 static int split_head_update(struct ref_update *update,
2604 struct ref_transaction *transaction,
2605 const char *head_ref,
2606 struct string_list *affected_refnames,
2609 struct string_list_item *item;
2610 struct ref_update *new_update;
2612 if ((update->flags & REF_LOG_ONLY) ||
2613 (update->flags & REF_ISPRUNING) ||
2614 (update->flags & REF_UPDATE_VIA_HEAD))
2617 if (strcmp(update->refname, head_ref))
2621 * First make sure that HEAD is not already in the
2622 * transaction. This insertion is O(N) in the transaction
2623 * size, but it happens at most once per transaction.
2625 item = string_list_insert(affected_refnames, "HEAD");
2627 /* An entry already existed */
2629 "multiple updates for 'HEAD' (including one "
2630 "via its referent '%s') are not allowed",
2632 return TRANSACTION_NAME_CONFLICT;
2635 new_update = ref_transaction_add_update(
2636 transaction, "HEAD",
2637 update->flags | REF_LOG_ONLY | REF_NODEREF,
2638 update->new_oid.hash, update->old_oid.hash,
2641 item->util = new_update;
2647 * update is for a symref that points at referent and doesn't have
2648 * REF_NODEREF set. Split it into two updates:
2649 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2650 * - A new, separate update for the referent reference
2651 * Note that the new update will itself be subject to splitting when
2652 * the iteration gets to it.
2654 static int split_symref_update(struct files_ref_store *refs,
2655 struct ref_update *update,
2656 const char *referent,
2657 struct ref_transaction *transaction,
2658 struct string_list *affected_refnames,
2661 struct string_list_item *item;
2662 struct ref_update *new_update;
2663 unsigned int new_flags;
2666 * First make sure that referent is not already in the
2667 * transaction. This insertion is O(N) in the transaction
2668 * size, but it happens at most once per symref in a
2671 item = string_list_insert(affected_refnames, referent);
2673 /* An entry already existed */
2675 "multiple updates for '%s' (including one "
2676 "via symref '%s') are not allowed",
2677 referent, update->refname);
2678 return TRANSACTION_NAME_CONFLICT;
2681 new_flags = update->flags;
2682 if (!strcmp(update->refname, "HEAD")) {
2684 * Record that the new update came via HEAD, so that
2685 * when we process it, split_head_update() doesn't try
2686 * to add another reflog update for HEAD. Note that
2687 * this bit will be propagated if the new_update
2688 * itself needs to be split.
2690 new_flags |= REF_UPDATE_VIA_HEAD;
2693 new_update = ref_transaction_add_update(
2694 transaction, referent, new_flags,
2695 update->new_oid.hash, update->old_oid.hash,
2698 new_update->parent_update = update;
2701 * Change the symbolic ref update to log only. Also, it
2702 * doesn't need to check its old SHA-1 value, as that will be
2703 * done when new_update is processed.
2705 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2706 update->flags &= ~REF_HAVE_OLD;
2708 item->util = new_update;
2714 * Return the refname under which update was originally requested.
2716 static const char *original_update_refname(struct ref_update *update)
2718 while (update->parent_update)
2719 update = update->parent_update;
2721 return update->refname;
2725 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2726 * are consistent with oid, which is the reference's current value. If
2727 * everything is OK, return 0; otherwise, write an error message to
2728 * err and return -1.
2730 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2733 if (!(update->flags & REF_HAVE_OLD) ||
2734 !oidcmp(oid, &update->old_oid))
2737 if (is_null_oid(&update->old_oid))
2738 strbuf_addf(err, "cannot lock ref '%s': "
2739 "reference already exists",
2740 original_update_refname(update));
2741 else if (is_null_oid(oid))
2742 strbuf_addf(err, "cannot lock ref '%s': "
2743 "reference is missing but expected %s",
2744 original_update_refname(update),
2745 oid_to_hex(&update->old_oid));
2747 strbuf_addf(err, "cannot lock ref '%s': "
2748 "is at %s but expected %s",
2749 original_update_refname(update),
2751 oid_to_hex(&update->old_oid));
2757 * Prepare for carrying out update:
2758 * - Lock the reference referred to by update.
2759 * - Read the reference under lock.
2760 * - Check that its old SHA-1 value (if specified) is correct, and in
2761 * any case record it in update->lock->old_oid for later use when
2762 * writing the reflog.
2763 * - If it is a symref update without REF_NODEREF, split it up into a
2764 * REF_LOG_ONLY update of the symref and add a separate update for
2765 * the referent to transaction.
2766 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2769 static int lock_ref_for_update(struct files_ref_store *refs,
2770 struct ref_update *update,
2771 struct ref_transaction *transaction,
2772 const char *head_ref,
2773 struct string_list *affected_refnames,
2776 struct strbuf referent = STRBUF_INIT;
2777 int mustexist = (update->flags & REF_HAVE_OLD) &&
2778 !is_null_oid(&update->old_oid);
2780 struct ref_lock *lock;
2782 files_assert_main_repository(refs, "lock_ref_for_update");
2784 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2785 update->flags |= REF_DELETING;
2788 ret = split_head_update(update, transaction, head_ref,
2789 affected_refnames, err);
2794 ret = lock_raw_ref(refs, update->refname, mustexist,
2795 affected_refnames, NULL,
2797 &update->type, err);
2801 reason = strbuf_detach(err, NULL);
2802 strbuf_addf(err, "cannot lock ref '%s': %s",
2803 original_update_refname(update), reason);
2808 update->backend_data = lock;
2810 if (update->type & REF_ISSYMREF) {
2811 if (update->flags & REF_NODEREF) {
2813 * We won't be reading the referent as part of
2814 * the transaction, so we have to read it here
2815 * to record and possibly check old_sha1:
2817 if (refs_read_ref_full(&refs->base,
2819 lock->old_oid.hash, NULL)) {
2820 if (update->flags & REF_HAVE_OLD) {
2821 strbuf_addf(err, "cannot lock ref '%s': "
2822 "error reading reference",
2823 original_update_refname(update));
2826 } else if (check_old_oid(update, &lock->old_oid, err)) {
2827 return TRANSACTION_GENERIC_ERROR;
2831 * Create a new update for the reference this
2832 * symref is pointing at. Also, we will record
2833 * and verify old_sha1 for this update as part
2834 * of processing the split-off update, so we
2835 * don't have to do it here.
2837 ret = split_symref_update(refs, update,
2838 referent.buf, transaction,
2839 affected_refnames, err);
2844 struct ref_update *parent_update;
2846 if (check_old_oid(update, &lock->old_oid, err))
2847 return TRANSACTION_GENERIC_ERROR;
2850 * If this update is happening indirectly because of a
2851 * symref update, record the old SHA-1 in the parent
2854 for (parent_update = update->parent_update;
2856 parent_update = parent_update->parent_update) {
2857 struct ref_lock *parent_lock = parent_update->backend_data;
2858 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2862 if ((update->flags & REF_HAVE_NEW) &&
2863 !(update->flags & REF_DELETING) &&
2864 !(update->flags & REF_LOG_ONLY)) {
2865 if (!(update->type & REF_ISSYMREF) &&
2866 !oidcmp(&lock->old_oid, &update->new_oid)) {
2868 * The reference already has the desired
2869 * value, so we don't need to write it.
2871 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2873 char *write_err = strbuf_detach(err, NULL);
2876 * The lock was freed upon failure of
2877 * write_ref_to_lockfile():
2879 update->backend_data = NULL;
2881 "cannot update ref '%s': %s",
2882 update->refname, write_err);
2884 return TRANSACTION_GENERIC_ERROR;
2886 update->flags |= REF_NEEDS_COMMIT;
2889 if (!(update->flags & REF_NEEDS_COMMIT)) {
2891 * We didn't call write_ref_to_lockfile(), so
2892 * the lockfile is still open. Close it to
2893 * free up the file descriptor:
2895 if (close_ref(lock)) {
2896 strbuf_addf(err, "couldn't close '%s.lock'",
2898 return TRANSACTION_GENERIC_ERROR;
2905 * Unlock any references in `transaction` that are still locked, and
2906 * mark the transaction closed.
2908 static void files_transaction_cleanup(struct ref_transaction *transaction)
2912 for (i = 0; i < transaction->nr; i++) {
2913 struct ref_update *update = transaction->updates[i];
2914 struct ref_lock *lock = update->backend_data;
2918 update->backend_data = NULL;
2922 transaction->state = REF_TRANSACTION_CLOSED;
2925 static int files_transaction_prepare(struct ref_store *ref_store,
2926 struct ref_transaction *transaction,
2929 struct files_ref_store *refs =
2930 files_downcast(ref_store, REF_STORE_WRITE,
2931 "ref_transaction_prepare");
2934 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2935 char *head_ref = NULL;
2937 struct object_id head_oid;
2941 if (!transaction->nr)
2945 * Fail if a refname appears more than once in the
2946 * transaction. (If we end up splitting up any updates using
2947 * split_symref_update() or split_head_update(), those
2948 * functions will check that the new updates don't have the
2949 * same refname as any existing ones.)
2951 for (i = 0; i < transaction->nr; i++) {
2952 struct ref_update *update = transaction->updates[i];
2953 struct string_list_item *item =
2954 string_list_append(&affected_refnames, update->refname);
2957 * We store a pointer to update in item->util, but at
2958 * the moment we never use the value of this field
2959 * except to check whether it is non-NULL.
2961 item->util = update;
2963 string_list_sort(&affected_refnames);
2964 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2965 ret = TRANSACTION_GENERIC_ERROR;
2970 * Special hack: If a branch is updated directly and HEAD
2971 * points to it (may happen on the remote side of a push
2972 * for example) then logically the HEAD reflog should be
2975 * A generic solution would require reverse symref lookups,
2976 * but finding all symrefs pointing to a given branch would be
2977 * rather costly for this rare event (the direct update of a
2978 * branch) to be worth it. So let's cheat and check with HEAD
2979 * only, which should cover 99% of all usage scenarios (even
2980 * 100% of the default ones).
2982 * So if HEAD is a symbolic reference, then record the name of
2983 * the reference that it points to. If we see an update of
2984 * head_ref within the transaction, then split_head_update()
2985 * arranges for the reflog of HEAD to be updated, too.
2987 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2988 RESOLVE_REF_NO_RECURSE,
2989 head_oid.hash, &head_type);
2991 if (head_ref && !(head_type & REF_ISSYMREF)) {
2997 * Acquire all locks, verify old values if provided, check
2998 * that new values are valid, and write new values to the
2999 * lockfiles, ready to be activated. Only keep one lockfile
3000 * open at a time to avoid running out of file descriptors.
3001 * Note that lock_ref_for_update() might append more updates
3002 * to the transaction.
3004 for (i = 0; i < transaction->nr; i++) {
3005 struct ref_update *update = transaction->updates[i];
3007 ret = lock_ref_for_update(refs, update, transaction,
3008 head_ref, &affected_refnames, err);
3015 string_list_clear(&affected_refnames, 0);
3018 files_transaction_cleanup(transaction);
3020 transaction->state = REF_TRANSACTION_PREPARED;
3025 static int files_transaction_finish(struct ref_store *ref_store,
3026 struct ref_transaction *transaction,
3029 struct files_ref_store *refs =
3030 files_downcast(ref_store, 0, "ref_transaction_finish");
3033 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3034 struct string_list_item *ref_to_delete;
3035 struct strbuf sb = STRBUF_INIT;
3039 if (!transaction->nr) {
3040 transaction->state = REF_TRANSACTION_CLOSED;
3044 /* Perform updates first so live commits remain referenced */
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_NEEDS_COMMIT ||
3050 update->flags & REF_LOG_ONLY) {
3051 if (files_log_ref_write(refs,
3055 update->msg, update->flags,
3057 char *old_msg = strbuf_detach(err, NULL);
3059 strbuf_addf(err, "cannot update the ref '%s': %s",
3060 lock->ref_name, old_msg);
3063 update->backend_data = NULL;
3064 ret = TRANSACTION_GENERIC_ERROR;
3068 if (update->flags & REF_NEEDS_COMMIT) {
3069 clear_loose_ref_cache(refs);
3070 if (commit_ref(lock)) {
3071 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3073 update->backend_data = NULL;
3074 ret = TRANSACTION_GENERIC_ERROR;
3079 /* Perform deletes now that updates are safely completed */
3080 for (i = 0; i < transaction->nr; i++) {
3081 struct ref_update *update = transaction->updates[i];
3082 struct ref_lock *lock = update->backend_data;
3084 if (update->flags & REF_DELETING &&
3085 !(update->flags & REF_LOG_ONLY)) {
3086 if (!(update->type & REF_ISPACKED) ||
3087 update->type & REF_ISSYMREF) {
3088 /* It is a loose reference. */
3090 files_ref_path(refs, &sb, lock->ref_name);
3091 if (unlink_or_msg(sb.buf, err)) {
3092 ret = TRANSACTION_GENERIC_ERROR;
3095 update->flags |= REF_DELETED_LOOSE;
3098 if (!(update->flags & REF_ISPRUNING))
3099 string_list_append(&refs_to_delete,
3104 if (repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {
3105 ret = TRANSACTION_GENERIC_ERROR;
3109 /* Delete the reflogs of any references that were deleted: */
3110 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3112 files_reflog_path(refs, &sb, ref_to_delete->string);
3113 if (!unlink_or_warn(sb.buf))
3114 try_remove_empty_parents(refs, ref_to_delete->string,
3115 REMOVE_EMPTY_PARENTS_REFLOG);
3118 clear_loose_ref_cache(refs);
3121 files_transaction_cleanup(transaction);
3123 for (i = 0; i < transaction->nr; i++) {
3124 struct ref_update *update = transaction->updates[i];
3126 if (update->flags & REF_DELETED_LOOSE) {
3128 * The loose reference was deleted. Delete any
3129 * empty parent directories. (Note that this
3130 * can only work because we have already
3131 * removed the lockfile.)
3133 try_remove_empty_parents(refs, update->refname,
3134 REMOVE_EMPTY_PARENTS_REF);
3138 strbuf_release(&sb);
3139 string_list_clear(&refs_to_delete, 0);
3143 static int files_transaction_abort(struct ref_store *ref_store,
3144 struct ref_transaction *transaction,
3147 files_transaction_cleanup(transaction);
3151 static int ref_present(const char *refname,
3152 const struct object_id *oid, int flags, void *cb_data)
3154 struct string_list *affected_refnames = cb_data;
3156 return string_list_has_string(affected_refnames, refname);
3159 static int files_initial_transaction_commit(struct ref_store *ref_store,
3160 struct ref_transaction *transaction,
3163 struct files_ref_store *refs =
3164 files_downcast(ref_store, REF_STORE_WRITE,
3165 "initial_ref_transaction_commit");
3168 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3172 if (transaction->state != REF_TRANSACTION_OPEN)
3173 die("BUG: commit called for transaction that is not open");
3175 /* Fail if a refname appears more than once in the transaction: */
3176 for (i = 0; i < transaction->nr; i++)
3177 string_list_append(&affected_refnames,
3178 transaction->updates[i]->refname);
3179 string_list_sort(&affected_refnames);
3180 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3181 ret = TRANSACTION_GENERIC_ERROR;
3186 * It's really undefined to call this function in an active
3187 * repository or when there are existing references: we are
3188 * only locking and changing packed-refs, so (1) any
3189 * simultaneous processes might try to change a reference at
3190 * the same time we do, and (2) any existing loose versions of
3191 * the references that we are setting would have precedence
3192 * over our values. But some remote helpers create the remote
3193 * "HEAD" and "master" branches before calling this function,
3194 * so here we really only check that none of the references
3195 * that we are creating already exists.
3197 if (refs_for_each_rawref(&refs->base, ref_present,
3198 &affected_refnames))
3199 die("BUG: initial ref transaction called with existing refs");
3201 for (i = 0; i < transaction->nr; i++) {
3202 struct ref_update *update = transaction->updates[i];
3204 if ((update->flags & REF_HAVE_OLD) &&
3205 !is_null_oid(&update->old_oid))
3206 die("BUG: initial ref transaction with old_sha1 set");
3207 if (refs_verify_refname_available(&refs->base, update->refname,
3208 &affected_refnames, NULL,
3210 ret = TRANSACTION_NAME_CONFLICT;
3215 if (lock_packed_refs(refs->packed_ref_store, 0)) {
3216 strbuf_addf(err, "unable to lock packed-refs file: %s",
3218 ret = TRANSACTION_GENERIC_ERROR;
3222 for (i = 0; i < transaction->nr; i++) {
3223 struct ref_update *update = transaction->updates[i];
3225 if ((update->flags & REF_HAVE_NEW) &&
3226 !is_null_oid(&update->new_oid))
3227 add_packed_ref(refs->packed_ref_store, update->refname,
3231 if (commit_packed_refs(refs->packed_ref_store)) {
3232 strbuf_addf(err, "unable to commit packed-refs file: %s",
3234 ret = TRANSACTION_GENERIC_ERROR;
3239 transaction->state = REF_TRANSACTION_CLOSED;
3240 string_list_clear(&affected_refnames, 0);
3244 struct expire_reflog_cb {
3246 reflog_expiry_should_prune_fn *should_prune_fn;
3249 struct object_id last_kept_oid;
3252 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3253 const char *email, timestamp_t timestamp, int tz,
3254 const char *message, void *cb_data)
3256 struct expire_reflog_cb *cb = cb_data;
3257 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3259 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3260 ooid = &cb->last_kept_oid;
3262 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3263 message, policy_cb)) {
3265 printf("would prune %s", message);
3266 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3267 printf("prune %s", message);
3270 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3271 oid_to_hex(ooid), oid_to_hex(noid),
3272 email, timestamp, tz, message);
3273 oidcpy(&cb->last_kept_oid, noid);
3275 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3276 printf("keep %s", message);
3281 static int files_reflog_expire(struct ref_store *ref_store,
3282 const char *refname, const unsigned char *sha1,
3284 reflog_expiry_prepare_fn prepare_fn,
3285 reflog_expiry_should_prune_fn should_prune_fn,
3286 reflog_expiry_cleanup_fn cleanup_fn,
3287 void *policy_cb_data)
3289 struct files_ref_store *refs =
3290 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3291 static struct lock_file reflog_lock;
3292 struct expire_reflog_cb cb;
3293 struct ref_lock *lock;
3294 struct strbuf log_file_sb = STRBUF_INIT;
3298 struct strbuf err = STRBUF_INIT;
3299 struct object_id oid;
3301 memset(&cb, 0, sizeof(cb));
3303 cb.policy_cb = policy_cb_data;
3304 cb.should_prune_fn = should_prune_fn;
3307 * The reflog file is locked by holding the lock on the
3308 * reference itself, plus we might need to update the
3309 * reference if --updateref was specified:
3311 lock = lock_ref_sha1_basic(refs, refname, sha1,
3312 NULL, NULL, REF_NODEREF,
3315 error("cannot lock ref '%s': %s", refname, err.buf);
3316 strbuf_release(&err);
3319 if (!refs_reflog_exists(ref_store, refname)) {
3324 files_reflog_path(refs, &log_file_sb, refname);
3325 log_file = strbuf_detach(&log_file_sb, NULL);
3326 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3328 * Even though holding $GIT_DIR/logs/$reflog.lock has
3329 * no locking implications, we use the lock_file
3330 * machinery here anyway because it does a lot of the
3331 * work we need, including cleaning up if the program
3332 * exits unexpectedly.
3334 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3335 struct strbuf err = STRBUF_INIT;
3336 unable_to_lock_message(log_file, errno, &err);
3337 error("%s", err.buf);
3338 strbuf_release(&err);
3341 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3343 error("cannot fdopen %s (%s)",
3344 get_lock_file_path(&reflog_lock), strerror(errno));
3349 hashcpy(oid.hash, sha1);
3351 (*prepare_fn)(refname, &oid, cb.policy_cb);
3352 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3353 (*cleanup_fn)(cb.policy_cb);
3355 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3357 * It doesn't make sense to adjust a reference pointed
3358 * to by a symbolic ref based on expiring entries in
3359 * the symbolic reference's reflog. Nor can we update
3360 * a reference if there are no remaining reflog
3363 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3364 !(type & REF_ISSYMREF) &&
3365 !is_null_oid(&cb.last_kept_oid);
3367 if (close_lock_file(&reflog_lock)) {
3368 status |= error("couldn't write %s: %s", log_file,
3370 } else if (update &&
3371 (write_in_full(get_lock_file_fd(lock->lk),
3372 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3373 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3374 close_ref(lock) < 0)) {
3375 status |= error("couldn't write %s",
3376 get_lock_file_path(lock->lk));
3377 rollback_lock_file(&reflog_lock);
3378 } else if (commit_lock_file(&reflog_lock)) {
3379 status |= error("unable to write reflog '%s' (%s)",
3380 log_file, strerror(errno));
3381 } else if (update && commit_ref(lock)) {
3382 status |= error("couldn't set %s", lock->ref_name);
3390 rollback_lock_file(&reflog_lock);
3396 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3398 struct files_ref_store *refs =
3399 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3400 struct strbuf sb = STRBUF_INIT;
3403 * Create .git/refs/{heads,tags}
3405 files_ref_path(refs, &sb, "refs/heads");
3406 safe_create_dir(sb.buf, 1);
3409 files_ref_path(refs, &sb, "refs/tags");
3410 safe_create_dir(sb.buf, 1);
3412 strbuf_release(&sb);
3416 struct ref_storage_be refs_be_files = {
3419 files_ref_store_create,
3421 files_transaction_prepare,
3422 files_transaction_finish,
3423 files_transaction_abort,
3424 files_initial_transaction_commit,
3428 files_create_symref,
3432 files_ref_iterator_begin,
3435 files_reflog_iterator_begin,
3436 files_for_each_reflog_ent,
3437 files_for_each_reflog_ent_reverse,
3438 files_reflog_exists,
3439 files_create_reflog,
3440 files_delete_reflog,