4 #include "refs-internal.h"
6 #include "packed-backend.h"
7 #include "../iterator.h"
8 #include "../dir-iterator.h"
9 #include "../lockfile.h"
10 #include "../object.h"
16 struct object_id old_oid;
20 * Future: need to be in "struct repository"
21 * when doing a full libification.
23 struct files_ref_store {
24 struct ref_store base;
25 unsigned int store_flags;
30 struct ref_cache *loose;
32 struct ref_store *packed_ref_store;
35 static void clear_loose_ref_cache(struct files_ref_store *refs)
38 free_ref_cache(refs->loose);
44 * Create a new submodule ref cache and add it to the internal
47 static struct ref_store *files_ref_store_create(const char *gitdir,
50 struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
51 struct ref_store *ref_store = (struct ref_store *)refs;
52 struct strbuf sb = STRBUF_INIT;
54 base_ref_store_init(ref_store, &refs_be_files);
55 refs->store_flags = flags;
57 refs->gitdir = xstrdup(gitdir);
58 get_common_dir_noenv(&sb, gitdir);
59 refs->gitcommondir = strbuf_detach(&sb, NULL);
60 strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
61 refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
68 * Die if refs is not the main ref store. caller is used in any
69 * necessary error messages.
71 static void files_assert_main_repository(struct files_ref_store *refs,
74 if (refs->store_flags & REF_STORE_MAIN)
77 die("BUG: operation %s only allowed for main ref store", caller);
81 * Downcast ref_store to files_ref_store. Die if ref_store is not a
82 * files_ref_store. required_flags is compared with ref_store's
83 * store_flags to ensure the ref_store has all required capabilities.
84 * "caller" is used in any necessary error messages.
86 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
87 unsigned int required_flags,
90 struct files_ref_store *refs;
92 if (ref_store->be != &refs_be_files)
93 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
94 ref_store->be->name, caller);
96 refs = (struct files_ref_store *)ref_store;
98 if ((refs->store_flags & required_flags) != required_flags)
99 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
100 caller, required_flags, refs->store_flags);
105 static void files_reflog_path(struct files_ref_store *refs,
111 * FIXME: of course this is wrong in multi worktree
112 * setting. To be fixed real soon.
114 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
118 switch (ref_type(refname)) {
119 case REF_TYPE_PER_WORKTREE:
120 case REF_TYPE_PSEUDOREF:
121 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
123 case REF_TYPE_NORMAL:
124 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
127 die("BUG: unknown ref type %d of ref %s",
128 ref_type(refname), refname);
132 static void files_ref_path(struct files_ref_store *refs,
136 switch (ref_type(refname)) {
137 case REF_TYPE_PER_WORKTREE:
138 case REF_TYPE_PSEUDOREF:
139 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
141 case REF_TYPE_NORMAL:
142 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
145 die("BUG: unknown ref type %d of ref %s",
146 ref_type(refname), refname);
151 * Read the loose references from the namespace dirname into dir
152 * (without recursing). dirname must end with '/'. dir must be the
153 * directory entry corresponding to dirname.
155 static void loose_fill_ref_dir(struct ref_store *ref_store,
156 struct ref_dir *dir, const char *dirname)
158 struct files_ref_store *refs =
159 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
162 int dirnamelen = strlen(dirname);
163 struct strbuf refname;
164 struct strbuf path = STRBUF_INIT;
167 files_ref_path(refs, &path, dirname);
168 path_baselen = path.len;
170 d = opendir(path.buf);
172 strbuf_release(&path);
176 strbuf_init(&refname, dirnamelen + 257);
177 strbuf_add(&refname, dirname, dirnamelen);
179 while ((de = readdir(d)) != NULL) {
180 struct object_id oid;
184 if (de->d_name[0] == '.')
186 if (ends_with(de->d_name, ".lock"))
188 strbuf_addstr(&refname, de->d_name);
189 strbuf_addstr(&path, de->d_name);
190 if (stat(path.buf, &st) < 0) {
191 ; /* silently ignore */
192 } else if (S_ISDIR(st.st_mode)) {
193 strbuf_addch(&refname, '/');
194 add_entry_to_dir(dir,
195 create_dir_entry(dir->cache, refname.buf,
198 if (!refs_resolve_ref_unsafe(&refs->base,
203 flag |= REF_ISBROKEN;
204 } else if (is_null_oid(&oid)) {
206 * It is so astronomically unlikely
207 * that NULL_SHA1 is the SHA-1 of an
208 * actual object that we consider its
209 * appearance in a loose reference
210 * file to be repo corruption
211 * (probably due to a software bug).
213 flag |= REF_ISBROKEN;
216 if (check_refname_format(refname.buf,
217 REFNAME_ALLOW_ONELEVEL)) {
218 if (!refname_is_safe(refname.buf))
219 die("loose refname is dangerous: %s", refname.buf);
221 flag |= REF_BAD_NAME | REF_ISBROKEN;
223 add_entry_to_dir(dir,
224 create_ref_entry(refname.buf, &oid, flag));
226 strbuf_setlen(&refname, dirnamelen);
227 strbuf_setlen(&path, path_baselen);
229 strbuf_release(&refname);
230 strbuf_release(&path);
234 * Manually add refs/bisect, which, being per-worktree, might
235 * not appear in the directory listing for refs/ in the main
238 if (!strcmp(dirname, "refs/")) {
239 int pos = search_ref_dir(dir, "refs/bisect/", 12);
242 struct ref_entry *child_entry = create_dir_entry(
243 dir->cache, "refs/bisect/", 12, 1);
244 add_entry_to_dir(dir, child_entry);
249 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
253 * Mark the top-level directory complete because we
254 * are about to read the only subdirectory that can
257 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
259 /* We're going to fill the top level ourselves: */
260 refs->loose->root->flag &= ~REF_INCOMPLETE;
263 * Add an incomplete entry for "refs/" (to be filled
266 add_entry_to_dir(get_ref_dir(refs->loose->root),
267 create_dir_entry(refs->loose, "refs/", 5, 1));
272 static int files_read_raw_ref(struct ref_store *ref_store,
273 const char *refname, unsigned char *sha1,
274 struct strbuf *referent, unsigned int *type)
276 struct files_ref_store *refs =
277 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
278 struct strbuf sb_contents = STRBUF_INIT;
279 struct strbuf sb_path = STRBUF_INIT;
286 int remaining_retries = 3;
289 strbuf_reset(&sb_path);
291 files_ref_path(refs, &sb_path, refname);
297 * We might have to loop back here to avoid a race
298 * condition: first we lstat() the file, then we try
299 * to read it as a link or as a file. But if somebody
300 * changes the type of the file (file <-> directory
301 * <-> symlink) between the lstat() and reading, then
302 * we don't want to report that as an error but rather
303 * try again starting with the lstat().
305 * We'll keep a count of the retries, though, just to avoid
306 * any confusing situation sending us into an infinite loop.
309 if (remaining_retries-- <= 0)
312 if (lstat(path, &st) < 0) {
315 if (refs_read_raw_ref(refs->packed_ref_store, refname,
316 sha1, referent, type)) {
324 /* Follow "normalized" - ie "refs/.." symlinks by hand */
325 if (S_ISLNK(st.st_mode)) {
326 strbuf_reset(&sb_contents);
327 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
328 if (errno == ENOENT || errno == EINVAL)
329 /* inconsistent with lstat; retry */
334 if (starts_with(sb_contents.buf, "refs/") &&
335 !check_refname_format(sb_contents.buf, 0)) {
336 strbuf_swap(&sb_contents, referent);
337 *type |= REF_ISSYMREF;
342 * It doesn't look like a refname; fall through to just
343 * treating it like a non-symlink, and reading whatever it
348 /* Is it a directory? */
349 if (S_ISDIR(st.st_mode)) {
351 * Even though there is a directory where the loose
352 * ref is supposed to be, there could still be a
355 if (refs_read_raw_ref(refs->packed_ref_store, refname,
356 sha1, referent, type)) {
365 * Anything else, just open it and try to use it as
368 fd = open(path, O_RDONLY);
370 if (errno == ENOENT && !S_ISLNK(st.st_mode))
371 /* inconsistent with lstat; retry */
376 strbuf_reset(&sb_contents);
377 if (strbuf_read(&sb_contents, fd, 256) < 0) {
378 int save_errno = errno;
384 strbuf_rtrim(&sb_contents);
385 buf = sb_contents.buf;
386 if (starts_with(buf, "ref:")) {
388 while (isspace(*buf))
391 strbuf_reset(referent);
392 strbuf_addstr(referent, buf);
393 *type |= REF_ISSYMREF;
399 * Please note that FETCH_HEAD has additional
400 * data after the sha.
402 if (get_sha1_hex(buf, sha1) ||
403 (buf[40] != '\0' && !isspace(buf[40]))) {
404 *type |= REF_ISBROKEN;
413 strbuf_release(&sb_path);
414 strbuf_release(&sb_contents);
419 static void unlock_ref(struct ref_lock *lock)
421 /* Do not free lock->lk -- atexit() still looks at them */
423 rollback_lock_file(lock->lk);
424 free(lock->ref_name);
429 * Lock refname, without following symrefs, and set *lock_p to point
430 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
431 * and type similarly to read_raw_ref().
433 * The caller must verify that refname is a "safe" reference name (in
434 * the sense of refname_is_safe()) before calling this function.
436 * If the reference doesn't already exist, verify that refname doesn't
437 * have a D/F conflict with any existing references. extras and skip
438 * are passed to refs_verify_refname_available() for this check.
440 * If mustexist is not set and the reference is not found or is
441 * broken, lock the reference anyway but clear sha1.
443 * Return 0 on success. On failure, write an error message to err and
444 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
446 * Implementation note: This function is basically
451 * but it includes a lot more code to
452 * - Deal with possible races with other processes
453 * - Avoid calling refs_verify_refname_available() when it can be
454 * avoided, namely if we were successfully able to read the ref
455 * - Generate informative error messages in the case of failure
457 static int lock_raw_ref(struct files_ref_store *refs,
458 const char *refname, int mustexist,
459 const struct string_list *extras,
460 const struct string_list *skip,
461 struct ref_lock **lock_p,
462 struct strbuf *referent,
466 struct ref_lock *lock;
467 struct strbuf ref_file = STRBUF_INIT;
468 int attempts_remaining = 3;
469 int ret = TRANSACTION_GENERIC_ERROR;
472 files_assert_main_repository(refs, "lock_raw_ref");
476 /* First lock the file so it can't change out from under us. */
478 *lock_p = lock = xcalloc(1, sizeof(*lock));
480 lock->ref_name = xstrdup(refname);
481 files_ref_path(refs, &ref_file, refname);
484 switch (safe_create_leading_directories(ref_file.buf)) {
489 * Suppose refname is "refs/foo/bar". We just failed
490 * to create the containing directory, "refs/foo",
491 * because there was a non-directory in the way. This
492 * indicates a D/F conflict, probably because of
493 * another reference such as "refs/foo". There is no
494 * reason to expect this error to be transitory.
496 if (refs_verify_refname_available(&refs->base, refname,
497 extras, skip, err)) {
500 * To the user the relevant error is
501 * that the "mustexist" reference is
505 strbuf_addf(err, "unable to resolve reference '%s'",
509 * The error message set by
510 * refs_verify_refname_available() is
513 ret = TRANSACTION_NAME_CONFLICT;
517 * The file that is in the way isn't a loose
518 * reference. Report it as a low-level
521 strbuf_addf(err, "unable to create lock file %s.lock; "
522 "non-directory in the way",
527 /* Maybe another process was tidying up. Try again. */
528 if (--attempts_remaining > 0)
532 strbuf_addf(err, "unable to create directory for %s",
538 lock->lk = xcalloc(1, sizeof(struct lock_file));
540 if (hold_lock_file_for_update_timeout(
541 lock->lk, ref_file.buf, LOCK_NO_DEREF,
542 get_files_ref_lock_timeout_ms()) < 0) {
543 if (errno == ENOENT && --attempts_remaining > 0) {
545 * Maybe somebody just deleted one of the
546 * directories leading to ref_file. Try
551 unable_to_lock_message(ref_file.buf, errno, err);
557 * Now we hold the lock and can read the reference without
558 * fear that its value will change.
561 if (files_read_raw_ref(&refs->base, refname,
562 lock->old_oid.hash, referent, type)) {
563 if (errno == ENOENT) {
565 /* Garden variety missing reference. */
566 strbuf_addf(err, "unable to resolve reference '%s'",
571 * Reference is missing, but that's OK. We
572 * know that there is not a conflict with
573 * another loose reference because
574 * (supposing that we are trying to lock
575 * reference "refs/foo/bar"):
577 * - We were successfully able to create
578 * the lockfile refs/foo/bar.lock, so we
579 * know there cannot be a loose reference
582 * - We got ENOENT and not EISDIR, so we
583 * know that there cannot be a loose
584 * reference named "refs/foo/bar/baz".
587 } else if (errno == EISDIR) {
589 * There is a directory in the way. It might have
590 * contained references that have been deleted. If
591 * we don't require that the reference already
592 * exists, try to remove the directory so that it
593 * doesn't cause trouble when we want to rename the
594 * lockfile into place later.
597 /* Garden variety missing reference. */
598 strbuf_addf(err, "unable to resolve reference '%s'",
601 } else if (remove_dir_recursively(&ref_file,
602 REMOVE_DIR_EMPTY_ONLY)) {
603 if (refs_verify_refname_available(
604 &refs->base, refname,
605 extras, skip, err)) {
607 * The error message set by
608 * verify_refname_available() is OK.
610 ret = TRANSACTION_NAME_CONFLICT;
614 * We can't delete the directory,
615 * but we also don't know of any
616 * references that it should
619 strbuf_addf(err, "there is a non-empty directory '%s' "
620 "blocking reference '%s'",
621 ref_file.buf, refname);
625 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
626 strbuf_addf(err, "unable to resolve reference '%s': "
627 "reference broken", refname);
630 strbuf_addf(err, "unable to resolve reference '%s': %s",
631 refname, strerror(errno));
636 * If the ref did not exist and we are creating it,
637 * make sure there is no existing packed ref that
638 * conflicts with refname:
640 if (refs_verify_refname_available(
641 refs->packed_ref_store, refname,
654 strbuf_release(&ref_file);
658 struct files_ref_iterator {
659 struct ref_iterator base;
661 struct ref_iterator *iter0;
665 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
667 struct files_ref_iterator *iter =
668 (struct files_ref_iterator *)ref_iterator;
671 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
672 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
673 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
676 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
677 !ref_resolves_to_object(iter->iter0->refname,
682 iter->base.refname = iter->iter0->refname;
683 iter->base.oid = iter->iter0->oid;
684 iter->base.flags = iter->iter0->flags;
689 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
695 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
696 struct object_id *peeled)
698 struct files_ref_iterator *iter =
699 (struct files_ref_iterator *)ref_iterator;
701 return ref_iterator_peel(iter->iter0, peeled);
704 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
706 struct files_ref_iterator *iter =
707 (struct files_ref_iterator *)ref_iterator;
711 ok = ref_iterator_abort(iter->iter0);
713 base_ref_iterator_free(ref_iterator);
717 static struct ref_iterator_vtable files_ref_iterator_vtable = {
718 files_ref_iterator_advance,
719 files_ref_iterator_peel,
720 files_ref_iterator_abort
723 static struct ref_iterator *files_ref_iterator_begin(
724 struct ref_store *ref_store,
725 const char *prefix, unsigned int flags)
727 struct files_ref_store *refs;
728 struct ref_iterator *loose_iter, *packed_iter, *overlay_iter;
729 struct files_ref_iterator *iter;
730 struct ref_iterator *ref_iterator;
731 unsigned int required_flags = REF_STORE_READ;
733 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
734 required_flags |= REF_STORE_ODB;
736 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
739 * We must make sure that all loose refs are read before
740 * accessing the packed-refs file; this avoids a race
741 * condition if loose refs are migrated to the packed-refs
742 * file by a simultaneous process, but our in-memory view is
743 * from before the migration. We ensure this as follows:
744 * First, we call start the loose refs iteration with its
745 * `prime_ref` argument set to true. This causes the loose
746 * references in the subtree to be pre-read into the cache.
747 * (If they've already been read, that's OK; we only need to
748 * guarantee that they're read before the packed refs, not
749 * *how much* before.) After that, we call
750 * packed_ref_iterator_begin(), which internally checks
751 * whether the packed-ref cache is up to date with what is on
752 * disk, and re-reads it if not.
755 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
759 * The packed-refs file might contain broken references, for
760 * example an old version of a reference that points at an
761 * object that has since been garbage-collected. This is OK as
762 * long as there is a corresponding loose reference that
763 * overrides it, and we don't want to emit an error message in
764 * this case. So ask the packed_ref_store for all of its
765 * references, and (if needed) do our own check for broken
766 * ones in files_ref_iterator_advance(), after we have merged
767 * the packed and loose references.
769 packed_iter = refs_ref_iterator_begin(
770 refs->packed_ref_store, prefix, 0,
771 DO_FOR_EACH_INCLUDE_BROKEN);
773 overlay_iter = overlay_ref_iterator_begin(loose_iter, packed_iter);
775 iter = xcalloc(1, sizeof(*iter));
776 ref_iterator = &iter->base;
777 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable,
778 overlay_iter->ordered);
779 iter->iter0 = overlay_iter;
786 * Verify that the reference locked by lock has the value old_sha1.
787 * Fail if the reference doesn't exist and mustexist is set. Return 0
788 * on success. On error, write an error message to err, set errno, and
789 * return a negative value.
791 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
792 const unsigned char *old_sha1, int mustexist,
797 if (refs_read_ref_full(ref_store, lock->ref_name,
798 mustexist ? RESOLVE_REF_READING : 0,
799 lock->old_oid.hash, NULL)) {
801 int save_errno = errno;
802 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
806 oidclr(&lock->old_oid);
810 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
811 strbuf_addf(err, "ref '%s' is at %s but expected %s",
813 oid_to_hex(&lock->old_oid),
814 sha1_to_hex(old_sha1));
821 static int remove_empty_directories(struct strbuf *path)
824 * we want to create a file but there is a directory there;
825 * if that is an empty directory (or a directory that contains
826 * only empty directories), remove them.
828 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
831 static int create_reflock(const char *path, void *cb)
833 struct lock_file *lk = cb;
835 return hold_lock_file_for_update_timeout(
836 lk, path, LOCK_NO_DEREF,
837 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
841 * Locks a ref returning the lock on success and NULL on failure.
842 * On failure errno is set to something meaningful.
844 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
846 const unsigned char *old_sha1,
847 const struct string_list *extras,
848 const struct string_list *skip,
849 unsigned int flags, int *type,
852 struct strbuf ref_file = STRBUF_INIT;
853 struct ref_lock *lock;
855 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
856 int resolve_flags = RESOLVE_REF_NO_RECURSE;
859 files_assert_main_repository(refs, "lock_ref_sha1_basic");
862 lock = xcalloc(1, sizeof(struct ref_lock));
865 resolve_flags |= RESOLVE_REF_READING;
866 if (flags & REF_DELETING)
867 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
869 files_ref_path(refs, &ref_file, refname);
870 resolved = !!refs_resolve_ref_unsafe(&refs->base,
871 refname, resolve_flags,
872 lock->old_oid.hash, type);
873 if (!resolved && errno == EISDIR) {
875 * we are trying to lock foo but we used to
876 * have foo/bar which now does not exist;
877 * it is normal for the empty directory 'foo'
880 if (remove_empty_directories(&ref_file)) {
882 if (!refs_verify_refname_available(
884 refname, extras, skip, err))
885 strbuf_addf(err, "there are still refs under '%s'",
889 resolved = !!refs_resolve_ref_unsafe(&refs->base,
890 refname, resolve_flags,
891 lock->old_oid.hash, type);
895 if (last_errno != ENOTDIR ||
896 !refs_verify_refname_available(&refs->base, refname,
898 strbuf_addf(err, "unable to resolve reference '%s': %s",
899 refname, strerror(last_errno));
905 * If the ref did not exist and we are creating it, make sure
906 * there is no existing packed ref whose name begins with our
907 * refname, nor a packed ref whose name is a proper prefix of
910 if (is_null_oid(&lock->old_oid) &&
911 refs_verify_refname_available(refs->packed_ref_store, refname,
912 extras, skip, err)) {
913 last_errno = ENOTDIR;
917 lock->lk = xcalloc(1, sizeof(struct lock_file));
919 lock->ref_name = xstrdup(refname);
921 if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
923 unable_to_lock_message(ref_file.buf, errno, err);
927 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
938 strbuf_release(&ref_file);
943 struct ref_to_prune {
944 struct ref_to_prune *next;
945 unsigned char sha1[20];
946 char name[FLEX_ARRAY];
950 REMOVE_EMPTY_PARENTS_REF = 0x01,
951 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
955 * Remove empty parent directories associated with the specified
956 * reference and/or its reflog, but spare [logs/]refs/ and immediate
957 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
958 * REMOVE_EMPTY_PARENTS_REFLOG.
960 static void try_remove_empty_parents(struct files_ref_store *refs,
964 struct strbuf buf = STRBUF_INIT;
965 struct strbuf sb = STRBUF_INIT;
969 strbuf_addstr(&buf, refname);
971 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
972 while (*p && *p != '/')
974 /* tolerate duplicate slashes; see check_refname_format() */
978 q = buf.buf + buf.len;
979 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
980 while (q > p && *q != '/')
982 while (q > p && *(q-1) == '/')
986 strbuf_setlen(&buf, q - buf.buf);
989 files_ref_path(refs, &sb, buf.buf);
990 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
991 flags &= ~REMOVE_EMPTY_PARENTS_REF;
994 files_reflog_path(refs, &sb, buf.buf);
995 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
996 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
998 strbuf_release(&buf);
1002 /* make sure nobody touched the ref, and unlink */
1003 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1005 struct ref_transaction *transaction;
1006 struct strbuf err = STRBUF_INIT;
1008 if (check_refname_format(r->name, 0))
1011 transaction = ref_store_transaction_begin(&refs->base, &err);
1013 ref_transaction_delete(transaction, r->name, r->sha1,
1014 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1015 ref_transaction_commit(transaction, &err)) {
1016 ref_transaction_free(transaction);
1017 error("%s", err.buf);
1018 strbuf_release(&err);
1021 ref_transaction_free(transaction);
1022 strbuf_release(&err);
1026 * Prune the loose versions of the references in the linked list
1027 * `*refs_to_prune`, freeing the entries in the list as we go.
1029 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune **refs_to_prune)
1031 while (*refs_to_prune) {
1032 struct ref_to_prune *r = *refs_to_prune;
1033 *refs_to_prune = r->next;
1040 * Return true if the specified reference should be packed.
1042 static int should_pack_ref(const char *refname,
1043 const struct object_id *oid, unsigned int ref_flags,
1044 unsigned int pack_flags)
1046 /* Do not pack per-worktree refs: */
1047 if (ref_type(refname) != REF_TYPE_NORMAL)
1050 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1051 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1054 /* Do not pack symbolic refs: */
1055 if (ref_flags & REF_ISSYMREF)
1058 /* Do not pack broken refs: */
1059 if (!ref_resolves_to_object(refname, oid, ref_flags))
1065 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1067 struct files_ref_store *refs =
1068 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1070 struct ref_iterator *iter;
1072 struct ref_to_prune *refs_to_prune = NULL;
1073 struct strbuf err = STRBUF_INIT;
1074 struct ref_transaction *transaction;
1076 transaction = ref_store_transaction_begin(refs->packed_ref_store, &err);
1080 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1082 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1083 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1085 * If the loose reference can be packed, add an entry
1086 * in the packed ref cache. If the reference should be
1087 * pruned, also add it to refs_to_prune.
1089 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1094 * Add a reference creation for this reference to the
1095 * packed-refs transaction:
1097 if (ref_transaction_update(transaction, iter->refname,
1098 iter->oid->hash, NULL,
1099 REF_NODEREF, NULL, &err))
1100 die("failure preparing to create packed reference %s: %s",
1101 iter->refname, err.buf);
1103 /* Schedule the loose reference for pruning if requested. */
1104 if ((flags & PACK_REFS_PRUNE)) {
1105 struct ref_to_prune *n;
1106 FLEX_ALLOC_STR(n, name, iter->refname);
1107 hashcpy(n->sha1, iter->oid->hash);
1108 n->next = refs_to_prune;
1112 if (ok != ITER_DONE)
1113 die("error while iterating over references");
1115 if (ref_transaction_commit(transaction, &err))
1116 die("unable to write new packed-refs: %s", err.buf);
1118 ref_transaction_free(transaction);
1120 packed_refs_unlock(refs->packed_ref_store);
1122 prune_refs(refs, &refs_to_prune);
1123 strbuf_release(&err);
1127 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1128 struct string_list *refnames, unsigned int flags)
1130 struct files_ref_store *refs =
1131 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1132 struct strbuf err = STRBUF_INIT;
1138 if (packed_refs_lock(refs->packed_ref_store, 0, &err))
1141 if (refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {
1142 packed_refs_unlock(refs->packed_ref_store);
1146 packed_refs_unlock(refs->packed_ref_store);
1148 for (i = 0; i < refnames->nr; i++) {
1149 const char *refname = refnames->items[i].string;
1151 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1152 result |= error(_("could not remove reference %s"), refname);
1155 strbuf_release(&err);
1160 * If we failed to rewrite the packed-refs file, then it is
1161 * unsafe to try to remove loose refs, because doing so might
1162 * expose an obsolete packed value for a reference that might
1163 * even point at an object that has been garbage collected.
1165 if (refnames->nr == 1)
1166 error(_("could not delete reference %s: %s"),
1167 refnames->items[0].string, err.buf);
1169 error(_("could not delete references: %s"), err.buf);
1171 strbuf_release(&err);
1176 * People using contrib's git-new-workdir have .git/logs/refs ->
1177 * /some/other/path/.git/logs/refs, and that may live on another device.
1179 * IOW, to avoid cross device rename errors, the temporary renamed log must
1180 * live into logs/refs.
1182 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1185 const char *tmp_renamed_log;
1189 static int rename_tmp_log_callback(const char *path, void *cb_data)
1191 struct rename_cb *cb = cb_data;
1193 if (rename(cb->tmp_renamed_log, path)) {
1195 * rename(a, b) when b is an existing directory ought
1196 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1197 * Sheesh. Record the true errno for error reporting,
1198 * but report EISDIR to raceproof_create_file() so
1199 * that it knows to retry.
1201 cb->true_errno = errno;
1202 if (errno == ENOTDIR)
1210 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1212 struct strbuf path = STRBUF_INIT;
1213 struct strbuf tmp = STRBUF_INIT;
1214 struct rename_cb cb;
1217 files_reflog_path(refs, &path, newrefname);
1218 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1219 cb.tmp_renamed_log = tmp.buf;
1220 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1222 if (errno == EISDIR)
1223 error("directory not empty: %s", path.buf);
1225 error("unable to move logfile %s to %s: %s",
1227 strerror(cb.true_errno));
1230 strbuf_release(&path);
1231 strbuf_release(&tmp);
1235 static int write_ref_to_lockfile(struct ref_lock *lock,
1236 const struct object_id *oid, struct strbuf *err);
1237 static int commit_ref_update(struct files_ref_store *refs,
1238 struct ref_lock *lock,
1239 const struct object_id *oid, const char *logmsg,
1240 struct strbuf *err);
1242 static int files_rename_ref(struct ref_store *ref_store,
1243 const char *oldrefname, const char *newrefname,
1246 struct files_ref_store *refs =
1247 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1248 struct object_id oid, orig_oid;
1249 int flag = 0, logmoved = 0;
1250 struct ref_lock *lock;
1251 struct stat loginfo;
1252 struct strbuf sb_oldref = STRBUF_INIT;
1253 struct strbuf sb_newref = STRBUF_INIT;
1254 struct strbuf tmp_renamed_log = STRBUF_INIT;
1256 struct strbuf err = STRBUF_INIT;
1258 files_reflog_path(refs, &sb_oldref, oldrefname);
1259 files_reflog_path(refs, &sb_newref, newrefname);
1260 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1262 log = !lstat(sb_oldref.buf, &loginfo);
1263 if (log && S_ISLNK(loginfo.st_mode)) {
1264 ret = error("reflog for %s is a symlink", oldrefname);
1268 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1269 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1270 orig_oid.hash, &flag)) {
1271 ret = error("refname %s not found", oldrefname);
1275 if (flag & REF_ISSYMREF) {
1276 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1280 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1285 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1286 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1287 oldrefname, strerror(errno));
1291 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1292 orig_oid.hash, REF_NODEREF)) {
1293 error("unable to delete old %s", oldrefname);
1298 * Since we are doing a shallow lookup, oid is not the
1299 * correct value to pass to delete_ref as old_oid. But that
1300 * doesn't matter, because an old_oid check wouldn't add to
1301 * the safety anyway; we want to delete the reference whatever
1302 * its current value.
1304 if (!refs_read_ref_full(&refs->base, newrefname,
1305 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1307 refs_delete_ref(&refs->base, NULL, newrefname,
1308 NULL, REF_NODEREF)) {
1309 if (errno == EISDIR) {
1310 struct strbuf path = STRBUF_INIT;
1313 files_ref_path(refs, &path, newrefname);
1314 result = remove_empty_directories(&path);
1315 strbuf_release(&path);
1318 error("Directory not empty: %s", newrefname);
1322 error("unable to delete existing %s", newrefname);
1327 if (log && rename_tmp_log(refs, newrefname))
1332 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1333 REF_NODEREF, NULL, &err);
1335 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1336 strbuf_release(&err);
1339 oidcpy(&lock->old_oid, &orig_oid);
1341 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1342 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1343 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1344 strbuf_release(&err);
1352 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1353 REF_NODEREF, NULL, &err);
1355 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1356 strbuf_release(&err);
1360 flag = log_all_ref_updates;
1361 log_all_ref_updates = LOG_REFS_NONE;
1362 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1363 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1364 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1365 strbuf_release(&err);
1367 log_all_ref_updates = flag;
1370 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1371 error("unable to restore logfile %s from %s: %s",
1372 oldrefname, newrefname, strerror(errno));
1373 if (!logmoved && log &&
1374 rename(tmp_renamed_log.buf, sb_oldref.buf))
1375 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1376 oldrefname, strerror(errno));
1379 strbuf_release(&sb_newref);
1380 strbuf_release(&sb_oldref);
1381 strbuf_release(&tmp_renamed_log);
1386 static int close_ref(struct ref_lock *lock)
1388 if (close_lock_file(lock->lk))
1393 static int commit_ref(struct ref_lock *lock)
1395 char *path = get_locked_file_path(lock->lk);
1398 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1400 * There is a directory at the path we want to rename
1401 * the lockfile to. Hopefully it is empty; try to
1404 size_t len = strlen(path);
1405 struct strbuf sb_path = STRBUF_INIT;
1407 strbuf_attach(&sb_path, path, len, len);
1410 * If this fails, commit_lock_file() will also fail
1411 * and will report the problem.
1413 remove_empty_directories(&sb_path);
1414 strbuf_release(&sb_path);
1419 if (commit_lock_file(lock->lk))
1424 static int open_or_create_logfile(const char *path, void *cb)
1428 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1429 return (*fd < 0) ? -1 : 0;
1433 * Create a reflog for a ref. If force_create = 0, only create the
1434 * reflog for certain refs (those for which should_autocreate_reflog
1435 * returns non-zero). Otherwise, create it regardless of the reference
1436 * name. If the logfile already existed or was created, return 0 and
1437 * set *logfd to the file descriptor opened for appending to the file.
1438 * If no logfile exists and we decided not to create one, return 0 and
1439 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1442 static int log_ref_setup(struct files_ref_store *refs,
1443 const char *refname, int force_create,
1444 int *logfd, struct strbuf *err)
1446 struct strbuf logfile_sb = STRBUF_INIT;
1449 files_reflog_path(refs, &logfile_sb, refname);
1450 logfile = strbuf_detach(&logfile_sb, NULL);
1452 if (force_create || should_autocreate_reflog(refname)) {
1453 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1454 if (errno == ENOENT)
1455 strbuf_addf(err, "unable to create directory for '%s': "
1456 "%s", logfile, strerror(errno));
1457 else if (errno == EISDIR)
1458 strbuf_addf(err, "there are still logs under '%s'",
1461 strbuf_addf(err, "unable to append to '%s': %s",
1462 logfile, strerror(errno));
1467 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1469 if (errno == ENOENT || errno == EISDIR) {
1471 * The logfile doesn't already exist,
1472 * but that is not an error; it only
1473 * means that we won't write log
1478 strbuf_addf(err, "unable to append to '%s': %s",
1479 logfile, strerror(errno));
1486 adjust_shared_perm(logfile);
1496 static int files_create_reflog(struct ref_store *ref_store,
1497 const char *refname, int force_create,
1500 struct files_ref_store *refs =
1501 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1504 if (log_ref_setup(refs, refname, force_create, &fd, err))
1513 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1514 const struct object_id *new_oid,
1515 const char *committer, const char *msg)
1517 int msglen, written;
1518 unsigned maxlen, len;
1521 msglen = msg ? strlen(msg) : 0;
1522 maxlen = strlen(committer) + msglen + 100;
1523 logrec = xmalloc(maxlen);
1524 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1525 oid_to_hex(old_oid),
1526 oid_to_hex(new_oid),
1529 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1531 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
1539 static int files_log_ref_write(struct files_ref_store *refs,
1540 const char *refname, const struct object_id *old_oid,
1541 const struct object_id *new_oid, const char *msg,
1542 int flags, struct strbuf *err)
1546 if (log_all_ref_updates == LOG_REFS_UNSET)
1547 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1549 result = log_ref_setup(refs, refname,
1550 flags & REF_FORCE_CREATE_REFLOG,
1558 result = log_ref_write_fd(logfd, old_oid, new_oid,
1559 git_committer_info(0), msg);
1561 struct strbuf sb = STRBUF_INIT;
1562 int save_errno = errno;
1564 files_reflog_path(refs, &sb, refname);
1565 strbuf_addf(err, "unable to append to '%s': %s",
1566 sb.buf, strerror(save_errno));
1567 strbuf_release(&sb);
1572 struct strbuf sb = STRBUF_INIT;
1573 int save_errno = errno;
1575 files_reflog_path(refs, &sb, refname);
1576 strbuf_addf(err, "unable to append to '%s': %s",
1577 sb.buf, strerror(save_errno));
1578 strbuf_release(&sb);
1585 * Write sha1 into the open lockfile, then close the lockfile. On
1586 * errors, rollback the lockfile, fill in *err and
1589 static int write_ref_to_lockfile(struct ref_lock *lock,
1590 const struct object_id *oid, struct strbuf *err)
1592 static char term = '\n';
1596 o = parse_object(oid);
1599 "trying to write ref '%s' with nonexistent object %s",
1600 lock->ref_name, oid_to_hex(oid));
1604 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1606 "trying to write non-commit object %s to branch '%s'",
1607 oid_to_hex(oid), lock->ref_name);
1611 fd = get_lock_file_fd(lock->lk);
1612 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
1613 write_in_full(fd, &term, 1) != 1 ||
1614 close_ref(lock) < 0) {
1616 "couldn't write '%s'", get_lock_file_path(lock->lk));
1624 * Commit a change to a loose reference that has already been written
1625 * to the loose reference lockfile. Also update the reflogs if
1626 * necessary, using the specified lockmsg (which can be NULL).
1628 static int commit_ref_update(struct files_ref_store *refs,
1629 struct ref_lock *lock,
1630 const struct object_id *oid, const char *logmsg,
1633 files_assert_main_repository(refs, "commit_ref_update");
1635 clear_loose_ref_cache(refs);
1636 if (files_log_ref_write(refs, lock->ref_name,
1637 &lock->old_oid, oid,
1639 char *old_msg = strbuf_detach(err, NULL);
1640 strbuf_addf(err, "cannot update the ref '%s': %s",
1641 lock->ref_name, old_msg);
1647 if (strcmp(lock->ref_name, "HEAD") != 0) {
1649 * Special hack: If a branch is updated directly and HEAD
1650 * points to it (may happen on the remote side of a push
1651 * for example) then logically the HEAD reflog should be
1653 * A generic solution implies reverse symref information,
1654 * but finding all symrefs pointing to the given branch
1655 * would be rather costly for this rare event (the direct
1656 * update of a branch) to be worth it. So let's cheat and
1657 * check with HEAD only which should cover 99% of all usage
1658 * scenarios (even 100% of the default ones).
1660 struct object_id head_oid;
1662 const char *head_ref;
1664 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1665 RESOLVE_REF_READING,
1666 head_oid.hash, &head_flag);
1667 if (head_ref && (head_flag & REF_ISSYMREF) &&
1668 !strcmp(head_ref, lock->ref_name)) {
1669 struct strbuf log_err = STRBUF_INIT;
1670 if (files_log_ref_write(refs, "HEAD",
1671 &lock->old_oid, oid,
1672 logmsg, 0, &log_err)) {
1673 error("%s", log_err.buf);
1674 strbuf_release(&log_err);
1679 if (commit_ref(lock)) {
1680 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1689 static int create_ref_symlink(struct ref_lock *lock, const char *target)
1692 #ifndef NO_SYMLINK_HEAD
1693 char *ref_path = get_locked_file_path(lock->lk);
1695 ret = symlink(target, ref_path);
1699 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1704 static void update_symref_reflog(struct files_ref_store *refs,
1705 struct ref_lock *lock, const char *refname,
1706 const char *target, const char *logmsg)
1708 struct strbuf err = STRBUF_INIT;
1709 struct object_id new_oid;
1711 !refs_read_ref_full(&refs->base, target,
1712 RESOLVE_REF_READING, new_oid.hash, NULL) &&
1713 files_log_ref_write(refs, refname, &lock->old_oid,
1714 &new_oid, logmsg, 0, &err)) {
1715 error("%s", err.buf);
1716 strbuf_release(&err);
1720 static int create_symref_locked(struct files_ref_store *refs,
1721 struct ref_lock *lock, const char *refname,
1722 const char *target, const char *logmsg)
1724 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1725 update_symref_reflog(refs, lock, refname, target, logmsg);
1729 if (!fdopen_lock_file(lock->lk, "w"))
1730 return error("unable to fdopen %s: %s",
1731 lock->lk->tempfile.filename.buf, strerror(errno));
1733 update_symref_reflog(refs, lock, refname, target, logmsg);
1735 /* no error check; commit_ref will check ferror */
1736 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
1737 if (commit_ref(lock) < 0)
1738 return error("unable to write symref for %s: %s", refname,
1743 static int files_create_symref(struct ref_store *ref_store,
1744 const char *refname, const char *target,
1747 struct files_ref_store *refs =
1748 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1749 struct strbuf err = STRBUF_INIT;
1750 struct ref_lock *lock;
1753 lock = lock_ref_sha1_basic(refs, refname, NULL,
1754 NULL, NULL, REF_NODEREF, NULL,
1757 error("%s", err.buf);
1758 strbuf_release(&err);
1762 ret = create_symref_locked(refs, lock, refname, target, logmsg);
1767 static int files_reflog_exists(struct ref_store *ref_store,
1768 const char *refname)
1770 struct files_ref_store *refs =
1771 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1772 struct strbuf sb = STRBUF_INIT;
1776 files_reflog_path(refs, &sb, refname);
1777 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1778 strbuf_release(&sb);
1782 static int files_delete_reflog(struct ref_store *ref_store,
1783 const char *refname)
1785 struct files_ref_store *refs =
1786 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1787 struct strbuf sb = STRBUF_INIT;
1790 files_reflog_path(refs, &sb, refname);
1791 ret = remove_path(sb.buf);
1792 strbuf_release(&sb);
1796 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1798 struct object_id ooid, noid;
1799 char *email_end, *message;
1800 timestamp_t timestamp;
1802 const char *p = sb->buf;
1804 /* old SP new SP name <email> SP time TAB msg LF */
1805 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1806 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1807 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1808 !(email_end = strchr(p, '>')) ||
1809 email_end[1] != ' ' ||
1810 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1811 !message || message[0] != ' ' ||
1812 (message[1] != '+' && message[1] != '-') ||
1813 !isdigit(message[2]) || !isdigit(message[3]) ||
1814 !isdigit(message[4]) || !isdigit(message[5]))
1815 return 0; /* corrupt? */
1816 email_end[1] = '\0';
1817 tz = strtol(message + 1, NULL, 10);
1818 if (message[6] != '\t')
1822 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1825 static char *find_beginning_of_line(char *bob, char *scan)
1827 while (bob < scan && *(--scan) != '\n')
1828 ; /* keep scanning backwards */
1830 * Return either beginning of the buffer, or LF at the end of
1831 * the previous line.
1836 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1837 const char *refname,
1838 each_reflog_ent_fn fn,
1841 struct files_ref_store *refs =
1842 files_downcast(ref_store, REF_STORE_READ,
1843 "for_each_reflog_ent_reverse");
1844 struct strbuf sb = STRBUF_INIT;
1847 int ret = 0, at_tail = 1;
1849 files_reflog_path(refs, &sb, refname);
1850 logfp = fopen(sb.buf, "r");
1851 strbuf_release(&sb);
1855 /* Jump to the end */
1856 if (fseek(logfp, 0, SEEK_END) < 0)
1857 ret = error("cannot seek back reflog for %s: %s",
1858 refname, strerror(errno));
1860 while (!ret && 0 < pos) {
1866 /* Fill next block from the end */
1867 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1868 if (fseek(logfp, pos - cnt, SEEK_SET)) {
1869 ret = error("cannot seek back reflog for %s: %s",
1870 refname, strerror(errno));
1873 nread = fread(buf, cnt, 1, logfp);
1875 ret = error("cannot read %d bytes from reflog for %s: %s",
1876 cnt, refname, strerror(errno));
1881 scanp = endp = buf + cnt;
1882 if (at_tail && scanp[-1] == '\n')
1883 /* Looking at the final LF at the end of the file */
1887 while (buf < scanp) {
1889 * terminating LF of the previous line, or the beginning
1894 bp = find_beginning_of_line(buf, scanp);
1898 * The newline is the end of the previous line,
1899 * so we know we have complete line starting
1900 * at (bp + 1). Prefix it onto any prior data
1901 * we collected for the line and process it.
1903 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1906 ret = show_one_reflog_ent(&sb, fn, cb_data);
1912 * We are at the start of the buffer, and the
1913 * start of the file; there is no previous
1914 * line, and we have everything for this one.
1915 * Process it, and we can end the loop.
1917 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1918 ret = show_one_reflog_ent(&sb, fn, cb_data);
1925 * We are at the start of the buffer, and there
1926 * is more file to read backwards. Which means
1927 * we are in the middle of a line. Note that we
1928 * may get here even if *bp was a newline; that
1929 * just means we are at the exact end of the
1930 * previous line, rather than some spot in the
1933 * Save away what we have to be combined with
1934 * the data from the next read.
1936 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1943 die("BUG: reverse reflog parser had leftover data");
1946 strbuf_release(&sb);
1950 static int files_for_each_reflog_ent(struct ref_store *ref_store,
1951 const char *refname,
1952 each_reflog_ent_fn fn, void *cb_data)
1954 struct files_ref_store *refs =
1955 files_downcast(ref_store, REF_STORE_READ,
1956 "for_each_reflog_ent");
1958 struct strbuf sb = STRBUF_INIT;
1961 files_reflog_path(refs, &sb, refname);
1962 logfp = fopen(sb.buf, "r");
1963 strbuf_release(&sb);
1967 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
1968 ret = show_one_reflog_ent(&sb, fn, cb_data);
1970 strbuf_release(&sb);
1974 struct files_reflog_iterator {
1975 struct ref_iterator base;
1977 struct ref_store *ref_store;
1978 struct dir_iterator *dir_iterator;
1979 struct object_id oid;
1982 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
1984 struct files_reflog_iterator *iter =
1985 (struct files_reflog_iterator *)ref_iterator;
1986 struct dir_iterator *diter = iter->dir_iterator;
1989 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
1992 if (!S_ISREG(diter->st.st_mode))
1994 if (diter->basename[0] == '.')
1996 if (ends_with(diter->basename, ".lock"))
1999 if (refs_read_ref_full(iter->ref_store,
2000 diter->relative_path, 0,
2001 iter->oid.hash, &flags)) {
2002 error("bad ref for %s", diter->path.buf);
2006 iter->base.refname = diter->relative_path;
2007 iter->base.oid = &iter->oid;
2008 iter->base.flags = flags;
2012 iter->dir_iterator = NULL;
2013 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2018 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2019 struct object_id *peeled)
2021 die("BUG: ref_iterator_peel() called for reflog_iterator");
2024 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2026 struct files_reflog_iterator *iter =
2027 (struct files_reflog_iterator *)ref_iterator;
2030 if (iter->dir_iterator)
2031 ok = dir_iterator_abort(iter->dir_iterator);
2033 base_ref_iterator_free(ref_iterator);
2037 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2038 files_reflog_iterator_advance,
2039 files_reflog_iterator_peel,
2040 files_reflog_iterator_abort
2043 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2045 struct files_ref_store *refs =
2046 files_downcast(ref_store, REF_STORE_READ,
2047 "reflog_iterator_begin");
2048 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2049 struct ref_iterator *ref_iterator = &iter->base;
2050 struct strbuf sb = STRBUF_INIT;
2052 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable, 0);
2053 files_reflog_path(refs, &sb, NULL);
2054 iter->dir_iterator = dir_iterator_begin(sb.buf);
2055 iter->ref_store = ref_store;
2056 strbuf_release(&sb);
2057 return ref_iterator;
2061 * If update is a direct update of head_ref (the reference pointed to
2062 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2064 static int split_head_update(struct ref_update *update,
2065 struct ref_transaction *transaction,
2066 const char *head_ref,
2067 struct string_list *affected_refnames,
2070 struct string_list_item *item;
2071 struct ref_update *new_update;
2073 if ((update->flags & REF_LOG_ONLY) ||
2074 (update->flags & REF_ISPRUNING) ||
2075 (update->flags & REF_UPDATE_VIA_HEAD))
2078 if (strcmp(update->refname, head_ref))
2082 * First make sure that HEAD is not already in the
2083 * transaction. This insertion is O(N) in the transaction
2084 * size, but it happens at most once per transaction.
2086 item = string_list_insert(affected_refnames, "HEAD");
2088 /* An entry already existed */
2090 "multiple updates for 'HEAD' (including one "
2091 "via its referent '%s') are not allowed",
2093 return TRANSACTION_NAME_CONFLICT;
2096 new_update = ref_transaction_add_update(
2097 transaction, "HEAD",
2098 update->flags | REF_LOG_ONLY | REF_NODEREF,
2099 update->new_oid.hash, update->old_oid.hash,
2102 item->util = new_update;
2108 * update is for a symref that points at referent and doesn't have
2109 * REF_NODEREF set. Split it into two updates:
2110 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2111 * - A new, separate update for the referent reference
2112 * Note that the new update will itself be subject to splitting when
2113 * the iteration gets to it.
2115 static int split_symref_update(struct files_ref_store *refs,
2116 struct ref_update *update,
2117 const char *referent,
2118 struct ref_transaction *transaction,
2119 struct string_list *affected_refnames,
2122 struct string_list_item *item;
2123 struct ref_update *new_update;
2124 unsigned int new_flags;
2127 * First make sure that referent is not already in the
2128 * transaction. This insertion is O(N) in the transaction
2129 * size, but it happens at most once per symref in a
2132 item = string_list_insert(affected_refnames, referent);
2134 /* An entry already existed */
2136 "multiple updates for '%s' (including one "
2137 "via symref '%s') are not allowed",
2138 referent, update->refname);
2139 return TRANSACTION_NAME_CONFLICT;
2142 new_flags = update->flags;
2143 if (!strcmp(update->refname, "HEAD")) {
2145 * Record that the new update came via HEAD, so that
2146 * when we process it, split_head_update() doesn't try
2147 * to add another reflog update for HEAD. Note that
2148 * this bit will be propagated if the new_update
2149 * itself needs to be split.
2151 new_flags |= REF_UPDATE_VIA_HEAD;
2154 new_update = ref_transaction_add_update(
2155 transaction, referent, new_flags,
2156 update->new_oid.hash, update->old_oid.hash,
2159 new_update->parent_update = update;
2162 * Change the symbolic ref update to log only. Also, it
2163 * doesn't need to check its old SHA-1 value, as that will be
2164 * done when new_update is processed.
2166 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2167 update->flags &= ~REF_HAVE_OLD;
2169 item->util = new_update;
2175 * Return the refname under which update was originally requested.
2177 static const char *original_update_refname(struct ref_update *update)
2179 while (update->parent_update)
2180 update = update->parent_update;
2182 return update->refname;
2186 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2187 * are consistent with oid, which is the reference's current value. If
2188 * everything is OK, return 0; otherwise, write an error message to
2189 * err and return -1.
2191 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2194 if (!(update->flags & REF_HAVE_OLD) ||
2195 !oidcmp(oid, &update->old_oid))
2198 if (is_null_oid(&update->old_oid))
2199 strbuf_addf(err, "cannot lock ref '%s': "
2200 "reference already exists",
2201 original_update_refname(update));
2202 else if (is_null_oid(oid))
2203 strbuf_addf(err, "cannot lock ref '%s': "
2204 "reference is missing but expected %s",
2205 original_update_refname(update),
2206 oid_to_hex(&update->old_oid));
2208 strbuf_addf(err, "cannot lock ref '%s': "
2209 "is at %s but expected %s",
2210 original_update_refname(update),
2212 oid_to_hex(&update->old_oid));
2218 * Prepare for carrying out update:
2219 * - Lock the reference referred to by update.
2220 * - Read the reference under lock.
2221 * - Check that its old SHA-1 value (if specified) is correct, and in
2222 * any case record it in update->lock->old_oid for later use when
2223 * writing the reflog.
2224 * - If it is a symref update without REF_NODEREF, split it up into a
2225 * REF_LOG_ONLY update of the symref and add a separate update for
2226 * the referent to transaction.
2227 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2230 static int lock_ref_for_update(struct files_ref_store *refs,
2231 struct ref_update *update,
2232 struct ref_transaction *transaction,
2233 const char *head_ref,
2234 struct string_list *affected_refnames,
2237 struct strbuf referent = STRBUF_INIT;
2238 int mustexist = (update->flags & REF_HAVE_OLD) &&
2239 !is_null_oid(&update->old_oid);
2241 struct ref_lock *lock;
2243 files_assert_main_repository(refs, "lock_ref_for_update");
2245 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2246 update->flags |= REF_DELETING;
2249 ret = split_head_update(update, transaction, head_ref,
2250 affected_refnames, err);
2255 ret = lock_raw_ref(refs, update->refname, mustexist,
2256 affected_refnames, NULL,
2258 &update->type, err);
2262 reason = strbuf_detach(err, NULL);
2263 strbuf_addf(err, "cannot lock ref '%s': %s",
2264 original_update_refname(update), reason);
2269 update->backend_data = lock;
2271 if (update->type & REF_ISSYMREF) {
2272 if (update->flags & REF_NODEREF) {
2274 * We won't be reading the referent as part of
2275 * the transaction, so we have to read it here
2276 * to record and possibly check old_sha1:
2278 if (refs_read_ref_full(&refs->base,
2280 lock->old_oid.hash, NULL)) {
2281 if (update->flags & REF_HAVE_OLD) {
2282 strbuf_addf(err, "cannot lock ref '%s': "
2283 "error reading reference",
2284 original_update_refname(update));
2287 } else if (check_old_oid(update, &lock->old_oid, err)) {
2288 return TRANSACTION_GENERIC_ERROR;
2292 * Create a new update for the reference this
2293 * symref is pointing at. Also, we will record
2294 * and verify old_sha1 for this update as part
2295 * of processing the split-off update, so we
2296 * don't have to do it here.
2298 ret = split_symref_update(refs, update,
2299 referent.buf, transaction,
2300 affected_refnames, err);
2305 struct ref_update *parent_update;
2307 if (check_old_oid(update, &lock->old_oid, err))
2308 return TRANSACTION_GENERIC_ERROR;
2311 * If this update is happening indirectly because of a
2312 * symref update, record the old SHA-1 in the parent
2315 for (parent_update = update->parent_update;
2317 parent_update = parent_update->parent_update) {
2318 struct ref_lock *parent_lock = parent_update->backend_data;
2319 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2323 if ((update->flags & REF_HAVE_NEW) &&
2324 !(update->flags & REF_DELETING) &&
2325 !(update->flags & REF_LOG_ONLY)) {
2326 if (!(update->type & REF_ISSYMREF) &&
2327 !oidcmp(&lock->old_oid, &update->new_oid)) {
2329 * The reference already has the desired
2330 * value, so we don't need to write it.
2332 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2334 char *write_err = strbuf_detach(err, NULL);
2337 * The lock was freed upon failure of
2338 * write_ref_to_lockfile():
2340 update->backend_data = NULL;
2342 "cannot update ref '%s': %s",
2343 update->refname, write_err);
2345 return TRANSACTION_GENERIC_ERROR;
2347 update->flags |= REF_NEEDS_COMMIT;
2350 if (!(update->flags & REF_NEEDS_COMMIT)) {
2352 * We didn't call write_ref_to_lockfile(), so
2353 * the lockfile is still open. Close it to
2354 * free up the file descriptor:
2356 if (close_ref(lock)) {
2357 strbuf_addf(err, "couldn't close '%s.lock'",
2359 return TRANSACTION_GENERIC_ERROR;
2365 struct files_transaction_backend_data {
2366 struct ref_transaction *packed_transaction;
2367 int packed_refs_locked;
2371 * Unlock any references in `transaction` that are still locked, and
2372 * mark the transaction closed.
2374 static void files_transaction_cleanup(struct files_ref_store *refs,
2375 struct ref_transaction *transaction)
2378 struct files_transaction_backend_data *backend_data =
2379 transaction->backend_data;
2380 struct strbuf err = STRBUF_INIT;
2382 for (i = 0; i < transaction->nr; i++) {
2383 struct ref_update *update = transaction->updates[i];
2384 struct ref_lock *lock = update->backend_data;
2388 update->backend_data = NULL;
2392 if (backend_data->packed_transaction &&
2393 ref_transaction_abort(backend_data->packed_transaction, &err)) {
2394 error("error aborting transaction: %s", err.buf);
2395 strbuf_release(&err);
2398 if (backend_data->packed_refs_locked)
2399 packed_refs_unlock(refs->packed_ref_store);
2403 transaction->state = REF_TRANSACTION_CLOSED;
2406 static int files_transaction_prepare(struct ref_store *ref_store,
2407 struct ref_transaction *transaction,
2410 struct files_ref_store *refs =
2411 files_downcast(ref_store, REF_STORE_WRITE,
2412 "ref_transaction_prepare");
2415 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2416 char *head_ref = NULL;
2418 struct object_id head_oid;
2419 struct files_transaction_backend_data *backend_data;
2420 struct ref_transaction *packed_transaction = NULL;
2424 if (!transaction->nr)
2427 backend_data = xcalloc(1, sizeof(*backend_data));
2428 transaction->backend_data = backend_data;
2431 * Fail if a refname appears more than once in the
2432 * transaction. (If we end up splitting up any updates using
2433 * split_symref_update() or split_head_update(), those
2434 * functions will check that the new updates don't have the
2435 * same refname as any existing ones.)
2437 for (i = 0; i < transaction->nr; i++) {
2438 struct ref_update *update = transaction->updates[i];
2439 struct string_list_item *item =
2440 string_list_append(&affected_refnames, update->refname);
2443 * We store a pointer to update in item->util, but at
2444 * the moment we never use the value of this field
2445 * except to check whether it is non-NULL.
2447 item->util = update;
2449 string_list_sort(&affected_refnames);
2450 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2451 ret = TRANSACTION_GENERIC_ERROR;
2456 * Special hack: If a branch is updated directly and HEAD
2457 * points to it (may happen on the remote side of a push
2458 * for example) then logically the HEAD reflog should be
2461 * A generic solution would require reverse symref lookups,
2462 * but finding all symrefs pointing to a given branch would be
2463 * rather costly for this rare event (the direct update of a
2464 * branch) to be worth it. So let's cheat and check with HEAD
2465 * only, which should cover 99% of all usage scenarios (even
2466 * 100% of the default ones).
2468 * So if HEAD is a symbolic reference, then record the name of
2469 * the reference that it points to. If we see an update of
2470 * head_ref within the transaction, then split_head_update()
2471 * arranges for the reflog of HEAD to be updated, too.
2473 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2474 RESOLVE_REF_NO_RECURSE,
2475 head_oid.hash, &head_type);
2477 if (head_ref && !(head_type & REF_ISSYMREF)) {
2478 FREE_AND_NULL(head_ref);
2482 * Acquire all locks, verify old values if provided, check
2483 * that new values are valid, and write new values to the
2484 * lockfiles, ready to be activated. Only keep one lockfile
2485 * open at a time to avoid running out of file descriptors.
2486 * Note that lock_ref_for_update() might append more updates
2487 * to the transaction.
2489 for (i = 0; i < transaction->nr; i++) {
2490 struct ref_update *update = transaction->updates[i];
2492 ret = lock_ref_for_update(refs, update, transaction,
2493 head_ref, &affected_refnames, err);
2497 if (update->flags & REF_DELETING &&
2498 !(update->flags & REF_LOG_ONLY) &&
2499 !(update->flags & REF_ISPRUNING)) {
2501 * This reference has to be deleted from
2502 * packed-refs if it exists there.
2504 if (!packed_transaction) {
2505 packed_transaction = ref_store_transaction_begin(
2506 refs->packed_ref_store, err);
2507 if (!packed_transaction) {
2508 ret = TRANSACTION_GENERIC_ERROR;
2512 backend_data->packed_transaction =
2516 ref_transaction_add_update(
2517 packed_transaction, update->refname,
2518 update->flags & ~REF_HAVE_OLD,
2519 update->new_oid.hash, update->old_oid.hash,
2524 if (packed_transaction) {
2525 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2526 ret = TRANSACTION_GENERIC_ERROR;
2529 backend_data->packed_refs_locked = 1;
2530 ret = ref_transaction_prepare(packed_transaction, err);
2535 string_list_clear(&affected_refnames, 0);
2538 files_transaction_cleanup(refs, transaction);
2540 transaction->state = REF_TRANSACTION_PREPARED;
2545 static int files_transaction_finish(struct ref_store *ref_store,
2546 struct ref_transaction *transaction,
2549 struct files_ref_store *refs =
2550 files_downcast(ref_store, 0, "ref_transaction_finish");
2553 struct strbuf sb = STRBUF_INIT;
2554 struct files_transaction_backend_data *backend_data;
2555 struct ref_transaction *packed_transaction;
2560 if (!transaction->nr) {
2561 transaction->state = REF_TRANSACTION_CLOSED;
2565 backend_data = transaction->backend_data;
2566 packed_transaction = backend_data->packed_transaction;
2568 /* Perform updates first so live commits remain referenced */
2569 for (i = 0; i < transaction->nr; i++) {
2570 struct ref_update *update = transaction->updates[i];
2571 struct ref_lock *lock = update->backend_data;
2573 if (update->flags & REF_NEEDS_COMMIT ||
2574 update->flags & REF_LOG_ONLY) {
2575 if (files_log_ref_write(refs,
2579 update->msg, update->flags,
2581 char *old_msg = strbuf_detach(err, NULL);
2583 strbuf_addf(err, "cannot update the ref '%s': %s",
2584 lock->ref_name, old_msg);
2587 update->backend_data = NULL;
2588 ret = TRANSACTION_GENERIC_ERROR;
2592 if (update->flags & REF_NEEDS_COMMIT) {
2593 clear_loose_ref_cache(refs);
2594 if (commit_ref(lock)) {
2595 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2597 update->backend_data = NULL;
2598 ret = TRANSACTION_GENERIC_ERROR;
2605 * Now that updates are safely completed, we can perform
2606 * deletes. First delete the reflogs of any references that
2607 * will be deleted, since (in the unexpected event of an
2608 * error) leaving a reference without a reflog is less bad
2609 * than leaving a reflog without a reference (the latter is a
2610 * mildly invalid repository state):
2612 for (i = 0; i < transaction->nr; i++) {
2613 struct ref_update *update = transaction->updates[i];
2614 if (update->flags & REF_DELETING &&
2615 !(update->flags & REF_LOG_ONLY) &&
2616 !(update->flags & REF_ISPRUNING)) {
2618 files_reflog_path(refs, &sb, update->refname);
2619 if (!unlink_or_warn(sb.buf))
2620 try_remove_empty_parents(refs, update->refname,
2621 REMOVE_EMPTY_PARENTS_REFLOG);
2626 * Perform deletes now that updates are safely completed.
2628 * First delete any packed versions of the references, while
2629 * retaining the packed-refs lock:
2631 if (packed_transaction) {
2632 ret = ref_transaction_commit(packed_transaction, err);
2633 ref_transaction_free(packed_transaction);
2634 packed_transaction = NULL;
2635 backend_data->packed_transaction = NULL;
2640 /* Now delete the loose versions of the references: */
2641 for (i = 0; i < transaction->nr; i++) {
2642 struct ref_update *update = transaction->updates[i];
2643 struct ref_lock *lock = update->backend_data;
2645 if (update->flags & REF_DELETING &&
2646 !(update->flags & REF_LOG_ONLY)) {
2647 if (!(update->type & REF_ISPACKED) ||
2648 update->type & REF_ISSYMREF) {
2649 /* It is a loose reference. */
2651 files_ref_path(refs, &sb, lock->ref_name);
2652 if (unlink_or_msg(sb.buf, err)) {
2653 ret = TRANSACTION_GENERIC_ERROR;
2656 update->flags |= REF_DELETED_LOOSE;
2661 clear_loose_ref_cache(refs);
2664 files_transaction_cleanup(refs, transaction);
2666 for (i = 0; i < transaction->nr; i++) {
2667 struct ref_update *update = transaction->updates[i];
2669 if (update->flags & REF_DELETED_LOOSE) {
2671 * The loose reference was deleted. Delete any
2672 * empty parent directories. (Note that this
2673 * can only work because we have already
2674 * removed the lockfile.)
2676 try_remove_empty_parents(refs, update->refname,
2677 REMOVE_EMPTY_PARENTS_REF);
2681 strbuf_release(&sb);
2685 static int files_transaction_abort(struct ref_store *ref_store,
2686 struct ref_transaction *transaction,
2689 struct files_ref_store *refs =
2690 files_downcast(ref_store, 0, "ref_transaction_abort");
2692 files_transaction_cleanup(refs, transaction);
2696 static int ref_present(const char *refname,
2697 const struct object_id *oid, int flags, void *cb_data)
2699 struct string_list *affected_refnames = cb_data;
2701 return string_list_has_string(affected_refnames, refname);
2704 static int files_initial_transaction_commit(struct ref_store *ref_store,
2705 struct ref_transaction *transaction,
2708 struct files_ref_store *refs =
2709 files_downcast(ref_store, REF_STORE_WRITE,
2710 "initial_ref_transaction_commit");
2713 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2714 struct ref_transaction *packed_transaction = NULL;
2718 if (transaction->state != REF_TRANSACTION_OPEN)
2719 die("BUG: commit called for transaction that is not open");
2721 /* Fail if a refname appears more than once in the transaction: */
2722 for (i = 0; i < transaction->nr; i++)
2723 string_list_append(&affected_refnames,
2724 transaction->updates[i]->refname);
2725 string_list_sort(&affected_refnames);
2726 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2727 ret = TRANSACTION_GENERIC_ERROR;
2732 * It's really undefined to call this function in an active
2733 * repository or when there are existing references: we are
2734 * only locking and changing packed-refs, so (1) any
2735 * simultaneous processes might try to change a reference at
2736 * the same time we do, and (2) any existing loose versions of
2737 * the references that we are setting would have precedence
2738 * over our values. But some remote helpers create the remote
2739 * "HEAD" and "master" branches before calling this function,
2740 * so here we really only check that none of the references
2741 * that we are creating already exists.
2743 if (refs_for_each_rawref(&refs->base, ref_present,
2744 &affected_refnames))
2745 die("BUG: initial ref transaction called with existing refs");
2747 packed_transaction = ref_store_transaction_begin(refs->packed_ref_store, err);
2748 if (!packed_transaction) {
2749 ret = TRANSACTION_GENERIC_ERROR;
2753 for (i = 0; i < transaction->nr; i++) {
2754 struct ref_update *update = transaction->updates[i];
2756 if ((update->flags & REF_HAVE_OLD) &&
2757 !is_null_oid(&update->old_oid))
2758 die("BUG: initial ref transaction with old_sha1 set");
2759 if (refs_verify_refname_available(&refs->base, update->refname,
2760 &affected_refnames, NULL,
2762 ret = TRANSACTION_NAME_CONFLICT;
2767 * Add a reference creation for this reference to the
2768 * packed-refs transaction:
2770 ref_transaction_add_update(packed_transaction, update->refname,
2771 update->flags & ~REF_HAVE_OLD,
2772 update->new_oid.hash, update->old_oid.hash,
2776 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2777 ret = TRANSACTION_GENERIC_ERROR;
2781 if (initial_ref_transaction_commit(packed_transaction, err)) {
2782 ret = TRANSACTION_GENERIC_ERROR;
2787 if (packed_transaction)
2788 ref_transaction_free(packed_transaction);
2789 packed_refs_unlock(refs->packed_ref_store);
2790 transaction->state = REF_TRANSACTION_CLOSED;
2791 string_list_clear(&affected_refnames, 0);
2795 struct expire_reflog_cb {
2797 reflog_expiry_should_prune_fn *should_prune_fn;
2800 struct object_id last_kept_oid;
2803 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
2804 const char *email, timestamp_t timestamp, int tz,
2805 const char *message, void *cb_data)
2807 struct expire_reflog_cb *cb = cb_data;
2808 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
2810 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
2811 ooid = &cb->last_kept_oid;
2813 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
2814 message, policy_cb)) {
2816 printf("would prune %s", message);
2817 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2818 printf("prune %s", message);
2821 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
2822 oid_to_hex(ooid), oid_to_hex(noid),
2823 email, timestamp, tz, message);
2824 oidcpy(&cb->last_kept_oid, noid);
2826 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2827 printf("keep %s", message);
2832 static int files_reflog_expire(struct ref_store *ref_store,
2833 const char *refname, const unsigned char *sha1,
2835 reflog_expiry_prepare_fn prepare_fn,
2836 reflog_expiry_should_prune_fn should_prune_fn,
2837 reflog_expiry_cleanup_fn cleanup_fn,
2838 void *policy_cb_data)
2840 struct files_ref_store *refs =
2841 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
2842 static struct lock_file reflog_lock;
2843 struct expire_reflog_cb cb;
2844 struct ref_lock *lock;
2845 struct strbuf log_file_sb = STRBUF_INIT;
2849 struct strbuf err = STRBUF_INIT;
2850 struct object_id oid;
2852 memset(&cb, 0, sizeof(cb));
2854 cb.policy_cb = policy_cb_data;
2855 cb.should_prune_fn = should_prune_fn;
2858 * The reflog file is locked by holding the lock on the
2859 * reference itself, plus we might need to update the
2860 * reference if --updateref was specified:
2862 lock = lock_ref_sha1_basic(refs, refname, sha1,
2863 NULL, NULL, REF_NODEREF,
2866 error("cannot lock ref '%s': %s", refname, err.buf);
2867 strbuf_release(&err);
2870 if (!refs_reflog_exists(ref_store, refname)) {
2875 files_reflog_path(refs, &log_file_sb, refname);
2876 log_file = strbuf_detach(&log_file_sb, NULL);
2877 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2879 * Even though holding $GIT_DIR/logs/$reflog.lock has
2880 * no locking implications, we use the lock_file
2881 * machinery here anyway because it does a lot of the
2882 * work we need, including cleaning up if the program
2883 * exits unexpectedly.
2885 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
2886 struct strbuf err = STRBUF_INIT;
2887 unable_to_lock_message(log_file, errno, &err);
2888 error("%s", err.buf);
2889 strbuf_release(&err);
2892 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
2894 error("cannot fdopen %s (%s)",
2895 get_lock_file_path(&reflog_lock), strerror(errno));
2900 hashcpy(oid.hash, sha1);
2902 (*prepare_fn)(refname, &oid, cb.policy_cb);
2903 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
2904 (*cleanup_fn)(cb.policy_cb);
2906 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2908 * It doesn't make sense to adjust a reference pointed
2909 * to by a symbolic ref based on expiring entries in
2910 * the symbolic reference's reflog. Nor can we update
2911 * a reference if there are no remaining reflog
2914 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
2915 !(type & REF_ISSYMREF) &&
2916 !is_null_oid(&cb.last_kept_oid);
2918 if (close_lock_file(&reflog_lock)) {
2919 status |= error("couldn't write %s: %s", log_file,
2921 } else if (update &&
2922 (write_in_full(get_lock_file_fd(lock->lk),
2923 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2924 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
2925 close_ref(lock) < 0)) {
2926 status |= error("couldn't write %s",
2927 get_lock_file_path(lock->lk));
2928 rollback_lock_file(&reflog_lock);
2929 } else if (commit_lock_file(&reflog_lock)) {
2930 status |= error("unable to write reflog '%s' (%s)",
2931 log_file, strerror(errno));
2932 } else if (update && commit_ref(lock)) {
2933 status |= error("couldn't set %s", lock->ref_name);
2941 rollback_lock_file(&reflog_lock);
2947 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
2949 struct files_ref_store *refs =
2950 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
2951 struct strbuf sb = STRBUF_INIT;
2954 * Create .git/refs/{heads,tags}
2956 files_ref_path(refs, &sb, "refs/heads");
2957 safe_create_dir(sb.buf, 1);
2960 files_ref_path(refs, &sb, "refs/tags");
2961 safe_create_dir(sb.buf, 1);
2963 strbuf_release(&sb);
2967 struct ref_storage_be refs_be_files = {
2970 files_ref_store_create,
2972 files_transaction_prepare,
2973 files_transaction_finish,
2974 files_transaction_abort,
2975 files_initial_transaction_commit,
2978 files_create_symref,
2982 files_ref_iterator_begin,
2985 files_reflog_iterator_begin,
2986 files_for_each_reflog_ent,
2987 files_for_each_reflog_ent_reverse,
2988 files_reflog_exists,
2989 files_create_reflog,
2990 files_delete_reflog,