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 rollback_lock_file(&lock->lk);
422 free(lock->ref_name);
427 * Lock refname, without following symrefs, and set *lock_p to point
428 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
429 * and type similarly to read_raw_ref().
431 * The caller must verify that refname is a "safe" reference name (in
432 * the sense of refname_is_safe()) before calling this function.
434 * If the reference doesn't already exist, verify that refname doesn't
435 * have a D/F conflict with any existing references. extras and skip
436 * are passed to refs_verify_refname_available() for this check.
438 * If mustexist is not set and the reference is not found or is
439 * broken, lock the reference anyway but clear sha1.
441 * Return 0 on success. On failure, write an error message to err and
442 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
444 * Implementation note: This function is basically
449 * but it includes a lot more code to
450 * - Deal with possible races with other processes
451 * - Avoid calling refs_verify_refname_available() when it can be
452 * avoided, namely if we were successfully able to read the ref
453 * - Generate informative error messages in the case of failure
455 static int lock_raw_ref(struct files_ref_store *refs,
456 const char *refname, int mustexist,
457 const struct string_list *extras,
458 const struct string_list *skip,
459 struct ref_lock **lock_p,
460 struct strbuf *referent,
464 struct ref_lock *lock;
465 struct strbuf ref_file = STRBUF_INIT;
466 int attempts_remaining = 3;
467 int ret = TRANSACTION_GENERIC_ERROR;
470 files_assert_main_repository(refs, "lock_raw_ref");
474 /* First lock the file so it can't change out from under us. */
476 *lock_p = lock = xcalloc(1, sizeof(*lock));
478 lock->ref_name = xstrdup(refname);
479 files_ref_path(refs, &ref_file, refname);
482 switch (safe_create_leading_directories(ref_file.buf)) {
487 * Suppose refname is "refs/foo/bar". We just failed
488 * to create the containing directory, "refs/foo",
489 * because there was a non-directory in the way. This
490 * indicates a D/F conflict, probably because of
491 * another reference such as "refs/foo". There is no
492 * reason to expect this error to be transitory.
494 if (refs_verify_refname_available(&refs->base, refname,
495 extras, skip, err)) {
498 * To the user the relevant error is
499 * that the "mustexist" reference is
503 strbuf_addf(err, "unable to resolve reference '%s'",
507 * The error message set by
508 * refs_verify_refname_available() is
511 ret = TRANSACTION_NAME_CONFLICT;
515 * The file that is in the way isn't a loose
516 * reference. Report it as a low-level
519 strbuf_addf(err, "unable to create lock file %s.lock; "
520 "non-directory in the way",
525 /* Maybe another process was tidying up. Try again. */
526 if (--attempts_remaining > 0)
530 strbuf_addf(err, "unable to create directory for %s",
535 if (hold_lock_file_for_update_timeout(
536 &lock->lk, ref_file.buf, LOCK_NO_DEREF,
537 get_files_ref_lock_timeout_ms()) < 0) {
538 if (errno == ENOENT && --attempts_remaining > 0) {
540 * Maybe somebody just deleted one of the
541 * directories leading to ref_file. Try
546 unable_to_lock_message(ref_file.buf, errno, err);
552 * Now we hold the lock and can read the reference without
553 * fear that its value will change.
556 if (files_read_raw_ref(&refs->base, refname,
557 lock->old_oid.hash, referent, type)) {
558 if (errno == ENOENT) {
560 /* Garden variety missing reference. */
561 strbuf_addf(err, "unable to resolve reference '%s'",
566 * Reference is missing, but that's OK. We
567 * know that there is not a conflict with
568 * another loose reference because
569 * (supposing that we are trying to lock
570 * reference "refs/foo/bar"):
572 * - We were successfully able to create
573 * the lockfile refs/foo/bar.lock, so we
574 * know there cannot be a loose reference
577 * - We got ENOENT and not EISDIR, so we
578 * know that there cannot be a loose
579 * reference named "refs/foo/bar/baz".
582 } else if (errno == EISDIR) {
584 * There is a directory in the way. It might have
585 * contained references that have been deleted. If
586 * we don't require that the reference already
587 * exists, try to remove the directory so that it
588 * doesn't cause trouble when we want to rename the
589 * lockfile into place later.
592 /* Garden variety missing reference. */
593 strbuf_addf(err, "unable to resolve reference '%s'",
596 } else if (remove_dir_recursively(&ref_file,
597 REMOVE_DIR_EMPTY_ONLY)) {
598 if (refs_verify_refname_available(
599 &refs->base, refname,
600 extras, skip, err)) {
602 * The error message set by
603 * verify_refname_available() is OK.
605 ret = TRANSACTION_NAME_CONFLICT;
609 * We can't delete the directory,
610 * but we also don't know of any
611 * references that it should
614 strbuf_addf(err, "there is a non-empty directory '%s' "
615 "blocking reference '%s'",
616 ref_file.buf, refname);
620 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
621 strbuf_addf(err, "unable to resolve reference '%s': "
622 "reference broken", refname);
625 strbuf_addf(err, "unable to resolve reference '%s': %s",
626 refname, strerror(errno));
631 * If the ref did not exist and we are creating it,
632 * make sure there is no existing packed ref that
633 * conflicts with refname:
635 if (refs_verify_refname_available(
636 refs->packed_ref_store, refname,
649 strbuf_release(&ref_file);
653 static int files_peel_ref(struct ref_store *ref_store,
654 const char *refname, unsigned char *sha1)
656 struct files_ref_store *refs =
657 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
660 unsigned char base[20];
662 if (current_ref_iter && current_ref_iter->refname == refname) {
663 struct object_id peeled;
665 if (ref_iterator_peel(current_ref_iter, &peeled))
667 hashcpy(sha1, peeled.hash);
671 if (refs_read_ref_full(ref_store, refname,
672 RESOLVE_REF_READING, base, &flag))
676 * If the reference is packed, read its ref_entry from the
677 * cache in the hope that we already know its peeled value.
678 * We only try this optimization on packed references because
679 * (a) forcing the filling of the loose reference cache could
680 * be expensive and (b) loose references anyway usually do not
681 * have REF_KNOWS_PEELED.
683 if (flag & REF_ISPACKED &&
684 !refs_peel_ref(refs->packed_ref_store, refname, sha1))
687 return peel_object(base, sha1);
690 struct files_ref_iterator {
691 struct ref_iterator base;
693 struct ref_iterator *iter0;
697 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
699 struct files_ref_iterator *iter =
700 (struct files_ref_iterator *)ref_iterator;
703 while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
704 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
705 ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
708 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
709 !ref_resolves_to_object(iter->iter0->refname,
714 iter->base.refname = iter->iter0->refname;
715 iter->base.oid = iter->iter0->oid;
716 iter->base.flags = iter->iter0->flags;
721 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
727 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
728 struct object_id *peeled)
730 struct files_ref_iterator *iter =
731 (struct files_ref_iterator *)ref_iterator;
733 return ref_iterator_peel(iter->iter0, peeled);
736 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
738 struct files_ref_iterator *iter =
739 (struct files_ref_iterator *)ref_iterator;
743 ok = ref_iterator_abort(iter->iter0);
745 base_ref_iterator_free(ref_iterator);
749 static struct ref_iterator_vtable files_ref_iterator_vtable = {
750 files_ref_iterator_advance,
751 files_ref_iterator_peel,
752 files_ref_iterator_abort
755 static struct ref_iterator *files_ref_iterator_begin(
756 struct ref_store *ref_store,
757 const char *prefix, unsigned int flags)
759 struct files_ref_store *refs;
760 struct ref_iterator *loose_iter, *packed_iter;
761 struct files_ref_iterator *iter;
762 struct ref_iterator *ref_iterator;
763 unsigned int required_flags = REF_STORE_READ;
765 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
766 required_flags |= REF_STORE_ODB;
768 refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
770 iter = xcalloc(1, sizeof(*iter));
771 ref_iterator = &iter->base;
772 base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
775 * We must make sure that all loose refs are read before
776 * accessing the packed-refs file; this avoids a race
777 * condition if loose refs are migrated to the packed-refs
778 * file by a simultaneous process, but our in-memory view is
779 * from before the migration. We ensure this as follows:
780 * First, we call start the loose refs iteration with its
781 * `prime_ref` argument set to true. This causes the loose
782 * references in the subtree to be pre-read into the cache.
783 * (If they've already been read, that's OK; we only need to
784 * guarantee that they're read before the packed refs, not
785 * *how much* before.) After that, we call
786 * packed_ref_iterator_begin(), which internally checks
787 * whether the packed-ref cache is up to date with what is on
788 * disk, and re-reads it if not.
791 loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
795 * The packed-refs file might contain broken references, for
796 * example an old version of a reference that points at an
797 * object that has since been garbage-collected. This is OK as
798 * long as there is a corresponding loose reference that
799 * overrides it, and we don't want to emit an error message in
800 * this case. So ask the packed_ref_store for all of its
801 * references, and (if needed) do our own check for broken
802 * ones in files_ref_iterator_advance(), after we have merged
803 * the packed and loose references.
805 packed_iter = refs_ref_iterator_begin(
806 refs->packed_ref_store, prefix, 0,
807 DO_FOR_EACH_INCLUDE_BROKEN);
809 iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
816 * Verify that the reference locked by lock has the value old_sha1.
817 * Fail if the reference doesn't exist and mustexist is set. Return 0
818 * on success. On error, write an error message to err, set errno, and
819 * return a negative value.
821 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
822 const unsigned char *old_sha1, int mustexist,
827 if (refs_read_ref_full(ref_store, lock->ref_name,
828 mustexist ? RESOLVE_REF_READING : 0,
829 lock->old_oid.hash, NULL)) {
831 int save_errno = errno;
832 strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
836 oidclr(&lock->old_oid);
840 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
841 strbuf_addf(err, "ref '%s' is at %s but expected %s",
843 oid_to_hex(&lock->old_oid),
844 sha1_to_hex(old_sha1));
851 static int remove_empty_directories(struct strbuf *path)
854 * we want to create a file but there is a directory there;
855 * if that is an empty directory (or a directory that contains
856 * only empty directories), remove them.
858 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
861 static int create_reflock(const char *path, void *cb)
863 struct lock_file *lk = cb;
865 return hold_lock_file_for_update_timeout(
866 lk, path, LOCK_NO_DEREF,
867 get_files_ref_lock_timeout_ms()) < 0 ? -1 : 0;
871 * Locks a ref returning the lock on success and NULL on failure.
872 * On failure errno is set to something meaningful.
874 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
876 const unsigned char *old_sha1,
877 const struct string_list *extras,
878 const struct string_list *skip,
879 unsigned int flags, int *type,
882 struct strbuf ref_file = STRBUF_INIT;
883 struct ref_lock *lock;
885 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
886 int resolve_flags = RESOLVE_REF_NO_RECURSE;
889 files_assert_main_repository(refs, "lock_ref_sha1_basic");
892 lock = xcalloc(1, sizeof(struct ref_lock));
895 resolve_flags |= RESOLVE_REF_READING;
896 if (flags & REF_DELETING)
897 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
899 files_ref_path(refs, &ref_file, refname);
900 resolved = !!refs_resolve_ref_unsafe(&refs->base,
901 refname, resolve_flags,
902 lock->old_oid.hash, type);
903 if (!resolved && errno == EISDIR) {
905 * we are trying to lock foo but we used to
906 * have foo/bar which now does not exist;
907 * it is normal for the empty directory 'foo'
910 if (remove_empty_directories(&ref_file)) {
912 if (!refs_verify_refname_available(
914 refname, extras, skip, err))
915 strbuf_addf(err, "there are still refs under '%s'",
919 resolved = !!refs_resolve_ref_unsafe(&refs->base,
920 refname, resolve_flags,
921 lock->old_oid.hash, type);
925 if (last_errno != ENOTDIR ||
926 !refs_verify_refname_available(&refs->base, refname,
928 strbuf_addf(err, "unable to resolve reference '%s': %s",
929 refname, strerror(last_errno));
935 * If the ref did not exist and we are creating it, make sure
936 * there is no existing packed ref whose name begins with our
937 * refname, nor a packed ref whose name is a proper prefix of
940 if (is_null_oid(&lock->old_oid) &&
941 refs_verify_refname_available(refs->packed_ref_store, refname,
942 extras, skip, err)) {
943 last_errno = ENOTDIR;
947 lock->ref_name = xstrdup(refname);
949 if (raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) {
951 unable_to_lock_message(ref_file.buf, errno, err);
955 if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
966 strbuf_release(&ref_file);
971 struct ref_to_prune {
972 struct ref_to_prune *next;
973 unsigned char sha1[20];
974 char name[FLEX_ARRAY];
978 REMOVE_EMPTY_PARENTS_REF = 0x01,
979 REMOVE_EMPTY_PARENTS_REFLOG = 0x02
983 * Remove empty parent directories associated with the specified
984 * reference and/or its reflog, but spare [logs/]refs/ and immediate
985 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
986 * REMOVE_EMPTY_PARENTS_REFLOG.
988 static void try_remove_empty_parents(struct files_ref_store *refs,
992 struct strbuf buf = STRBUF_INIT;
993 struct strbuf sb = STRBUF_INIT;
997 strbuf_addstr(&buf, refname);
999 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1000 while (*p && *p != '/')
1002 /* tolerate duplicate slashes; see check_refname_format() */
1006 q = buf.buf + buf.len;
1007 while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1008 while (q > p && *q != '/')
1010 while (q > p && *(q-1) == '/')
1014 strbuf_setlen(&buf, q - buf.buf);
1017 files_ref_path(refs, &sb, buf.buf);
1018 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1019 flags &= ~REMOVE_EMPTY_PARENTS_REF;
1022 files_reflog_path(refs, &sb, buf.buf);
1023 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1024 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1026 strbuf_release(&buf);
1027 strbuf_release(&sb);
1030 /* make sure nobody touched the ref, and unlink */
1031 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1033 struct ref_transaction *transaction;
1034 struct strbuf err = STRBUF_INIT;
1036 if (check_refname_format(r->name, 0))
1039 transaction = ref_store_transaction_begin(&refs->base, &err);
1041 ref_transaction_delete(transaction, r->name, r->sha1,
1042 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1043 ref_transaction_commit(transaction, &err)) {
1044 ref_transaction_free(transaction);
1045 error("%s", err.buf);
1046 strbuf_release(&err);
1049 ref_transaction_free(transaction);
1050 strbuf_release(&err);
1053 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1062 * Return true if the specified reference should be packed.
1064 static int should_pack_ref(const char *refname,
1065 const struct object_id *oid, unsigned int ref_flags,
1066 unsigned int pack_flags)
1068 /* Do not pack per-worktree refs: */
1069 if (ref_type(refname) != REF_TYPE_NORMAL)
1072 /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1073 if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1076 /* Do not pack symbolic refs: */
1077 if (ref_flags & REF_ISSYMREF)
1080 /* Do not pack broken refs: */
1081 if (!ref_resolves_to_object(refname, oid, ref_flags))
1087 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1089 struct files_ref_store *refs =
1090 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1092 struct ref_iterator *iter;
1094 struct ref_to_prune *refs_to_prune = NULL;
1095 struct strbuf err = STRBUF_INIT;
1097 packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1099 iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1100 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1102 * If the loose reference can be packed, add an entry
1103 * in the packed ref cache. If the reference should be
1104 * pruned, also add it to refs_to_prune.
1106 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1111 * Create an entry in the packed-refs cache equivalent
1112 * to the one from the loose ref cache, except that
1113 * we don't copy the peeled status, because we want it
1116 add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);
1118 /* Schedule the loose reference for pruning if requested. */
1119 if ((flags & PACK_REFS_PRUNE)) {
1120 struct ref_to_prune *n;
1121 FLEX_ALLOC_STR(n, name, iter->refname);
1122 hashcpy(n->sha1, iter->oid->hash);
1123 n->next = refs_to_prune;
1127 if (ok != ITER_DONE)
1128 die("error while iterating over references");
1130 if (commit_packed_refs(refs->packed_ref_store, &err))
1131 die("unable to overwrite old ref-pack file: %s", err.buf);
1132 packed_refs_unlock(refs->packed_ref_store);
1134 prune_refs(refs, refs_to_prune);
1135 strbuf_release(&err);
1139 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1140 struct string_list *refnames, unsigned int flags)
1142 struct files_ref_store *refs =
1143 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1144 struct strbuf err = STRBUF_INIT;
1150 if (packed_refs_lock(refs->packed_ref_store, 0, &err))
1153 if (repack_without_refs(refs->packed_ref_store, refnames, &err)) {
1154 packed_refs_unlock(refs->packed_ref_store);
1158 packed_refs_unlock(refs->packed_ref_store);
1160 for (i = 0; i < refnames->nr; i++) {
1161 const char *refname = refnames->items[i].string;
1163 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1164 result |= error(_("could not remove reference %s"), refname);
1167 strbuf_release(&err);
1172 * If we failed to rewrite the packed-refs file, then it is
1173 * unsafe to try to remove loose refs, because doing so might
1174 * expose an obsolete packed value for a reference that might
1175 * even point at an object that has been garbage collected.
1177 if (refnames->nr == 1)
1178 error(_("could not delete reference %s: %s"),
1179 refnames->items[0].string, err.buf);
1181 error(_("could not delete references: %s"), err.buf);
1183 strbuf_release(&err);
1188 * People using contrib's git-new-workdir have .git/logs/refs ->
1189 * /some/other/path/.git/logs/refs, and that may live on another device.
1191 * IOW, to avoid cross device rename errors, the temporary renamed log must
1192 * live into logs/refs.
1194 #define TMP_RENAMED_LOG "refs/.tmp-renamed-log"
1197 const char *tmp_renamed_log;
1201 static int rename_tmp_log_callback(const char *path, void *cb_data)
1203 struct rename_cb *cb = cb_data;
1205 if (rename(cb->tmp_renamed_log, path)) {
1207 * rename(a, b) when b is an existing directory ought
1208 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1209 * Sheesh. Record the true errno for error reporting,
1210 * but report EISDIR to raceproof_create_file() so
1211 * that it knows to retry.
1213 cb->true_errno = errno;
1214 if (errno == ENOTDIR)
1222 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1224 struct strbuf path = STRBUF_INIT;
1225 struct strbuf tmp = STRBUF_INIT;
1226 struct rename_cb cb;
1229 files_reflog_path(refs, &path, newrefname);
1230 files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1231 cb.tmp_renamed_log = tmp.buf;
1232 ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1234 if (errno == EISDIR)
1235 error("directory not empty: %s", path.buf);
1237 error("unable to move logfile %s to %s: %s",
1239 strerror(cb.true_errno));
1242 strbuf_release(&path);
1243 strbuf_release(&tmp);
1247 static int write_ref_to_lockfile(struct ref_lock *lock,
1248 const struct object_id *oid, struct strbuf *err);
1249 static int commit_ref_update(struct files_ref_store *refs,
1250 struct ref_lock *lock,
1251 const struct object_id *oid, const char *logmsg,
1252 struct strbuf *err);
1254 static int files_rename_ref(struct ref_store *ref_store,
1255 const char *oldrefname, const char *newrefname,
1258 struct files_ref_store *refs =
1259 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1260 struct object_id oid, orig_oid;
1261 int flag = 0, logmoved = 0;
1262 struct ref_lock *lock;
1263 struct stat loginfo;
1264 struct strbuf sb_oldref = STRBUF_INIT;
1265 struct strbuf sb_newref = STRBUF_INIT;
1266 struct strbuf tmp_renamed_log = STRBUF_INIT;
1268 struct strbuf err = STRBUF_INIT;
1270 files_reflog_path(refs, &sb_oldref, oldrefname);
1271 files_reflog_path(refs, &sb_newref, newrefname);
1272 files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1274 log = !lstat(sb_oldref.buf, &loginfo);
1275 if (log && S_ISLNK(loginfo.st_mode)) {
1276 ret = error("reflog for %s is a symlink", oldrefname);
1280 if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1281 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1282 orig_oid.hash, &flag)) {
1283 ret = error("refname %s not found", oldrefname);
1287 if (flag & REF_ISSYMREF) {
1288 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1292 if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1297 if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1298 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1299 oldrefname, strerror(errno));
1303 if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1304 orig_oid.hash, REF_NODEREF)) {
1305 error("unable to delete old %s", oldrefname);
1310 * Since we are doing a shallow lookup, oid is not the
1311 * correct value to pass to delete_ref as old_oid. But that
1312 * doesn't matter, because an old_oid check wouldn't add to
1313 * the safety anyway; we want to delete the reference whatever
1314 * its current value.
1316 if (!refs_read_ref_full(&refs->base, newrefname,
1317 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1319 refs_delete_ref(&refs->base, NULL, newrefname,
1320 NULL, REF_NODEREF)) {
1321 if (errno == EISDIR) {
1322 struct strbuf path = STRBUF_INIT;
1325 files_ref_path(refs, &path, newrefname);
1326 result = remove_empty_directories(&path);
1327 strbuf_release(&path);
1330 error("Directory not empty: %s", newrefname);
1334 error("unable to delete existing %s", newrefname);
1339 if (log && rename_tmp_log(refs, newrefname))
1344 lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1345 REF_NODEREF, NULL, &err);
1347 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1348 strbuf_release(&err);
1351 oidcpy(&lock->old_oid, &orig_oid);
1353 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1354 commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1355 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1356 strbuf_release(&err);
1364 lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1365 REF_NODEREF, NULL, &err);
1367 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1368 strbuf_release(&err);
1372 flag = log_all_ref_updates;
1373 log_all_ref_updates = LOG_REFS_NONE;
1374 if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1375 commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1376 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1377 strbuf_release(&err);
1379 log_all_ref_updates = flag;
1382 if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1383 error("unable to restore logfile %s from %s: %s",
1384 oldrefname, newrefname, strerror(errno));
1385 if (!logmoved && log &&
1386 rename(tmp_renamed_log.buf, sb_oldref.buf))
1387 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1388 oldrefname, strerror(errno));
1391 strbuf_release(&sb_newref);
1392 strbuf_release(&sb_oldref);
1393 strbuf_release(&tmp_renamed_log);
1398 static int close_ref_gently(struct ref_lock *lock)
1400 if (close_lock_file_gently(&lock->lk))
1405 static int commit_ref(struct ref_lock *lock)
1407 char *path = get_locked_file_path(&lock->lk);
1410 if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1412 * There is a directory at the path we want to rename
1413 * the lockfile to. Hopefully it is empty; try to
1416 size_t len = strlen(path);
1417 struct strbuf sb_path = STRBUF_INIT;
1419 strbuf_attach(&sb_path, path, len, len);
1422 * If this fails, commit_lock_file() will also fail
1423 * and will report the problem.
1425 remove_empty_directories(&sb_path);
1426 strbuf_release(&sb_path);
1431 if (commit_lock_file(&lock->lk))
1436 static int open_or_create_logfile(const char *path, void *cb)
1440 *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1441 return (*fd < 0) ? -1 : 0;
1445 * Create a reflog for a ref. If force_create = 0, only create the
1446 * reflog for certain refs (those for which should_autocreate_reflog
1447 * returns non-zero). Otherwise, create it regardless of the reference
1448 * name. If the logfile already existed or was created, return 0 and
1449 * set *logfd to the file descriptor opened for appending to the file.
1450 * If no logfile exists and we decided not to create one, return 0 and
1451 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1454 static int log_ref_setup(struct files_ref_store *refs,
1455 const char *refname, int force_create,
1456 int *logfd, struct strbuf *err)
1458 struct strbuf logfile_sb = STRBUF_INIT;
1461 files_reflog_path(refs, &logfile_sb, refname);
1462 logfile = strbuf_detach(&logfile_sb, NULL);
1464 if (force_create || should_autocreate_reflog(refname)) {
1465 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1466 if (errno == ENOENT)
1467 strbuf_addf(err, "unable to create directory for '%s': "
1468 "%s", logfile, strerror(errno));
1469 else if (errno == EISDIR)
1470 strbuf_addf(err, "there are still logs under '%s'",
1473 strbuf_addf(err, "unable to append to '%s': %s",
1474 logfile, strerror(errno));
1479 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1481 if (errno == ENOENT || errno == EISDIR) {
1483 * The logfile doesn't already exist,
1484 * but that is not an error; it only
1485 * means that we won't write log
1490 strbuf_addf(err, "unable to append to '%s': %s",
1491 logfile, strerror(errno));
1498 adjust_shared_perm(logfile);
1508 static int files_create_reflog(struct ref_store *ref_store,
1509 const char *refname, int force_create,
1512 struct files_ref_store *refs =
1513 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1516 if (log_ref_setup(refs, refname, force_create, &fd, err))
1525 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1526 const struct object_id *new_oid,
1527 const char *committer, const char *msg)
1529 int msglen, written;
1530 unsigned maxlen, len;
1533 msglen = msg ? strlen(msg) : 0;
1534 maxlen = strlen(committer) + msglen + 100;
1535 logrec = xmalloc(maxlen);
1536 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
1537 oid_to_hex(old_oid),
1538 oid_to_hex(new_oid),
1541 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
1543 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
1551 static int files_log_ref_write(struct files_ref_store *refs,
1552 const char *refname, const struct object_id *old_oid,
1553 const struct object_id *new_oid, const char *msg,
1554 int flags, struct strbuf *err)
1558 if (log_all_ref_updates == LOG_REFS_UNSET)
1559 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1561 result = log_ref_setup(refs, refname,
1562 flags & REF_FORCE_CREATE_REFLOG,
1570 result = log_ref_write_fd(logfd, old_oid, new_oid,
1571 git_committer_info(0), msg);
1573 struct strbuf sb = STRBUF_INIT;
1574 int save_errno = errno;
1576 files_reflog_path(refs, &sb, refname);
1577 strbuf_addf(err, "unable to append to '%s': %s",
1578 sb.buf, strerror(save_errno));
1579 strbuf_release(&sb);
1584 struct strbuf sb = STRBUF_INIT;
1585 int save_errno = errno;
1587 files_reflog_path(refs, &sb, refname);
1588 strbuf_addf(err, "unable to append to '%s': %s",
1589 sb.buf, strerror(save_errno));
1590 strbuf_release(&sb);
1597 * Write sha1 into the open lockfile, then close the lockfile. On
1598 * errors, rollback the lockfile, fill in *err and
1601 static int write_ref_to_lockfile(struct ref_lock *lock,
1602 const struct object_id *oid, struct strbuf *err)
1604 static char term = '\n';
1608 o = parse_object(oid);
1611 "trying to write ref '%s' with nonexistent object %s",
1612 lock->ref_name, oid_to_hex(oid));
1616 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1618 "trying to write non-commit object %s to branch '%s'",
1619 oid_to_hex(oid), lock->ref_name);
1623 fd = get_lock_file_fd(&lock->lk);
1624 if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
1625 write_in_full(fd, &term, 1) != 1 ||
1626 close_ref_gently(lock) < 0) {
1628 "couldn't write '%s'", get_lock_file_path(&lock->lk));
1636 * Commit a change to a loose reference that has already been written
1637 * to the loose reference lockfile. Also update the reflogs if
1638 * necessary, using the specified lockmsg (which can be NULL).
1640 static int commit_ref_update(struct files_ref_store *refs,
1641 struct ref_lock *lock,
1642 const struct object_id *oid, const char *logmsg,
1645 files_assert_main_repository(refs, "commit_ref_update");
1647 clear_loose_ref_cache(refs);
1648 if (files_log_ref_write(refs, lock->ref_name,
1649 &lock->old_oid, oid,
1651 char *old_msg = strbuf_detach(err, NULL);
1652 strbuf_addf(err, "cannot update the ref '%s': %s",
1653 lock->ref_name, old_msg);
1659 if (strcmp(lock->ref_name, "HEAD") != 0) {
1661 * Special hack: If a branch is updated directly and HEAD
1662 * points to it (may happen on the remote side of a push
1663 * for example) then logically the HEAD reflog should be
1665 * A generic solution implies reverse symref information,
1666 * but finding all symrefs pointing to the given branch
1667 * would be rather costly for this rare event (the direct
1668 * update of a branch) to be worth it. So let's cheat and
1669 * check with HEAD only which should cover 99% of all usage
1670 * scenarios (even 100% of the default ones).
1672 struct object_id head_oid;
1674 const char *head_ref;
1676 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1677 RESOLVE_REF_READING,
1678 head_oid.hash, &head_flag);
1679 if (head_ref && (head_flag & REF_ISSYMREF) &&
1680 !strcmp(head_ref, lock->ref_name)) {
1681 struct strbuf log_err = STRBUF_INIT;
1682 if (files_log_ref_write(refs, "HEAD",
1683 &lock->old_oid, oid,
1684 logmsg, 0, &log_err)) {
1685 error("%s", log_err.buf);
1686 strbuf_release(&log_err);
1691 if (commit_ref(lock)) {
1692 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1701 static int create_ref_symlink(struct ref_lock *lock, const char *target)
1704 #ifndef NO_SYMLINK_HEAD
1705 char *ref_path = get_locked_file_path(&lock->lk);
1707 ret = symlink(target, ref_path);
1711 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1716 static void update_symref_reflog(struct files_ref_store *refs,
1717 struct ref_lock *lock, const char *refname,
1718 const char *target, const char *logmsg)
1720 struct strbuf err = STRBUF_INIT;
1721 struct object_id new_oid;
1723 !refs_read_ref_full(&refs->base, target,
1724 RESOLVE_REF_READING, new_oid.hash, NULL) &&
1725 files_log_ref_write(refs, refname, &lock->old_oid,
1726 &new_oid, logmsg, 0, &err)) {
1727 error("%s", err.buf);
1728 strbuf_release(&err);
1732 static int create_symref_locked(struct files_ref_store *refs,
1733 struct ref_lock *lock, const char *refname,
1734 const char *target, const char *logmsg)
1736 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1737 update_symref_reflog(refs, lock, refname, target, logmsg);
1741 if (!fdopen_lock_file(&lock->lk, "w"))
1742 return error("unable to fdopen %s: %s",
1743 lock->lk.tempfile->filename.buf, strerror(errno));
1745 update_symref_reflog(refs, lock, refname, target, logmsg);
1747 /* no error check; commit_ref will check ferror */
1748 fprintf(lock->lk.tempfile->fp, "ref: %s\n", target);
1749 if (commit_ref(lock) < 0)
1750 return error("unable to write symref for %s: %s", refname,
1755 static int files_create_symref(struct ref_store *ref_store,
1756 const char *refname, const char *target,
1759 struct files_ref_store *refs =
1760 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1761 struct strbuf err = STRBUF_INIT;
1762 struct ref_lock *lock;
1765 lock = lock_ref_sha1_basic(refs, refname, NULL,
1766 NULL, NULL, REF_NODEREF, NULL,
1769 error("%s", err.buf);
1770 strbuf_release(&err);
1774 ret = create_symref_locked(refs, lock, refname, target, logmsg);
1779 static int files_reflog_exists(struct ref_store *ref_store,
1780 const char *refname)
1782 struct files_ref_store *refs =
1783 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1784 struct strbuf sb = STRBUF_INIT;
1788 files_reflog_path(refs, &sb, refname);
1789 ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1790 strbuf_release(&sb);
1794 static int files_delete_reflog(struct ref_store *ref_store,
1795 const char *refname)
1797 struct files_ref_store *refs =
1798 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1799 struct strbuf sb = STRBUF_INIT;
1802 files_reflog_path(refs, &sb, refname);
1803 ret = remove_path(sb.buf);
1804 strbuf_release(&sb);
1808 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1810 struct object_id ooid, noid;
1811 char *email_end, *message;
1812 timestamp_t timestamp;
1814 const char *p = sb->buf;
1816 /* old SP new SP name <email> SP time TAB msg LF */
1817 if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1818 parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1819 parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1820 !(email_end = strchr(p, '>')) ||
1821 email_end[1] != ' ' ||
1822 !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1823 !message || message[0] != ' ' ||
1824 (message[1] != '+' && message[1] != '-') ||
1825 !isdigit(message[2]) || !isdigit(message[3]) ||
1826 !isdigit(message[4]) || !isdigit(message[5]))
1827 return 0; /* corrupt? */
1828 email_end[1] = '\0';
1829 tz = strtol(message + 1, NULL, 10);
1830 if (message[6] != '\t')
1834 return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1837 static char *find_beginning_of_line(char *bob, char *scan)
1839 while (bob < scan && *(--scan) != '\n')
1840 ; /* keep scanning backwards */
1842 * Return either beginning of the buffer, or LF at the end of
1843 * the previous line.
1848 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1849 const char *refname,
1850 each_reflog_ent_fn fn,
1853 struct files_ref_store *refs =
1854 files_downcast(ref_store, REF_STORE_READ,
1855 "for_each_reflog_ent_reverse");
1856 struct strbuf sb = STRBUF_INIT;
1859 int ret = 0, at_tail = 1;
1861 files_reflog_path(refs, &sb, refname);
1862 logfp = fopen(sb.buf, "r");
1863 strbuf_release(&sb);
1867 /* Jump to the end */
1868 if (fseek(logfp, 0, SEEK_END) < 0)
1869 ret = error("cannot seek back reflog for %s: %s",
1870 refname, strerror(errno));
1872 while (!ret && 0 < pos) {
1878 /* Fill next block from the end */
1879 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1880 if (fseek(logfp, pos - cnt, SEEK_SET)) {
1881 ret = error("cannot seek back reflog for %s: %s",
1882 refname, strerror(errno));
1885 nread = fread(buf, cnt, 1, logfp);
1887 ret = error("cannot read %d bytes from reflog for %s: %s",
1888 cnt, refname, strerror(errno));
1893 scanp = endp = buf + cnt;
1894 if (at_tail && scanp[-1] == '\n')
1895 /* Looking at the final LF at the end of the file */
1899 while (buf < scanp) {
1901 * terminating LF of the previous line, or the beginning
1906 bp = find_beginning_of_line(buf, scanp);
1910 * The newline is the end of the previous line,
1911 * so we know we have complete line starting
1912 * at (bp + 1). Prefix it onto any prior data
1913 * we collected for the line and process it.
1915 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1918 ret = show_one_reflog_ent(&sb, fn, cb_data);
1924 * We are at the start of the buffer, and the
1925 * start of the file; there is no previous
1926 * line, and we have everything for this one.
1927 * Process it, and we can end the loop.
1929 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1930 ret = show_one_reflog_ent(&sb, fn, cb_data);
1937 * We are at the start of the buffer, and there
1938 * is more file to read backwards. Which means
1939 * we are in the middle of a line. Note that we
1940 * may get here even if *bp was a newline; that
1941 * just means we are at the exact end of the
1942 * previous line, rather than some spot in the
1945 * Save away what we have to be combined with
1946 * the data from the next read.
1948 strbuf_splice(&sb, 0, 0, buf, endp - buf);
1955 die("BUG: reverse reflog parser had leftover data");
1958 strbuf_release(&sb);
1962 static int files_for_each_reflog_ent(struct ref_store *ref_store,
1963 const char *refname,
1964 each_reflog_ent_fn fn, void *cb_data)
1966 struct files_ref_store *refs =
1967 files_downcast(ref_store, REF_STORE_READ,
1968 "for_each_reflog_ent");
1970 struct strbuf sb = STRBUF_INIT;
1973 files_reflog_path(refs, &sb, refname);
1974 logfp = fopen(sb.buf, "r");
1975 strbuf_release(&sb);
1979 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
1980 ret = show_one_reflog_ent(&sb, fn, cb_data);
1982 strbuf_release(&sb);
1986 struct files_reflog_iterator {
1987 struct ref_iterator base;
1989 struct ref_store *ref_store;
1990 struct dir_iterator *dir_iterator;
1991 struct object_id oid;
1994 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
1996 struct files_reflog_iterator *iter =
1997 (struct files_reflog_iterator *)ref_iterator;
1998 struct dir_iterator *diter = iter->dir_iterator;
2001 while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2004 if (!S_ISREG(diter->st.st_mode))
2006 if (diter->basename[0] == '.')
2008 if (ends_with(diter->basename, ".lock"))
2011 if (refs_read_ref_full(iter->ref_store,
2012 diter->relative_path, 0,
2013 iter->oid.hash, &flags)) {
2014 error("bad ref for %s", diter->path.buf);
2018 iter->base.refname = diter->relative_path;
2019 iter->base.oid = &iter->oid;
2020 iter->base.flags = flags;
2024 iter->dir_iterator = NULL;
2025 if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2030 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2031 struct object_id *peeled)
2033 die("BUG: ref_iterator_peel() called for reflog_iterator");
2036 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2038 struct files_reflog_iterator *iter =
2039 (struct files_reflog_iterator *)ref_iterator;
2042 if (iter->dir_iterator)
2043 ok = dir_iterator_abort(iter->dir_iterator);
2045 base_ref_iterator_free(ref_iterator);
2049 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2050 files_reflog_iterator_advance,
2051 files_reflog_iterator_peel,
2052 files_reflog_iterator_abort
2055 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2057 struct files_ref_store *refs =
2058 files_downcast(ref_store, REF_STORE_READ,
2059 "reflog_iterator_begin");
2060 struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2061 struct ref_iterator *ref_iterator = &iter->base;
2062 struct strbuf sb = STRBUF_INIT;
2064 base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2065 files_reflog_path(refs, &sb, NULL);
2066 iter->dir_iterator = dir_iterator_begin(sb.buf);
2067 iter->ref_store = ref_store;
2068 strbuf_release(&sb);
2069 return ref_iterator;
2073 * If update is a direct update of head_ref (the reference pointed to
2074 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2076 static int split_head_update(struct ref_update *update,
2077 struct ref_transaction *transaction,
2078 const char *head_ref,
2079 struct string_list *affected_refnames,
2082 struct string_list_item *item;
2083 struct ref_update *new_update;
2085 if ((update->flags & REF_LOG_ONLY) ||
2086 (update->flags & REF_ISPRUNING) ||
2087 (update->flags & REF_UPDATE_VIA_HEAD))
2090 if (strcmp(update->refname, head_ref))
2094 * First make sure that HEAD is not already in the
2095 * transaction. This insertion is O(N) in the transaction
2096 * size, but it happens at most once per transaction.
2098 item = string_list_insert(affected_refnames, "HEAD");
2100 /* An entry already existed */
2102 "multiple updates for 'HEAD' (including one "
2103 "via its referent '%s') are not allowed",
2105 return TRANSACTION_NAME_CONFLICT;
2108 new_update = ref_transaction_add_update(
2109 transaction, "HEAD",
2110 update->flags | REF_LOG_ONLY | REF_NODEREF,
2111 update->new_oid.hash, update->old_oid.hash,
2114 item->util = new_update;
2120 * update is for a symref that points at referent and doesn't have
2121 * REF_NODEREF set. Split it into two updates:
2122 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2123 * - A new, separate update for the referent reference
2124 * Note that the new update will itself be subject to splitting when
2125 * the iteration gets to it.
2127 static int split_symref_update(struct files_ref_store *refs,
2128 struct ref_update *update,
2129 const char *referent,
2130 struct ref_transaction *transaction,
2131 struct string_list *affected_refnames,
2134 struct string_list_item *item;
2135 struct ref_update *new_update;
2136 unsigned int new_flags;
2139 * First make sure that referent is not already in the
2140 * transaction. This insertion is O(N) in the transaction
2141 * size, but it happens at most once per symref in a
2144 item = string_list_insert(affected_refnames, referent);
2146 /* An entry already existed */
2148 "multiple updates for '%s' (including one "
2149 "via symref '%s') are not allowed",
2150 referent, update->refname);
2151 return TRANSACTION_NAME_CONFLICT;
2154 new_flags = update->flags;
2155 if (!strcmp(update->refname, "HEAD")) {
2157 * Record that the new update came via HEAD, so that
2158 * when we process it, split_head_update() doesn't try
2159 * to add another reflog update for HEAD. Note that
2160 * this bit will be propagated if the new_update
2161 * itself needs to be split.
2163 new_flags |= REF_UPDATE_VIA_HEAD;
2166 new_update = ref_transaction_add_update(
2167 transaction, referent, new_flags,
2168 update->new_oid.hash, update->old_oid.hash,
2171 new_update->parent_update = update;
2174 * Change the symbolic ref update to log only. Also, it
2175 * doesn't need to check its old SHA-1 value, as that will be
2176 * done when new_update is processed.
2178 update->flags |= REF_LOG_ONLY | REF_NODEREF;
2179 update->flags &= ~REF_HAVE_OLD;
2181 item->util = new_update;
2187 * Return the refname under which update was originally requested.
2189 static const char *original_update_refname(struct ref_update *update)
2191 while (update->parent_update)
2192 update = update->parent_update;
2194 return update->refname;
2198 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2199 * are consistent with oid, which is the reference's current value. If
2200 * everything is OK, return 0; otherwise, write an error message to
2201 * err and return -1.
2203 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2206 if (!(update->flags & REF_HAVE_OLD) ||
2207 !oidcmp(oid, &update->old_oid))
2210 if (is_null_oid(&update->old_oid))
2211 strbuf_addf(err, "cannot lock ref '%s': "
2212 "reference already exists",
2213 original_update_refname(update));
2214 else if (is_null_oid(oid))
2215 strbuf_addf(err, "cannot lock ref '%s': "
2216 "reference is missing but expected %s",
2217 original_update_refname(update),
2218 oid_to_hex(&update->old_oid));
2220 strbuf_addf(err, "cannot lock ref '%s': "
2221 "is at %s but expected %s",
2222 original_update_refname(update),
2224 oid_to_hex(&update->old_oid));
2230 * Prepare for carrying out update:
2231 * - Lock the reference referred to by update.
2232 * - Read the reference under lock.
2233 * - Check that its old SHA-1 value (if specified) is correct, and in
2234 * any case record it in update->lock->old_oid for later use when
2235 * writing the reflog.
2236 * - If it is a symref update without REF_NODEREF, split it up into a
2237 * REF_LOG_ONLY update of the symref and add a separate update for
2238 * the referent to transaction.
2239 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2242 static int lock_ref_for_update(struct files_ref_store *refs,
2243 struct ref_update *update,
2244 struct ref_transaction *transaction,
2245 const char *head_ref,
2246 struct string_list *affected_refnames,
2249 struct strbuf referent = STRBUF_INIT;
2250 int mustexist = (update->flags & REF_HAVE_OLD) &&
2251 !is_null_oid(&update->old_oid);
2253 struct ref_lock *lock;
2255 files_assert_main_repository(refs, "lock_ref_for_update");
2257 if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2258 update->flags |= REF_DELETING;
2261 ret = split_head_update(update, transaction, head_ref,
2262 affected_refnames, err);
2267 ret = lock_raw_ref(refs, update->refname, mustexist,
2268 affected_refnames, NULL,
2270 &update->type, err);
2274 reason = strbuf_detach(err, NULL);
2275 strbuf_addf(err, "cannot lock ref '%s': %s",
2276 original_update_refname(update), reason);
2281 update->backend_data = lock;
2283 if (update->type & REF_ISSYMREF) {
2284 if (update->flags & REF_NODEREF) {
2286 * We won't be reading the referent as part of
2287 * the transaction, so we have to read it here
2288 * to record and possibly check old_sha1:
2290 if (refs_read_ref_full(&refs->base,
2292 lock->old_oid.hash, NULL)) {
2293 if (update->flags & REF_HAVE_OLD) {
2294 strbuf_addf(err, "cannot lock ref '%s': "
2295 "error reading reference",
2296 original_update_refname(update));
2299 } else if (check_old_oid(update, &lock->old_oid, err)) {
2300 return TRANSACTION_GENERIC_ERROR;
2304 * Create a new update for the reference this
2305 * symref is pointing at. Also, we will record
2306 * and verify old_sha1 for this update as part
2307 * of processing the split-off update, so we
2308 * don't have to do it here.
2310 ret = split_symref_update(refs, update,
2311 referent.buf, transaction,
2312 affected_refnames, err);
2317 struct ref_update *parent_update;
2319 if (check_old_oid(update, &lock->old_oid, err))
2320 return TRANSACTION_GENERIC_ERROR;
2323 * If this update is happening indirectly because of a
2324 * symref update, record the old SHA-1 in the parent
2327 for (parent_update = update->parent_update;
2329 parent_update = parent_update->parent_update) {
2330 struct ref_lock *parent_lock = parent_update->backend_data;
2331 oidcpy(&parent_lock->old_oid, &lock->old_oid);
2335 if ((update->flags & REF_HAVE_NEW) &&
2336 !(update->flags & REF_DELETING) &&
2337 !(update->flags & REF_LOG_ONLY)) {
2338 if (!(update->type & REF_ISSYMREF) &&
2339 !oidcmp(&lock->old_oid, &update->new_oid)) {
2341 * The reference already has the desired
2342 * value, so we don't need to write it.
2344 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2346 char *write_err = strbuf_detach(err, NULL);
2349 * The lock was freed upon failure of
2350 * write_ref_to_lockfile():
2352 update->backend_data = NULL;
2354 "cannot update ref '%s': %s",
2355 update->refname, write_err);
2357 return TRANSACTION_GENERIC_ERROR;
2359 update->flags |= REF_NEEDS_COMMIT;
2362 if (!(update->flags & REF_NEEDS_COMMIT)) {
2364 * We didn't call write_ref_to_lockfile(), so
2365 * the lockfile is still open. Close it to
2366 * free up the file descriptor:
2368 if (close_ref_gently(lock)) {
2369 strbuf_addf(err, "couldn't close '%s.lock'",
2371 return TRANSACTION_GENERIC_ERROR;
2378 * Unlock any references in `transaction` that are still locked, and
2379 * mark the transaction closed.
2381 static void files_transaction_cleanup(struct ref_transaction *transaction)
2385 for (i = 0; i < transaction->nr; i++) {
2386 struct ref_update *update = transaction->updates[i];
2387 struct ref_lock *lock = update->backend_data;
2391 update->backend_data = NULL;
2395 transaction->state = REF_TRANSACTION_CLOSED;
2398 static int files_transaction_prepare(struct ref_store *ref_store,
2399 struct ref_transaction *transaction,
2402 struct files_ref_store *refs =
2403 files_downcast(ref_store, REF_STORE_WRITE,
2404 "ref_transaction_prepare");
2407 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2408 char *head_ref = NULL;
2410 struct object_id head_oid;
2414 if (!transaction->nr)
2418 * Fail if a refname appears more than once in the
2419 * transaction. (If we end up splitting up any updates using
2420 * split_symref_update() or split_head_update(), those
2421 * functions will check that the new updates don't have the
2422 * same refname as any existing ones.)
2424 for (i = 0; i < transaction->nr; i++) {
2425 struct ref_update *update = transaction->updates[i];
2426 struct string_list_item *item =
2427 string_list_append(&affected_refnames, update->refname);
2430 * We store a pointer to update in item->util, but at
2431 * the moment we never use the value of this field
2432 * except to check whether it is non-NULL.
2434 item->util = update;
2436 string_list_sort(&affected_refnames);
2437 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2438 ret = TRANSACTION_GENERIC_ERROR;
2443 * Special hack: If a branch is updated directly and HEAD
2444 * points to it (may happen on the remote side of a push
2445 * for example) then logically the HEAD reflog should be
2448 * A generic solution would require reverse symref lookups,
2449 * but finding all symrefs pointing to a given branch would be
2450 * rather costly for this rare event (the direct update of a
2451 * branch) to be worth it. So let's cheat and check with HEAD
2452 * only, which should cover 99% of all usage scenarios (even
2453 * 100% of the default ones).
2455 * So if HEAD is a symbolic reference, then record the name of
2456 * the reference that it points to. If we see an update of
2457 * head_ref within the transaction, then split_head_update()
2458 * arranges for the reflog of HEAD to be updated, too.
2460 head_ref = refs_resolve_refdup(ref_store, "HEAD",
2461 RESOLVE_REF_NO_RECURSE,
2462 head_oid.hash, &head_type);
2464 if (head_ref && !(head_type & REF_ISSYMREF)) {
2465 FREE_AND_NULL(head_ref);
2469 * Acquire all locks, verify old values if provided, check
2470 * that new values are valid, and write new values to the
2471 * lockfiles, ready to be activated. Only keep one lockfile
2472 * open at a time to avoid running out of file descriptors.
2473 * Note that lock_ref_for_update() might append more updates
2474 * to the transaction.
2476 for (i = 0; i < transaction->nr; i++) {
2477 struct ref_update *update = transaction->updates[i];
2479 ret = lock_ref_for_update(refs, update, transaction,
2480 head_ref, &affected_refnames, err);
2487 string_list_clear(&affected_refnames, 0);
2490 files_transaction_cleanup(transaction);
2492 transaction->state = REF_TRANSACTION_PREPARED;
2497 static int files_transaction_finish(struct ref_store *ref_store,
2498 struct ref_transaction *transaction,
2501 struct files_ref_store *refs =
2502 files_downcast(ref_store, 0, "ref_transaction_finish");
2505 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2506 struct string_list_item *ref_to_delete;
2507 struct strbuf sb = STRBUF_INIT;
2511 if (!transaction->nr) {
2512 transaction->state = REF_TRANSACTION_CLOSED;
2516 /* Perform updates first so live commits remain referenced */
2517 for (i = 0; i < transaction->nr; i++) {
2518 struct ref_update *update = transaction->updates[i];
2519 struct ref_lock *lock = update->backend_data;
2521 if (update->flags & REF_NEEDS_COMMIT ||
2522 update->flags & REF_LOG_ONLY) {
2523 if (files_log_ref_write(refs,
2527 update->msg, update->flags,
2529 char *old_msg = strbuf_detach(err, NULL);
2531 strbuf_addf(err, "cannot update the ref '%s': %s",
2532 lock->ref_name, old_msg);
2535 update->backend_data = NULL;
2536 ret = TRANSACTION_GENERIC_ERROR;
2540 if (update->flags & REF_NEEDS_COMMIT) {
2541 clear_loose_ref_cache(refs);
2542 if (commit_ref(lock)) {
2543 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2545 update->backend_data = NULL;
2546 ret = TRANSACTION_GENERIC_ERROR;
2551 /* Perform deletes now that updates are safely completed */
2552 for (i = 0; i < transaction->nr; i++) {
2553 struct ref_update *update = transaction->updates[i];
2554 struct ref_lock *lock = update->backend_data;
2556 if (update->flags & REF_DELETING &&
2557 !(update->flags & REF_LOG_ONLY)) {
2558 if (!(update->type & REF_ISPACKED) ||
2559 update->type & REF_ISSYMREF) {
2560 /* It is a loose reference. */
2562 files_ref_path(refs, &sb, lock->ref_name);
2563 if (unlink_or_msg(sb.buf, err)) {
2564 ret = TRANSACTION_GENERIC_ERROR;
2567 update->flags |= REF_DELETED_LOOSE;
2570 if (!(update->flags & REF_ISPRUNING))
2571 string_list_append(&refs_to_delete,
2576 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2577 ret = TRANSACTION_GENERIC_ERROR;
2581 if (repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {
2582 ret = TRANSACTION_GENERIC_ERROR;
2583 packed_refs_unlock(refs->packed_ref_store);
2587 packed_refs_unlock(refs->packed_ref_store);
2589 /* Delete the reflogs of any references that were deleted: */
2590 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2592 files_reflog_path(refs, &sb, ref_to_delete->string);
2593 if (!unlink_or_warn(sb.buf))
2594 try_remove_empty_parents(refs, ref_to_delete->string,
2595 REMOVE_EMPTY_PARENTS_REFLOG);
2598 clear_loose_ref_cache(refs);
2601 files_transaction_cleanup(transaction);
2603 for (i = 0; i < transaction->nr; i++) {
2604 struct ref_update *update = transaction->updates[i];
2606 if (update->flags & REF_DELETED_LOOSE) {
2608 * The loose reference was deleted. Delete any
2609 * empty parent directories. (Note that this
2610 * can only work because we have already
2611 * removed the lockfile.)
2613 try_remove_empty_parents(refs, update->refname,
2614 REMOVE_EMPTY_PARENTS_REF);
2618 strbuf_release(&sb);
2619 string_list_clear(&refs_to_delete, 0);
2623 static int files_transaction_abort(struct ref_store *ref_store,
2624 struct ref_transaction *transaction,
2627 files_transaction_cleanup(transaction);
2631 static int ref_present(const char *refname,
2632 const struct object_id *oid, int flags, void *cb_data)
2634 struct string_list *affected_refnames = cb_data;
2636 return string_list_has_string(affected_refnames, refname);
2639 static int files_initial_transaction_commit(struct ref_store *ref_store,
2640 struct ref_transaction *transaction,
2643 struct files_ref_store *refs =
2644 files_downcast(ref_store, REF_STORE_WRITE,
2645 "initial_ref_transaction_commit");
2648 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2652 if (transaction->state != REF_TRANSACTION_OPEN)
2653 die("BUG: commit called for transaction that is not open");
2655 /* Fail if a refname appears more than once in the transaction: */
2656 for (i = 0; i < transaction->nr; i++)
2657 string_list_append(&affected_refnames,
2658 transaction->updates[i]->refname);
2659 string_list_sort(&affected_refnames);
2660 if (ref_update_reject_duplicates(&affected_refnames, err)) {
2661 ret = TRANSACTION_GENERIC_ERROR;
2666 * It's really undefined to call this function in an active
2667 * repository or when there are existing references: we are
2668 * only locking and changing packed-refs, so (1) any
2669 * simultaneous processes might try to change a reference at
2670 * the same time we do, and (2) any existing loose versions of
2671 * the references that we are setting would have precedence
2672 * over our values. But some remote helpers create the remote
2673 * "HEAD" and "master" branches before calling this function,
2674 * so here we really only check that none of the references
2675 * that we are creating already exists.
2677 if (refs_for_each_rawref(&refs->base, ref_present,
2678 &affected_refnames))
2679 die("BUG: initial ref transaction called with existing refs");
2681 for (i = 0; i < transaction->nr; i++) {
2682 struct ref_update *update = transaction->updates[i];
2684 if ((update->flags & REF_HAVE_OLD) &&
2685 !is_null_oid(&update->old_oid))
2686 die("BUG: initial ref transaction with old_sha1 set");
2687 if (refs_verify_refname_available(&refs->base, update->refname,
2688 &affected_refnames, NULL,
2690 ret = TRANSACTION_NAME_CONFLICT;
2695 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2696 ret = TRANSACTION_GENERIC_ERROR;
2700 for (i = 0; i < transaction->nr; i++) {
2701 struct ref_update *update = transaction->updates[i];
2703 if ((update->flags & REF_HAVE_NEW) &&
2704 !is_null_oid(&update->new_oid))
2705 add_packed_ref(refs->packed_ref_store, update->refname,
2709 if (commit_packed_refs(refs->packed_ref_store, err)) {
2710 ret = TRANSACTION_GENERIC_ERROR;
2715 packed_refs_unlock(refs->packed_ref_store);
2716 transaction->state = REF_TRANSACTION_CLOSED;
2717 string_list_clear(&affected_refnames, 0);
2721 struct expire_reflog_cb {
2723 reflog_expiry_should_prune_fn *should_prune_fn;
2726 struct object_id last_kept_oid;
2729 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
2730 const char *email, timestamp_t timestamp, int tz,
2731 const char *message, void *cb_data)
2733 struct expire_reflog_cb *cb = cb_data;
2734 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
2736 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
2737 ooid = &cb->last_kept_oid;
2739 if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
2740 message, policy_cb)) {
2742 printf("would prune %s", message);
2743 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2744 printf("prune %s", message);
2747 fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
2748 oid_to_hex(ooid), oid_to_hex(noid),
2749 email, timestamp, tz, message);
2750 oidcpy(&cb->last_kept_oid, noid);
2752 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
2753 printf("keep %s", message);
2758 static int files_reflog_expire(struct ref_store *ref_store,
2759 const char *refname, const unsigned char *sha1,
2761 reflog_expiry_prepare_fn prepare_fn,
2762 reflog_expiry_should_prune_fn should_prune_fn,
2763 reflog_expiry_cleanup_fn cleanup_fn,
2764 void *policy_cb_data)
2766 struct files_ref_store *refs =
2767 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
2768 static struct lock_file reflog_lock;
2769 struct expire_reflog_cb cb;
2770 struct ref_lock *lock;
2771 struct strbuf log_file_sb = STRBUF_INIT;
2775 struct strbuf err = STRBUF_INIT;
2776 struct object_id oid;
2778 memset(&cb, 0, sizeof(cb));
2780 cb.policy_cb = policy_cb_data;
2781 cb.should_prune_fn = should_prune_fn;
2784 * The reflog file is locked by holding the lock on the
2785 * reference itself, plus we might need to update the
2786 * reference if --updateref was specified:
2788 lock = lock_ref_sha1_basic(refs, refname, sha1,
2789 NULL, NULL, REF_NODEREF,
2792 error("cannot lock ref '%s': %s", refname, err.buf);
2793 strbuf_release(&err);
2796 if (!refs_reflog_exists(ref_store, refname)) {
2801 files_reflog_path(refs, &log_file_sb, refname);
2802 log_file = strbuf_detach(&log_file_sb, NULL);
2803 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2805 * Even though holding $GIT_DIR/logs/$reflog.lock has
2806 * no locking implications, we use the lock_file
2807 * machinery here anyway because it does a lot of the
2808 * work we need, including cleaning up if the program
2809 * exits unexpectedly.
2811 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
2812 struct strbuf err = STRBUF_INIT;
2813 unable_to_lock_message(log_file, errno, &err);
2814 error("%s", err.buf);
2815 strbuf_release(&err);
2818 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
2820 error("cannot fdopen %s (%s)",
2821 get_lock_file_path(&reflog_lock), strerror(errno));
2826 hashcpy(oid.hash, sha1);
2828 (*prepare_fn)(refname, &oid, cb.policy_cb);
2829 refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
2830 (*cleanup_fn)(cb.policy_cb);
2832 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
2834 * It doesn't make sense to adjust a reference pointed
2835 * to by a symbolic ref based on expiring entries in
2836 * the symbolic reference's reflog. Nor can we update
2837 * a reference if there are no remaining reflog
2840 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
2841 !(type & REF_ISSYMREF) &&
2842 !is_null_oid(&cb.last_kept_oid);
2844 if (close_lock_file_gently(&reflog_lock)) {
2845 status |= error("couldn't write %s: %s", log_file,
2847 rollback_lock_file(&reflog_lock);
2848 } else if (update &&
2849 (write_in_full(get_lock_file_fd(&lock->lk),
2850 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2851 write_str_in_full(get_lock_file_fd(&lock->lk), "\n") != 1 ||
2852 close_ref_gently(lock) < 0)) {
2853 status |= error("couldn't write %s",
2854 get_lock_file_path(&lock->lk));
2855 rollback_lock_file(&reflog_lock);
2856 } else if (commit_lock_file(&reflog_lock)) {
2857 status |= error("unable to write reflog '%s' (%s)",
2858 log_file, strerror(errno));
2859 } else if (update && commit_ref(lock)) {
2860 status |= error("couldn't set %s", lock->ref_name);
2868 rollback_lock_file(&reflog_lock);
2874 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
2876 struct files_ref_store *refs =
2877 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
2878 struct strbuf sb = STRBUF_INIT;
2881 * Create .git/refs/{heads,tags}
2883 files_ref_path(refs, &sb, "refs/heads");
2884 safe_create_dir(sb.buf, 1);
2887 files_ref_path(refs, &sb, "refs/tags");
2888 safe_create_dir(sb.buf, 1);
2890 strbuf_release(&sb);
2894 struct ref_storage_be refs_be_files = {
2897 files_ref_store_create,
2899 files_transaction_prepare,
2900 files_transaction_finish,
2901 files_transaction_abort,
2902 files_initial_transaction_commit,
2906 files_create_symref,
2910 files_ref_iterator_begin,
2913 files_reflog_iterator_begin,
2914 files_for_each_reflog_ent,
2915 files_for_each_reflog_ent_reverse,
2916 files_reflog_exists,
2917 files_create_reflog,
2918 files_delete_reflog,