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 * Future: need to be in "struct repository"
85 * when doing a full libification.
87 struct files_ref_store {
88 struct ref_store base;
89 unsigned int store_flags;
94 struct ref_cache *loose;
96 struct packed_ref_store *packed_ref_store;
100 * Increment the reference count of *packed_refs.
102 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
104 packed_refs->referrers++;
108 * Decrease the reference count of *packed_refs. If it goes to zero,
109 * free *packed_refs and return true; otherwise return false.
111 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
113 if (!--packed_refs->referrers) {
114 free_ref_cache(packed_refs->cache);
115 stat_validity_clear(&packed_refs->validity);
123 static void clear_packed_ref_cache(struct packed_ref_store *refs)
126 struct packed_ref_cache *cache = refs->cache;
128 if (is_lock_file_locked(&refs->lock))
129 die("BUG: packed-ref cache cleared while locked");
131 release_packed_ref_cache(cache);
135 static void clear_loose_ref_cache(struct files_ref_store *refs)
138 free_ref_cache(refs->loose);
144 * Create a new submodule ref cache and add it to the internal
147 static struct ref_store *files_ref_store_create(const char *gitdir,
150 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
151 struct ref_store *ref_store = (struct ref_store *)refs;
152 struct strbuf sb = STRBUF_INIT;
154 base_ref_store_init(ref_store, &refs_be_files);
155 refs->store_flags = flags;
157 refs->gitdir = xstrdup(gitdir);
158 get_common_dir_noenv(&sb, gitdir);
159 refs->gitcommondir = strbuf_detach(&sb, NULL);
160 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
161 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
168 * Die if refs is not the main ref store. caller is used in any
169 * necessary error messages.
171 static void files_assert_main_repository(struct files_ref_store *refs,
174 if (refs->store_flags & REF_STORE_MAIN)
177 die("BUG: operation %s only allowed for main ref store", caller);
181 * Downcast ref_store to files_ref_store. Die if ref_store is not a
182 * files_ref_store. required_flags is compared with ref_store's
183 * store_flags to ensure the ref_store has all required capabilities.
184 * "caller" is used in any necessary error messages.
186 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
187 unsigned int required_flags,
190 struct files_ref_store *refs;
192 if (ref_store->be != &refs_be_files)
193 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
194 ref_store->be->name, caller);
196 refs = (struct files_ref_store *)ref_store;
198 if ((refs->store_flags & required_flags) != required_flags)
199 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
200 caller, required_flags, refs->store_flags);
205 /* The length of a peeled reference line in packed-refs, including EOL: */
206 #define PEELED_LINE_LENGTH 42
209 * The packed-refs header line that we write out. Perhaps other
210 * traits will be added later. The trailing space is required.
212 static const char PACKED_REFS_HEADER[] =
213 "# pack-refs with: peeled fully-peeled \n";
216 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
217 * Return a pointer to the refname within the line (null-terminated),
218 * or NULL if there was a problem.
220 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
224 if (parse_oid_hex(line->buf, oid, &ref) < 0)
226 if (!isspace(*ref++))
232 if (line->buf[line->len - 1] != '\n')
234 line->buf[--line->len] = 0;
240 * Read from `packed_refs_file` into a newly-allocated
241 * `packed_ref_cache` and return it. The return value will already
242 * have its reference count incremented.
244 * A comment line of the form "# pack-refs with: " may contain zero or
245 * more traits. We interpret the traits as follows:
249 * Probably no references are peeled. But if the file contains a
250 * peeled value for a reference, we will use it.
254 * References under "refs/tags/", if they *can* be peeled, *are*
255 * peeled in this file. References outside of "refs/tags/" are
256 * probably not peeled even if they could have been, but if we find
257 * a peeled value for such a reference we will use it.
261 * All references in the file that can be peeled are peeled.
262 * Inversely (and this is more important), any references in the
263 * file for which no peeled value is recorded is not peelable. This
264 * trait should typically be written alongside "peeled" for
265 * compatibility with older clients, but we do not require it
266 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
268 static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
271 struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
272 struct ref_entry *last = NULL;
273 struct strbuf line = STRBUF_INIT;
274 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
277 acquire_packed_ref_cache(packed_refs);
278 packed_refs->cache = create_ref_cache(NULL, NULL);
279 packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
281 f = fopen(packed_refs_file, "r");
283 if (errno == ENOENT) {
285 * This is OK; it just means that no
286 * "packed-refs" file has been written yet,
287 * which is equivalent to it being empty.
291 die_errno("couldn't read %s", packed_refs_file);
295 stat_validity_update(&packed_refs->validity, fileno(f));
297 dir = get_ref_dir(packed_refs->cache->root);
298 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
299 struct object_id oid;
303 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
304 if (strstr(traits, " fully-peeled "))
305 peeled = PEELED_FULLY;
306 else if (strstr(traits, " peeled "))
307 peeled = PEELED_TAGS;
308 /* perhaps other traits later as well */
312 refname = parse_ref_line(&line, &oid);
314 int flag = REF_ISPACKED;
316 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
317 if (!refname_is_safe(refname))
318 die("packed refname is dangerous: %s", refname);
320 flag |= REF_BAD_NAME | REF_ISBROKEN;
322 last = create_ref_entry(refname, &oid, flag);
323 if (peeled == PEELED_FULLY ||
324 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
325 last->flag |= REF_KNOWS_PEELED;
326 add_ref_entry(dir, last);
330 line.buf[0] == '^' &&
331 line.len == PEELED_LINE_LENGTH &&
332 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
333 !get_oid_hex(line.buf + 1, &oid)) {
334 oidcpy(&last->u.value.peeled, &oid);
336 * Regardless of what the file header said,
337 * we definitely know the value of *this*
340 last->flag |= REF_KNOWS_PEELED;
345 strbuf_release(&line);
350 static void files_reflog_path(struct files_ref_store *refs,
356 * FIXME: of course this is wrong in multi worktree
357 * setting. To be fixed real soon.
359 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
363 switch (ref_type(refname)) {
364 case REF_TYPE_PER_WORKTREE:
365 case REF_TYPE_PSEUDOREF:
366 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
368 case REF_TYPE_NORMAL:
369 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
372 die("BUG: unknown ref type %d of ref %s",
373 ref_type(refname), refname);
377 static void files_ref_path(struct files_ref_store *refs,
381 switch (ref_type(refname)) {
382 case REF_TYPE_PER_WORKTREE:
383 case REF_TYPE_PSEUDOREF:
384 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
386 case REF_TYPE_NORMAL:
387 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
390 die("BUG: unknown ref type %d of ref %s",
391 ref_type(refname), refname);
396 * Check that the packed refs cache (if any) still reflects the
397 * contents of the file. If not, clear the cache.
399 static void validate_packed_ref_cache(struct packed_ref_store *refs)
402 !stat_validity_check(&refs->cache->validity, refs->path))
403 clear_packed_ref_cache(refs);
407 * Get the packed_ref_cache for the specified files_ref_store,
408 * creating and populating it if it hasn't been read before or if the
409 * file has been changed (according to its `validity` field) since it
410 * was last read. On the other hand, if we hold the lock, then assume
411 * that the file hasn't been changed out from under us, so skip the
412 * extra `stat()` call in `stat_validity_check()`.
414 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
416 const char *packed_refs_file = refs->packed_ref_store->path;
418 if (!is_lock_file_locked(&refs->packed_ref_store->lock))
419 validate_packed_ref_cache(refs->packed_ref_store);
421 if (!refs->packed_ref_store->cache)
422 refs->packed_ref_store->cache = read_packed_refs(packed_refs_file);
424 return refs->packed_ref_store->cache;
427 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
429 return get_ref_dir(packed_ref_cache->cache->root);
432 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
434 return get_packed_ref_dir(get_packed_ref_cache(refs));
438 * Add or overwrite a reference in the in-memory packed reference
439 * cache. This may only be called while the packed-refs file is locked
440 * (see lock_packed_refs()). To actually write the packed-refs file,
441 * call commit_packed_refs().
443 static void add_packed_ref(struct files_ref_store *refs,
444 const char *refname, const struct object_id *oid)
446 struct ref_dir *packed_refs;
447 struct ref_entry *packed_entry;
449 if (!is_lock_file_locked(&refs->packed_ref_store->lock))
450 die("BUG: packed refs not locked");
452 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
453 die("Reference has invalid format: '%s'", refname);
455 packed_refs = get_packed_refs(refs);
456 packed_entry = find_ref_entry(packed_refs, refname);
458 /* Overwrite the existing entry: */
459 oidcpy(&packed_entry->u.value.oid, oid);
460 packed_entry->flag = REF_ISPACKED;
461 oidclr(&packed_entry->u.value.peeled);
463 packed_entry = create_ref_entry(refname, oid, REF_ISPACKED);
464 add_ref_entry(packed_refs, packed_entry);
469 * Read the loose references from the namespace dirname into dir
470 * (without recursing). dirname must end with '/'. dir must be the
471 * directory entry corresponding to dirname.
473 static void loose_fill_ref_dir(struct ref_store *ref_store,
474 struct ref_dir *dir, const char *dirname)
476 struct files_ref_store *refs =
477 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
480 int dirnamelen = strlen(dirname);
481 struct strbuf refname;
482 struct strbuf path = STRBUF_INIT;
485 files_ref_path(refs, &path, dirname);
486 path_baselen = path.len;
488 d = opendir(path.buf);
490 strbuf_release(&path);
494 strbuf_init(&refname, dirnamelen + 257);
495 strbuf_add(&refname, dirname, dirnamelen);
497 while ((de = readdir(d)) != NULL) {
498 struct object_id oid;
502 if (de->d_name[0] == '.')
504 if (ends_with(de->d_name, ".lock"))
506 strbuf_addstr(&refname, de->d_name);
507 strbuf_addstr(&path, de->d_name);
508 if (stat(path.buf, &st) < 0) {
509 ; /* silently ignore */
510 } else if (S_ISDIR(st.st_mode)) {
511 strbuf_addch(&refname, '/');
512 add_entry_to_dir(dir,
513 create_dir_entry(dir->cache, refname.buf,
516 if (!refs_resolve_ref_unsafe(&refs->base,
521 flag |= REF_ISBROKEN;
522 } else if (is_null_oid(&oid)) {
524 * It is so astronomically unlikely
525 * that NULL_SHA1 is the SHA-1 of an
526 * actual object that we consider its
527 * appearance in a loose reference
528 * file to be repo corruption
529 * (probably due to a software bug).
531 flag |= REF_ISBROKEN;
534 if (check_refname_format(refname.buf,
535 REFNAME_ALLOW_ONELEVEL)) {
536 if (!refname_is_safe(refname.buf))
537 die("loose refname is dangerous: %s", refname.buf);
539 flag |= REF_BAD_NAME | REF_ISBROKEN;
541 add_entry_to_dir(dir,
542 create_ref_entry(refname.buf, &oid, flag));
544 strbuf_setlen(&refname, dirnamelen);
545 strbuf_setlen(&path, path_baselen);
547 strbuf_release(&refname);
548 strbuf_release(&path);
552 * Manually add refs/bisect, which, being per-worktree, might
553 * not appear in the directory listing for refs/ in the main
556 if (!strcmp(dirname, "refs/")) {
557 int pos = search_ref_dir(dir, "refs/bisect/", 12);
560 struct ref_entry *child_entry = create_dir_entry(
561 dir->cache, "refs/bisect/", 12, 1);
562 add_entry_to_dir(dir, child_entry);
567 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
571 * Mark the top-level directory complete because we
572 * are about to read the only subdirectory that can
575 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
577 /* We're going to fill the top level ourselves: */
578 refs->loose->root->flag &= ~REF_INCOMPLETE;
581 * Add an incomplete entry for "refs/" (to be filled
584 add_entry_to_dir(get_ref_dir(refs->loose->root),
585 create_dir_entry(refs->loose, "refs/", 5, 1));
591 * Return the ref_entry for the given refname from the packed
592 * references. If it does not exist, return NULL.
594 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
597 return find_ref_entry(get_packed_refs(refs), refname);
601 * A loose ref file doesn't exist; check for a packed ref.
603 static int resolve_packed_ref(struct files_ref_store *refs,
605 unsigned char *sha1, unsigned int *flags)
607 struct ref_entry *entry;
610 * The loose reference file does not exist; check for a packed
613 entry = get_packed_ref(refs, refname);
615 hashcpy(sha1, entry->u.value.oid.hash);
616 *flags |= REF_ISPACKED;
619 /* refname is not a packed reference. */
623 static int files_read_raw_ref(struct ref_store *ref_store,
624 const char *refname, unsigned char *sha1,
625 struct strbuf *referent, unsigned int *type)
627 struct files_ref_store *refs =
628 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
629 struct strbuf sb_contents = STRBUF_INIT;
630 struct strbuf sb_path = STRBUF_INIT;
637 int remaining_retries = 3;
640 strbuf_reset(&sb_path);
642 files_ref_path(refs, &sb_path, refname);
648 * We might have to loop back here to avoid a race
649 * condition: first we lstat() the file, then we try
650 * to read it as a link or as a file. But if somebody
651 * changes the type of the file (file <-> directory
652 * <-> symlink) between the lstat() and reading, then
653 * we don't want to report that as an error but rather
654 * try again starting with the lstat().
656 * We'll keep a count of the retries, though, just to avoid
657 * any confusing situation sending us into an infinite loop.
660 if (remaining_retries-- <= 0)
663 if (lstat(path, &st) < 0) {
666 if (resolve_packed_ref(refs, refname, sha1, type)) {
674 /* Follow "normalized" - ie "refs/.." symlinks by hand */
675 if (S_ISLNK(st.st_mode)) {
676 strbuf_reset(&sb_contents);
677 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
678 if (errno == ENOENT || errno == EINVAL)
679 /* inconsistent with lstat; retry */
684 if (starts_with(sb_contents.buf, "refs/") &&
685 !check_refname_format(sb_contents.buf, 0)) {
686 strbuf_swap(&sb_contents, referent);
687 *type |= REF_ISSYMREF;
692 * It doesn't look like a refname; fall through to just
693 * treating it like a non-symlink, and reading whatever it
698 /* Is it a directory? */
699 if (S_ISDIR(st.st_mode)) {
701 * Even though there is a directory where the loose
702 * ref is supposed to be, there could still be a
705 if (resolve_packed_ref(refs, refname, sha1, type)) {
714 * Anything else, just open it and try to use it as
717 fd = open(path, O_RDONLY);
719 if (errno == ENOENT && !S_ISLNK(st.st_mode))
720 /* inconsistent with lstat; retry */
725 strbuf_reset(&sb_contents);
726 if (strbuf_read(&sb_contents, fd, 256) < 0) {
727 int save_errno = errno;
733 strbuf_rtrim(&sb_contents);
734 buf = sb_contents.buf;
735 if (starts_with(buf, "ref:")) {
737 while (isspace(*buf))
740 strbuf_reset(referent);
741 strbuf_addstr(referent, buf);
742 *type |= REF_ISSYMREF;
748 * Please note that FETCH_HEAD has additional
749 * data after the sha.
751 if (get_sha1_hex(buf, sha1) ||
752 (buf[40] != '\0' && !isspace(buf[40]))) {
753 *type |= REF_ISBROKEN;
762 strbuf_release(&sb_path);
763 strbuf_release(&sb_contents);
768 static void unlock_ref(struct ref_lock *lock)
770 /* Do not free lock->lk -- atexit() still looks at them */
772 rollback_lock_file(lock->lk);
773 free(lock->ref_name);
778 * Lock refname, without following symrefs, and set *lock_p to point
779 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
780 * and type similarly to read_raw_ref().
782 * The caller must verify that refname is a "safe" reference name (in
783 * the sense of refname_is_safe()) before calling this function.
785 * If the reference doesn't already exist, verify that refname doesn't
786 * have a D/F conflict with any existing references. extras and skip
787 * are passed to refs_verify_refname_available() for this check.
789 * If mustexist is not set and the reference is not found or is
790 * broken, lock the reference anyway but clear sha1.
792 * Return 0 on success. On failure, write an error message to err and
793 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
795 * Implementation note: This function is basically
800 * but it includes a lot more code to
801 * - Deal with possible races with other processes
802 * - Avoid calling refs_verify_refname_available() when it can be
803 * avoided, namely if we were successfully able to read the ref
804 * - Generate informative error messages in the case of failure
806 static int lock_raw_ref(struct files_ref_store *refs,
807 const char *refname, int mustexist,
808 const struct string_list *extras,
809 const struct string_list *skip,
810 struct ref_lock **lock_p,
811 struct strbuf *referent,
815 struct ref_lock *lock;
816 struct strbuf ref_file = STRBUF_INIT;
817 int attempts_remaining = 3;
818 int ret = TRANSACTION_GENERIC_ERROR;
821 files_assert_main_repository(refs, "lock_raw_ref");
825 /* First lock the file so it can't change out from under us. */
827 *lock_p = lock = xcalloc(1, sizeof(*lock));
829 lock->ref_name = xstrdup(refname);
830 files_ref_path(refs, &ref_file, refname);
833 switch (safe_create_leading_directories(ref_file.buf)) {
838 * Suppose refname is "refs/foo/bar". We just failed
839 * to create the containing directory, "refs/foo",
840 * because there was a non-directory in the way. This
841 * indicates a D/F conflict, probably because of
842 * another reference such as "refs/foo". There is no
843 * reason to expect this error to be transitory.
845 if (refs_verify_refname_available(&refs->base, refname,
846 extras, skip, err)) {
849 * To the user the relevant error is
850 * that the "mustexist" reference is
854 strbuf_addf(err, "unable to resolve reference '%s'",
858 * The error message set by
859 * refs_verify_refname_available() is
862 ret = TRANSACTION_NAME_CONFLICT;
866 * The file that is in the way isn't a loose
867 * reference. Report it as a low-level
870 strbuf_addf(err, "unable to create lock file %s.lock; "
871 "non-directory in the way",
876 /* Maybe another process was tidying up. Try again. */
877 if (--attempts_remaining > 0)
881 strbuf_addf(err, "unable to create directory for %s",
887 lock->lk = xcalloc(1, sizeof(struct lock_file));
889 if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
890 if (errno == ENOENT && --attempts_remaining > 0) {
892 * Maybe somebody just deleted one of the
893 * directories leading to ref_file. Try
898 unable_to_lock_message(ref_file.buf, errno, err);
904 * Now we hold the lock and can read the reference without
905 * fear that its value will change.
908 if (files_read_raw_ref(&refs->base, refname,
909 lock->old_oid.hash, referent, type)) {
910 if (errno == ENOENT) {
912 /* Garden variety missing reference. */
913 strbuf_addf(err, "unable to resolve reference '%s'",
918 * Reference is missing, but that's OK. We
919 * know that there is not a conflict with
920 * another loose reference because
921 * (supposing that we are trying to lock
922 * reference "refs/foo/bar"):
924 * - We were successfully able to create
925 * the lockfile refs/foo/bar.lock, so we
926 * know there cannot be a loose reference
929 * - We got ENOENT and not EISDIR, so we
930 * know that there cannot be a loose
931 * reference named "refs/foo/bar/baz".
934 } else if (errno == EISDIR) {
936 * There is a directory in the way. It might have
937 * contained references that have been deleted. If
938 * we don't require that the reference already
939 * exists, try to remove the directory so that it
940 * doesn't cause trouble when we want to rename the
941 * lockfile into place later.
944 /* Garden variety missing reference. */
945 strbuf_addf(err, "unable to resolve reference '%s'",
948 } else if (remove_dir_recursively(&ref_file,
949 REMOVE_DIR_EMPTY_ONLY)) {
950 if (refs_verify_refname_available(
951 &refs->base, refname,
952 extras, skip, err)) {
954 * The error message set by
955 * verify_refname_available() is OK.
957 ret = TRANSACTION_NAME_CONFLICT;
961 * We can't delete the directory,
962 * but we also don't know of any
963 * references that it should
966 strbuf_addf(err, "there is a non-empty directory '%s' "
967 "blocking reference '%s'",
968 ref_file.buf, refname);
972 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
973 strbuf_addf(err, "unable to resolve reference '%s': "
974 "reference broken", refname);
977 strbuf_addf(err, "unable to resolve reference '%s': %s",
978 refname, strerror(errno));
983 * If the ref did not exist and we are creating it,
984 * make sure there is no existing ref that conflicts
987 if (refs_verify_refname_available(
988 &refs->base, refname,
1001 strbuf_release(&ref_file);
1005 static int files_peel_ref(struct ref_store *ref_store,
1006 const char *refname, unsigned char *sha1)
1008 struct files_ref_store *refs =
1009 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
1012 unsigned char base[20];
1014 if (current_ref_iter && current_ref_iter->refname == refname) {
1015 struct object_id peeled;
1017 if (ref_iterator_peel(current_ref_iter, &peeled))
1019 hashcpy(sha1, peeled.hash);
1023 if (refs_read_ref_full(ref_store, refname,
1024 RESOLVE_REF_READING, base, &flag))
1028 * If the reference is packed, read its ref_entry from the
1029 * cache in the hope that we already know its peeled value.
1030 * We only try this optimization on packed references because
1031 * (a) forcing the filling of the loose reference cache could
1032 * be expensive and (b) loose references anyway usually do not
1033 * have REF_KNOWS_PEELED.
1035 if (flag & REF_ISPACKED) {
1036 struct ref_entry *r = get_packed_ref(refs, refname);
1038 if (peel_entry(r, 0))
1040 hashcpy(sha1, r->u.value.peeled.hash);
1045 return peel_object(base, sha1);
1048 struct files_ref_iterator {
1049 struct ref_iterator base;
1051 struct packed_ref_cache *packed_ref_cache;
1052 struct ref_iterator *iter0;
1056 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1058 struct files_ref_iterator *iter =
1059 (struct files_ref_iterator *)ref_iterator;
1062 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1063 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1064 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1067 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1068 !ref_resolves_to_object(iter->iter0->refname,
1070 iter->iter0->flags))
1073 iter->base.refname = iter->iter0->refname;
1074 iter->base.oid = iter->iter0->oid;
1075 iter->base.flags = iter->iter0->flags;
1080 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1086 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1087 struct object_id *peeled)
1089 struct files_ref_iterator *iter =
1090 (struct files_ref_iterator *)ref_iterator;
1092 return ref_iterator_peel(iter->iter0, peeled);
1095 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1097 struct files_ref_iterator *iter =
1098 (struct files_ref_iterator *)ref_iterator;
1102 ok = ref_iterator_abort(iter->iter0);
1104 release_packed_ref_cache(iter->packed_ref_cache);
1105 base_ref_iterator_free(ref_iterator);
1109 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1110 files_ref_iterator_advance,
1111 files_ref_iterator_peel,
1112 files_ref_iterator_abort
1115 static struct ref_iterator *files_ref_iterator_begin(
1116 struct ref_store *ref_store,
1117 const char *prefix, unsigned int flags)
1119 struct files_ref_store *refs;
1120 struct ref_iterator *loose_iter, *packed_iter;
1121 struct files_ref_iterator *iter;
1122 struct ref_iterator *ref_iterator;
1123 unsigned int required_flags = REF_STORE_READ;
1125 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1126 required_flags |= REF_STORE_ODB;
1128 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1130 iter = xcalloc(1, sizeof(*iter));
1131 ref_iterator = &iter->base;
1132 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1135 * We must make sure that all loose refs are read before
1136 * accessing the packed-refs file; this avoids a race
1137 * condition if loose refs are migrated to the packed-refs
1138 * file by a simultaneous process, but our in-memory view is
1139 * from before the migration. We ensure this as follows:
1140 * First, we call start the loose refs iteration with its
1141 * `prime_ref` argument set to true. This causes the loose
1142 * references in the subtree to be pre-read into the cache.
1143 * (If they've already been read, that's OK; we only need to
1144 * guarantee that they're read before the packed refs, not
1145 * *how much* before.) After that, we call
1146 * get_packed_ref_cache(), which internally checks whether the
1147 * packed-ref cache is up to date with what is on disk, and
1148 * re-reads it if not.
1151 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1154 iter->packed_ref_cache = get_packed_ref_cache(refs);
1155 acquire_packed_ref_cache(iter->packed_ref_cache);
1156 packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1159 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1160 iter->flags = flags;
1162 return ref_iterator;
1166 * Verify that the reference locked by lock has the value old_sha1.
1167 * Fail if the reference doesn't exist and mustexist is set. Return 0
1168 * on success. On error, write an error message to err, set errno, and
1169 * return a negative value.
1171 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1172 const unsigned char *old_sha1, int mustexist,
1177 if (refs_read_ref_full(ref_store, lock->ref_name,
1178 mustexist ? RESOLVE_REF_READING : 0,
1179 lock->old_oid.hash, NULL)) {
1181 int save_errno = errno;
1182 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1186 oidclr(&lock->old_oid);
1190 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1191 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1193 oid_to_hex(&lock->old_oid),
1194 sha1_to_hex(old_sha1));
1201 static int remove_empty_directories(struct strbuf *path)
1204 * we want to create a file but there is a directory there;
1205 * if that is an empty directory (or a directory that contains
1206 * only empty directories), remove them.
1208 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1211 static int create_reflock(const char *path, void *cb)
1213 struct lock_file *lk = cb;
1215 return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1219 * Locks a ref returning the lock on success and NULL on failure.
1220 * On failure errno is set to something meaningful.
1222 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1223 const char *refname,
1224 const unsigned char *old_sha1,
1225 const struct string_list *extras,
1226 const struct string_list *skip,
1227 unsigned int flags, int *type,
1230 struct strbuf ref_file = STRBUF_INIT;
1231 struct ref_lock *lock;
1233 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1234 int resolve_flags = RESOLVE_REF_NO_RECURSE;
1237 files_assert_main_repository(refs, "lock_ref_sha1_basic");
1240 lock = xcalloc(1, sizeof(struct ref_lock));
1243 resolve_flags |= RESOLVE_REF_READING;
1244 if (flags & REF_DELETING)
1245 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1247 files_ref_path(refs, &ref_file, refname);
1248 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1249 refname, resolve_flags,
1250 lock->old_oid.hash, type);
1251 if (!resolved && errno == EISDIR) {
1253 * we are trying to lock foo but we used to
1254 * have foo/bar which now does not exist;
1255 * it is normal for the empty directory 'foo'
1258 if (remove_empty_directories(&ref_file)) {
1260 if (!refs_verify_refname_available(
1262 refname, extras, skip, err))
1263 strbuf_addf(err, "there are still refs under '%s'",
1267 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1268 refname, resolve_flags,
1269 lock->old_oid.hash, type);
1273 if (last_errno != ENOTDIR ||
1274 !refs_verify_refname_available(&refs->base, refname,
1276 strbuf_addf(err, "unable to resolve reference '%s': %s",
1277 refname, strerror(last_errno));
1283 * If the ref did not exist and we are creating it, make sure
1284 * there is no existing packed ref whose name begins with our
1285 * refname, nor a packed ref whose name is a proper prefix of
1288 if (is_null_oid(&lock->old_oid) &&
1289 refs_verify_refname_available(&refs->base, refname,
1290 extras, skip, err)) {
1291 last_errno = ENOTDIR;
1295 lock->lk = xcalloc(1, sizeof(struct lock_file));
1297 lock->ref_name = xstrdup(refname);
1299 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1301 unable_to_lock_message(ref_file.buf, errno, err);
1305 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1316 strbuf_release(&ref_file);
1322 * Write an entry to the packed-refs file for the specified refname.
1323 * If peeled is non-NULL, write it as the entry's peeled value.
1325 static void write_packed_entry(FILE *fh, const char *refname,
1326 const unsigned char *sha1,
1327 const unsigned char *peeled)
1329 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1331 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1335 * Lock the packed-refs file for writing. Flags is passed to
1336 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1337 * errno appropriately and return a nonzero value.
1339 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1341 static int timeout_configured = 0;
1342 static int timeout_value = 1000;
1343 struct packed_ref_cache *packed_ref_cache;
1345 files_assert_main_repository(refs, "lock_packed_refs");
1347 if (!timeout_configured) {
1348 git_config_get_int("core.packedrefstimeout", &timeout_value);
1349 timeout_configured = 1;
1352 if (hold_lock_file_for_update_timeout(
1353 &refs->packed_ref_store->lock,
1354 refs->packed_ref_store->path,
1355 flags, timeout_value) < 0)
1359 * Now that we hold the `packed-refs` lock, make sure that our
1360 * cache matches the current version of the file. Normally
1361 * `get_packed_ref_cache()` does that for us, but that
1362 * function assumes that when the file is locked, any existing
1363 * cache is still valid. We've just locked the file, but it
1364 * might have changed the moment *before* we locked it.
1366 validate_packed_ref_cache(refs->packed_ref_store);
1368 packed_ref_cache = get_packed_ref_cache(refs);
1369 /* Increment the reference count to prevent it from being freed: */
1370 acquire_packed_ref_cache(packed_ref_cache);
1375 * Write the current version of the packed refs cache from memory to
1376 * disk. The packed-refs file must already be locked for writing (see
1377 * lock_packed_refs()). Return zero on success. On errors, set errno
1378 * and return a nonzero value
1380 static int commit_packed_refs(struct files_ref_store *refs)
1382 struct packed_ref_cache *packed_ref_cache =
1383 get_packed_ref_cache(refs);
1387 struct ref_iterator *iter;
1389 files_assert_main_repository(refs, "commit_packed_refs");
1391 if (!is_lock_file_locked(&refs->packed_ref_store->lock))
1392 die("BUG: packed-refs not locked");
1394 out = fdopen_lock_file(&refs->packed_ref_store->lock, "w");
1396 die_errno("unable to fdopen packed-refs descriptor");
1398 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1400 iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1401 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1402 struct object_id peeled;
1403 int peel_error = ref_iterator_peel(iter, &peeled);
1405 write_packed_entry(out, iter->refname, iter->oid->hash,
1406 peel_error ? NULL : peeled.hash);
1409 if (ok != ITER_DONE)
1410 die("error while iterating over references");
1412 if (commit_lock_file(&refs->packed_ref_store->lock)) {
1416 release_packed_ref_cache(packed_ref_cache);
1422 * Rollback the lockfile for the packed-refs file, and discard the
1423 * in-memory packed reference cache. (The packed-refs file will be
1424 * read anew if it is needed again after this function is called.)
1426 static void rollback_packed_refs(struct files_ref_store *refs)
1428 struct packed_ref_cache *packed_ref_cache =
1429 get_packed_ref_cache(refs);
1431 files_assert_main_repository(refs, "rollback_packed_refs");
1433 if (!is_lock_file_locked(&refs->packed_ref_store->lock))
1434 die("BUG: packed-refs not locked");
1435 rollback_lock_file(&refs->packed_ref_store->lock);
1436 release_packed_ref_cache(packed_ref_cache);
1437 clear_packed_ref_cache(refs->packed_ref_store);
1440 struct ref_to_prune {
1441 struct ref_to_prune *next;
1442 unsigned char sha1[20];
1443 char name[FLEX_ARRAY];
1447 REMOVE_EMPTY_PARENTS_REF = 0x01,
1448 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1452 * Remove empty parent directories associated with the specified
1453 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1454 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1455 * REMOVE_EMPTY_PARENTS_REFLOG.
1457 static void try_remove_empty_parents(struct files_ref_store *refs,
1458 const char *refname,
1461 struct strbuf buf = STRBUF_INIT;
1462 struct strbuf sb = STRBUF_INIT;
1466 strbuf_addstr(&buf, refname);
1468 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1469 while (*p && *p != '/')
1471 /* tolerate duplicate slashes; see check_refname_format() */
1475 q = buf.buf + buf.len;
1476 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1477 while (q > p && *q != '/')
1479 while (q > p && *(q-1) == '/')
1483 strbuf_setlen(&buf, q - buf.buf);
1486 files_ref_path(refs, &sb, buf.buf);
1487 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1488 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1491 files_reflog_path(refs, &sb, buf.buf);
1492 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1493 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1495 strbuf_release(&buf);
1496 strbuf_release(&sb);
1499 /* make sure nobody touched the ref, and unlink */
1500 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1502 struct ref_transaction *transaction;
1503 struct strbuf err = STRBUF_INIT;
1505 if (check_refname_format(r->name, 0))
1508 transaction = ref_store_transaction_begin(&refs->base, &err);
1510 ref_transaction_delete(transaction, r->name, r->sha1,
1511 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1512 ref_transaction_commit(transaction, &err)) {
1513 ref_transaction_free(transaction);
1514 error("%s", err.buf);
1515 strbuf_release(&err);
1518 ref_transaction_free(transaction);
1519 strbuf_release(&err);
1522 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1531 * Return true if the specified reference should be packed.
1533 static int should_pack_ref(const char *refname,
1534 const struct object_id *oid, unsigned int ref_flags,
1535 unsigned int pack_flags)
1537 /* Do not pack per-worktree refs: */
1538 if (ref_type(refname) != REF_TYPE_NORMAL)
1541 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1542 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1545 /* Do not pack symbolic refs: */
1546 if (ref_flags & REF_ISSYMREF)
1549 /* Do not pack broken refs: */
1550 if (!ref_resolves_to_object(refname, oid, ref_flags))
1556 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1558 struct files_ref_store *refs =
1559 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1561 struct ref_iterator *iter;
1563 struct ref_to_prune *refs_to_prune = NULL;
1565 lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1567 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1568 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1570 * If the loose reference can be packed, add an entry
1571 * in the packed ref cache. If the reference should be
1572 * pruned, also add it to refs_to_prune.
1574 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1579 * Create an entry in the packed-refs cache equivalent
1580 * to the one from the loose ref cache, except that
1581 * we don't copy the peeled status, because we want it
1584 add_packed_ref(refs, iter->refname, iter->oid);
1586 /* Schedule the loose reference for pruning if requested. */
1587 if ((flags & PACK_REFS_PRUNE)) {
1588 struct ref_to_prune *n;
1589 FLEX_ALLOC_STR(n, name, iter->refname);
1590 hashcpy(n->sha1, iter->oid->hash);
1591 n->next = refs_to_prune;
1595 if (ok != ITER_DONE)
1596 die("error while iterating over references");
1598 if (commit_packed_refs(refs))
1599 die_errno("unable to overwrite old ref-pack file");
1601 prune_refs(refs, refs_to_prune);
1606 * Rewrite the packed-refs file, omitting any refs listed in
1607 * 'refnames'. On error, leave packed-refs unchanged, write an error
1608 * message to 'err', and return a nonzero value.
1610 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1612 static int repack_without_refs(struct files_ref_store *refs,
1613 struct string_list *refnames, struct strbuf *err)
1615 struct ref_dir *packed;
1616 struct string_list_item *refname;
1617 int ret, needs_repacking = 0, removed = 0;
1619 files_assert_main_repository(refs, "repack_without_refs");
1622 /* Look for a packed ref */
1623 for_each_string_list_item(refname, refnames) {
1624 if (get_packed_ref(refs, refname->string)) {
1625 needs_repacking = 1;
1630 /* Avoid locking if we have nothing to do */
1631 if (!needs_repacking)
1632 return 0; /* no refname exists in packed refs */
1634 if (lock_packed_refs(refs, 0)) {
1635 unable_to_lock_message(refs->packed_ref_store->path, errno, err);
1638 packed = get_packed_refs(refs);
1640 /* Remove refnames from the cache */
1641 for_each_string_list_item(refname, refnames)
1642 if (remove_entry_from_dir(packed, refname->string) != -1)
1646 * All packed entries disappeared while we were
1647 * acquiring the lock.
1649 rollback_packed_refs(refs);
1653 /* Write what remains */
1654 ret = commit_packed_refs(refs);
1656 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1661 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1662 struct string_list *refnames, unsigned int flags)
1664 struct files_ref_store *refs =
1665 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1666 struct strbuf err = STRBUF_INIT;
1672 result = repack_without_refs(refs, refnames, &err);
1675 * If we failed to rewrite the packed-refs file, then
1676 * it is unsafe to try to remove loose refs, because
1677 * doing so might expose an obsolete packed value for
1678 * a reference that might even point at an object that
1679 * has been garbage collected.
1681 if (refnames->nr == 1)
1682 error(_("could not delete reference %s: %s"),
1683 refnames->items[0].string, err.buf);
1685 error(_("could not delete references: %s"), err.buf);
1690 for (i = 0; i < refnames->nr; i++) {
1691 const char *refname = refnames->items[i].string;
1693 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1694 result |= error(_("could not remove reference %s"), refname);
1698 strbuf_release(&err);
1703 * People using contrib's git-new-workdir have .git/logs/refs ->
1704 * /some/other/path/.git/logs/refs, and that may live on another device.
1706 * IOW, to avoid cross device rename errors, the temporary renamed log must
1707 * live into logs/refs.
1709 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1712 const char *tmp_renamed_log;
1716 static int rename_tmp_log_callback(const char *path, void *cb_data)
1718 struct rename_cb *cb = cb_data;
1720 if (rename(cb->tmp_renamed_log, path)) {
1722 * rename(a, b) when b is an existing directory ought
1723 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1724 * Sheesh. Record the true errno for error reporting,
1725 * but report EISDIR to raceproof_create_file() so
1726 * that it knows to retry.
1728 cb->true_errno = errno;
1729 if (errno == ENOTDIR)
1737 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1739 struct strbuf path = STRBUF_INIT;
1740 struct strbuf tmp = STRBUF_INIT;
1741 struct rename_cb cb;
1744 files_reflog_path(refs, &path, newrefname);
1745 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1746 cb.tmp_renamed_log = tmp.buf;
1747 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1749 if (errno == EISDIR)
1750 error("directory not empty: %s", path.buf);
1752 error("unable to move logfile %s to %s: %s",
1754 strerror(cb.true_errno));
1757 strbuf_release(&path);
1758 strbuf_release(&tmp);
1762 static int write_ref_to_lockfile(struct ref_lock *lock,
1763 const struct object_id *oid, struct strbuf *err);
1764 static int commit_ref_update(struct files_ref_store *refs,
1765 struct ref_lock *lock,
1766 const struct object_id *oid, const char *logmsg,
1767 struct strbuf *err);
1769 static int files_rename_ref(struct ref_store *ref_store,
1770 const char *oldrefname, const char *newrefname,
1773 struct files_ref_store *refs =
1774 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1775 struct object_id oid, orig_oid;
1776 int flag = 0, logmoved = 0;
1777 struct ref_lock *lock;
1778 struct stat loginfo;
1779 struct strbuf sb_oldref = STRBUF_INIT;
1780 struct strbuf sb_newref = STRBUF_INIT;
1781 struct strbuf tmp_renamed_log = STRBUF_INIT;
1783 struct strbuf err = STRBUF_INIT;
1785 files_reflog_path(refs, &sb_oldref, oldrefname);
1786 files_reflog_path(refs, &sb_newref, newrefname);
1787 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1789 log = !lstat(sb_oldref.buf, &loginfo);
1790 if (log && S_ISLNK(loginfo.st_mode)) {
1791 ret = error("reflog for %s is a symlink", oldrefname);
1795 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1796 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1797 orig_oid.hash, &flag)) {
1798 ret = error("refname %s not found", oldrefname);
1802 if (flag & REF_ISSYMREF) {
1803 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1807 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1812 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1813 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1814 oldrefname, strerror(errno));
1818 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1819 orig_oid.hash, REF_NODEREF)) {
1820 error("unable to delete old %s", oldrefname);
1825 * Since we are doing a shallow lookup, oid is not the
1826 * correct value to pass to delete_ref as old_oid. But that
1827 * doesn't matter, because an old_oid check wouldn't add to
1828 * the safety anyway; we want to delete the reference whatever
1829 * its current value.
1831 if (!refs_read_ref_full(&refs->base, newrefname,
1832 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1834 refs_delete_ref(&refs->base, NULL, newrefname,
1835 NULL, REF_NODEREF)) {
1836 if (errno == EISDIR) {
1837 struct strbuf path = STRBUF_INIT;
1840 files_ref_path(refs, &path, newrefname);
1841 result = remove_empty_directories(&path);
1842 strbuf_release(&path);
1845 error("Directory not empty: %s", newrefname);
1849 error("unable to delete existing %s", newrefname);
1854 if (log && rename_tmp_log(refs, newrefname))
1859 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1860 REF_NODEREF, NULL, &err);
1862 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1863 strbuf_release(&err);
1866 oidcpy(&lock->old_oid, &orig_oid);
1868 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1869 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1870 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1871 strbuf_release(&err);
1879 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1880 REF_NODEREF, NULL, &err);
1882 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1883 strbuf_release(&err);
1887 flag = log_all_ref_updates;
1888 log_all_ref_updates = LOG_REFS_NONE;
1889 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1890 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1891 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1892 strbuf_release(&err);
1894 log_all_ref_updates = flag;
1897 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1898 error("unable to restore logfile %s from %s: %s",
1899 oldrefname, newrefname, strerror(errno));
1900 if (!logmoved && log &&
1901 rename(tmp_renamed_log.buf, sb_oldref.buf))
1902 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1903 oldrefname, strerror(errno));
1906 strbuf_release(&sb_newref);
1907 strbuf_release(&sb_oldref);
1908 strbuf_release(&tmp_renamed_log);
1913 static int close_ref(struct ref_lock *lock)
1915 if (close_lock_file(lock->lk))
1920 static int commit_ref(struct ref_lock *lock)
1922 char *path = get_locked_file_path(lock->lk);
1925 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1927 * There is a directory at the path we want to rename
1928 * the lockfile to. Hopefully it is empty; try to
1931 size_t len = strlen(path);
1932 struct strbuf sb_path = STRBUF_INIT;
1934 strbuf_attach(&sb_path, path, len, len);
1937 * If this fails, commit_lock_file() will also fail
1938 * and will report the problem.
1940 remove_empty_directories(&sb_path);
1941 strbuf_release(&sb_path);
1946 if (commit_lock_file(lock->lk))
1951 static int open_or_create_logfile(const char *path, void *cb)
1955 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1956 return (*fd < 0) ? -1 : 0;
1960 * Create a reflog for a ref. If force_create = 0, only create the
1961 * reflog for certain refs (those for which should_autocreate_reflog
1962 * returns non-zero). Otherwise, create it regardless of the reference
1963 * name. If the logfile already existed or was created, return 0 and
1964 * set *logfd to the file descriptor opened for appending to the file.
1965 * If no logfile exists and we decided not to create one, return 0 and
1966 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1969 static int log_ref_setup(struct files_ref_store *refs,
1970 const char *refname, int force_create,
1971 int *logfd, struct strbuf *err)
1973 struct strbuf logfile_sb = STRBUF_INIT;
1976 files_reflog_path(refs, &logfile_sb, refname);
1977 logfile = strbuf_detach(&logfile_sb, NULL);
1979 if (force_create || should_autocreate_reflog(refname)) {
1980 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1981 if (errno == ENOENT)
1982 strbuf_addf(err, "unable to create directory for '%s': "
1983 "%s", logfile, strerror(errno));
1984 else if (errno == EISDIR)
1985 strbuf_addf(err, "there are still logs under '%s'",
1988 strbuf_addf(err, "unable to append to '%s': %s",
1989 logfile, strerror(errno));
1994 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1996 if (errno == ENOENT || errno == EISDIR) {
1998 * The logfile doesn't already exist,
1999 * but that is not an error; it only
2000 * means that we won't write log
2005 strbuf_addf(err, "unable to append to '%s': %s",
2006 logfile, strerror(errno));
2013 adjust_shared_perm(logfile);
2023 static int files_create_reflog(struct ref_store *ref_store,
2024 const char *refname, int force_create,
2027 struct files_ref_store *refs =
2028 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2031 if (log_ref_setup(refs, refname, force_create, &fd, err))
2040 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2041 const struct object_id *new_oid,
2042 const char *committer, const char *msg)
2044 int msglen, written;
2045 unsigned maxlen, len;
2048 msglen = msg ? strlen(msg) : 0;
2049 maxlen = strlen(committer) + msglen + 100;
2050 logrec = xmalloc(maxlen);
2051 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2052 oid_to_hex(old_oid),
2053 oid_to_hex(new_oid),
2056 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2058 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2066 static int files_log_ref_write(struct files_ref_store *refs,
2067 const char *refname, const struct object_id *old_oid,
2068 const struct object_id *new_oid, const char *msg,
2069 int flags, struct strbuf *err)
2073 if (log_all_ref_updates == LOG_REFS_UNSET)
2074 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2076 result = log_ref_setup(refs, refname,
2077 flags & REF_FORCE_CREATE_REFLOG,
2085 result = log_ref_write_fd(logfd, old_oid, new_oid,
2086 git_committer_info(0), msg);
2088 struct strbuf sb = STRBUF_INIT;
2089 int save_errno = errno;
2091 files_reflog_path(refs, &sb, refname);
2092 strbuf_addf(err, "unable to append to '%s': %s",
2093 sb.buf, strerror(save_errno));
2094 strbuf_release(&sb);
2099 struct strbuf sb = STRBUF_INIT;
2100 int save_errno = errno;
2102 files_reflog_path(refs, &sb, refname);
2103 strbuf_addf(err, "unable to append to '%s': %s",
2104 sb.buf, strerror(save_errno));
2105 strbuf_release(&sb);
2112 * Write sha1 into the open lockfile, then close the lockfile. On
2113 * errors, rollback the lockfile, fill in *err and
2116 static int write_ref_to_lockfile(struct ref_lock *lock,
2117 const struct object_id *oid, struct strbuf *err)
2119 static char term = '\n';
2123 o = parse_object(oid);
2126 "trying to write ref '%s' with nonexistent object %s",
2127 lock->ref_name, oid_to_hex(oid));
2131 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2133 "trying to write non-commit object %s to branch '%s'",
2134 oid_to_hex(oid), lock->ref_name);
2138 fd = get_lock_file_fd(lock->lk);
2139 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2140 write_in_full(fd, &term, 1) != 1 ||
2141 close_ref(lock) < 0) {
2143 "couldn't write '%s'", get_lock_file_path(lock->lk));
2151 * Commit a change to a loose reference that has already been written
2152 * to the loose reference lockfile. Also update the reflogs if
2153 * necessary, using the specified lockmsg (which can be NULL).
2155 static int commit_ref_update(struct files_ref_store *refs,
2156 struct ref_lock *lock,
2157 const struct object_id *oid, const char *logmsg,
2160 files_assert_main_repository(refs, "commit_ref_update");
2162 clear_loose_ref_cache(refs);
2163 if (files_log_ref_write(refs, lock->ref_name,
2164 &lock->old_oid, oid,
2166 char *old_msg = strbuf_detach(err, NULL);
2167 strbuf_addf(err, "cannot update the ref '%s': %s",
2168 lock->ref_name, old_msg);
2174 if (strcmp(lock->ref_name, "HEAD") != 0) {
2176 * Special hack: If a branch is updated directly and HEAD
2177 * points to it (may happen on the remote side of a push
2178 * for example) then logically the HEAD reflog should be
2180 * A generic solution implies reverse symref information,
2181 * but finding all symrefs pointing to the given branch
2182 * would be rather costly for this rare event (the direct
2183 * update of a branch) to be worth it. So let's cheat and
2184 * check with HEAD only which should cover 99% of all usage
2185 * scenarios (even 100% of the default ones).
2187 struct object_id head_oid;
2189 const char *head_ref;
2191 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2192 RESOLVE_REF_READING,
2193 head_oid.hash, &head_flag);
2194 if (head_ref && (head_flag & REF_ISSYMREF) &&
2195 !strcmp(head_ref, lock->ref_name)) {
2196 struct strbuf log_err = STRBUF_INIT;
2197 if (files_log_ref_write(refs, "HEAD",
2198 &lock->old_oid, oid,
2199 logmsg, 0, &log_err)) {
2200 error("%s", log_err.buf);
2201 strbuf_release(&log_err);
2206 if (commit_ref(lock)) {
2207 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2216 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2219 #ifndef NO_SYMLINK_HEAD
2220 char *ref_path = get_locked_file_path(lock->lk);
2222 ret = symlink(target, ref_path);
2226 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2231 static void update_symref_reflog(struct files_ref_store *refs,
2232 struct ref_lock *lock, const char *refname,
2233 const char *target, const char *logmsg)
2235 struct strbuf err = STRBUF_INIT;
2236 struct object_id new_oid;
2238 !refs_read_ref_full(&refs->base, target,
2239 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2240 files_log_ref_write(refs, refname, &lock->old_oid,
2241 &new_oid, logmsg, 0, &err)) {
2242 error("%s", err.buf);
2243 strbuf_release(&err);
2247 static int create_symref_locked(struct files_ref_store *refs,
2248 struct ref_lock *lock, const char *refname,
2249 const char *target, const char *logmsg)
2251 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2252 update_symref_reflog(refs, lock, refname, target, logmsg);
2256 if (!fdopen_lock_file(lock->lk, "w"))
2257 return error("unable to fdopen %s: %s",
2258 lock->lk->tempfile.filename.buf, strerror(errno));
2260 update_symref_reflog(refs, lock, refname, target, logmsg);
2262 /* no error check; commit_ref will check ferror */
2263 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2264 if (commit_ref(lock) < 0)
2265 return error("unable to write symref for %s: %s", refname,
2270 static int files_create_symref(struct ref_store *ref_store,
2271 const char *refname, const char *target,
2274 struct files_ref_store *refs =
2275 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2276 struct strbuf err = STRBUF_INIT;
2277 struct ref_lock *lock;
2280 lock = lock_ref_sha1_basic(refs, refname, NULL,
2281 NULL, NULL, REF_NODEREF, NULL,
2284 error("%s", err.buf);
2285 strbuf_release(&err);
2289 ret = create_symref_locked(refs, lock, refname, target, logmsg);
2294 static int files_reflog_exists(struct ref_store *ref_store,
2295 const char *refname)
2297 struct files_ref_store *refs =
2298 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2299 struct strbuf sb = STRBUF_INIT;
2303 files_reflog_path(refs, &sb, refname);
2304 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2305 strbuf_release(&sb);
2309 static int files_delete_reflog(struct ref_store *ref_store,
2310 const char *refname)
2312 struct files_ref_store *refs =
2313 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2314 struct strbuf sb = STRBUF_INIT;
2317 files_reflog_path(refs, &sb, refname);
2318 ret = remove_path(sb.buf);
2319 strbuf_release(&sb);
2323 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2325 struct object_id ooid, noid;
2326 char *email_end, *message;
2327 timestamp_t timestamp;
2329 const char *p = sb->buf;
2331 /* old SP new SP name <email> SP time TAB msg LF */
2332 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2333 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2334 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2335 !(email_end = strchr(p, '>')) ||
2336 email_end[1] != ' ' ||
2337 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2338 !message || message[0] != ' ' ||
2339 (message[1] != '+' && message[1] != '-') ||
2340 !isdigit(message[2]) || !isdigit(message[3]) ||
2341 !isdigit(message[4]) || !isdigit(message[5]))
2342 return 0; /* corrupt? */
2343 email_end[1] = '\0';
2344 tz = strtol(message + 1, NULL, 10);
2345 if (message[6] != '\t')
2349 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2352 static char *find_beginning_of_line(char *bob, char *scan)
2354 while (bob < scan && *(--scan) != '\n')
2355 ; /* keep scanning backwards */
2357 * Return either beginning of the buffer, or LF at the end of
2358 * the previous line.
2363 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2364 const char *refname,
2365 each_reflog_ent_fn fn,
2368 struct files_ref_store *refs =
2369 files_downcast(ref_store, REF_STORE_READ,
2370 "for_each_reflog_ent_reverse");
2371 struct strbuf sb = STRBUF_INIT;
2374 int ret = 0, at_tail = 1;
2376 files_reflog_path(refs, &sb, refname);
2377 logfp = fopen(sb.buf, "r");
2378 strbuf_release(&sb);
2382 /* Jump to the end */
2383 if (fseek(logfp, 0, SEEK_END) < 0)
2384 ret = error("cannot seek back reflog for %s: %s",
2385 refname, strerror(errno));
2387 while (!ret && 0 < pos) {
2393 /* Fill next block from the end */
2394 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2395 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2396 ret = error("cannot seek back reflog for %s: %s",
2397 refname, strerror(errno));
2400 nread = fread(buf, cnt, 1, logfp);
2402 ret = error("cannot read %d bytes from reflog for %s: %s",
2403 cnt, refname, strerror(errno));
2408 scanp = endp = buf + cnt;
2409 if (at_tail && scanp[-1] == '\n')
2410 /* Looking at the final LF at the end of the file */
2414 while (buf < scanp) {
2416 * terminating LF of the previous line, or the beginning
2421 bp = find_beginning_of_line(buf, scanp);
2425 * The newline is the end of the previous line,
2426 * so we know we have complete line starting
2427 * at (bp + 1). Prefix it onto any prior data
2428 * we collected for the line and process it.
2430 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2433 ret = show_one_reflog_ent(&sb, fn, cb_data);
2439 * We are at the start of the buffer, and the
2440 * start of the file; there is no previous
2441 * line, and we have everything for this one.
2442 * Process it, and we can end the loop.
2444 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2445 ret = show_one_reflog_ent(&sb, fn, cb_data);
2452 * We are at the start of the buffer, and there
2453 * is more file to read backwards. Which means
2454 * we are in the middle of a line. Note that we
2455 * may get here even if *bp was a newline; that
2456 * just means we are at the exact end of the
2457 * previous line, rather than some spot in the
2460 * Save away what we have to be combined with
2461 * the data from the next read.
2463 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2470 die("BUG: reverse reflog parser had leftover data");
2473 strbuf_release(&sb);
2477 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2478 const char *refname,
2479 each_reflog_ent_fn fn, void *cb_data)
2481 struct files_ref_store *refs =
2482 files_downcast(ref_store, REF_STORE_READ,
2483 "for_each_reflog_ent");
2485 struct strbuf sb = STRBUF_INIT;
2488 files_reflog_path(refs, &sb, refname);
2489 logfp = fopen(sb.buf, "r");
2490 strbuf_release(&sb);
2494 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2495 ret = show_one_reflog_ent(&sb, fn, cb_data);
2497 strbuf_release(&sb);
2501 struct files_reflog_iterator {
2502 struct ref_iterator base;
2504 struct ref_store *ref_store;
2505 struct dir_iterator *dir_iterator;
2506 struct object_id oid;
2509 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2511 struct files_reflog_iterator *iter =
2512 (struct files_reflog_iterator *)ref_iterator;
2513 struct dir_iterator *diter = iter->dir_iterator;
2516 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2519 if (!S_ISREG(diter->st.st_mode))
2521 if (diter->basename[0] == '.')
2523 if (ends_with(diter->basename, ".lock"))
2526 if (refs_read_ref_full(iter->ref_store,
2527 diter->relative_path, 0,
2528 iter->oid.hash, &flags)) {
2529 error("bad ref for %s", diter->path.buf);
2533 iter->base.refname = diter->relative_path;
2534 iter->base.oid = &iter->oid;
2535 iter->base.flags = flags;
2539 iter->dir_iterator = NULL;
2540 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2545 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2546 struct object_id *peeled)
2548 die("BUG: ref_iterator_peel() called for reflog_iterator");
2551 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2553 struct files_reflog_iterator *iter =
2554 (struct files_reflog_iterator *)ref_iterator;
2557 if (iter->dir_iterator)
2558 ok = dir_iterator_abort(iter->dir_iterator);
2560 base_ref_iterator_free(ref_iterator);
2564 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2565 files_reflog_iterator_advance,
2566 files_reflog_iterator_peel,
2567 files_reflog_iterator_abort
2570 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2572 struct files_ref_store *refs =
2573 files_downcast(ref_store, REF_STORE_READ,
2574 "reflog_iterator_begin");
2575 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2576 struct ref_iterator *ref_iterator = &iter->base;
2577 struct strbuf sb = STRBUF_INIT;
2579 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2580 files_reflog_path(refs, &sb, NULL);
2581 iter->dir_iterator = dir_iterator_begin(sb.buf);
2582 iter->ref_store = ref_store;
2583 strbuf_release(&sb);
2584 return ref_iterator;
2588 * If update is a direct update of head_ref (the reference pointed to
2589 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2591 static int split_head_update(struct ref_update *update,
2592 struct ref_transaction *transaction,
2593 const char *head_ref,
2594 struct string_list *affected_refnames,
2597 struct string_list_item *item;
2598 struct ref_update *new_update;
2600 if ((update->flags & REF_LOG_ONLY) ||
2601 (update->flags & REF_ISPRUNING) ||
2602 (update->flags & REF_UPDATE_VIA_HEAD))
2605 if (strcmp(update->refname, head_ref))
2609 * First make sure that HEAD is not already in the
2610 * transaction. This insertion is O(N) in the transaction
2611 * size, but it happens at most once per transaction.
2613 item = string_list_insert(affected_refnames, "HEAD");
2615 /* An entry already existed */
2617 "multiple updates for 'HEAD' (including one "
2618 "via its referent '%s') are not allowed",
2620 return TRANSACTION_NAME_CONFLICT;
2623 new_update = ref_transaction_add_update(
2624 transaction, "HEAD",
2625 update->flags | REF_LOG_ONLY | REF_NODEREF,
2626 update->new_oid.hash, update->old_oid.hash,
2629 item->util = new_update;
2635 * update is for a symref that points at referent and doesn't have
2636 * REF_NODEREF set. Split it into two updates:
2637 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2638 * - A new, separate update for the referent reference
2639 * Note that the new update will itself be subject to splitting when
2640 * the iteration gets to it.
2642 static int split_symref_update(struct files_ref_store *refs,
2643 struct ref_update *update,
2644 const char *referent,
2645 struct ref_transaction *transaction,
2646 struct string_list *affected_refnames,
2649 struct string_list_item *item;
2650 struct ref_update *new_update;
2651 unsigned int new_flags;
2654 * First make sure that referent is not already in the
2655 * transaction. This insertion is O(N) in the transaction
2656 * size, but it happens at most once per symref in a
2659 item = string_list_insert(affected_refnames, referent);
2661 /* An entry already existed */
2663 "multiple updates for '%s' (including one "
2664 "via symref '%s') are not allowed",
2665 referent, update->refname);
2666 return TRANSACTION_NAME_CONFLICT;
2669 new_flags = update->flags;
2670 if (!strcmp(update->refname, "HEAD")) {
2672 * Record that the new update came via HEAD, so that
2673 * when we process it, split_head_update() doesn't try
2674 * to add another reflog update for HEAD. Note that
2675 * this bit will be propagated if the new_update
2676 * itself needs to be split.
2678 new_flags |= REF_UPDATE_VIA_HEAD;
2681 new_update = ref_transaction_add_update(
2682 transaction, referent, new_flags,
2683 update->new_oid.hash, update->old_oid.hash,
2686 new_update->parent_update = update;
2689 * Change the symbolic ref update to log only. Also, it
2690 * doesn't need to check its old SHA-1 value, as that will be
2691 * done when new_update is processed.
2693 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2694 update->flags &= ~REF_HAVE_OLD;
2696 item->util = new_update;
2702 * Return the refname under which update was originally requested.
2704 static const char *original_update_refname(struct ref_update *update)
2706 while (update->parent_update)
2707 update = update->parent_update;
2709 return update->refname;
2713 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2714 * are consistent with oid, which is the reference's current value. If
2715 * everything is OK, return 0; otherwise, write an error message to
2716 * err and return -1.
2718 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2721 if (!(update->flags & REF_HAVE_OLD) ||
2722 !oidcmp(oid, &update->old_oid))
2725 if (is_null_oid(&update->old_oid))
2726 strbuf_addf(err, "cannot lock ref '%s': "
2727 "reference already exists",
2728 original_update_refname(update));
2729 else if (is_null_oid(oid))
2730 strbuf_addf(err, "cannot lock ref '%s': "
2731 "reference is missing but expected %s",
2732 original_update_refname(update),
2733 oid_to_hex(&update->old_oid));
2735 strbuf_addf(err, "cannot lock ref '%s': "
2736 "is at %s but expected %s",
2737 original_update_refname(update),
2739 oid_to_hex(&update->old_oid));
2745 * Prepare for carrying out update:
2746 * - Lock the reference referred to by update.
2747 * - Read the reference under lock.
2748 * - Check that its old SHA-1 value (if specified) is correct, and in
2749 * any case record it in update->lock->old_oid for later use when
2750 * writing the reflog.
2751 * - If it is a symref update without REF_NODEREF, split it up into a
2752 * REF_LOG_ONLY update of the symref and add a separate update for
2753 * the referent to transaction.
2754 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2757 static int lock_ref_for_update(struct files_ref_store *refs,
2758 struct ref_update *update,
2759 struct ref_transaction *transaction,
2760 const char *head_ref,
2761 struct string_list *affected_refnames,
2764 struct strbuf referent = STRBUF_INIT;
2765 int mustexist = (update->flags & REF_HAVE_OLD) &&
2766 !is_null_oid(&update->old_oid);
2768 struct ref_lock *lock;
2770 files_assert_main_repository(refs, "lock_ref_for_update");
2772 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2773 update->flags |= REF_DELETING;
2776 ret = split_head_update(update, transaction, head_ref,
2777 affected_refnames, err);
2782 ret = lock_raw_ref(refs, update->refname, mustexist,
2783 affected_refnames, NULL,
2785 &update->type, err);
2789 reason = strbuf_detach(err, NULL);
2790 strbuf_addf(err, "cannot lock ref '%s': %s",
2791 original_update_refname(update), reason);
2796 update->backend_data = lock;
2798 if (update->type & REF_ISSYMREF) {
2799 if (update->flags & REF_NODEREF) {
2801 * We won't be reading the referent as part of
2802 * the transaction, so we have to read it here
2803 * to record and possibly check old_sha1:
2805 if (refs_read_ref_full(&refs->base,
2807 lock->old_oid.hash, NULL)) {
2808 if (update->flags & REF_HAVE_OLD) {
2809 strbuf_addf(err, "cannot lock ref '%s': "
2810 "error reading reference",
2811 original_update_refname(update));
2814 } else if (check_old_oid(update, &lock->old_oid, err)) {
2815 return TRANSACTION_GENERIC_ERROR;
2819 * Create a new update for the reference this
2820 * symref is pointing at. Also, we will record
2821 * and verify old_sha1 for this update as part
2822 * of processing the split-off update, so we
2823 * don't have to do it here.
2825 ret = split_symref_update(refs, update,
2826 referent.buf, transaction,
2827 affected_refnames, err);
2832 struct ref_update *parent_update;
2834 if (check_old_oid(update, &lock->old_oid, err))
2835 return TRANSACTION_GENERIC_ERROR;
2838 * If this update is happening indirectly because of a
2839 * symref update, record the old SHA-1 in the parent
2842 for (parent_update = update->parent_update;
2844 parent_update = parent_update->parent_update) {
2845 struct ref_lock *parent_lock = parent_update->backend_data;
2846 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2850 if ((update->flags & REF_HAVE_NEW) &&
2851 !(update->flags & REF_DELETING) &&
2852 !(update->flags & REF_LOG_ONLY)) {
2853 if (!(update->type & REF_ISSYMREF) &&
2854 !oidcmp(&lock->old_oid, &update->new_oid)) {
2856 * The reference already has the desired
2857 * value, so we don't need to write it.
2859 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2861 char *write_err = strbuf_detach(err, NULL);
2864 * The lock was freed upon failure of
2865 * write_ref_to_lockfile():
2867 update->backend_data = NULL;
2869 "cannot update ref '%s': %s",
2870 update->refname, write_err);
2872 return TRANSACTION_GENERIC_ERROR;
2874 update->flags |= REF_NEEDS_COMMIT;
2877 if (!(update->flags & REF_NEEDS_COMMIT)) {
2879 * We didn't call write_ref_to_lockfile(), so
2880 * the lockfile is still open. Close it to
2881 * free up the file descriptor:
2883 if (close_ref(lock)) {
2884 strbuf_addf(err, "couldn't close '%s.lock'",
2886 return TRANSACTION_GENERIC_ERROR;
2893 * Unlock any references in `transaction` that are still locked, and
2894 * mark the transaction closed.
2896 static void files_transaction_cleanup(struct ref_transaction *transaction)
2900 for (i = 0; i < transaction->nr; i++) {
2901 struct ref_update *update = transaction->updates[i];
2902 struct ref_lock *lock = update->backend_data;
2906 update->backend_data = NULL;
2910 transaction->state = REF_TRANSACTION_CLOSED;
2913 static int files_transaction_prepare(struct ref_store *ref_store,
2914 struct ref_transaction *transaction,
2917 struct files_ref_store *refs =
2918 files_downcast(ref_store, REF_STORE_WRITE,
2919 "ref_transaction_prepare");
2922 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2923 char *head_ref = NULL;
2925 struct object_id head_oid;
2929 if (!transaction->nr)
2933 * Fail if a refname appears more than once in the
2934 * transaction. (If we end up splitting up any updates using
2935 * split_symref_update() or split_head_update(), those
2936 * functions will check that the new updates don't have the
2937 * same refname as any existing ones.)
2939 for (i = 0; i < transaction->nr; i++) {
2940 struct ref_update *update = transaction->updates[i];
2941 struct string_list_item *item =
2942 string_list_append(&affected_refnames, update->refname);
2945 * We store a pointer to update in item->util, but at
2946 * the moment we never use the value of this field
2947 * except to check whether it is non-NULL.
2949 item->util = update;
2951 string_list_sort(&affected_refnames);
2952 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2953 ret = TRANSACTION_GENERIC_ERROR;
2958 * Special hack: If a branch is updated directly and HEAD
2959 * points to it (may happen on the remote side of a push
2960 * for example) then logically the HEAD reflog should be
2963 * A generic solution would require reverse symref lookups,
2964 * but finding all symrefs pointing to a given branch would be
2965 * rather costly for this rare event (the direct update of a
2966 * branch) to be worth it. So let's cheat and check with HEAD
2967 * only, which should cover 99% of all usage scenarios (even
2968 * 100% of the default ones).
2970 * So if HEAD is a symbolic reference, then record the name of
2971 * the reference that it points to. If we see an update of
2972 * head_ref within the transaction, then split_head_update()
2973 * arranges for the reflog of HEAD to be updated, too.
2975 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2976 RESOLVE_REF_NO_RECURSE,
2977 head_oid.hash, &head_type);
2979 if (head_ref && !(head_type & REF_ISSYMREF)) {
2985 * Acquire all locks, verify old values if provided, check
2986 * that new values are valid, and write new values to the
2987 * lockfiles, ready to be activated. Only keep one lockfile
2988 * open at a time to avoid running out of file descriptors.
2989 * Note that lock_ref_for_update() might append more updates
2990 * to the transaction.
2992 for (i = 0; i < transaction->nr; i++) {
2993 struct ref_update *update = transaction->updates[i];
2995 ret = lock_ref_for_update(refs, update, transaction,
2996 head_ref, &affected_refnames, err);
3003 string_list_clear(&affected_refnames, 0);
3006 files_transaction_cleanup(transaction);
3008 transaction->state = REF_TRANSACTION_PREPARED;
3013 static int files_transaction_finish(struct ref_store *ref_store,
3014 struct ref_transaction *transaction,
3017 struct files_ref_store *refs =
3018 files_downcast(ref_store, 0, "ref_transaction_finish");
3021 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3022 struct string_list_item *ref_to_delete;
3023 struct strbuf sb = STRBUF_INIT;
3027 if (!transaction->nr) {
3028 transaction->state = REF_TRANSACTION_CLOSED;
3032 /* Perform updates first so live commits remain referenced */
3033 for (i = 0; i < transaction->nr; i++) {
3034 struct ref_update *update = transaction->updates[i];
3035 struct ref_lock *lock = update->backend_data;
3037 if (update->flags & REF_NEEDS_COMMIT ||
3038 update->flags & REF_LOG_ONLY) {
3039 if (files_log_ref_write(refs,
3043 update->msg, update->flags,
3045 char *old_msg = strbuf_detach(err, NULL);
3047 strbuf_addf(err, "cannot update the ref '%s': %s",
3048 lock->ref_name, old_msg);
3051 update->backend_data = NULL;
3052 ret = TRANSACTION_GENERIC_ERROR;
3056 if (update->flags & REF_NEEDS_COMMIT) {
3057 clear_loose_ref_cache(refs);
3058 if (commit_ref(lock)) {
3059 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3061 update->backend_data = NULL;
3062 ret = TRANSACTION_GENERIC_ERROR;
3067 /* Perform deletes now that updates are safely completed */
3068 for (i = 0; i < transaction->nr; i++) {
3069 struct ref_update *update = transaction->updates[i];
3070 struct ref_lock *lock = update->backend_data;
3072 if (update->flags & REF_DELETING &&
3073 !(update->flags & REF_LOG_ONLY)) {
3074 if (!(update->type & REF_ISPACKED) ||
3075 update->type & REF_ISSYMREF) {
3076 /* It is a loose reference. */
3078 files_ref_path(refs, &sb, lock->ref_name);
3079 if (unlink_or_msg(sb.buf, err)) {
3080 ret = TRANSACTION_GENERIC_ERROR;
3083 update->flags |= REF_DELETED_LOOSE;
3086 if (!(update->flags & REF_ISPRUNING))
3087 string_list_append(&refs_to_delete,
3092 if (repack_without_refs(refs, &refs_to_delete, err)) {
3093 ret = TRANSACTION_GENERIC_ERROR;
3097 /* Delete the reflogs of any references that were deleted: */
3098 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3100 files_reflog_path(refs, &sb, ref_to_delete->string);
3101 if (!unlink_or_warn(sb.buf))
3102 try_remove_empty_parents(refs, ref_to_delete->string,
3103 REMOVE_EMPTY_PARENTS_REFLOG);
3106 clear_loose_ref_cache(refs);
3109 files_transaction_cleanup(transaction);
3111 for (i = 0; i < transaction->nr; i++) {
3112 struct ref_update *update = transaction->updates[i];
3114 if (update->flags & REF_DELETED_LOOSE) {
3116 * The loose reference was deleted. Delete any
3117 * empty parent directories. (Note that this
3118 * can only work because we have already
3119 * removed the lockfile.)
3121 try_remove_empty_parents(refs, update->refname,
3122 REMOVE_EMPTY_PARENTS_REF);
3126 strbuf_release(&sb);
3127 string_list_clear(&refs_to_delete, 0);
3131 static int files_transaction_abort(struct ref_store *ref_store,
3132 struct ref_transaction *transaction,
3135 files_transaction_cleanup(transaction);
3139 static int ref_present(const char *refname,
3140 const struct object_id *oid, int flags, void *cb_data)
3142 struct string_list *affected_refnames = cb_data;
3144 return string_list_has_string(affected_refnames, refname);
3147 static int files_initial_transaction_commit(struct ref_store *ref_store,
3148 struct ref_transaction *transaction,
3151 struct files_ref_store *refs =
3152 files_downcast(ref_store, REF_STORE_WRITE,
3153 "initial_ref_transaction_commit");
3156 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3160 if (transaction->state != REF_TRANSACTION_OPEN)
3161 die("BUG: commit called for transaction that is not open");
3163 /* Fail if a refname appears more than once in the transaction: */
3164 for (i = 0; i < transaction->nr; i++)
3165 string_list_append(&affected_refnames,
3166 transaction->updates[i]->refname);
3167 string_list_sort(&affected_refnames);
3168 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3169 ret = TRANSACTION_GENERIC_ERROR;
3174 * It's really undefined to call this function in an active
3175 * repository or when there are existing references: we are
3176 * only locking and changing packed-refs, so (1) any
3177 * simultaneous processes might try to change a reference at
3178 * the same time we do, and (2) any existing loose versions of
3179 * the references that we are setting would have precedence
3180 * over our values. But some remote helpers create the remote
3181 * "HEAD" and "master" branches before calling this function,
3182 * so here we really only check that none of the references
3183 * that we are creating already exists.
3185 if (refs_for_each_rawref(&refs->base, ref_present,
3186 &affected_refnames))
3187 die("BUG: initial ref transaction called with existing refs");
3189 for (i = 0; i < transaction->nr; i++) {
3190 struct ref_update *update = transaction->updates[i];
3192 if ((update->flags & REF_HAVE_OLD) &&
3193 !is_null_oid(&update->old_oid))
3194 die("BUG: initial ref transaction with old_sha1 set");
3195 if (refs_verify_refname_available(&refs->base, update->refname,
3196 &affected_refnames, NULL,
3198 ret = TRANSACTION_NAME_CONFLICT;
3203 if (lock_packed_refs(refs, 0)) {
3204 strbuf_addf(err, "unable to lock packed-refs file: %s",
3206 ret = TRANSACTION_GENERIC_ERROR;
3210 for (i = 0; i < transaction->nr; i++) {
3211 struct ref_update *update = transaction->updates[i];
3213 if ((update->flags & REF_HAVE_NEW) &&
3214 !is_null_oid(&update->new_oid))
3215 add_packed_ref(refs, update->refname,
3219 if (commit_packed_refs(refs)) {
3220 strbuf_addf(err, "unable to commit packed-refs file: %s",
3222 ret = TRANSACTION_GENERIC_ERROR;
3227 transaction->state = REF_TRANSACTION_CLOSED;
3228 string_list_clear(&affected_refnames, 0);
3232 struct expire_reflog_cb {
3234 reflog_expiry_should_prune_fn *should_prune_fn;
3237 struct object_id last_kept_oid;
3240 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3241 const char *email, timestamp_t timestamp, int tz,
3242 const char *message, void *cb_data)
3244 struct expire_reflog_cb *cb = cb_data;
3245 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3247 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3248 ooid = &cb->last_kept_oid;
3250 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3251 message, policy_cb)) {
3253 printf("would prune %s", message);
3254 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3255 printf("prune %s", message);
3258 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3259 oid_to_hex(ooid), oid_to_hex(noid),
3260 email, timestamp, tz, message);
3261 oidcpy(&cb->last_kept_oid, noid);
3263 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3264 printf("keep %s", message);
3269 static int files_reflog_expire(struct ref_store *ref_store,
3270 const char *refname, const unsigned char *sha1,
3272 reflog_expiry_prepare_fn prepare_fn,
3273 reflog_expiry_should_prune_fn should_prune_fn,
3274 reflog_expiry_cleanup_fn cleanup_fn,
3275 void *policy_cb_data)
3277 struct files_ref_store *refs =
3278 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3279 static struct lock_file reflog_lock;
3280 struct expire_reflog_cb cb;
3281 struct ref_lock *lock;
3282 struct strbuf log_file_sb = STRBUF_INIT;
3286 struct strbuf err = STRBUF_INIT;
3287 struct object_id oid;
3289 memset(&cb, 0, sizeof(cb));
3291 cb.policy_cb = policy_cb_data;
3292 cb.should_prune_fn = should_prune_fn;
3295 * The reflog file is locked by holding the lock on the
3296 * reference itself, plus we might need to update the
3297 * reference if --updateref was specified:
3299 lock = lock_ref_sha1_basic(refs, refname, sha1,
3300 NULL, NULL, REF_NODEREF,
3303 error("cannot lock ref '%s': %s", refname, err.buf);
3304 strbuf_release(&err);
3307 if (!refs_reflog_exists(ref_store, refname)) {
3312 files_reflog_path(refs, &log_file_sb, refname);
3313 log_file = strbuf_detach(&log_file_sb, NULL);
3314 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3316 * Even though holding $GIT_DIR/logs/$reflog.lock has
3317 * no locking implications, we use the lock_file
3318 * machinery here anyway because it does a lot of the
3319 * work we need, including cleaning up if the program
3320 * exits unexpectedly.
3322 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3323 struct strbuf err = STRBUF_INIT;
3324 unable_to_lock_message(log_file, errno, &err);
3325 error("%s", err.buf);
3326 strbuf_release(&err);
3329 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3331 error("cannot fdopen %s (%s)",
3332 get_lock_file_path(&reflog_lock), strerror(errno));
3337 hashcpy(oid.hash, sha1);
3339 (*prepare_fn)(refname, &oid, cb.policy_cb);
3340 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3341 (*cleanup_fn)(cb.policy_cb);
3343 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3345 * It doesn't make sense to adjust a reference pointed
3346 * to by a symbolic ref based on expiring entries in
3347 * the symbolic reference's reflog. Nor can we update
3348 * a reference if there are no remaining reflog
3351 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3352 !(type & REF_ISSYMREF) &&
3353 !is_null_oid(&cb.last_kept_oid);
3355 if (close_lock_file(&reflog_lock)) {
3356 status |= error("couldn't write %s: %s", log_file,
3358 } else if (update &&
3359 (write_in_full(get_lock_file_fd(lock->lk),
3360 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3361 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3362 close_ref(lock) < 0)) {
3363 status |= error("couldn't write %s",
3364 get_lock_file_path(lock->lk));
3365 rollback_lock_file(&reflog_lock);
3366 } else if (commit_lock_file(&reflog_lock)) {
3367 status |= error("unable to write reflog '%s' (%s)",
3368 log_file, strerror(errno));
3369 } else if (update && commit_ref(lock)) {
3370 status |= error("couldn't set %s", lock->ref_name);
3378 rollback_lock_file(&reflog_lock);
3384 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3386 struct files_ref_store *refs =
3387 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3388 struct strbuf sb = STRBUF_INIT;
3391 * Create .git/refs/{heads,tags}
3393 files_ref_path(refs, &sb, "refs/heads");
3394 safe_create_dir(sb.buf, 1);
3397 files_ref_path(refs, &sb, "refs/tags");
3398 safe_create_dir(sb.buf, 1);
3400 strbuf_release(&sb);
3404 struct ref_storage_be refs_be_files = {
3407 files_ref_store_create,
3409 files_transaction_prepare,
3410 files_transaction_finish,
3411 files_transaction_abort,
3412 files_initial_transaction_commit,
3416 files_create_symref,
3420 files_ref_iterator_begin,
3423 files_reflog_iterator_begin,
3424 files_for_each_reflog_ent,
3425 files_for_each_reflog_ent_reverse,
3426 files_reflog_exists,
3427 files_create_reflog,
3428 files_delete_reflog,