3 #include "refs-internal.h"
4 #include "../lockfile.h"
12 struct object_id old_oid;
18 * Information used (along with the information in ref_entry) to
19 * describe a single cached reference. This data structure only
20 * occurs embedded in a union in struct ref_entry, and only when
21 * (ref_entry->flag & REF_DIR) is zero.
25 * The name of the object to which this reference resolves
26 * (which may be a tag object). If REF_ISBROKEN, this is
27 * null. If REF_ISSYMREF, then this is the name of the object
28 * referred to by the last reference in the symlink chain.
33 * If REF_KNOWS_PEELED, then this field holds the peeled value
34 * of this reference, or null if the reference is known not to
35 * be peelable. See the documentation for peel_ref() for an
36 * exact definition of "peelable".
38 struct object_id peeled;
44 * Information used (along with the information in ref_entry) to
45 * describe a level in the hierarchy of references. This data
46 * structure only occurs embedded in a union in struct ref_entry, and
47 * only when (ref_entry.flag & REF_DIR) is set. In that case,
48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
49 * in the directory have already been read:
51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
52 * or packed references, already read.
54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
55 * references that hasn't been read yet (nor has any of its
58 * Entries within a directory are stored within a growable array of
59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
60 * sorted are sorted by their component name in strcmp() order and the
61 * remaining entries are unsorted.
63 * Loose references are read lazily, one directory at a time. When a
64 * directory of loose references is read, then all of the references
65 * in that directory are stored, and REF_INCOMPLETE stubs are created
66 * for any subdirectories, but the subdirectories themselves are not
67 * read. The reading is triggered by get_ref_dir().
73 * Entries with index 0 <= i < sorted are sorted by name. New
74 * entries are appended to the list unsorted, and are sorted
75 * only when required; thus we avoid the need to sort the list
76 * after the addition of every reference.
80 /* A pointer to the ref_cache that contains this ref_dir. */
81 struct ref_cache *ref_cache;
83 struct ref_entry **entries;
87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
89 * public values; see refs.h.
93 * The field ref_entry->u.value.peeled of this value entry contains
94 * the correct peeled value for the reference, which might be
95 * null_sha1 if the reference is not a tag or if it is broken.
97 #define REF_KNOWS_PEELED 0x10
99 /* ref_entry represents a directory of references */
103 * Entry has not yet been read from disk (used only for REF_DIR
104 * entries representing loose references)
106 #define REF_INCOMPLETE 0x40
109 * A ref_entry represents either a reference or a "subdirectory" of
112 * Each directory in the reference namespace is represented by a
113 * ref_entry with (flags & REF_DIR) set and containing a subdir member
114 * that holds the entries in that directory that have been read so
115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
117 * used for loose reference directories.
119 * References are represented by a ref_entry with (flags & REF_DIR)
120 * unset and a value member that describes the reference's value. The
121 * flag member is at the ref_entry level, but it is also needed to
122 * interpret the contents of the value field (in other words, a
123 * ref_value object is not very much use without the enclosing
126 * Reference names cannot end with slash and directories' names are
127 * always stored with a trailing slash (except for the top-level
128 * directory, which is always denoted by ""). This has two nice
129 * consequences: (1) when the entries in each subdir are sorted
130 * lexicographically by name (as they usually are), the references in
131 * a whole tree can be generated in lexicographic order by traversing
132 * the tree in left-to-right, depth-first order; (2) the names of
133 * references and subdirectories cannot conflict, and therefore the
134 * presence of an empty subdirectory does not block the creation of a
135 * similarly-named reference. (The fact that reference names with the
136 * same leading components can conflict *with each other* is a
137 * separate issue that is regulated by verify_refname_available().)
139 * Please note that the name field contains the fully-qualified
140 * reference (or subdirectory) name. Space could be saved by only
141 * storing the relative names. But that would require the full names
142 * to be generated on the fly when iterating in do_for_each_ref(), and
143 * would break callback functions, who have always been able to assume
144 * that the name strings that they are passed will not be freed during
148 unsigned char flag; /* ISSYMREF? ISPACKED? */
150 struct ref_value value; /* if not (flags&REF_DIR) */
151 struct ref_dir subdir; /* if (flags&REF_DIR) */
154 * The full name of the reference (e.g., "refs/heads/master")
155 * or the full name of the directory with a trailing slash
156 * (e.g., "refs/heads/"):
158 char name[FLEX_ARRAY];
161 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
162 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
163 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
164 const char *dirname, size_t len,
166 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
168 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
171 assert(entry->flag & REF_DIR);
172 dir = &entry->u.subdir;
173 if (entry->flag & REF_INCOMPLETE) {
174 read_loose_refs(entry->name, dir);
177 * Manually add refs/bisect, which, being
178 * per-worktree, might not appear in the directory
179 * listing for refs/ in the main repo.
181 if (!strcmp(entry->name, "refs/")) {
182 int pos = search_ref_dir(dir, "refs/bisect/", 12);
184 struct ref_entry *child_entry;
185 child_entry = create_dir_entry(dir->ref_cache,
188 add_entry_to_dir(dir, child_entry);
189 read_loose_refs("refs/bisect",
190 &child_entry->u.subdir);
193 entry->flag &= ~REF_INCOMPLETE;
198 static struct ref_entry *create_ref_entry(const char *refname,
199 const unsigned char *sha1, int flag,
203 struct ref_entry *ref;
206 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
207 die("Reference has invalid format: '%s'", refname);
208 len = strlen(refname) + 1;
209 ref = xmalloc(sizeof(struct ref_entry) + len);
210 hashcpy(ref->u.value.oid.hash, sha1);
211 oidclr(&ref->u.value.peeled);
212 memcpy(ref->name, refname, len);
217 static void clear_ref_dir(struct ref_dir *dir);
219 static void free_ref_entry(struct ref_entry *entry)
221 if (entry->flag & REF_DIR) {
223 * Do not use get_ref_dir() here, as that might
224 * trigger the reading of loose refs.
226 clear_ref_dir(&entry->u.subdir);
232 * Add a ref_entry to the end of dir (unsorted). Entry is always
233 * stored directly in dir; no recursion into subdirectories is
236 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
238 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
239 dir->entries[dir->nr++] = entry;
240 /* optimize for the case that entries are added in order */
242 (dir->nr == dir->sorted + 1 &&
243 strcmp(dir->entries[dir->nr - 2]->name,
244 dir->entries[dir->nr - 1]->name) < 0))
245 dir->sorted = dir->nr;
249 * Clear and free all entries in dir, recursively.
251 static void clear_ref_dir(struct ref_dir *dir)
254 for (i = 0; i < dir->nr; i++)
255 free_ref_entry(dir->entries[i]);
257 dir->sorted = dir->nr = dir->alloc = 0;
262 * Create a struct ref_entry object for the specified dirname.
263 * dirname is the name of the directory with a trailing slash (e.g.,
264 * "refs/heads/") or "" for the top-level directory.
266 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
267 const char *dirname, size_t len,
270 struct ref_entry *direntry;
271 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
272 memcpy(direntry->name, dirname, len);
273 direntry->name[len] = '\0';
274 direntry->u.subdir.ref_cache = ref_cache;
275 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
279 static int ref_entry_cmp(const void *a, const void *b)
281 struct ref_entry *one = *(struct ref_entry **)a;
282 struct ref_entry *two = *(struct ref_entry **)b;
283 return strcmp(one->name, two->name);
286 static void sort_ref_dir(struct ref_dir *dir);
288 struct string_slice {
293 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
295 const struct string_slice *key = key_;
296 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
297 int cmp = strncmp(key->str, ent->name, key->len);
300 return '\0' - (unsigned char)ent->name[key->len];
304 * Return the index of the entry with the given refname from the
305 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
306 * no such entry is found. dir must already be complete.
308 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
310 struct ref_entry **r;
311 struct string_slice key;
313 if (refname == NULL || !dir->nr)
319 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
320 ref_entry_cmp_sslice);
325 return r - dir->entries;
329 * Search for a directory entry directly within dir (without
330 * recursing). Sort dir if necessary. subdirname must be a directory
331 * name (i.e., end in '/'). If mkdir is set, then create the
332 * directory if it is missing; otherwise, return NULL if the desired
333 * directory cannot be found. dir must already be complete.
335 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
336 const char *subdirname, size_t len,
339 int entry_index = search_ref_dir(dir, subdirname, len);
340 struct ref_entry *entry;
341 if (entry_index == -1) {
345 * Since dir is complete, the absence of a subdir
346 * means that the subdir really doesn't exist;
347 * therefore, create an empty record for it but mark
348 * the record complete.
350 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
351 add_entry_to_dir(dir, entry);
353 entry = dir->entries[entry_index];
355 return get_ref_dir(entry);
359 * If refname is a reference name, find the ref_dir within the dir
360 * tree that should hold refname. If refname is a directory name
361 * (i.e., ends in '/'), then return that ref_dir itself. dir must
362 * represent the top-level directory and must already be complete.
363 * Sort ref_dirs and recurse into subdirectories as necessary. If
364 * mkdir is set, then create any missing directories; otherwise,
365 * return NULL if the desired directory cannot be found.
367 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
368 const char *refname, int mkdir)
371 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
372 size_t dirnamelen = slash - refname + 1;
373 struct ref_dir *subdir;
374 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
386 * Find the value entry with the given name in dir, sorting ref_dirs
387 * and recursing into subdirectories as necessary. If the name is not
388 * found or it corresponds to a directory entry, return NULL.
390 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
393 struct ref_entry *entry;
394 dir = find_containing_dir(dir, refname, 0);
397 entry_index = search_ref_dir(dir, refname, strlen(refname));
398 if (entry_index == -1)
400 entry = dir->entries[entry_index];
401 return (entry->flag & REF_DIR) ? NULL : entry;
405 * Remove the entry with the given name from dir, recursing into
406 * subdirectories as necessary. If refname is the name of a directory
407 * (i.e., ends with '/'), then remove the directory and its contents.
408 * If the removal was successful, return the number of entries
409 * remaining in the directory entry that contained the deleted entry.
410 * If the name was not found, return -1. Please note that this
411 * function only deletes the entry from the cache; it does not delete
412 * it from the filesystem or ensure that other cache entries (which
413 * might be symbolic references to the removed entry) are updated.
414 * Nor does it remove any containing dir entries that might be made
415 * empty by the removal. dir must represent the top-level directory
416 * and must already be complete.
418 static int remove_entry(struct ref_dir *dir, const char *refname)
420 int refname_len = strlen(refname);
422 struct ref_entry *entry;
423 int is_dir = refname[refname_len - 1] == '/';
426 * refname represents a reference directory. Remove
427 * the trailing slash; otherwise we will get the
428 * directory *representing* refname rather than the
429 * one *containing* it.
431 char *dirname = xmemdupz(refname, refname_len - 1);
432 dir = find_containing_dir(dir, dirname, 0);
435 dir = find_containing_dir(dir, refname, 0);
439 entry_index = search_ref_dir(dir, refname, refname_len);
440 if (entry_index == -1)
442 entry = dir->entries[entry_index];
444 memmove(&dir->entries[entry_index],
445 &dir->entries[entry_index + 1],
446 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
449 if (dir->sorted > entry_index)
451 free_ref_entry(entry);
456 * Add a ref_entry to the ref_dir (unsorted), recursing into
457 * subdirectories as necessary. dir must represent the top-level
458 * directory. Return 0 on success.
460 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
462 dir = find_containing_dir(dir, ref->name, 1);
465 add_entry_to_dir(dir, ref);
470 * Emit a warning and return true iff ref1 and ref2 have the same name
471 * and the same sha1. Die if they have the same name but different
474 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
476 if (strcmp(ref1->name, ref2->name))
479 /* Duplicate name; make sure that they don't conflict: */
481 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
482 /* This is impossible by construction */
483 die("Reference directory conflict: %s", ref1->name);
485 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
486 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
488 warning("Duplicated ref: %s", ref1->name);
493 * Sort the entries in dir non-recursively (if they are not already
494 * sorted) and remove any duplicate entries.
496 static void sort_ref_dir(struct ref_dir *dir)
499 struct ref_entry *last = NULL;
502 * This check also prevents passing a zero-length array to qsort(),
503 * which is a problem on some platforms.
505 if (dir->sorted == dir->nr)
508 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
510 /* Remove any duplicates: */
511 for (i = 0, j = 0; j < dir->nr; j++) {
512 struct ref_entry *entry = dir->entries[j];
513 if (last && is_dup_ref(last, entry))
514 free_ref_entry(entry);
516 last = dir->entries[i++] = entry;
518 dir->sorted = dir->nr = i;
521 /* Include broken references in a do_for_each_ref*() iteration: */
522 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
525 * Return true iff the reference described by entry can be resolved to
526 * an object in the database. Emit a warning if the referred-to
527 * object does not exist.
529 static int ref_resolves_to_object(struct ref_entry *entry)
531 if (entry->flag & REF_ISBROKEN)
533 if (!has_sha1_file(entry->u.value.oid.hash)) {
534 error("%s does not point to a valid object!", entry->name);
541 * current_ref is a performance hack: when iterating over references
542 * using the for_each_ref*() functions, current_ref is set to the
543 * current reference's entry before calling the callback function. If
544 * the callback function calls peel_ref(), then peel_ref() first
545 * checks whether the reference to be peeled is the current reference
546 * (it usually is) and if so, returns that reference's peeled version
547 * if it is available. This avoids a refname lookup in a common case.
549 static struct ref_entry *current_ref;
551 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
553 struct ref_entry_cb {
562 * Handle one reference in a do_for_each_ref*()-style iteration,
563 * calling an each_ref_fn for each entry.
565 static int do_one_ref(struct ref_entry *entry, void *cb_data)
567 struct ref_entry_cb *data = cb_data;
568 struct ref_entry *old_current_ref;
571 if (!starts_with(entry->name, data->base))
574 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
575 !ref_resolves_to_object(entry))
578 /* Store the old value, in case this is a recursive call: */
579 old_current_ref = current_ref;
581 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
582 entry->flag, data->cb_data);
583 current_ref = old_current_ref;
588 * Call fn for each reference in dir that has index in the range
589 * offset <= index < dir->nr. Recurse into subdirectories that are in
590 * that index range, sorting them before iterating. This function
591 * does not sort dir itself; it should be sorted beforehand. fn is
592 * called for all references, including broken ones.
594 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
595 each_ref_entry_fn fn, void *cb_data)
598 assert(dir->sorted == dir->nr);
599 for (i = offset; i < dir->nr; i++) {
600 struct ref_entry *entry = dir->entries[i];
602 if (entry->flag & REF_DIR) {
603 struct ref_dir *subdir = get_ref_dir(entry);
604 sort_ref_dir(subdir);
605 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
607 retval = fn(entry, cb_data);
616 * Call fn for each reference in the union of dir1 and dir2, in order
617 * by refname. Recurse into subdirectories. If a value entry appears
618 * in both dir1 and dir2, then only process the version that is in
619 * dir2. The input dirs must already be sorted, but subdirs will be
620 * sorted as needed. fn is called for all references, including
623 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
624 struct ref_dir *dir2,
625 each_ref_entry_fn fn, void *cb_data)
630 assert(dir1->sorted == dir1->nr);
631 assert(dir2->sorted == dir2->nr);
633 struct ref_entry *e1, *e2;
635 if (i1 == dir1->nr) {
636 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
638 if (i2 == dir2->nr) {
639 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
641 e1 = dir1->entries[i1];
642 e2 = dir2->entries[i2];
643 cmp = strcmp(e1->name, e2->name);
645 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
646 /* Both are directories; descend them in parallel. */
647 struct ref_dir *subdir1 = get_ref_dir(e1);
648 struct ref_dir *subdir2 = get_ref_dir(e2);
649 sort_ref_dir(subdir1);
650 sort_ref_dir(subdir2);
651 retval = do_for_each_entry_in_dirs(
652 subdir1, subdir2, fn, cb_data);
655 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
656 /* Both are references; ignore the one from dir1. */
657 retval = fn(e2, cb_data);
661 die("conflict between reference and directory: %s",
673 if (e->flag & REF_DIR) {
674 struct ref_dir *subdir = get_ref_dir(e);
675 sort_ref_dir(subdir);
676 retval = do_for_each_entry_in_dir(
677 subdir, 0, fn, cb_data);
679 retval = fn(e, cb_data);
688 * Load all of the refs from the dir into our in-memory cache. The hard work
689 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
690 * through all of the sub-directories. We do not even need to care about
691 * sorting, as traversal order does not matter to us.
693 static void prime_ref_dir(struct ref_dir *dir)
696 for (i = 0; i < dir->nr; i++) {
697 struct ref_entry *entry = dir->entries[i];
698 if (entry->flag & REF_DIR)
699 prime_ref_dir(get_ref_dir(entry));
703 struct nonmatching_ref_data {
704 const struct string_list *skip;
705 const char *conflicting_refname;
708 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
710 struct nonmatching_ref_data *data = vdata;
712 if (data->skip && string_list_has_string(data->skip, entry->name))
715 data->conflicting_refname = entry->name;
720 * Return 0 if a reference named refname could be created without
721 * conflicting with the name of an existing reference in dir.
722 * See verify_refname_available for more information.
724 static int verify_refname_available_dir(const char *refname,
725 const struct string_list *extras,
726 const struct string_list *skip,
731 const char *extra_refname;
733 struct strbuf dirname = STRBUF_INIT;
737 * For the sake of comments in this function, suppose that
738 * refname is "refs/foo/bar".
743 strbuf_grow(&dirname, strlen(refname) + 1);
744 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
745 /* Expand dirname to the new prefix, not including the trailing slash: */
746 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
749 * We are still at a leading dir of the refname (e.g.,
750 * "refs/foo"; if there is a reference with that name,
751 * it is a conflict, *unless* it is in skip.
754 pos = search_ref_dir(dir, dirname.buf, dirname.len);
756 (!skip || !string_list_has_string(skip, dirname.buf))) {
758 * We found a reference whose name is
759 * a proper prefix of refname; e.g.,
760 * "refs/foo", and is not in skip.
762 strbuf_addf(err, "'%s' exists; cannot create '%s'",
763 dirname.buf, refname);
768 if (extras && string_list_has_string(extras, dirname.buf) &&
769 (!skip || !string_list_has_string(skip, dirname.buf))) {
770 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
771 refname, dirname.buf);
776 * Otherwise, we can try to continue our search with
777 * the next component. So try to look up the
778 * directory, e.g., "refs/foo/". If we come up empty,
779 * we know there is nothing under this whole prefix,
780 * but even in that case we still have to continue the
781 * search for conflicts with extras.
783 strbuf_addch(&dirname, '/');
785 pos = search_ref_dir(dir, dirname.buf, dirname.len);
788 * There was no directory "refs/foo/",
789 * so there is nothing under this
790 * whole prefix. So there is no need
791 * to continue looking for conflicting
792 * references. But we need to continue
793 * looking for conflicting extras.
797 dir = get_ref_dir(dir->entries[pos]);
803 * We are at the leaf of our refname (e.g., "refs/foo/bar").
804 * There is no point in searching for a reference with that
805 * name, because a refname isn't considered to conflict with
806 * itself. But we still need to check for references whose
807 * names are in the "refs/foo/bar/" namespace, because they
810 strbuf_addstr(&dirname, refname + dirname.len);
811 strbuf_addch(&dirname, '/');
814 pos = search_ref_dir(dir, dirname.buf, dirname.len);
818 * We found a directory named "$refname/"
819 * (e.g., "refs/foo/bar/"). It is a problem
820 * iff it contains any ref that is not in
823 struct nonmatching_ref_data data;
826 data.conflicting_refname = NULL;
827 dir = get_ref_dir(dir->entries[pos]);
829 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
830 strbuf_addf(err, "'%s' exists; cannot create '%s'",
831 data.conflicting_refname, refname);
837 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
839 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
840 refname, extra_refname);
845 strbuf_release(&dirname);
849 struct packed_ref_cache {
850 struct ref_entry *root;
853 * Count of references to the data structure in this instance,
854 * including the pointer from ref_cache::packed if any. The
855 * data will not be freed as long as the reference count is
858 unsigned int referrers;
861 * Iff the packed-refs file associated with this instance is
862 * currently locked for writing, this points at the associated
863 * lock (which is owned by somebody else). The referrer count
864 * is also incremented when the file is locked and decremented
865 * when it is unlocked.
867 struct lock_file *lock;
869 /* The metadata from when this packed-refs cache was read */
870 struct stat_validity validity;
874 * Future: need to be in "struct repository"
875 * when doing a full libification.
877 static struct ref_cache {
878 struct ref_cache *next;
879 struct ref_entry *loose;
880 struct packed_ref_cache *packed;
882 * The submodule name, or "" for the main repo. We allocate
883 * length 1 rather than FLEX_ARRAY so that the main ref_cache
884 * is initialized correctly.
887 } ref_cache, *submodule_ref_caches;
889 /* Lock used for the main packed-refs file: */
890 static struct lock_file packlock;
893 * Increment the reference count of *packed_refs.
895 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
897 packed_refs->referrers++;
901 * Decrease the reference count of *packed_refs. If it goes to zero,
902 * free *packed_refs and return true; otherwise return false.
904 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
906 if (!--packed_refs->referrers) {
907 free_ref_entry(packed_refs->root);
908 stat_validity_clear(&packed_refs->validity);
916 static void clear_packed_ref_cache(struct ref_cache *refs)
919 struct packed_ref_cache *packed_refs = refs->packed;
921 if (packed_refs->lock)
922 die("internal error: packed-ref cache cleared while locked");
924 release_packed_ref_cache(packed_refs);
928 static void clear_loose_ref_cache(struct ref_cache *refs)
931 free_ref_entry(refs->loose);
937 * Create a new submodule ref cache and add it to the internal
940 static struct ref_cache *create_ref_cache(const char *submodule)
943 struct ref_cache *refs;
946 len = strlen(submodule) + 1;
947 refs = xcalloc(1, sizeof(struct ref_cache) + len);
948 memcpy(refs->name, submodule, len);
949 refs->next = submodule_ref_caches;
950 submodule_ref_caches = refs;
954 static struct ref_cache *lookup_ref_cache(const char *submodule)
956 struct ref_cache *refs;
958 if (!submodule || !*submodule)
961 for (refs = submodule_ref_caches; refs; refs = refs->next)
962 if (!strcmp(submodule, refs->name))
968 * Return a pointer to a ref_cache for the specified submodule. For
969 * the main repository, use submodule==NULL. The returned structure
970 * will be allocated and initialized but not necessarily populated; it
971 * should not be freed.
973 static struct ref_cache *get_ref_cache(const char *submodule)
975 struct ref_cache *refs = lookup_ref_cache(submodule);
977 refs = create_ref_cache(submodule);
981 /* The length of a peeled reference line in packed-refs, including EOL: */
982 #define PEELED_LINE_LENGTH 42
985 * The packed-refs header line that we write out. Perhaps other
986 * traits will be added later. The trailing space is required.
988 static const char PACKED_REFS_HEADER[] =
989 "# pack-refs with: peeled fully-peeled \n";
992 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
993 * Return a pointer to the refname within the line (null-terminated),
994 * or NULL if there was a problem.
996 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1001 * 42: the answer to everything.
1003 * In this case, it happens to be the answer to
1004 * 40 (length of sha1 hex representation)
1005 * +1 (space in between hex and name)
1006 * +1 (newline at the end of the line)
1008 if (line->len <= 42)
1011 if (get_sha1_hex(line->buf, sha1) < 0)
1013 if (!isspace(line->buf[40]))
1016 ref = line->buf + 41;
1020 if (line->buf[line->len - 1] != '\n')
1022 line->buf[--line->len] = 0;
1028 * Read f, which is a packed-refs file, into dir.
1030 * A comment line of the form "# pack-refs with: " may contain zero or
1031 * more traits. We interpret the traits as follows:
1035 * Probably no references are peeled. But if the file contains a
1036 * peeled value for a reference, we will use it.
1040 * References under "refs/tags/", if they *can* be peeled, *are*
1041 * peeled in this file. References outside of "refs/tags/" are
1042 * probably not peeled even if they could have been, but if we find
1043 * a peeled value for such a reference we will use it.
1047 * All references in the file that can be peeled are peeled.
1048 * Inversely (and this is more important), any references in the
1049 * file for which no peeled value is recorded is not peelable. This
1050 * trait should typically be written alongside "peeled" for
1051 * compatibility with older clients, but we do not require it
1052 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1054 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1056 struct ref_entry *last = NULL;
1057 struct strbuf line = STRBUF_INIT;
1058 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1060 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1061 unsigned char sha1[20];
1062 const char *refname;
1065 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1066 if (strstr(traits, " fully-peeled "))
1067 peeled = PEELED_FULLY;
1068 else if (strstr(traits, " peeled "))
1069 peeled = PEELED_TAGS;
1070 /* perhaps other traits later as well */
1074 refname = parse_ref_line(&line, sha1);
1076 int flag = REF_ISPACKED;
1078 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1079 if (!refname_is_safe(refname))
1080 die("packed refname is dangerous: %s", refname);
1082 flag |= REF_BAD_NAME | REF_ISBROKEN;
1084 last = create_ref_entry(refname, sha1, flag, 0);
1085 if (peeled == PEELED_FULLY ||
1086 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1087 last->flag |= REF_KNOWS_PEELED;
1092 line.buf[0] == '^' &&
1093 line.len == PEELED_LINE_LENGTH &&
1094 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1095 !get_sha1_hex(line.buf + 1, sha1)) {
1096 hashcpy(last->u.value.peeled.hash, sha1);
1098 * Regardless of what the file header said,
1099 * we definitely know the value of *this*
1102 last->flag |= REF_KNOWS_PEELED;
1106 strbuf_release(&line);
1110 * Get the packed_ref_cache for the specified ref_cache, creating it
1113 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1115 char *packed_refs_file;
1118 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1120 packed_refs_file = git_pathdup("packed-refs");
1123 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1124 clear_packed_ref_cache(refs);
1126 if (!refs->packed) {
1129 refs->packed = xcalloc(1, sizeof(*refs->packed));
1130 acquire_packed_ref_cache(refs->packed);
1131 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1132 f = fopen(packed_refs_file, "r");
1134 stat_validity_update(&refs->packed->validity, fileno(f));
1135 read_packed_refs(f, get_ref_dir(refs->packed->root));
1139 free(packed_refs_file);
1140 return refs->packed;
1143 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1145 return get_ref_dir(packed_ref_cache->root);
1148 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1150 return get_packed_ref_dir(get_packed_ref_cache(refs));
1154 * Add a reference to the in-memory packed reference cache. This may
1155 * only be called while the packed-refs file is locked (see
1156 * lock_packed_refs()). To actually write the packed-refs file, call
1157 * commit_packed_refs().
1159 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1161 struct packed_ref_cache *packed_ref_cache =
1162 get_packed_ref_cache(&ref_cache);
1164 if (!packed_ref_cache->lock)
1165 die("internal error: packed refs not locked");
1166 add_ref(get_packed_ref_dir(packed_ref_cache),
1167 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1171 * Read the loose references from the namespace dirname into dir
1172 * (without recursing). dirname must end with '/'. dir must be the
1173 * directory entry corresponding to dirname.
1175 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1177 struct ref_cache *refs = dir->ref_cache;
1180 int dirnamelen = strlen(dirname);
1181 struct strbuf refname;
1182 struct strbuf path = STRBUF_INIT;
1183 size_t path_baselen;
1186 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1188 strbuf_git_path(&path, "%s", dirname);
1189 path_baselen = path.len;
1191 d = opendir(path.buf);
1193 strbuf_release(&path);
1197 strbuf_init(&refname, dirnamelen + 257);
1198 strbuf_add(&refname, dirname, dirnamelen);
1200 while ((de = readdir(d)) != NULL) {
1201 unsigned char sha1[20];
1205 if (de->d_name[0] == '.')
1207 if (ends_with(de->d_name, ".lock"))
1209 strbuf_addstr(&refname, de->d_name);
1210 strbuf_addstr(&path, de->d_name);
1211 if (stat(path.buf, &st) < 0) {
1212 ; /* silently ignore */
1213 } else if (S_ISDIR(st.st_mode)) {
1214 strbuf_addch(&refname, '/');
1215 add_entry_to_dir(dir,
1216 create_dir_entry(refs, refname.buf,
1224 read_ok = !resolve_gitlink_ref(refs->name,
1227 read_ok = !read_ref_full(refname.buf,
1228 RESOLVE_REF_READING,
1234 flag |= REF_ISBROKEN;
1235 } else if (is_null_sha1(sha1)) {
1237 * It is so astronomically unlikely
1238 * that NULL_SHA1 is the SHA-1 of an
1239 * actual object that we consider its
1240 * appearance in a loose reference
1241 * file to be repo corruption
1242 * (probably due to a software bug).
1244 flag |= REF_ISBROKEN;
1247 if (check_refname_format(refname.buf,
1248 REFNAME_ALLOW_ONELEVEL)) {
1249 if (!refname_is_safe(refname.buf))
1250 die("loose refname is dangerous: %s", refname.buf);
1252 flag |= REF_BAD_NAME | REF_ISBROKEN;
1254 add_entry_to_dir(dir,
1255 create_ref_entry(refname.buf, sha1, flag, 0));
1257 strbuf_setlen(&refname, dirnamelen);
1258 strbuf_setlen(&path, path_baselen);
1260 strbuf_release(&refname);
1261 strbuf_release(&path);
1265 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1269 * Mark the top-level directory complete because we
1270 * are about to read the only subdirectory that can
1273 refs->loose = create_dir_entry(refs, "", 0, 0);
1275 * Create an incomplete entry for "refs/":
1277 add_entry_to_dir(get_ref_dir(refs->loose),
1278 create_dir_entry(refs, "refs/", 5, 1));
1280 return get_ref_dir(refs->loose);
1283 /* We allow "recursive" symbolic refs. Only within reason, though */
1285 #define MAXREFLEN (1024)
1288 * Called by resolve_gitlink_ref_recursive() after it failed to read
1289 * from the loose refs in ref_cache refs. Find <refname> in the
1290 * packed-refs file for the submodule.
1292 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1293 const char *refname, unsigned char *sha1)
1295 struct ref_entry *ref;
1296 struct ref_dir *dir = get_packed_refs(refs);
1298 ref = find_ref(dir, refname);
1302 hashcpy(sha1, ref->u.value.oid.hash);
1306 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1307 const char *refname, unsigned char *sha1,
1311 char buffer[128], *p;
1314 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1317 ? git_pathdup_submodule(refs->name, "%s", refname)
1318 : git_pathdup("%s", refname);
1319 fd = open(path, O_RDONLY);
1322 return resolve_gitlink_packed_ref(refs, refname, sha1);
1324 len = read(fd, buffer, sizeof(buffer)-1);
1328 while (len && isspace(buffer[len-1]))
1332 /* Was it a detached head or an old-fashioned symlink? */
1333 if (!get_sha1_hex(buffer, sha1))
1337 if (strncmp(buffer, "ref:", 4))
1343 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1346 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1348 int len = strlen(path), retval;
1349 struct strbuf submodule = STRBUF_INIT;
1350 struct ref_cache *refs;
1352 while (len && path[len-1] == '/')
1357 strbuf_add(&submodule, path, len);
1358 refs = lookup_ref_cache(submodule.buf);
1360 if (!is_nonbare_repository_dir(&submodule)) {
1361 strbuf_release(&submodule);
1364 refs = create_ref_cache(submodule.buf);
1366 strbuf_release(&submodule);
1368 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1373 * Return the ref_entry for the given refname from the packed
1374 * references. If it does not exist, return NULL.
1376 static struct ref_entry *get_packed_ref(const char *refname)
1378 return find_ref(get_packed_refs(&ref_cache), refname);
1382 * A loose ref file doesn't exist; check for a packed ref. The
1383 * options are forwarded from resolve_safe_unsafe().
1385 static int resolve_missing_loose_ref(const char *refname,
1387 unsigned char *sha1,
1390 struct ref_entry *entry;
1393 * The loose reference file does not exist; check for a packed
1396 entry = get_packed_ref(refname);
1398 hashcpy(sha1, entry->u.value.oid.hash);
1400 *flags |= REF_ISPACKED;
1403 /* The reference is not a packed reference, either. */
1404 if (resolve_flags & RESOLVE_REF_READING) {
1413 /* This function needs to return a meaningful errno on failure */
1414 static const char *resolve_ref_1(const char *refname,
1416 unsigned char *sha1,
1418 struct strbuf *sb_refname,
1419 struct strbuf *sb_path,
1420 struct strbuf *sb_contents)
1422 int depth = MAXDEPTH;
1428 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1430 *flags |= REF_BAD_NAME;
1432 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1433 !refname_is_safe(refname)) {
1438 * dwim_ref() uses REF_ISBROKEN to distinguish between
1439 * missing refs and refs that were present but invalid,
1440 * to complain about the latter to stderr.
1442 * We don't know whether the ref exists, so don't set
1458 strbuf_reset(sb_path);
1459 strbuf_git_path(sb_path, "%s", refname);
1460 path = sb_path->buf;
1463 * We might have to loop back here to avoid a race
1464 * condition: first we lstat() the file, then we try
1465 * to read it as a link or as a file. But if somebody
1466 * changes the type of the file (file <-> directory
1467 * <-> symlink) between the lstat() and reading, then
1468 * we don't want to report that as an error but rather
1469 * try again starting with the lstat().
1472 if (lstat(path, &st) < 0) {
1473 if (errno != ENOENT)
1475 if (resolve_missing_loose_ref(refname, resolve_flags,
1481 *flags |= REF_ISBROKEN;
1486 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1487 if (S_ISLNK(st.st_mode)) {
1488 strbuf_reset(sb_contents);
1489 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1490 if (errno == ENOENT || errno == EINVAL)
1491 /* inconsistent with lstat; retry */
1496 if (starts_with(sb_contents->buf, "refs/") &&
1497 !check_refname_format(sb_contents->buf, 0)) {
1498 strbuf_swap(sb_refname, sb_contents);
1499 refname = sb_refname->buf;
1501 *flags |= REF_ISSYMREF;
1502 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1510 /* Is it a directory? */
1511 if (S_ISDIR(st.st_mode)) {
1517 * Anything else, just open it and try to use it as
1520 fd = open(path, O_RDONLY);
1522 if (errno == ENOENT)
1523 /* inconsistent with lstat; retry */
1528 strbuf_reset(sb_contents);
1529 if (strbuf_read(sb_contents, fd, 256) < 0) {
1530 int save_errno = errno;
1536 strbuf_rtrim(sb_contents);
1539 * Is it a symbolic ref?
1541 if (!starts_with(sb_contents->buf, "ref:")) {
1543 * Please note that FETCH_HEAD has a second
1544 * line containing other data.
1546 if (get_sha1_hex(sb_contents->buf, sha1) ||
1547 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1549 *flags |= REF_ISBROKEN;
1556 *flags |= REF_ISBROKEN;
1561 *flags |= REF_ISSYMREF;
1562 buf = sb_contents->buf + 4;
1563 while (isspace(*buf))
1565 strbuf_reset(sb_refname);
1566 strbuf_addstr(sb_refname, buf);
1567 refname = sb_refname->buf;
1568 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1572 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1574 *flags |= REF_ISBROKEN;
1576 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1577 !refname_is_safe(buf)) {
1586 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1587 unsigned char *sha1, int *flags)
1589 static struct strbuf sb_refname = STRBUF_INIT;
1590 struct strbuf sb_contents = STRBUF_INIT;
1591 struct strbuf sb_path = STRBUF_INIT;
1594 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1595 &sb_refname, &sb_path, &sb_contents);
1596 strbuf_release(&sb_path);
1597 strbuf_release(&sb_contents);
1602 * Peel the entry (if possible) and return its new peel_status. If
1603 * repeel is true, re-peel the entry even if there is an old peeled
1604 * value that is already stored in it.
1606 * It is OK to call this function with a packed reference entry that
1607 * might be stale and might even refer to an object that has since
1608 * been garbage-collected. In such a case, if the entry has
1609 * REF_KNOWS_PEELED then leave the status unchanged and return
1610 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1612 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1614 enum peel_status status;
1616 if (entry->flag & REF_KNOWS_PEELED) {
1618 entry->flag &= ~REF_KNOWS_PEELED;
1619 oidclr(&entry->u.value.peeled);
1621 return is_null_oid(&entry->u.value.peeled) ?
1622 PEEL_NON_TAG : PEEL_PEELED;
1625 if (entry->flag & REF_ISBROKEN)
1627 if (entry->flag & REF_ISSYMREF)
1628 return PEEL_IS_SYMREF;
1630 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1631 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1632 entry->flag |= REF_KNOWS_PEELED;
1636 int peel_ref(const char *refname, unsigned char *sha1)
1639 unsigned char base[20];
1641 if (current_ref && (current_ref->name == refname
1642 || !strcmp(current_ref->name, refname))) {
1643 if (peel_entry(current_ref, 0))
1645 hashcpy(sha1, current_ref->u.value.peeled.hash);
1649 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1653 * If the reference is packed, read its ref_entry from the
1654 * cache in the hope that we already know its peeled value.
1655 * We only try this optimization on packed references because
1656 * (a) forcing the filling of the loose reference cache could
1657 * be expensive and (b) loose references anyway usually do not
1658 * have REF_KNOWS_PEELED.
1660 if (flag & REF_ISPACKED) {
1661 struct ref_entry *r = get_packed_ref(refname);
1663 if (peel_entry(r, 0))
1665 hashcpy(sha1, r->u.value.peeled.hash);
1670 return peel_object(base, sha1);
1674 * Call fn for each reference in the specified ref_cache, omitting
1675 * references not in the containing_dir of base. fn is called for all
1676 * references, including broken ones. If fn ever returns a non-zero
1677 * value, stop the iteration and return that value; otherwise, return
1680 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1681 each_ref_entry_fn fn, void *cb_data)
1683 struct packed_ref_cache *packed_ref_cache;
1684 struct ref_dir *loose_dir;
1685 struct ref_dir *packed_dir;
1689 * We must make sure that all loose refs are read before accessing the
1690 * packed-refs file; this avoids a race condition in which loose refs
1691 * are migrated to the packed-refs file by a simultaneous process, but
1692 * our in-memory view is from before the migration. get_packed_ref_cache()
1693 * takes care of making sure our view is up to date with what is on
1696 loose_dir = get_loose_refs(refs);
1697 if (base && *base) {
1698 loose_dir = find_containing_dir(loose_dir, base, 0);
1701 prime_ref_dir(loose_dir);
1703 packed_ref_cache = get_packed_ref_cache(refs);
1704 acquire_packed_ref_cache(packed_ref_cache);
1705 packed_dir = get_packed_ref_dir(packed_ref_cache);
1706 if (base && *base) {
1707 packed_dir = find_containing_dir(packed_dir, base, 0);
1710 if (packed_dir && loose_dir) {
1711 sort_ref_dir(packed_dir);
1712 sort_ref_dir(loose_dir);
1713 retval = do_for_each_entry_in_dirs(
1714 packed_dir, loose_dir, fn, cb_data);
1715 } else if (packed_dir) {
1716 sort_ref_dir(packed_dir);
1717 retval = do_for_each_entry_in_dir(
1718 packed_dir, 0, fn, cb_data);
1719 } else if (loose_dir) {
1720 sort_ref_dir(loose_dir);
1721 retval = do_for_each_entry_in_dir(
1722 loose_dir, 0, fn, cb_data);
1725 release_packed_ref_cache(packed_ref_cache);
1730 * Call fn for each reference in the specified ref_cache for which the
1731 * refname begins with base. If trim is non-zero, then trim that many
1732 * characters off the beginning of each refname before passing the
1733 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1734 * broken references in the iteration. If fn ever returns a non-zero
1735 * value, stop the iteration and return that value; otherwise, return
1738 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1739 each_ref_fn fn, int trim, int flags, void *cb_data)
1741 struct ref_entry_cb data;
1746 data.cb_data = cb_data;
1748 if (ref_paranoia < 0)
1749 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1751 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1753 return do_for_each_entry(refs, base, do_one_ref, &data);
1756 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1758 struct object_id oid;
1762 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1763 return fn("HEAD", &oid, 0, cb_data);
1768 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1769 return fn("HEAD", &oid, flag, cb_data);
1774 int head_ref(each_ref_fn fn, void *cb_data)
1776 return do_head_ref(NULL, fn, cb_data);
1779 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1781 return do_head_ref(submodule, fn, cb_data);
1784 int for_each_ref(each_ref_fn fn, void *cb_data)
1786 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1789 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1791 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1794 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1796 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1799 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1801 unsigned int flag = 0;
1804 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1805 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
1808 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1809 each_ref_fn fn, void *cb_data)
1811 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1814 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1816 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
1817 strlen(git_replace_ref_base), 0, cb_data);
1820 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1822 struct strbuf buf = STRBUF_INIT;
1824 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1825 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1826 strbuf_release(&buf);
1830 int for_each_rawref(each_ref_fn fn, void *cb_data)
1832 return do_for_each_ref(&ref_cache, "", fn, 0,
1833 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1836 static void unlock_ref(struct ref_lock *lock)
1838 /* Do not free lock->lk -- atexit() still looks at them */
1840 rollback_lock_file(lock->lk);
1841 free(lock->ref_name);
1842 free(lock->orig_ref_name);
1847 * Verify that the reference locked by lock has the value old_sha1.
1848 * Fail if the reference doesn't exist and mustexist is set. Return 0
1849 * on success. On error, write an error message to err, set errno, and
1850 * return a negative value.
1852 static int verify_lock(struct ref_lock *lock,
1853 const unsigned char *old_sha1, int mustexist,
1858 if (read_ref_full(lock->ref_name,
1859 mustexist ? RESOLVE_REF_READING : 0,
1860 lock->old_oid.hash, NULL)) {
1862 int save_errno = errno;
1863 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1867 hashclr(lock->old_oid.hash);
1871 if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1872 strbuf_addf(err, "ref %s is at %s but expected %s",
1874 sha1_to_hex(lock->old_oid.hash),
1875 sha1_to_hex(old_sha1));
1882 static int remove_empty_directories(struct strbuf *path)
1885 * we want to create a file but there is a directory there;
1886 * if that is an empty directory (or a directory that contains
1887 * only empty directories), remove them.
1889 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1893 * Locks a ref returning the lock on success and NULL on failure.
1894 * On failure errno is set to something meaningful.
1896 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1897 const unsigned char *old_sha1,
1898 const struct string_list *extras,
1899 const struct string_list *skip,
1900 unsigned int flags, int *type_p,
1903 struct strbuf ref_file = STRBUF_INIT;
1904 struct strbuf orig_ref_file = STRBUF_INIT;
1905 const char *orig_refname = refname;
1906 struct ref_lock *lock;
1910 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1911 int resolve_flags = 0;
1912 int attempts_remaining = 3;
1916 lock = xcalloc(1, sizeof(struct ref_lock));
1919 resolve_flags |= RESOLVE_REF_READING;
1920 if (flags & REF_DELETING)
1921 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1922 if (flags & REF_NODEREF) {
1923 resolve_flags |= RESOLVE_REF_NO_RECURSE;
1924 lflags |= LOCK_NO_DEREF;
1927 refname = resolve_ref_unsafe(refname, resolve_flags,
1928 lock->old_oid.hash, &type);
1929 if (!refname && errno == EISDIR) {
1931 * we are trying to lock foo but we used to
1932 * have foo/bar which now does not exist;
1933 * it is normal for the empty directory 'foo'
1936 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1937 if (remove_empty_directories(&orig_ref_file)) {
1939 if (!verify_refname_available_dir(orig_refname, extras, skip,
1940 get_loose_refs(&ref_cache), err))
1941 strbuf_addf(err, "there are still refs under '%s'",
1945 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1946 lock->old_oid.hash, &type);
1952 if (last_errno != ENOTDIR ||
1953 !verify_refname_available_dir(orig_refname, extras, skip,
1954 get_loose_refs(&ref_cache), err))
1955 strbuf_addf(err, "unable to resolve reference %s: %s",
1956 orig_refname, strerror(last_errno));
1961 if (flags & REF_NODEREF)
1962 refname = orig_refname;
1965 * If the ref did not exist and we are creating it, make sure
1966 * there is no existing packed ref whose name begins with our
1967 * refname, nor a packed ref whose name is a proper prefix of
1970 if (is_null_oid(&lock->old_oid) &&
1971 verify_refname_available_dir(refname, extras, skip,
1972 get_packed_refs(&ref_cache), err)) {
1973 last_errno = ENOTDIR;
1977 lock->lk = xcalloc(1, sizeof(struct lock_file));
1979 lock->ref_name = xstrdup(refname);
1980 lock->orig_ref_name = xstrdup(orig_refname);
1981 strbuf_git_path(&ref_file, "%s", refname);
1984 switch (safe_create_leading_directories_const(ref_file.buf)) {
1986 break; /* success */
1988 if (--attempts_remaining > 0)
1993 strbuf_addf(err, "unable to create directory for %s",
1998 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
2000 if (errno == ENOENT && --attempts_remaining > 0)
2002 * Maybe somebody just deleted one of the
2003 * directories leading to ref_file. Try
2008 unable_to_lock_message(ref_file.buf, errno, err);
2012 if (verify_lock(lock, old_sha1, mustexist, err)) {
2023 strbuf_release(&ref_file);
2024 strbuf_release(&orig_ref_file);
2030 * Write an entry to the packed-refs file for the specified refname.
2031 * If peeled is non-NULL, write it as the entry's peeled value.
2033 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2034 unsigned char *peeled)
2036 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2038 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2042 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2044 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2046 enum peel_status peel_status = peel_entry(entry, 0);
2048 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2049 error("internal error: %s is not a valid packed reference!",
2051 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2052 peel_status == PEEL_PEELED ?
2053 entry->u.value.peeled.hash : NULL);
2058 * Lock the packed-refs file for writing. Flags is passed to
2059 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2060 * errno appropriately and return a nonzero value.
2062 static int lock_packed_refs(int flags)
2064 static int timeout_configured = 0;
2065 static int timeout_value = 1000;
2067 struct packed_ref_cache *packed_ref_cache;
2069 if (!timeout_configured) {
2070 git_config_get_int("core.packedrefstimeout", &timeout_value);
2071 timeout_configured = 1;
2074 if (hold_lock_file_for_update_timeout(
2075 &packlock, git_path("packed-refs"),
2076 flags, timeout_value) < 0)
2079 * Get the current packed-refs while holding the lock. If the
2080 * packed-refs file has been modified since we last read it,
2081 * this will automatically invalidate the cache and re-read
2082 * the packed-refs file.
2084 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2085 packed_ref_cache->lock = &packlock;
2086 /* Increment the reference count to prevent it from being freed: */
2087 acquire_packed_ref_cache(packed_ref_cache);
2092 * Write the current version of the packed refs cache from memory to
2093 * disk. The packed-refs file must already be locked for writing (see
2094 * lock_packed_refs()). Return zero on success. On errors, set errno
2095 * and return a nonzero value
2097 static int commit_packed_refs(void)
2099 struct packed_ref_cache *packed_ref_cache =
2100 get_packed_ref_cache(&ref_cache);
2105 if (!packed_ref_cache->lock)
2106 die("internal error: packed-refs not locked");
2108 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2110 die_errno("unable to fdopen packed-refs descriptor");
2112 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2113 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2114 0, write_packed_entry_fn, out);
2116 if (commit_lock_file(packed_ref_cache->lock)) {
2120 packed_ref_cache->lock = NULL;
2121 release_packed_ref_cache(packed_ref_cache);
2127 * Rollback the lockfile for the packed-refs file, and discard the
2128 * in-memory packed reference cache. (The packed-refs file will be
2129 * read anew if it is needed again after this function is called.)
2131 static void rollback_packed_refs(void)
2133 struct packed_ref_cache *packed_ref_cache =
2134 get_packed_ref_cache(&ref_cache);
2136 if (!packed_ref_cache->lock)
2137 die("internal error: packed-refs not locked");
2138 rollback_lock_file(packed_ref_cache->lock);
2139 packed_ref_cache->lock = NULL;
2140 release_packed_ref_cache(packed_ref_cache);
2141 clear_packed_ref_cache(&ref_cache);
2144 struct ref_to_prune {
2145 struct ref_to_prune *next;
2146 unsigned char sha1[20];
2147 char name[FLEX_ARRAY];
2150 struct pack_refs_cb_data {
2152 struct ref_dir *packed_refs;
2153 struct ref_to_prune *ref_to_prune;
2157 * An each_ref_entry_fn that is run over loose references only. If
2158 * the loose reference can be packed, add an entry in the packed ref
2159 * cache. If the reference should be pruned, also add it to
2160 * ref_to_prune in the pack_refs_cb_data.
2162 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2164 struct pack_refs_cb_data *cb = cb_data;
2165 enum peel_status peel_status;
2166 struct ref_entry *packed_entry;
2167 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2169 /* Do not pack per-worktree refs: */
2170 if (ref_type(entry->name) != REF_TYPE_NORMAL)
2173 /* ALWAYS pack tags */
2174 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2177 /* Do not pack symbolic or broken refs: */
2178 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2181 /* Add a packed ref cache entry equivalent to the loose entry. */
2182 peel_status = peel_entry(entry, 1);
2183 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2184 die("internal error peeling reference %s (%s)",
2185 entry->name, oid_to_hex(&entry->u.value.oid));
2186 packed_entry = find_ref(cb->packed_refs, entry->name);
2188 /* Overwrite existing packed entry with info from loose entry */
2189 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2190 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2192 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2193 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2194 add_ref(cb->packed_refs, packed_entry);
2196 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2198 /* Schedule the loose reference for pruning if requested. */
2199 if ((cb->flags & PACK_REFS_PRUNE)) {
2200 int namelen = strlen(entry->name) + 1;
2201 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2202 hashcpy(n->sha1, entry->u.value.oid.hash);
2203 memcpy(n->name, entry->name, namelen); /* includes NUL */
2204 n->next = cb->ref_to_prune;
2205 cb->ref_to_prune = n;
2211 * Remove empty parents, but spare refs/ and immediate subdirs.
2212 * Note: munges *name.
2214 static void try_remove_empty_parents(char *name)
2219 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2220 while (*p && *p != '/')
2222 /* tolerate duplicate slashes; see check_refname_format() */
2226 for (q = p; *q; q++)
2229 while (q > p && *q != '/')
2231 while (q > p && *(q-1) == '/')
2236 if (rmdir(git_path("%s", name)))
2241 /* make sure nobody touched the ref, and unlink */
2242 static void prune_ref(struct ref_to_prune *r)
2244 struct ref_transaction *transaction;
2245 struct strbuf err = STRBUF_INIT;
2247 if (check_refname_format(r->name, 0))
2250 transaction = ref_transaction_begin(&err);
2252 ref_transaction_delete(transaction, r->name, r->sha1,
2253 REF_ISPRUNING, NULL, &err) ||
2254 ref_transaction_commit(transaction, &err)) {
2255 ref_transaction_free(transaction);
2256 error("%s", err.buf);
2257 strbuf_release(&err);
2260 ref_transaction_free(transaction);
2261 strbuf_release(&err);
2262 try_remove_empty_parents(r->name);
2265 static void prune_refs(struct ref_to_prune *r)
2273 int pack_refs(unsigned int flags)
2275 struct pack_refs_cb_data cbdata;
2277 memset(&cbdata, 0, sizeof(cbdata));
2278 cbdata.flags = flags;
2280 lock_packed_refs(LOCK_DIE_ON_ERROR);
2281 cbdata.packed_refs = get_packed_refs(&ref_cache);
2283 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2284 pack_if_possible_fn, &cbdata);
2286 if (commit_packed_refs())
2287 die_errno("unable to overwrite old ref-pack file");
2289 prune_refs(cbdata.ref_to_prune);
2294 * Rewrite the packed-refs file, omitting any refs listed in
2295 * 'refnames'. On error, leave packed-refs unchanged, write an error
2296 * message to 'err', and return a nonzero value.
2298 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2300 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2302 struct ref_dir *packed;
2303 struct string_list_item *refname;
2304 int ret, needs_repacking = 0, removed = 0;
2308 /* Look for a packed ref */
2309 for_each_string_list_item(refname, refnames) {
2310 if (get_packed_ref(refname->string)) {
2311 needs_repacking = 1;
2316 /* Avoid locking if we have nothing to do */
2317 if (!needs_repacking)
2318 return 0; /* no refname exists in packed refs */
2320 if (lock_packed_refs(0)) {
2321 unable_to_lock_message(git_path("packed-refs"), errno, err);
2324 packed = get_packed_refs(&ref_cache);
2326 /* Remove refnames from the cache */
2327 for_each_string_list_item(refname, refnames)
2328 if (remove_entry(packed, refname->string) != -1)
2332 * All packed entries disappeared while we were
2333 * acquiring the lock.
2335 rollback_packed_refs();
2339 /* Write what remains */
2340 ret = commit_packed_refs();
2342 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2347 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2351 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2353 * loose. The loose file name is the same as the
2354 * lockfile name, minus ".lock":
2356 char *loose_filename = get_locked_file_path(lock->lk);
2357 int res = unlink_or_msg(loose_filename, err);
2358 free(loose_filename);
2365 int delete_refs(struct string_list *refnames)
2367 struct strbuf err = STRBUF_INIT;
2373 result = repack_without_refs(refnames, &err);
2376 * If we failed to rewrite the packed-refs file, then
2377 * it is unsafe to try to remove loose refs, because
2378 * doing so might expose an obsolete packed value for
2379 * a reference that might even point at an object that
2380 * has been garbage collected.
2382 if (refnames->nr == 1)
2383 error(_("could not delete reference %s: %s"),
2384 refnames->items[0].string, err.buf);
2386 error(_("could not delete references: %s"), err.buf);
2391 for (i = 0; i < refnames->nr; i++) {
2392 const char *refname = refnames->items[i].string;
2394 if (delete_ref(refname, NULL, 0))
2395 result |= error(_("could not remove reference %s"), refname);
2399 strbuf_release(&err);
2404 * People using contrib's git-new-workdir have .git/logs/refs ->
2405 * /some/other/path/.git/logs/refs, and that may live on another device.
2407 * IOW, to avoid cross device rename errors, the temporary renamed log must
2408 * live into logs/refs.
2410 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2412 static int rename_tmp_log(const char *newrefname)
2414 int attempts_remaining = 4;
2415 struct strbuf path = STRBUF_INIT;
2419 strbuf_reset(&path);
2420 strbuf_git_path(&path, "logs/%s", newrefname);
2421 switch (safe_create_leading_directories_const(path.buf)) {
2423 break; /* success */
2425 if (--attempts_remaining > 0)
2429 error("unable to create directory for %s", newrefname);
2433 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2434 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2436 * rename(a, b) when b is an existing
2437 * directory ought to result in ISDIR, but
2438 * Solaris 5.8 gives ENOTDIR. Sheesh.
2440 if (remove_empty_directories(&path)) {
2441 error("Directory not empty: logs/%s", newrefname);
2445 } else if (errno == ENOENT && --attempts_remaining > 0) {
2447 * Maybe another process just deleted one of
2448 * the directories in the path to newrefname.
2449 * Try again from the beginning.
2453 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2454 newrefname, strerror(errno));
2460 strbuf_release(&path);
2464 int verify_refname_available(const char *newname,
2465 struct string_list *extras,
2466 struct string_list *skip,
2469 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2470 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2472 if (verify_refname_available_dir(newname, extras, skip,
2473 packed_refs, err) ||
2474 verify_refname_available_dir(newname, extras, skip,
2481 static int write_ref_to_lockfile(struct ref_lock *lock,
2482 const unsigned char *sha1, struct strbuf *err);
2483 static int commit_ref_update(struct ref_lock *lock,
2484 const unsigned char *sha1, const char *logmsg,
2485 int flags, struct strbuf *err);
2487 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2489 unsigned char sha1[20], orig_sha1[20];
2490 int flag = 0, logmoved = 0;
2491 struct ref_lock *lock;
2492 struct stat loginfo;
2493 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2494 const char *symref = NULL;
2495 struct strbuf err = STRBUF_INIT;
2497 if (log && S_ISLNK(loginfo.st_mode))
2498 return error("reflog for %s is a symlink", oldrefname);
2500 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2502 if (flag & REF_ISSYMREF)
2503 return error("refname %s is a symbolic ref, renaming it is not supported",
2506 return error("refname %s not found", oldrefname);
2508 if (!rename_ref_available(oldrefname, newrefname))
2511 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2512 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2513 oldrefname, strerror(errno));
2515 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2516 error("unable to delete old %s", oldrefname);
2520 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2521 delete_ref(newrefname, sha1, REF_NODEREF)) {
2522 if (errno==EISDIR) {
2523 struct strbuf path = STRBUF_INIT;
2526 strbuf_git_path(&path, "%s", newrefname);
2527 result = remove_empty_directories(&path);
2528 strbuf_release(&path);
2531 error("Directory not empty: %s", newrefname);
2535 error("unable to delete existing %s", newrefname);
2540 if (log && rename_tmp_log(newrefname))
2545 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2547 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2548 strbuf_release(&err);
2551 hashcpy(lock->old_oid.hash, orig_sha1);
2553 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2554 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2555 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2556 strbuf_release(&err);
2563 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2565 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2566 strbuf_release(&err);
2570 flag = log_all_ref_updates;
2571 log_all_ref_updates = 0;
2572 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2573 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2574 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2575 strbuf_release(&err);
2577 log_all_ref_updates = flag;
2580 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2581 error("unable to restore logfile %s from %s: %s",
2582 oldrefname, newrefname, strerror(errno));
2583 if (!logmoved && log &&
2584 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2585 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2586 oldrefname, strerror(errno));
2591 static int close_ref(struct ref_lock *lock)
2593 if (close_lock_file(lock->lk))
2598 static int commit_ref(struct ref_lock *lock)
2600 if (commit_lock_file(lock->lk))
2606 * Create a reflog for a ref. If force_create = 0, the reflog will
2607 * only be created for certain refs (those for which
2608 * should_autocreate_reflog returns non-zero. Otherwise, create it
2609 * regardless of the ref name. Fill in *err and return -1 on failure.
2611 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2613 int logfd, oflags = O_APPEND | O_WRONLY;
2615 strbuf_git_path(logfile, "logs/%s", refname);
2616 if (force_create || should_autocreate_reflog(refname)) {
2617 if (safe_create_leading_directories(logfile->buf) < 0) {
2618 strbuf_addf(err, "unable to create directory for %s: "
2619 "%s", logfile->buf, strerror(errno));
2625 logfd = open(logfile->buf, oflags, 0666);
2627 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2630 if (errno == EISDIR) {
2631 if (remove_empty_directories(logfile)) {
2632 strbuf_addf(err, "There are still logs under "
2633 "'%s'", logfile->buf);
2636 logfd = open(logfile->buf, oflags, 0666);
2640 strbuf_addf(err, "unable to append to %s: %s",
2641 logfile->buf, strerror(errno));
2646 adjust_shared_perm(logfile->buf);
2652 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2655 struct strbuf sb = STRBUF_INIT;
2657 ret = log_ref_setup(refname, &sb, err, force_create);
2658 strbuf_release(&sb);
2662 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2663 const unsigned char *new_sha1,
2664 const char *committer, const char *msg)
2666 int msglen, written;
2667 unsigned maxlen, len;
2670 msglen = msg ? strlen(msg) : 0;
2671 maxlen = strlen(committer) + msglen + 100;
2672 logrec = xmalloc(maxlen);
2673 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2674 sha1_to_hex(old_sha1),
2675 sha1_to_hex(new_sha1),
2678 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2680 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2688 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2689 const unsigned char *new_sha1, const char *msg,
2690 struct strbuf *logfile, int flags,
2693 int logfd, result, oflags = O_APPEND | O_WRONLY;
2695 if (log_all_ref_updates < 0)
2696 log_all_ref_updates = !is_bare_repository();
2698 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2703 logfd = open(logfile->buf, oflags);
2706 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2707 git_committer_info(0), msg);
2709 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2715 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2722 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2723 const unsigned char *new_sha1, const char *msg,
2724 int flags, struct strbuf *err)
2726 return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2730 int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2731 const unsigned char *new_sha1, const char *msg,
2732 int flags, struct strbuf *err)
2734 struct strbuf sb = STRBUF_INIT;
2735 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2737 strbuf_release(&sb);
2742 * Write sha1 into the open lockfile, then close the lockfile. On
2743 * errors, rollback the lockfile, fill in *err and
2746 static int write_ref_to_lockfile(struct ref_lock *lock,
2747 const unsigned char *sha1, struct strbuf *err)
2749 static char term = '\n';
2753 o = parse_object(sha1);
2756 "Trying to write ref %s with nonexistent object %s",
2757 lock->ref_name, sha1_to_hex(sha1));
2761 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2763 "Trying to write non-commit object %s to branch %s",
2764 sha1_to_hex(sha1), lock->ref_name);
2768 fd = get_lock_file_fd(lock->lk);
2769 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2770 write_in_full(fd, &term, 1) != 1 ||
2771 close_ref(lock) < 0) {
2773 "Couldn't write %s", get_lock_file_path(lock->lk));
2781 * Commit a change to a loose reference that has already been written
2782 * to the loose reference lockfile. Also update the reflogs if
2783 * necessary, using the specified lockmsg (which can be NULL).
2785 static int commit_ref_update(struct ref_lock *lock,
2786 const unsigned char *sha1, const char *logmsg,
2787 int flags, struct strbuf *err)
2789 clear_loose_ref_cache(&ref_cache);
2790 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2791 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2792 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2793 char *old_msg = strbuf_detach(err, NULL);
2794 strbuf_addf(err, "Cannot update the ref '%s': %s",
2795 lock->ref_name, old_msg);
2800 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2802 * Special hack: If a branch is updated directly and HEAD
2803 * points to it (may happen on the remote side of a push
2804 * for example) then logically the HEAD reflog should be
2806 * A generic solution implies reverse symref information,
2807 * but finding all symrefs pointing to the given branch
2808 * would be rather costly for this rare event (the direct
2809 * update of a branch) to be worth it. So let's cheat and
2810 * check with HEAD only which should cover 99% of all usage
2811 * scenarios (even 100% of the default ones).
2813 unsigned char head_sha1[20];
2815 const char *head_ref;
2816 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2817 head_sha1, &head_flag);
2818 if (head_ref && (head_flag & REF_ISSYMREF) &&
2819 !strcmp(head_ref, lock->ref_name)) {
2820 struct strbuf log_err = STRBUF_INIT;
2821 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2822 logmsg, 0, &log_err)) {
2823 error("%s", log_err.buf);
2824 strbuf_release(&log_err);
2828 if (commit_ref(lock)) {
2829 error("Couldn't set %s", lock->ref_name);
2838 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2841 #ifndef NO_SYMLINK_HEAD
2842 char *ref_path = get_locked_file_path(lock->lk);
2844 ret = symlink(target, ref_path);
2848 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2853 static void update_symref_reflog(struct ref_lock *lock, const char *refname,
2854 const char *target, const char *logmsg)
2856 struct strbuf err = STRBUF_INIT;
2857 unsigned char new_sha1[20];
2858 if (logmsg && !read_ref(target, new_sha1) &&
2859 log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg, 0, &err)) {
2860 error("%s", err.buf);
2861 strbuf_release(&err);
2865 static int create_symref_locked(struct ref_lock *lock, const char *refname,
2866 const char *target, const char *logmsg)
2868 if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2869 update_symref_reflog(lock, refname, target, logmsg);
2873 if (!fdopen_lock_file(lock->lk, "w"))
2874 return error("unable to fdopen %s: %s",
2875 lock->lk->tempfile.filename.buf, strerror(errno));
2877 update_symref_reflog(lock, refname, target, logmsg);
2879 /* no error check; commit_ref will check ferror */
2880 fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2881 if (commit_ref(lock) < 0)
2882 return error("unable to write symref for %s: %s", refname,
2887 int create_symref(const char *refname, const char *target, const char *logmsg)
2889 struct strbuf err = STRBUF_INIT;
2890 struct ref_lock *lock;
2893 lock = lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,
2896 error("%s", err.buf);
2897 strbuf_release(&err);
2901 ret = create_symref_locked(lock, refname, target, logmsg);
2906 int reflog_exists(const char *refname)
2910 return !lstat(git_path("logs/%s", refname), &st) &&
2911 S_ISREG(st.st_mode);
2914 int delete_reflog(const char *refname)
2916 return remove_path(git_path("logs/%s", refname));
2919 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2921 unsigned char osha1[20], nsha1[20];
2922 char *email_end, *message;
2923 unsigned long timestamp;
2926 /* old SP new SP name <email> SP time TAB msg LF */
2927 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2928 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2929 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2930 !(email_end = strchr(sb->buf + 82, '>')) ||
2931 email_end[1] != ' ' ||
2932 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2933 !message || message[0] != ' ' ||
2934 (message[1] != '+' && message[1] != '-') ||
2935 !isdigit(message[2]) || !isdigit(message[3]) ||
2936 !isdigit(message[4]) || !isdigit(message[5]))
2937 return 0; /* corrupt? */
2938 email_end[1] = '\0';
2939 tz = strtol(message + 1, NULL, 10);
2940 if (message[6] != '\t')
2944 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2947 static char *find_beginning_of_line(char *bob, char *scan)
2949 while (bob < scan && *(--scan) != '\n')
2950 ; /* keep scanning backwards */
2952 * Return either beginning of the buffer, or LF at the end of
2953 * the previous line.
2958 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2960 struct strbuf sb = STRBUF_INIT;
2963 int ret = 0, at_tail = 1;
2965 logfp = fopen(git_path("logs/%s", refname), "r");
2969 /* Jump to the end */
2970 if (fseek(logfp, 0, SEEK_END) < 0)
2971 return error("cannot seek back reflog for %s: %s",
2972 refname, strerror(errno));
2974 while (!ret && 0 < pos) {
2980 /* Fill next block from the end */
2981 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2982 if (fseek(logfp, pos - cnt, SEEK_SET))
2983 return error("cannot seek back reflog for %s: %s",
2984 refname, strerror(errno));
2985 nread = fread(buf, cnt, 1, logfp);
2987 return error("cannot read %d bytes from reflog for %s: %s",
2988 cnt, refname, strerror(errno));
2991 scanp = endp = buf + cnt;
2992 if (at_tail && scanp[-1] == '\n')
2993 /* Looking at the final LF at the end of the file */
2997 while (buf < scanp) {
2999 * terminating LF of the previous line, or the beginning
3004 bp = find_beginning_of_line(buf, scanp);
3008 * The newline is the end of the previous line,
3009 * so we know we have complete line starting
3010 * at (bp + 1). Prefix it onto any prior data
3011 * we collected for the line and process it.
3013 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3016 ret = show_one_reflog_ent(&sb, fn, cb_data);
3022 * We are at the start of the buffer, and the
3023 * start of the file; there is no previous
3024 * line, and we have everything for this one.
3025 * Process it, and we can end the loop.
3027 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3028 ret = show_one_reflog_ent(&sb, fn, cb_data);
3035 * We are at the start of the buffer, and there
3036 * is more file to read backwards. Which means
3037 * we are in the middle of a line. Note that we
3038 * may get here even if *bp was a newline; that
3039 * just means we are at the exact end of the
3040 * previous line, rather than some spot in the
3043 * Save away what we have to be combined with
3044 * the data from the next read.
3046 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3053 die("BUG: reverse reflog parser had leftover data");
3056 strbuf_release(&sb);
3060 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3063 struct strbuf sb = STRBUF_INIT;
3066 logfp = fopen(git_path("logs/%s", refname), "r");
3070 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3071 ret = show_one_reflog_ent(&sb, fn, cb_data);
3073 strbuf_release(&sb);
3077 * Call fn for each reflog in the namespace indicated by name. name
3078 * must be empty or end with '/'. Name will be used as a scratch
3079 * space, but its contents will be restored before return.
3081 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3083 DIR *d = opendir(git_path("logs/%s", name->buf));
3086 int oldlen = name->len;
3089 return name->len ? errno : 0;
3091 while ((de = readdir(d)) != NULL) {
3094 if (de->d_name[0] == '.')
3096 if (ends_with(de->d_name, ".lock"))
3098 strbuf_addstr(name, de->d_name);
3099 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3100 ; /* silently ignore */
3102 if (S_ISDIR(st.st_mode)) {
3103 strbuf_addch(name, '/');
3104 retval = do_for_each_reflog(name, fn, cb_data);
3106 struct object_id oid;
3108 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3109 retval = error("bad ref for %s", name->buf);
3111 retval = fn(name->buf, &oid, 0, cb_data);
3116 strbuf_setlen(name, oldlen);
3122 int for_each_reflog(each_ref_fn fn, void *cb_data)
3126 strbuf_init(&name, PATH_MAX);
3127 retval = do_for_each_reflog(&name, fn, cb_data);
3128 strbuf_release(&name);
3132 static int ref_update_reject_duplicates(struct string_list *refnames,
3135 int i, n = refnames->nr;
3139 for (i = 1; i < n; i++)
3140 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3142 "Multiple updates for ref '%s' not allowed.",
3143 refnames->items[i].string);
3149 int ref_transaction_commit(struct ref_transaction *transaction,
3153 int n = transaction->nr;
3154 struct ref_update **updates = transaction->updates;
3155 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3156 struct string_list_item *ref_to_delete;
3157 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3161 if (transaction->state != REF_TRANSACTION_OPEN)
3162 die("BUG: commit called for transaction that is not open");
3165 transaction->state = REF_TRANSACTION_CLOSED;
3169 /* Fail if a refname appears more than once in the transaction: */
3170 for (i = 0; i < n; i++)
3171 string_list_append(&affected_refnames, updates[i]->refname);
3172 string_list_sort(&affected_refnames);
3173 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3174 ret = TRANSACTION_GENERIC_ERROR;
3179 * Acquire all locks, verify old values if provided, check
3180 * that new values are valid, and write new values to the
3181 * lockfiles, ready to be activated. Only keep one lockfile
3182 * open at a time to avoid running out of file descriptors.
3184 for (i = 0; i < n; i++) {
3185 struct ref_update *update = updates[i];
3187 if ((update->flags & REF_HAVE_NEW) &&
3188 is_null_sha1(update->new_sha1))
3189 update->flags |= REF_DELETING;
3190 update->lock = lock_ref_sha1_basic(
3192 ((update->flags & REF_HAVE_OLD) ?
3193 update->old_sha1 : NULL),
3194 &affected_refnames, NULL,
3198 if (!update->lock) {
3201 ret = (errno == ENOTDIR)
3202 ? TRANSACTION_NAME_CONFLICT
3203 : TRANSACTION_GENERIC_ERROR;
3204 reason = strbuf_detach(err, NULL);
3205 strbuf_addf(err, "cannot lock ref '%s': %s",
3206 update->refname, reason);
3210 if ((update->flags & REF_HAVE_NEW) &&
3211 !(update->flags & REF_DELETING)) {
3212 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3213 (update->flags & REF_NODEREF));
3215 if (!overwriting_symref &&
3216 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3218 * The reference already has the desired
3219 * value, so we don't need to write it.
3221 } else if (write_ref_to_lockfile(update->lock,
3224 char *write_err = strbuf_detach(err, NULL);
3227 * The lock was freed upon failure of
3228 * write_ref_to_lockfile():
3230 update->lock = NULL;
3232 "cannot update the ref '%s': %s",
3233 update->refname, write_err);
3235 ret = TRANSACTION_GENERIC_ERROR;
3238 update->flags |= REF_NEEDS_COMMIT;
3241 if (!(update->flags & REF_NEEDS_COMMIT)) {
3243 * We didn't have to write anything to the lockfile.
3244 * Close it to free up the file descriptor:
3246 if (close_ref(update->lock)) {
3247 strbuf_addf(err, "Couldn't close %s.lock",
3254 /* Perform updates first so live commits remain referenced */
3255 for (i = 0; i < n; i++) {
3256 struct ref_update *update = updates[i];
3258 if (update->flags & REF_NEEDS_COMMIT) {
3259 if (commit_ref_update(update->lock,
3260 update->new_sha1, update->msg,
3261 update->flags, err)) {
3262 /* freed by commit_ref_update(): */
3263 update->lock = NULL;
3264 ret = TRANSACTION_GENERIC_ERROR;
3267 /* freed by commit_ref_update(): */
3268 update->lock = NULL;
3273 /* Perform deletes now that updates are safely completed */
3274 for (i = 0; i < n; i++) {
3275 struct ref_update *update = updates[i];
3277 if (update->flags & REF_DELETING) {
3278 if (delete_ref_loose(update->lock, update->type, err)) {
3279 ret = TRANSACTION_GENERIC_ERROR;
3283 if (!(update->flags & REF_ISPRUNING))
3284 string_list_append(&refs_to_delete,
3285 update->lock->ref_name);
3289 if (repack_without_refs(&refs_to_delete, err)) {
3290 ret = TRANSACTION_GENERIC_ERROR;
3293 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3294 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3295 clear_loose_ref_cache(&ref_cache);
3298 transaction->state = REF_TRANSACTION_CLOSED;
3300 for (i = 0; i < n; i++)
3301 if (updates[i]->lock)
3302 unlock_ref(updates[i]->lock);
3303 string_list_clear(&refs_to_delete, 0);
3304 string_list_clear(&affected_refnames, 0);
3308 static int ref_present(const char *refname,
3309 const struct object_id *oid, int flags, void *cb_data)
3311 struct string_list *affected_refnames = cb_data;
3313 return string_list_has_string(affected_refnames, refname);
3316 int initial_ref_transaction_commit(struct ref_transaction *transaction,
3320 int n = transaction->nr;
3321 struct ref_update **updates = transaction->updates;
3322 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3326 if (transaction->state != REF_TRANSACTION_OPEN)
3327 die("BUG: commit called for transaction that is not open");
3329 /* Fail if a refname appears more than once in the transaction: */
3330 for (i = 0; i < n; i++)
3331 string_list_append(&affected_refnames, updates[i]->refname);
3332 string_list_sort(&affected_refnames);
3333 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3334 ret = TRANSACTION_GENERIC_ERROR;
3339 * It's really undefined to call this function in an active
3340 * repository or when there are existing references: we are
3341 * only locking and changing packed-refs, so (1) any
3342 * simultaneous processes might try to change a reference at
3343 * the same time we do, and (2) any existing loose versions of
3344 * the references that we are setting would have precedence
3345 * over our values. But some remote helpers create the remote
3346 * "HEAD" and "master" branches before calling this function,
3347 * so here we really only check that none of the references
3348 * that we are creating already exists.
3350 if (for_each_rawref(ref_present, &affected_refnames))
3351 die("BUG: initial ref transaction called with existing refs");
3353 for (i = 0; i < n; i++) {
3354 struct ref_update *update = updates[i];
3356 if ((update->flags & REF_HAVE_OLD) &&
3357 !is_null_sha1(update->old_sha1))
3358 die("BUG: initial ref transaction with old_sha1 set");
3359 if (verify_refname_available(update->refname,
3360 &affected_refnames, NULL,
3362 ret = TRANSACTION_NAME_CONFLICT;
3367 if (lock_packed_refs(0)) {
3368 strbuf_addf(err, "unable to lock packed-refs file: %s",
3370 ret = TRANSACTION_GENERIC_ERROR;
3374 for (i = 0; i < n; i++) {
3375 struct ref_update *update = updates[i];
3377 if ((update->flags & REF_HAVE_NEW) &&
3378 !is_null_sha1(update->new_sha1))
3379 add_packed_ref(update->refname, update->new_sha1);
3382 if (commit_packed_refs()) {
3383 strbuf_addf(err, "unable to commit packed-refs file: %s",
3385 ret = TRANSACTION_GENERIC_ERROR;
3390 transaction->state = REF_TRANSACTION_CLOSED;
3391 string_list_clear(&affected_refnames, 0);
3395 struct expire_reflog_cb {
3397 reflog_expiry_should_prune_fn *should_prune_fn;
3400 unsigned char last_kept_sha1[20];
3403 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3404 const char *email, unsigned long timestamp, int tz,
3405 const char *message, void *cb_data)
3407 struct expire_reflog_cb *cb = cb_data;
3408 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3410 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3411 osha1 = cb->last_kept_sha1;
3413 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3414 message, policy_cb)) {
3416 printf("would prune %s", message);
3417 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3418 printf("prune %s", message);
3421 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3422 sha1_to_hex(osha1), sha1_to_hex(nsha1),
3423 email, timestamp, tz, message);
3424 hashcpy(cb->last_kept_sha1, nsha1);
3426 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3427 printf("keep %s", message);
3432 int reflog_expire(const char *refname, const unsigned char *sha1,
3434 reflog_expiry_prepare_fn prepare_fn,
3435 reflog_expiry_should_prune_fn should_prune_fn,
3436 reflog_expiry_cleanup_fn cleanup_fn,
3437 void *policy_cb_data)
3439 static struct lock_file reflog_lock;
3440 struct expire_reflog_cb cb;
3441 struct ref_lock *lock;
3445 struct strbuf err = STRBUF_INIT;
3447 memset(&cb, 0, sizeof(cb));
3449 cb.policy_cb = policy_cb_data;
3450 cb.should_prune_fn = should_prune_fn;
3453 * The reflog file is locked by holding the lock on the
3454 * reference itself, plus we might need to update the
3455 * reference if --updateref was specified:
3457 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3459 error("cannot lock ref '%s': %s", refname, err.buf);
3460 strbuf_release(&err);
3463 if (!reflog_exists(refname)) {
3468 log_file = git_pathdup("logs/%s", refname);
3469 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3471 * Even though holding $GIT_DIR/logs/$reflog.lock has
3472 * no locking implications, we use the lock_file
3473 * machinery here anyway because it does a lot of the
3474 * work we need, including cleaning up if the program
3475 * exits unexpectedly.
3477 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3478 struct strbuf err = STRBUF_INIT;
3479 unable_to_lock_message(log_file, errno, &err);
3480 error("%s", err.buf);
3481 strbuf_release(&err);
3484 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3486 error("cannot fdopen %s (%s)",
3487 get_lock_file_path(&reflog_lock), strerror(errno));
3492 (*prepare_fn)(refname, sha1, cb.policy_cb);
3493 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3494 (*cleanup_fn)(cb.policy_cb);
3496 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3498 * It doesn't make sense to adjust a reference pointed
3499 * to by a symbolic ref based on expiring entries in
3500 * the symbolic reference's reflog. Nor can we update
3501 * a reference if there are no remaining reflog
3504 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3505 !(type & REF_ISSYMREF) &&
3506 !is_null_sha1(cb.last_kept_sha1);
3508 if (close_lock_file(&reflog_lock)) {
3509 status |= error("couldn't write %s: %s", log_file,
3511 } else if (update &&
3512 (write_in_full(get_lock_file_fd(lock->lk),
3513 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3514 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3515 close_ref(lock) < 0)) {
3516 status |= error("couldn't write %s",
3517 get_lock_file_path(lock->lk));
3518 rollback_lock_file(&reflog_lock);
3519 } else if (commit_lock_file(&reflog_lock)) {
3520 status |= error("unable to write reflog '%s' (%s)",
3521 log_file, strerror(errno));
3522 } else if (update && commit_ref(lock)) {
3523 status |= error("couldn't set %s", lock->ref_name);
3531 rollback_lock_file(&reflog_lock);