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,
202 struct ref_entry *ref;
205 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
206 die("Reference has invalid format: '%s'", refname);
207 FLEX_ALLOC_STR(ref, name, refname);
208 hashcpy(ref->u.value.oid.hash, sha1);
209 oidclr(&ref->u.value.peeled);
214 static void clear_ref_dir(struct ref_dir *dir);
216 static void free_ref_entry(struct ref_entry *entry)
218 if (entry->flag & REF_DIR) {
220 * Do not use get_ref_dir() here, as that might
221 * trigger the reading of loose refs.
223 clear_ref_dir(&entry->u.subdir);
229 * Add a ref_entry to the end of dir (unsorted). Entry is always
230 * stored directly in dir; no recursion into subdirectories is
233 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
235 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
236 dir->entries[dir->nr++] = entry;
237 /* optimize for the case that entries are added in order */
239 (dir->nr == dir->sorted + 1 &&
240 strcmp(dir->entries[dir->nr - 2]->name,
241 dir->entries[dir->nr - 1]->name) < 0))
242 dir->sorted = dir->nr;
246 * Clear and free all entries in dir, recursively.
248 static void clear_ref_dir(struct ref_dir *dir)
251 for (i = 0; i < dir->nr; i++)
252 free_ref_entry(dir->entries[i]);
254 dir->sorted = dir->nr = dir->alloc = 0;
259 * Create a struct ref_entry object for the specified dirname.
260 * dirname is the name of the directory with a trailing slash (e.g.,
261 * "refs/heads/") or "" for the top-level directory.
263 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
264 const char *dirname, size_t len,
267 struct ref_entry *direntry;
268 FLEX_ALLOC_MEM(direntry, name, dirname, len);
269 direntry->u.subdir.ref_cache = ref_cache;
270 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
274 static int ref_entry_cmp(const void *a, const void *b)
276 struct ref_entry *one = *(struct ref_entry **)a;
277 struct ref_entry *two = *(struct ref_entry **)b;
278 return strcmp(one->name, two->name);
281 static void sort_ref_dir(struct ref_dir *dir);
283 struct string_slice {
288 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
290 const struct string_slice *key = key_;
291 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
292 int cmp = strncmp(key->str, ent->name, key->len);
295 return '\0' - (unsigned char)ent->name[key->len];
299 * Return the index of the entry with the given refname from the
300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
301 * no such entry is found. dir must already be complete.
303 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
305 struct ref_entry **r;
306 struct string_slice key;
308 if (refname == NULL || !dir->nr)
314 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
315 ref_entry_cmp_sslice);
320 return r - dir->entries;
324 * Search for a directory entry directly within dir (without
325 * recursing). Sort dir if necessary. subdirname must be a directory
326 * name (i.e., end in '/'). If mkdir is set, then create the
327 * directory if it is missing; otherwise, return NULL if the desired
328 * directory cannot be found. dir must already be complete.
330 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
331 const char *subdirname, size_t len,
334 int entry_index = search_ref_dir(dir, subdirname, len);
335 struct ref_entry *entry;
336 if (entry_index == -1) {
340 * Since dir is complete, the absence of a subdir
341 * means that the subdir really doesn't exist;
342 * therefore, create an empty record for it but mark
343 * the record complete.
345 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
346 add_entry_to_dir(dir, entry);
348 entry = dir->entries[entry_index];
350 return get_ref_dir(entry);
354 * If refname is a reference name, find the ref_dir within the dir
355 * tree that should hold refname. If refname is a directory name
356 * (i.e., ends in '/'), then return that ref_dir itself. dir must
357 * represent the top-level directory and must already be complete.
358 * Sort ref_dirs and recurse into subdirectories as necessary. If
359 * mkdir is set, then create any missing directories; otherwise,
360 * return NULL if the desired directory cannot be found.
362 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
363 const char *refname, int mkdir)
366 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
367 size_t dirnamelen = slash - refname + 1;
368 struct ref_dir *subdir;
369 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
381 * Find the value entry with the given name in dir, sorting ref_dirs
382 * and recursing into subdirectories as necessary. If the name is not
383 * found or it corresponds to a directory entry, return NULL.
385 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
388 struct ref_entry *entry;
389 dir = find_containing_dir(dir, refname, 0);
392 entry_index = search_ref_dir(dir, refname, strlen(refname));
393 if (entry_index == -1)
395 entry = dir->entries[entry_index];
396 return (entry->flag & REF_DIR) ? NULL : entry;
400 * Remove the entry with the given name from dir, recursing into
401 * subdirectories as necessary. If refname is the name of a directory
402 * (i.e., ends with '/'), then remove the directory and its contents.
403 * If the removal was successful, return the number of entries
404 * remaining in the directory entry that contained the deleted entry.
405 * If the name was not found, return -1. Please note that this
406 * function only deletes the entry from the cache; it does not delete
407 * it from the filesystem or ensure that other cache entries (which
408 * might be symbolic references to the removed entry) are updated.
409 * Nor does it remove any containing dir entries that might be made
410 * empty by the removal. dir must represent the top-level directory
411 * and must already be complete.
413 static int remove_entry(struct ref_dir *dir, const char *refname)
415 int refname_len = strlen(refname);
417 struct ref_entry *entry;
418 int is_dir = refname[refname_len - 1] == '/';
421 * refname represents a reference directory. Remove
422 * the trailing slash; otherwise we will get the
423 * directory *representing* refname rather than the
424 * one *containing* it.
426 char *dirname = xmemdupz(refname, refname_len - 1);
427 dir = find_containing_dir(dir, dirname, 0);
430 dir = find_containing_dir(dir, refname, 0);
434 entry_index = search_ref_dir(dir, refname, refname_len);
435 if (entry_index == -1)
437 entry = dir->entries[entry_index];
439 memmove(&dir->entries[entry_index],
440 &dir->entries[entry_index + 1],
441 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
444 if (dir->sorted > entry_index)
446 free_ref_entry(entry);
451 * Add a ref_entry to the ref_dir (unsorted), recursing into
452 * subdirectories as necessary. dir must represent the top-level
453 * directory. Return 0 on success.
455 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
457 dir = find_containing_dir(dir, ref->name, 1);
460 add_entry_to_dir(dir, ref);
465 * Emit a warning and return true iff ref1 and ref2 have the same name
466 * and the same sha1. Die if they have the same name but different
469 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
471 if (strcmp(ref1->name, ref2->name))
474 /* Duplicate name; make sure that they don't conflict: */
476 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
477 /* This is impossible by construction */
478 die("Reference directory conflict: %s", ref1->name);
480 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
481 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
483 warning("Duplicated ref: %s", ref1->name);
488 * Sort the entries in dir non-recursively (if they are not already
489 * sorted) and remove any duplicate entries.
491 static void sort_ref_dir(struct ref_dir *dir)
494 struct ref_entry *last = NULL;
497 * This check also prevents passing a zero-length array to qsort(),
498 * which is a problem on some platforms.
500 if (dir->sorted == dir->nr)
503 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
505 /* Remove any duplicates: */
506 for (i = 0, j = 0; j < dir->nr; j++) {
507 struct ref_entry *entry = dir->entries[j];
508 if (last && is_dup_ref(last, entry))
509 free_ref_entry(entry);
511 last = dir->entries[i++] = entry;
513 dir->sorted = dir->nr = i;
516 /* Include broken references in a do_for_each_ref*() iteration: */
517 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
520 * Return true iff the reference described by entry can be resolved to
521 * an object in the database. Emit a warning if the referred-to
522 * object does not exist.
524 static int ref_resolves_to_object(struct ref_entry *entry)
526 if (entry->flag & REF_ISBROKEN)
528 if (!has_sha1_file(entry->u.value.oid.hash)) {
529 error("%s does not point to a valid object!", entry->name);
536 * current_ref is a performance hack: when iterating over references
537 * using the for_each_ref*() functions, current_ref is set to the
538 * current reference's entry before calling the callback function. If
539 * the callback function calls peel_ref(), then peel_ref() first
540 * checks whether the reference to be peeled is the current reference
541 * (it usually is) and if so, returns that reference's peeled version
542 * if it is available. This avoids a refname lookup in a common case.
544 static struct ref_entry *current_ref;
546 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
548 struct ref_entry_cb {
557 * Handle one reference in a do_for_each_ref*()-style iteration,
558 * calling an each_ref_fn for each entry.
560 static int do_one_ref(struct ref_entry *entry, void *cb_data)
562 struct ref_entry_cb *data = cb_data;
563 struct ref_entry *old_current_ref;
566 if (!starts_with(entry->name, data->base))
569 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
570 !ref_resolves_to_object(entry))
573 /* Store the old value, in case this is a recursive call: */
574 old_current_ref = current_ref;
576 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
577 entry->flag, data->cb_data);
578 current_ref = old_current_ref;
583 * Call fn for each reference in dir that has index in the range
584 * offset <= index < dir->nr. Recurse into subdirectories that are in
585 * that index range, sorting them before iterating. This function
586 * does not sort dir itself; it should be sorted beforehand. fn is
587 * called for all references, including broken ones.
589 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
590 each_ref_entry_fn fn, void *cb_data)
593 assert(dir->sorted == dir->nr);
594 for (i = offset; i < dir->nr; i++) {
595 struct ref_entry *entry = dir->entries[i];
597 if (entry->flag & REF_DIR) {
598 struct ref_dir *subdir = get_ref_dir(entry);
599 sort_ref_dir(subdir);
600 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
602 retval = fn(entry, cb_data);
611 * Call fn for each reference in the union of dir1 and dir2, in order
612 * by refname. Recurse into subdirectories. If a value entry appears
613 * in both dir1 and dir2, then only process the version that is in
614 * dir2. The input dirs must already be sorted, but subdirs will be
615 * sorted as needed. fn is called for all references, including
618 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
619 struct ref_dir *dir2,
620 each_ref_entry_fn fn, void *cb_data)
625 assert(dir1->sorted == dir1->nr);
626 assert(dir2->sorted == dir2->nr);
628 struct ref_entry *e1, *e2;
630 if (i1 == dir1->nr) {
631 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
633 if (i2 == dir2->nr) {
634 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
636 e1 = dir1->entries[i1];
637 e2 = dir2->entries[i2];
638 cmp = strcmp(e1->name, e2->name);
640 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
641 /* Both are directories; descend them in parallel. */
642 struct ref_dir *subdir1 = get_ref_dir(e1);
643 struct ref_dir *subdir2 = get_ref_dir(e2);
644 sort_ref_dir(subdir1);
645 sort_ref_dir(subdir2);
646 retval = do_for_each_entry_in_dirs(
647 subdir1, subdir2, fn, cb_data);
650 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
651 /* Both are references; ignore the one from dir1. */
652 retval = fn(e2, cb_data);
656 die("conflict between reference and directory: %s",
668 if (e->flag & REF_DIR) {
669 struct ref_dir *subdir = get_ref_dir(e);
670 sort_ref_dir(subdir);
671 retval = do_for_each_entry_in_dir(
672 subdir, 0, fn, cb_data);
674 retval = fn(e, cb_data);
683 * Load all of the refs from the dir into our in-memory cache. The hard work
684 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
685 * through all of the sub-directories. We do not even need to care about
686 * sorting, as traversal order does not matter to us.
688 static void prime_ref_dir(struct ref_dir *dir)
691 for (i = 0; i < dir->nr; i++) {
692 struct ref_entry *entry = dir->entries[i];
693 if (entry->flag & REF_DIR)
694 prime_ref_dir(get_ref_dir(entry));
698 struct nonmatching_ref_data {
699 const struct string_list *skip;
700 const char *conflicting_refname;
703 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
705 struct nonmatching_ref_data *data = vdata;
707 if (data->skip && string_list_has_string(data->skip, entry->name))
710 data->conflicting_refname = entry->name;
715 * Return 0 if a reference named refname could be created without
716 * conflicting with the name of an existing reference in dir.
717 * See verify_refname_available for more information.
719 static int verify_refname_available_dir(const char *refname,
720 const struct string_list *extras,
721 const struct string_list *skip,
726 const char *extra_refname;
728 struct strbuf dirname = STRBUF_INIT;
732 * For the sake of comments in this function, suppose that
733 * refname is "refs/foo/bar".
738 strbuf_grow(&dirname, strlen(refname) + 1);
739 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
740 /* Expand dirname to the new prefix, not including the trailing slash: */
741 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
744 * We are still at a leading dir of the refname (e.g.,
745 * "refs/foo"; if there is a reference with that name,
746 * it is a conflict, *unless* it is in skip.
749 pos = search_ref_dir(dir, dirname.buf, dirname.len);
751 (!skip || !string_list_has_string(skip, dirname.buf))) {
753 * We found a reference whose name is
754 * a proper prefix of refname; e.g.,
755 * "refs/foo", and is not in skip.
757 strbuf_addf(err, "'%s' exists; cannot create '%s'",
758 dirname.buf, refname);
763 if (extras && string_list_has_string(extras, dirname.buf) &&
764 (!skip || !string_list_has_string(skip, dirname.buf))) {
765 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
766 refname, dirname.buf);
771 * Otherwise, we can try to continue our search with
772 * the next component. So try to look up the
773 * directory, e.g., "refs/foo/". If we come up empty,
774 * we know there is nothing under this whole prefix,
775 * but even in that case we still have to continue the
776 * search for conflicts with extras.
778 strbuf_addch(&dirname, '/');
780 pos = search_ref_dir(dir, dirname.buf, dirname.len);
783 * There was no directory "refs/foo/",
784 * so there is nothing under this
785 * whole prefix. So there is no need
786 * to continue looking for conflicting
787 * references. But we need to continue
788 * looking for conflicting extras.
792 dir = get_ref_dir(dir->entries[pos]);
798 * We are at the leaf of our refname (e.g., "refs/foo/bar").
799 * There is no point in searching for a reference with that
800 * name, because a refname isn't considered to conflict with
801 * itself. But we still need to check for references whose
802 * names are in the "refs/foo/bar/" namespace, because they
805 strbuf_addstr(&dirname, refname + dirname.len);
806 strbuf_addch(&dirname, '/');
809 pos = search_ref_dir(dir, dirname.buf, dirname.len);
813 * We found a directory named "$refname/"
814 * (e.g., "refs/foo/bar/"). It is a problem
815 * iff it contains any ref that is not in
818 struct nonmatching_ref_data data;
821 data.conflicting_refname = NULL;
822 dir = get_ref_dir(dir->entries[pos]);
824 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
825 strbuf_addf(err, "'%s' exists; cannot create '%s'",
826 data.conflicting_refname, refname);
832 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
834 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
835 refname, extra_refname);
840 strbuf_release(&dirname);
844 struct packed_ref_cache {
845 struct ref_entry *root;
848 * Count of references to the data structure in this instance,
849 * including the pointer from ref_cache::packed if any. The
850 * data will not be freed as long as the reference count is
853 unsigned int referrers;
856 * Iff the packed-refs file associated with this instance is
857 * currently locked for writing, this points at the associated
858 * lock (which is owned by somebody else). The referrer count
859 * is also incremented when the file is locked and decremented
860 * when it is unlocked.
862 struct lock_file *lock;
864 /* The metadata from when this packed-refs cache was read */
865 struct stat_validity validity;
869 * Future: need to be in "struct repository"
870 * when doing a full libification.
872 static struct ref_cache {
873 struct ref_cache *next;
874 struct ref_entry *loose;
875 struct packed_ref_cache *packed;
877 * The submodule name, or "" for the main repo. We allocate
878 * length 1 rather than FLEX_ARRAY so that the main ref_cache
879 * is initialized correctly.
882 } ref_cache, *submodule_ref_caches;
884 /* Lock used for the main packed-refs file: */
885 static struct lock_file packlock;
888 * Increment the reference count of *packed_refs.
890 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
892 packed_refs->referrers++;
896 * Decrease the reference count of *packed_refs. If it goes to zero,
897 * free *packed_refs and return true; otherwise return false.
899 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
901 if (!--packed_refs->referrers) {
902 free_ref_entry(packed_refs->root);
903 stat_validity_clear(&packed_refs->validity);
911 static void clear_packed_ref_cache(struct ref_cache *refs)
914 struct packed_ref_cache *packed_refs = refs->packed;
916 if (packed_refs->lock)
917 die("internal error: packed-ref cache cleared while locked");
919 release_packed_ref_cache(packed_refs);
923 static void clear_loose_ref_cache(struct ref_cache *refs)
926 free_ref_entry(refs->loose);
932 * Create a new submodule ref cache and add it to the internal
935 static struct ref_cache *create_ref_cache(const char *submodule)
937 struct ref_cache *refs;
940 FLEX_ALLOC_STR(refs, name, submodule);
941 refs->next = submodule_ref_caches;
942 submodule_ref_caches = refs;
946 static struct ref_cache *lookup_ref_cache(const char *submodule)
948 struct ref_cache *refs;
950 if (!submodule || !*submodule)
953 for (refs = submodule_ref_caches; refs; refs = refs->next)
954 if (!strcmp(submodule, refs->name))
960 * Return a pointer to a ref_cache for the specified submodule. For
961 * the main repository, use submodule==NULL. The returned structure
962 * will be allocated and initialized but not necessarily populated; it
963 * should not be freed.
965 static struct ref_cache *get_ref_cache(const char *submodule)
967 struct ref_cache *refs = lookup_ref_cache(submodule);
969 refs = create_ref_cache(submodule);
973 /* The length of a peeled reference line in packed-refs, including EOL: */
974 #define PEELED_LINE_LENGTH 42
977 * The packed-refs header line that we write out. Perhaps other
978 * traits will be added later. The trailing space is required.
980 static const char PACKED_REFS_HEADER[] =
981 "# pack-refs with: peeled fully-peeled \n";
984 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
985 * Return a pointer to the refname within the line (null-terminated),
986 * or NULL if there was a problem.
988 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
993 * 42: the answer to everything.
995 * In this case, it happens to be the answer to
996 * 40 (length of sha1 hex representation)
997 * +1 (space in between hex and name)
998 * +1 (newline at the end of the line)
1000 if (line->len <= 42)
1003 if (get_sha1_hex(line->buf, sha1) < 0)
1005 if (!isspace(line->buf[40]))
1008 ref = line->buf + 41;
1012 if (line->buf[line->len - 1] != '\n')
1014 line->buf[--line->len] = 0;
1020 * Read f, which is a packed-refs file, into dir.
1022 * A comment line of the form "# pack-refs with: " may contain zero or
1023 * more traits. We interpret the traits as follows:
1027 * Probably no references are peeled. But if the file contains a
1028 * peeled value for a reference, we will use it.
1032 * References under "refs/tags/", if they *can* be peeled, *are*
1033 * peeled in this file. References outside of "refs/tags/" are
1034 * probably not peeled even if they could have been, but if we find
1035 * a peeled value for such a reference we will use it.
1039 * All references in the file that can be peeled are peeled.
1040 * Inversely (and this is more important), any references in the
1041 * file for which no peeled value is recorded is not peelable. This
1042 * trait should typically be written alongside "peeled" for
1043 * compatibility with older clients, but we do not require it
1044 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1046 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1048 struct ref_entry *last = NULL;
1049 struct strbuf line = STRBUF_INIT;
1050 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1052 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1053 unsigned char sha1[20];
1054 const char *refname;
1057 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1058 if (strstr(traits, " fully-peeled "))
1059 peeled = PEELED_FULLY;
1060 else if (strstr(traits, " peeled "))
1061 peeled = PEELED_TAGS;
1062 /* perhaps other traits later as well */
1066 refname = parse_ref_line(&line, sha1);
1068 int flag = REF_ISPACKED;
1070 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1071 if (!refname_is_safe(refname))
1072 die("packed refname is dangerous: %s", refname);
1074 flag |= REF_BAD_NAME | REF_ISBROKEN;
1076 last = create_ref_entry(refname, sha1, flag, 0);
1077 if (peeled == PEELED_FULLY ||
1078 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1079 last->flag |= REF_KNOWS_PEELED;
1084 line.buf[0] == '^' &&
1085 line.len == PEELED_LINE_LENGTH &&
1086 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1087 !get_sha1_hex(line.buf + 1, sha1)) {
1088 hashcpy(last->u.value.peeled.hash, sha1);
1090 * Regardless of what the file header said,
1091 * we definitely know the value of *this*
1094 last->flag |= REF_KNOWS_PEELED;
1098 strbuf_release(&line);
1102 * Get the packed_ref_cache for the specified ref_cache, creating it
1105 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1107 char *packed_refs_file;
1110 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1112 packed_refs_file = git_pathdup("packed-refs");
1115 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1116 clear_packed_ref_cache(refs);
1118 if (!refs->packed) {
1121 refs->packed = xcalloc(1, sizeof(*refs->packed));
1122 acquire_packed_ref_cache(refs->packed);
1123 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1124 f = fopen(packed_refs_file, "r");
1126 stat_validity_update(&refs->packed->validity, fileno(f));
1127 read_packed_refs(f, get_ref_dir(refs->packed->root));
1131 free(packed_refs_file);
1132 return refs->packed;
1135 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1137 return get_ref_dir(packed_ref_cache->root);
1140 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1142 return get_packed_ref_dir(get_packed_ref_cache(refs));
1146 * Add a reference to the in-memory packed reference cache. This may
1147 * only be called while the packed-refs file is locked (see
1148 * lock_packed_refs()). To actually write the packed-refs file, call
1149 * commit_packed_refs().
1151 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1153 struct packed_ref_cache *packed_ref_cache =
1154 get_packed_ref_cache(&ref_cache);
1156 if (!packed_ref_cache->lock)
1157 die("internal error: packed refs not locked");
1158 add_ref(get_packed_ref_dir(packed_ref_cache),
1159 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1163 * Read the loose references from the namespace dirname into dir
1164 * (without recursing). dirname must end with '/'. dir must be the
1165 * directory entry corresponding to dirname.
1167 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1169 struct ref_cache *refs = dir->ref_cache;
1172 int dirnamelen = strlen(dirname);
1173 struct strbuf refname;
1174 struct strbuf path = STRBUF_INIT;
1175 size_t path_baselen;
1178 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1180 strbuf_git_path(&path, "%s", dirname);
1181 path_baselen = path.len;
1183 d = opendir(path.buf);
1185 strbuf_release(&path);
1189 strbuf_init(&refname, dirnamelen + 257);
1190 strbuf_add(&refname, dirname, dirnamelen);
1192 while ((de = readdir(d)) != NULL) {
1193 unsigned char sha1[20];
1197 if (de->d_name[0] == '.')
1199 if (ends_with(de->d_name, ".lock"))
1201 strbuf_addstr(&refname, de->d_name);
1202 strbuf_addstr(&path, de->d_name);
1203 if (stat(path.buf, &st) < 0) {
1204 ; /* silently ignore */
1205 } else if (S_ISDIR(st.st_mode)) {
1206 strbuf_addch(&refname, '/');
1207 add_entry_to_dir(dir,
1208 create_dir_entry(refs, refname.buf,
1216 read_ok = !resolve_gitlink_ref(refs->name,
1219 read_ok = !read_ref_full(refname.buf,
1220 RESOLVE_REF_READING,
1226 flag |= REF_ISBROKEN;
1227 } else if (is_null_sha1(sha1)) {
1229 * It is so astronomically unlikely
1230 * that NULL_SHA1 is the SHA-1 of an
1231 * actual object that we consider its
1232 * appearance in a loose reference
1233 * file to be repo corruption
1234 * (probably due to a software bug).
1236 flag |= REF_ISBROKEN;
1239 if (check_refname_format(refname.buf,
1240 REFNAME_ALLOW_ONELEVEL)) {
1241 if (!refname_is_safe(refname.buf))
1242 die("loose refname is dangerous: %s", refname.buf);
1244 flag |= REF_BAD_NAME | REF_ISBROKEN;
1246 add_entry_to_dir(dir,
1247 create_ref_entry(refname.buf, sha1, flag, 0));
1249 strbuf_setlen(&refname, dirnamelen);
1250 strbuf_setlen(&path, path_baselen);
1252 strbuf_release(&refname);
1253 strbuf_release(&path);
1257 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1261 * Mark the top-level directory complete because we
1262 * are about to read the only subdirectory that can
1265 refs->loose = create_dir_entry(refs, "", 0, 0);
1267 * Create an incomplete entry for "refs/":
1269 add_entry_to_dir(get_ref_dir(refs->loose),
1270 create_dir_entry(refs, "refs/", 5, 1));
1272 return get_ref_dir(refs->loose);
1275 /* We allow "recursive" symbolic refs. Only within reason, though */
1277 #define MAXREFLEN (1024)
1280 * Called by resolve_gitlink_ref_recursive() after it failed to read
1281 * from the loose refs in ref_cache refs. Find <refname> in the
1282 * packed-refs file for the submodule.
1284 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1285 const char *refname, unsigned char *sha1)
1287 struct ref_entry *ref;
1288 struct ref_dir *dir = get_packed_refs(refs);
1290 ref = find_ref(dir, refname);
1294 hashcpy(sha1, ref->u.value.oid.hash);
1298 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1299 const char *refname, unsigned char *sha1,
1303 char buffer[128], *p;
1306 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1309 ? git_pathdup_submodule(refs->name, "%s", refname)
1310 : git_pathdup("%s", refname);
1311 fd = open(path, O_RDONLY);
1314 return resolve_gitlink_packed_ref(refs, refname, sha1);
1316 len = read(fd, buffer, sizeof(buffer)-1);
1320 while (len && isspace(buffer[len-1]))
1324 /* Was it a detached head or an old-fashioned symlink? */
1325 if (!get_sha1_hex(buffer, sha1))
1329 if (strncmp(buffer, "ref:", 4))
1335 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1338 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1340 int len = strlen(path), retval;
1341 struct strbuf submodule = STRBUF_INIT;
1342 struct ref_cache *refs;
1344 while (len && path[len-1] == '/')
1349 strbuf_add(&submodule, path, len);
1350 refs = lookup_ref_cache(submodule.buf);
1352 if (!is_nonbare_repository_dir(&submodule)) {
1353 strbuf_release(&submodule);
1356 refs = create_ref_cache(submodule.buf);
1358 strbuf_release(&submodule);
1360 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1365 * Return the ref_entry for the given refname from the packed
1366 * references. If it does not exist, return NULL.
1368 static struct ref_entry *get_packed_ref(const char *refname)
1370 return find_ref(get_packed_refs(&ref_cache), refname);
1374 * A loose ref file doesn't exist; check for a packed ref. The
1375 * options are forwarded from resolve_safe_unsafe().
1377 static int resolve_missing_loose_ref(const char *refname,
1379 unsigned char *sha1,
1382 struct ref_entry *entry;
1385 * The loose reference file does not exist; check for a packed
1388 entry = get_packed_ref(refname);
1390 hashcpy(sha1, entry->u.value.oid.hash);
1392 *flags |= REF_ISPACKED;
1395 /* The reference is not a packed reference, either. */
1396 if (resolve_flags & RESOLVE_REF_READING) {
1405 /* This function needs to return a meaningful errno on failure */
1406 static const char *resolve_ref_1(const char *refname,
1408 unsigned char *sha1,
1410 struct strbuf *sb_refname,
1411 struct strbuf *sb_path,
1412 struct strbuf *sb_contents)
1414 int depth = MAXDEPTH;
1420 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1422 *flags |= REF_BAD_NAME;
1424 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1425 !refname_is_safe(refname)) {
1430 * dwim_ref() uses REF_ISBROKEN to distinguish between
1431 * missing refs and refs that were present but invalid,
1432 * to complain about the latter to stderr.
1434 * We don't know whether the ref exists, so don't set
1450 strbuf_reset(sb_path);
1451 strbuf_git_path(sb_path, "%s", refname);
1452 path = sb_path->buf;
1455 * We might have to loop back here to avoid a race
1456 * condition: first we lstat() the file, then we try
1457 * to read it as a link or as a file. But if somebody
1458 * changes the type of the file (file <-> directory
1459 * <-> symlink) between the lstat() and reading, then
1460 * we don't want to report that as an error but rather
1461 * try again starting with the lstat().
1464 if (lstat(path, &st) < 0) {
1465 if (errno != ENOENT)
1467 if (resolve_missing_loose_ref(refname, resolve_flags,
1473 *flags |= REF_ISBROKEN;
1478 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1479 if (S_ISLNK(st.st_mode)) {
1480 strbuf_reset(sb_contents);
1481 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1482 if (errno == ENOENT || errno == EINVAL)
1483 /* inconsistent with lstat; retry */
1488 if (starts_with(sb_contents->buf, "refs/") &&
1489 !check_refname_format(sb_contents->buf, 0)) {
1490 strbuf_swap(sb_refname, sb_contents);
1491 refname = sb_refname->buf;
1493 *flags |= REF_ISSYMREF;
1494 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1502 /* Is it a directory? */
1503 if (S_ISDIR(st.st_mode)) {
1509 * Anything else, just open it and try to use it as
1512 fd = open(path, O_RDONLY);
1514 if (errno == ENOENT)
1515 /* inconsistent with lstat; retry */
1520 strbuf_reset(sb_contents);
1521 if (strbuf_read(sb_contents, fd, 256) < 0) {
1522 int save_errno = errno;
1528 strbuf_rtrim(sb_contents);
1531 * Is it a symbolic ref?
1533 if (!starts_with(sb_contents->buf, "ref:")) {
1535 * Please note that FETCH_HEAD has a second
1536 * line containing other data.
1538 if (get_sha1_hex(sb_contents->buf, sha1) ||
1539 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1541 *flags |= REF_ISBROKEN;
1548 *flags |= REF_ISBROKEN;
1553 *flags |= REF_ISSYMREF;
1554 buf = sb_contents->buf + 4;
1555 while (isspace(*buf))
1557 strbuf_reset(sb_refname);
1558 strbuf_addstr(sb_refname, buf);
1559 refname = sb_refname->buf;
1560 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1564 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1566 *flags |= REF_ISBROKEN;
1568 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1569 !refname_is_safe(buf)) {
1578 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1579 unsigned char *sha1, int *flags)
1581 static struct strbuf sb_refname = STRBUF_INIT;
1582 struct strbuf sb_contents = STRBUF_INIT;
1583 struct strbuf sb_path = STRBUF_INIT;
1586 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1587 &sb_refname, &sb_path, &sb_contents);
1588 strbuf_release(&sb_path);
1589 strbuf_release(&sb_contents);
1594 * Peel the entry (if possible) and return its new peel_status. If
1595 * repeel is true, re-peel the entry even if there is an old peeled
1596 * value that is already stored in it.
1598 * It is OK to call this function with a packed reference entry that
1599 * might be stale and might even refer to an object that has since
1600 * been garbage-collected. In such a case, if the entry has
1601 * REF_KNOWS_PEELED then leave the status unchanged and return
1602 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1604 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1606 enum peel_status status;
1608 if (entry->flag & REF_KNOWS_PEELED) {
1610 entry->flag &= ~REF_KNOWS_PEELED;
1611 oidclr(&entry->u.value.peeled);
1613 return is_null_oid(&entry->u.value.peeled) ?
1614 PEEL_NON_TAG : PEEL_PEELED;
1617 if (entry->flag & REF_ISBROKEN)
1619 if (entry->flag & REF_ISSYMREF)
1620 return PEEL_IS_SYMREF;
1622 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1623 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1624 entry->flag |= REF_KNOWS_PEELED;
1628 int peel_ref(const char *refname, unsigned char *sha1)
1631 unsigned char base[20];
1633 if (current_ref && (current_ref->name == refname
1634 || !strcmp(current_ref->name, refname))) {
1635 if (peel_entry(current_ref, 0))
1637 hashcpy(sha1, current_ref->u.value.peeled.hash);
1641 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1645 * If the reference is packed, read its ref_entry from the
1646 * cache in the hope that we already know its peeled value.
1647 * We only try this optimization on packed references because
1648 * (a) forcing the filling of the loose reference cache could
1649 * be expensive and (b) loose references anyway usually do not
1650 * have REF_KNOWS_PEELED.
1652 if (flag & REF_ISPACKED) {
1653 struct ref_entry *r = get_packed_ref(refname);
1655 if (peel_entry(r, 0))
1657 hashcpy(sha1, r->u.value.peeled.hash);
1662 return peel_object(base, sha1);
1666 * Call fn for each reference in the specified ref_cache, omitting
1667 * references not in the containing_dir of base. fn is called for all
1668 * references, including broken ones. If fn ever returns a non-zero
1669 * value, stop the iteration and return that value; otherwise, return
1672 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1673 each_ref_entry_fn fn, void *cb_data)
1675 struct packed_ref_cache *packed_ref_cache;
1676 struct ref_dir *loose_dir;
1677 struct ref_dir *packed_dir;
1681 * We must make sure that all loose refs are read before accessing the
1682 * packed-refs file; this avoids a race condition in which loose refs
1683 * are migrated to the packed-refs file by a simultaneous process, but
1684 * our in-memory view is from before the migration. get_packed_ref_cache()
1685 * takes care of making sure our view is up to date with what is on
1688 loose_dir = get_loose_refs(refs);
1689 if (base && *base) {
1690 loose_dir = find_containing_dir(loose_dir, base, 0);
1693 prime_ref_dir(loose_dir);
1695 packed_ref_cache = get_packed_ref_cache(refs);
1696 acquire_packed_ref_cache(packed_ref_cache);
1697 packed_dir = get_packed_ref_dir(packed_ref_cache);
1698 if (base && *base) {
1699 packed_dir = find_containing_dir(packed_dir, base, 0);
1702 if (packed_dir && loose_dir) {
1703 sort_ref_dir(packed_dir);
1704 sort_ref_dir(loose_dir);
1705 retval = do_for_each_entry_in_dirs(
1706 packed_dir, loose_dir, fn, cb_data);
1707 } else if (packed_dir) {
1708 sort_ref_dir(packed_dir);
1709 retval = do_for_each_entry_in_dir(
1710 packed_dir, 0, fn, cb_data);
1711 } else if (loose_dir) {
1712 sort_ref_dir(loose_dir);
1713 retval = do_for_each_entry_in_dir(
1714 loose_dir, 0, fn, cb_data);
1717 release_packed_ref_cache(packed_ref_cache);
1722 * Call fn for each reference in the specified ref_cache for which the
1723 * refname begins with base. If trim is non-zero, then trim that many
1724 * characters off the beginning of each refname before passing the
1725 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1726 * broken references in the iteration. If fn ever returns a non-zero
1727 * value, stop the iteration and return that value; otherwise, return
1730 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1731 each_ref_fn fn, int trim, int flags, void *cb_data)
1733 struct ref_entry_cb data;
1738 data.cb_data = cb_data;
1740 if (ref_paranoia < 0)
1741 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1743 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1745 return do_for_each_entry(refs, base, do_one_ref, &data);
1748 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1750 struct object_id oid;
1754 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1755 return fn("HEAD", &oid, 0, cb_data);
1760 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1761 return fn("HEAD", &oid, flag, cb_data);
1766 int head_ref(each_ref_fn fn, void *cb_data)
1768 return do_head_ref(NULL, fn, cb_data);
1771 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1773 return do_head_ref(submodule, fn, cb_data);
1776 int for_each_ref(each_ref_fn fn, void *cb_data)
1778 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1781 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1783 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1786 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1788 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1791 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1793 unsigned int flag = 0;
1796 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1797 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
1800 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1801 each_ref_fn fn, void *cb_data)
1803 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1806 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1808 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
1809 strlen(git_replace_ref_base), 0, cb_data);
1812 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1814 struct strbuf buf = STRBUF_INIT;
1816 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1817 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1818 strbuf_release(&buf);
1822 int for_each_rawref(each_ref_fn fn, void *cb_data)
1824 return do_for_each_ref(&ref_cache, "", fn, 0,
1825 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1828 static void unlock_ref(struct ref_lock *lock)
1830 /* Do not free lock->lk -- atexit() still looks at them */
1832 rollback_lock_file(lock->lk);
1833 free(lock->ref_name);
1834 free(lock->orig_ref_name);
1839 * Verify that the reference locked by lock has the value old_sha1.
1840 * Fail if the reference doesn't exist and mustexist is set. Return 0
1841 * on success. On error, write an error message to err, set errno, and
1842 * return a negative value.
1844 static int verify_lock(struct ref_lock *lock,
1845 const unsigned char *old_sha1, int mustexist,
1850 if (read_ref_full(lock->ref_name,
1851 mustexist ? RESOLVE_REF_READING : 0,
1852 lock->old_oid.hash, NULL)) {
1853 int save_errno = errno;
1854 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1858 if (hashcmp(lock->old_oid.hash, old_sha1)) {
1859 strbuf_addf(err, "ref %s is at %s but expected %s",
1861 sha1_to_hex(lock->old_oid.hash),
1862 sha1_to_hex(old_sha1));
1869 static int remove_empty_directories(struct strbuf *path)
1872 * we want to create a file but there is a directory there;
1873 * if that is an empty directory (or a directory that contains
1874 * only empty directories), remove them.
1876 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1880 * Locks a ref returning the lock on success and NULL on failure.
1881 * On failure errno is set to something meaningful.
1883 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1884 const unsigned char *old_sha1,
1885 const struct string_list *extras,
1886 const struct string_list *skip,
1887 unsigned int flags, int *type_p,
1890 struct strbuf ref_file = STRBUF_INIT;
1891 struct strbuf orig_ref_file = STRBUF_INIT;
1892 const char *orig_refname = refname;
1893 struct ref_lock *lock;
1896 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1897 int resolve_flags = 0;
1898 int attempts_remaining = 3;
1902 lock = xcalloc(1, sizeof(struct ref_lock));
1905 resolve_flags |= RESOLVE_REF_READING;
1906 if (flags & REF_DELETING) {
1907 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1908 if (flags & REF_NODEREF)
1909 resolve_flags |= RESOLVE_REF_NO_RECURSE;
1912 refname = resolve_ref_unsafe(refname, resolve_flags,
1913 lock->old_oid.hash, &type);
1914 if (!refname && errno == EISDIR) {
1916 * we are trying to lock foo but we used to
1917 * have foo/bar which now does not exist;
1918 * it is normal for the empty directory 'foo'
1921 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1922 if (remove_empty_directories(&orig_ref_file)) {
1924 if (!verify_refname_available_dir(orig_refname, extras, skip,
1925 get_loose_refs(&ref_cache), err))
1926 strbuf_addf(err, "there are still refs under '%s'",
1930 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1931 lock->old_oid.hash, &type);
1937 if (last_errno != ENOTDIR ||
1938 !verify_refname_available_dir(orig_refname, extras, skip,
1939 get_loose_refs(&ref_cache), err))
1940 strbuf_addf(err, "unable to resolve reference %s: %s",
1941 orig_refname, strerror(last_errno));
1946 * If the ref did not exist and we are creating it, make sure
1947 * there is no existing packed ref whose name begins with our
1948 * refname, nor a packed ref whose name is a proper prefix of
1951 if (is_null_oid(&lock->old_oid) &&
1952 verify_refname_available_dir(refname, extras, skip,
1953 get_packed_refs(&ref_cache), err)) {
1954 last_errno = ENOTDIR;
1958 lock->lk = xcalloc(1, sizeof(struct lock_file));
1961 if (flags & REF_NODEREF) {
1962 refname = orig_refname;
1963 lflags |= LOCK_NO_DEREF;
1965 lock->ref_name = xstrdup(refname);
1966 lock->orig_ref_name = xstrdup(orig_refname);
1967 strbuf_git_path(&ref_file, "%s", refname);
1970 switch (safe_create_leading_directories_const(ref_file.buf)) {
1972 break; /* success */
1974 if (--attempts_remaining > 0)
1979 strbuf_addf(err, "unable to create directory for %s",
1984 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1986 if (errno == ENOENT && --attempts_remaining > 0)
1988 * Maybe somebody just deleted one of the
1989 * directories leading to ref_file. Try
1994 unable_to_lock_message(ref_file.buf, errno, err);
1998 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2009 strbuf_release(&ref_file);
2010 strbuf_release(&orig_ref_file);
2016 * Write an entry to the packed-refs file for the specified refname.
2017 * If peeled is non-NULL, write it as the entry's peeled value.
2019 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2020 unsigned char *peeled)
2022 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2024 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2028 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2030 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2032 enum peel_status peel_status = peel_entry(entry, 0);
2034 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2035 error("internal error: %s is not a valid packed reference!",
2037 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2038 peel_status == PEEL_PEELED ?
2039 entry->u.value.peeled.hash : NULL);
2044 * Lock the packed-refs file for writing. Flags is passed to
2045 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2046 * errno appropriately and return a nonzero value.
2048 static int lock_packed_refs(int flags)
2050 static int timeout_configured = 0;
2051 static int timeout_value = 1000;
2053 struct packed_ref_cache *packed_ref_cache;
2055 if (!timeout_configured) {
2056 git_config_get_int("core.packedrefstimeout", &timeout_value);
2057 timeout_configured = 1;
2060 if (hold_lock_file_for_update_timeout(
2061 &packlock, git_path("packed-refs"),
2062 flags, timeout_value) < 0)
2065 * Get the current packed-refs while holding the lock. If the
2066 * packed-refs file has been modified since we last read it,
2067 * this will automatically invalidate the cache and re-read
2068 * the packed-refs file.
2070 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2071 packed_ref_cache->lock = &packlock;
2072 /* Increment the reference count to prevent it from being freed: */
2073 acquire_packed_ref_cache(packed_ref_cache);
2078 * Write the current version of the packed refs cache from memory to
2079 * disk. The packed-refs file must already be locked for writing (see
2080 * lock_packed_refs()). Return zero on success. On errors, set errno
2081 * and return a nonzero value
2083 static int commit_packed_refs(void)
2085 struct packed_ref_cache *packed_ref_cache =
2086 get_packed_ref_cache(&ref_cache);
2091 if (!packed_ref_cache->lock)
2092 die("internal error: packed-refs not locked");
2094 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2096 die_errno("unable to fdopen packed-refs descriptor");
2098 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2099 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2100 0, write_packed_entry_fn, out);
2102 if (commit_lock_file(packed_ref_cache->lock)) {
2106 packed_ref_cache->lock = NULL;
2107 release_packed_ref_cache(packed_ref_cache);
2113 * Rollback the lockfile for the packed-refs file, and discard the
2114 * in-memory packed reference cache. (The packed-refs file will be
2115 * read anew if it is needed again after this function is called.)
2117 static void rollback_packed_refs(void)
2119 struct packed_ref_cache *packed_ref_cache =
2120 get_packed_ref_cache(&ref_cache);
2122 if (!packed_ref_cache->lock)
2123 die("internal error: packed-refs not locked");
2124 rollback_lock_file(packed_ref_cache->lock);
2125 packed_ref_cache->lock = NULL;
2126 release_packed_ref_cache(packed_ref_cache);
2127 clear_packed_ref_cache(&ref_cache);
2130 struct ref_to_prune {
2131 struct ref_to_prune *next;
2132 unsigned char sha1[20];
2133 char name[FLEX_ARRAY];
2136 struct pack_refs_cb_data {
2138 struct ref_dir *packed_refs;
2139 struct ref_to_prune *ref_to_prune;
2143 * An each_ref_entry_fn that is run over loose references only. If
2144 * the loose reference can be packed, add an entry in the packed ref
2145 * cache. If the reference should be pruned, also add it to
2146 * ref_to_prune in the pack_refs_cb_data.
2148 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2150 struct pack_refs_cb_data *cb = cb_data;
2151 enum peel_status peel_status;
2152 struct ref_entry *packed_entry;
2153 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2155 /* Do not pack per-worktree refs: */
2156 if (ref_type(entry->name) != REF_TYPE_NORMAL)
2159 /* ALWAYS pack tags */
2160 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2163 /* Do not pack symbolic or broken refs: */
2164 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2167 /* Add a packed ref cache entry equivalent to the loose entry. */
2168 peel_status = peel_entry(entry, 1);
2169 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2170 die("internal error peeling reference %s (%s)",
2171 entry->name, oid_to_hex(&entry->u.value.oid));
2172 packed_entry = find_ref(cb->packed_refs, entry->name);
2174 /* Overwrite existing packed entry with info from loose entry */
2175 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2176 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2178 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2179 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2180 add_ref(cb->packed_refs, packed_entry);
2182 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2184 /* Schedule the loose reference for pruning if requested. */
2185 if ((cb->flags & PACK_REFS_PRUNE)) {
2186 struct ref_to_prune *n;
2187 FLEX_ALLOC_STR(n, name, entry->name);
2188 hashcpy(n->sha1, entry->u.value.oid.hash);
2189 n->next = cb->ref_to_prune;
2190 cb->ref_to_prune = n;
2196 * Remove empty parents, but spare refs/ and immediate subdirs.
2197 * Note: munges *name.
2199 static void try_remove_empty_parents(char *name)
2204 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2205 while (*p && *p != '/')
2207 /* tolerate duplicate slashes; see check_refname_format() */
2211 for (q = p; *q; q++)
2214 while (q > p && *q != '/')
2216 while (q > p && *(q-1) == '/')
2221 if (rmdir(git_path("%s", name)))
2226 /* make sure nobody touched the ref, and unlink */
2227 static void prune_ref(struct ref_to_prune *r)
2229 struct ref_transaction *transaction;
2230 struct strbuf err = STRBUF_INIT;
2232 if (check_refname_format(r->name, 0))
2235 transaction = ref_transaction_begin(&err);
2237 ref_transaction_delete(transaction, r->name, r->sha1,
2238 REF_ISPRUNING, NULL, &err) ||
2239 ref_transaction_commit(transaction, &err)) {
2240 ref_transaction_free(transaction);
2241 error("%s", err.buf);
2242 strbuf_release(&err);
2245 ref_transaction_free(transaction);
2246 strbuf_release(&err);
2247 try_remove_empty_parents(r->name);
2250 static void prune_refs(struct ref_to_prune *r)
2258 int pack_refs(unsigned int flags)
2260 struct pack_refs_cb_data cbdata;
2262 memset(&cbdata, 0, sizeof(cbdata));
2263 cbdata.flags = flags;
2265 lock_packed_refs(LOCK_DIE_ON_ERROR);
2266 cbdata.packed_refs = get_packed_refs(&ref_cache);
2268 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2269 pack_if_possible_fn, &cbdata);
2271 if (commit_packed_refs())
2272 die_errno("unable to overwrite old ref-pack file");
2274 prune_refs(cbdata.ref_to_prune);
2279 * Rewrite the packed-refs file, omitting any refs listed in
2280 * 'refnames'. On error, leave packed-refs unchanged, write an error
2281 * message to 'err', and return a nonzero value.
2283 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2285 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2287 struct ref_dir *packed;
2288 struct string_list_item *refname;
2289 int ret, needs_repacking = 0, removed = 0;
2293 /* Look for a packed ref */
2294 for_each_string_list_item(refname, refnames) {
2295 if (get_packed_ref(refname->string)) {
2296 needs_repacking = 1;
2301 /* Avoid locking if we have nothing to do */
2302 if (!needs_repacking)
2303 return 0; /* no refname exists in packed refs */
2305 if (lock_packed_refs(0)) {
2306 unable_to_lock_message(git_path("packed-refs"), errno, err);
2309 packed = get_packed_refs(&ref_cache);
2311 /* Remove refnames from the cache */
2312 for_each_string_list_item(refname, refnames)
2313 if (remove_entry(packed, refname->string) != -1)
2317 * All packed entries disappeared while we were
2318 * acquiring the lock.
2320 rollback_packed_refs();
2324 /* Write what remains */
2325 ret = commit_packed_refs();
2327 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2332 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2336 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2338 * loose. The loose file name is the same as the
2339 * lockfile name, minus ".lock":
2341 char *loose_filename = get_locked_file_path(lock->lk);
2342 int res = unlink_or_msg(loose_filename, err);
2343 free(loose_filename);
2350 int delete_refs(struct string_list *refnames)
2352 struct strbuf err = STRBUF_INIT;
2358 result = repack_without_refs(refnames, &err);
2361 * If we failed to rewrite the packed-refs file, then
2362 * it is unsafe to try to remove loose refs, because
2363 * doing so might expose an obsolete packed value for
2364 * a reference that might even point at an object that
2365 * has been garbage collected.
2367 if (refnames->nr == 1)
2368 error(_("could not delete reference %s: %s"),
2369 refnames->items[0].string, err.buf);
2371 error(_("could not delete references: %s"), err.buf);
2376 for (i = 0; i < refnames->nr; i++) {
2377 const char *refname = refnames->items[i].string;
2379 if (delete_ref(refname, NULL, 0))
2380 result |= error(_("could not remove reference %s"), refname);
2384 strbuf_release(&err);
2389 * People using contrib's git-new-workdir have .git/logs/refs ->
2390 * /some/other/path/.git/logs/refs, and that may live on another device.
2392 * IOW, to avoid cross device rename errors, the temporary renamed log must
2393 * live into logs/refs.
2395 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2397 static int rename_tmp_log(const char *newrefname)
2399 int attempts_remaining = 4;
2400 struct strbuf path = STRBUF_INIT;
2404 strbuf_reset(&path);
2405 strbuf_git_path(&path, "logs/%s", newrefname);
2406 switch (safe_create_leading_directories_const(path.buf)) {
2408 break; /* success */
2410 if (--attempts_remaining > 0)
2414 error("unable to create directory for %s", newrefname);
2418 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2419 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2421 * rename(a, b) when b is an existing
2422 * directory ought to result in ISDIR, but
2423 * Solaris 5.8 gives ENOTDIR. Sheesh.
2425 if (remove_empty_directories(&path)) {
2426 error("Directory not empty: logs/%s", newrefname);
2430 } else if (errno == ENOENT && --attempts_remaining > 0) {
2432 * Maybe another process just deleted one of
2433 * the directories in the path to newrefname.
2434 * Try again from the beginning.
2438 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2439 newrefname, strerror(errno));
2445 strbuf_release(&path);
2449 int verify_refname_available(const char *newname,
2450 struct string_list *extras,
2451 struct string_list *skip,
2454 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2455 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2457 if (verify_refname_available_dir(newname, extras, skip,
2458 packed_refs, err) ||
2459 verify_refname_available_dir(newname, extras, skip,
2466 static int write_ref_to_lockfile(struct ref_lock *lock,
2467 const unsigned char *sha1, struct strbuf *err);
2468 static int commit_ref_update(struct ref_lock *lock,
2469 const unsigned char *sha1, const char *logmsg,
2470 int flags, struct strbuf *err);
2472 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2474 unsigned char sha1[20], orig_sha1[20];
2475 int flag = 0, logmoved = 0;
2476 struct ref_lock *lock;
2477 struct stat loginfo;
2478 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2479 const char *symref = NULL;
2480 struct strbuf err = STRBUF_INIT;
2482 if (log && S_ISLNK(loginfo.st_mode))
2483 return error("reflog for %s is a symlink", oldrefname);
2485 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2487 if (flag & REF_ISSYMREF)
2488 return error("refname %s is a symbolic ref, renaming it is not supported",
2491 return error("refname %s not found", oldrefname);
2493 if (!rename_ref_available(oldrefname, newrefname))
2496 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2497 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2498 oldrefname, strerror(errno));
2500 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2501 error("unable to delete old %s", oldrefname);
2505 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2506 delete_ref(newrefname, sha1, REF_NODEREF)) {
2507 if (errno==EISDIR) {
2508 struct strbuf path = STRBUF_INIT;
2511 strbuf_git_path(&path, "%s", newrefname);
2512 result = remove_empty_directories(&path);
2513 strbuf_release(&path);
2516 error("Directory not empty: %s", newrefname);
2520 error("unable to delete existing %s", newrefname);
2525 if (log && rename_tmp_log(newrefname))
2530 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2532 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2533 strbuf_release(&err);
2536 hashcpy(lock->old_oid.hash, orig_sha1);
2538 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2539 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2540 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2541 strbuf_release(&err);
2548 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2550 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2551 strbuf_release(&err);
2555 flag = log_all_ref_updates;
2556 log_all_ref_updates = 0;
2557 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2558 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2559 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2560 strbuf_release(&err);
2562 log_all_ref_updates = flag;
2565 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2566 error("unable to restore logfile %s from %s: %s",
2567 oldrefname, newrefname, strerror(errno));
2568 if (!logmoved && log &&
2569 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2570 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2571 oldrefname, strerror(errno));
2576 static int close_ref(struct ref_lock *lock)
2578 if (close_lock_file(lock->lk))
2583 static int commit_ref(struct ref_lock *lock)
2585 if (commit_lock_file(lock->lk))
2591 * Create a reflog for a ref. If force_create = 0, the reflog will
2592 * only be created for certain refs (those for which
2593 * should_autocreate_reflog returns non-zero. Otherwise, create it
2594 * regardless of the ref name. Fill in *err and return -1 on failure.
2596 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2598 int logfd, oflags = O_APPEND | O_WRONLY;
2600 strbuf_git_path(logfile, "logs/%s", refname);
2601 if (force_create || should_autocreate_reflog(refname)) {
2602 if (safe_create_leading_directories(logfile->buf) < 0) {
2603 strbuf_addf(err, "unable to create directory for %s: "
2604 "%s", logfile->buf, strerror(errno));
2610 logfd = open(logfile->buf, oflags, 0666);
2612 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2615 if (errno == EISDIR) {
2616 if (remove_empty_directories(logfile)) {
2617 strbuf_addf(err, "There are still logs under "
2618 "'%s'", logfile->buf);
2621 logfd = open(logfile->buf, oflags, 0666);
2625 strbuf_addf(err, "unable to append to %s: %s",
2626 logfile->buf, strerror(errno));
2631 adjust_shared_perm(logfile->buf);
2637 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2640 struct strbuf sb = STRBUF_INIT;
2642 ret = log_ref_setup(refname, &sb, err, force_create);
2643 strbuf_release(&sb);
2647 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2648 const unsigned char *new_sha1,
2649 const char *committer, const char *msg)
2651 int msglen, written;
2652 unsigned maxlen, len;
2655 msglen = msg ? strlen(msg) : 0;
2656 maxlen = strlen(committer) + msglen + 100;
2657 logrec = xmalloc(maxlen);
2658 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2659 sha1_to_hex(old_sha1),
2660 sha1_to_hex(new_sha1),
2663 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2665 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2673 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2674 const unsigned char *new_sha1, const char *msg,
2675 struct strbuf *logfile, int flags,
2678 int logfd, result, oflags = O_APPEND | O_WRONLY;
2680 if (log_all_ref_updates < 0)
2681 log_all_ref_updates = !is_bare_repository();
2683 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2688 logfd = open(logfile->buf, oflags);
2691 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2692 git_committer_info(0), msg);
2694 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2700 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2707 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2708 const unsigned char *new_sha1, const char *msg,
2709 int flags, struct strbuf *err)
2711 return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2715 int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2716 const unsigned char *new_sha1, const char *msg,
2717 int flags, struct strbuf *err)
2719 struct strbuf sb = STRBUF_INIT;
2720 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2722 strbuf_release(&sb);
2727 * Write sha1 into the open lockfile, then close the lockfile. On
2728 * errors, rollback the lockfile, fill in *err and
2731 static int write_ref_to_lockfile(struct ref_lock *lock,
2732 const unsigned char *sha1, struct strbuf *err)
2734 static char term = '\n';
2738 o = parse_object(sha1);
2741 "Trying to write ref %s with nonexistent object %s",
2742 lock->ref_name, sha1_to_hex(sha1));
2746 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2748 "Trying to write non-commit object %s to branch %s",
2749 sha1_to_hex(sha1), lock->ref_name);
2753 fd = get_lock_file_fd(lock->lk);
2754 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2755 write_in_full(fd, &term, 1) != 1 ||
2756 close_ref(lock) < 0) {
2758 "Couldn't write %s", get_lock_file_path(lock->lk));
2766 * Commit a change to a loose reference that has already been written
2767 * to the loose reference lockfile. Also update the reflogs if
2768 * necessary, using the specified lockmsg (which can be NULL).
2770 static int commit_ref_update(struct ref_lock *lock,
2771 const unsigned char *sha1, const char *logmsg,
2772 int flags, struct strbuf *err)
2774 clear_loose_ref_cache(&ref_cache);
2775 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2776 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2777 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2778 char *old_msg = strbuf_detach(err, NULL);
2779 strbuf_addf(err, "Cannot update the ref '%s': %s",
2780 lock->ref_name, old_msg);
2785 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2787 * Special hack: If a branch is updated directly and HEAD
2788 * points to it (may happen on the remote side of a push
2789 * for example) then logically the HEAD reflog should be
2791 * A generic solution implies reverse symref information,
2792 * but finding all symrefs pointing to the given branch
2793 * would be rather costly for this rare event (the direct
2794 * update of a branch) to be worth it. So let's cheat and
2795 * check with HEAD only which should cover 99% of all usage
2796 * scenarios (even 100% of the default ones).
2798 unsigned char head_sha1[20];
2800 const char *head_ref;
2801 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2802 head_sha1, &head_flag);
2803 if (head_ref && (head_flag & REF_ISSYMREF) &&
2804 !strcmp(head_ref, lock->ref_name)) {
2805 struct strbuf log_err = STRBUF_INIT;
2806 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2807 logmsg, 0, &log_err)) {
2808 error("%s", log_err.buf);
2809 strbuf_release(&log_err);
2813 if (commit_ref(lock)) {
2814 error("Couldn't set %s", lock->ref_name);
2823 int create_symref(const char *ref_target, const char *refs_heads_master,
2826 char *lockpath = NULL;
2828 int fd, len, written;
2829 char *git_HEAD = git_pathdup("%s", ref_target);
2830 unsigned char old_sha1[20], new_sha1[20];
2831 struct strbuf err = STRBUF_INIT;
2833 if (logmsg && read_ref(ref_target, old_sha1))
2836 if (safe_create_leading_directories(git_HEAD) < 0)
2837 return error("unable to create directory for %s", git_HEAD);
2839 #ifndef NO_SYMLINK_HEAD
2840 if (prefer_symlink_refs) {
2842 if (!symlink(refs_heads_master, git_HEAD))
2844 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2848 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2849 if (sizeof(ref) <= len) {
2850 error("refname too long: %s", refs_heads_master);
2851 goto error_free_return;
2853 lockpath = mkpathdup("%s.lock", git_HEAD);
2854 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2856 error("Unable to open %s for writing", lockpath);
2857 goto error_free_return;
2859 written = write_in_full(fd, ref, len);
2860 if (close(fd) != 0 || written != len) {
2861 error("Unable to write to %s", lockpath);
2862 goto error_unlink_return;
2864 if (rename(lockpath, git_HEAD) < 0) {
2865 error("Unable to create %s", git_HEAD);
2866 goto error_unlink_return;
2868 if (adjust_shared_perm(git_HEAD)) {
2869 error("Unable to fix permissions on %s", lockpath);
2870 error_unlink_return:
2871 unlink_or_warn(lockpath);
2879 #ifndef NO_SYMLINK_HEAD
2882 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
2883 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
2884 error("%s", err.buf);
2885 strbuf_release(&err);
2892 int reflog_exists(const char *refname)
2896 return !lstat(git_path("logs/%s", refname), &st) &&
2897 S_ISREG(st.st_mode);
2900 int delete_reflog(const char *refname)
2902 return remove_path(git_path("logs/%s", refname));
2905 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2907 unsigned char osha1[20], nsha1[20];
2908 char *email_end, *message;
2909 unsigned long timestamp;
2912 /* old SP new SP name <email> SP time TAB msg LF */
2913 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2914 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2915 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2916 !(email_end = strchr(sb->buf + 82, '>')) ||
2917 email_end[1] != ' ' ||
2918 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2919 !message || message[0] != ' ' ||
2920 (message[1] != '+' && message[1] != '-') ||
2921 !isdigit(message[2]) || !isdigit(message[3]) ||
2922 !isdigit(message[4]) || !isdigit(message[5]))
2923 return 0; /* corrupt? */
2924 email_end[1] = '\0';
2925 tz = strtol(message + 1, NULL, 10);
2926 if (message[6] != '\t')
2930 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2933 static char *find_beginning_of_line(char *bob, char *scan)
2935 while (bob < scan && *(--scan) != '\n')
2936 ; /* keep scanning backwards */
2938 * Return either beginning of the buffer, or LF at the end of
2939 * the previous line.
2944 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2946 struct strbuf sb = STRBUF_INIT;
2949 int ret = 0, at_tail = 1;
2951 logfp = fopen(git_path("logs/%s", refname), "r");
2955 /* Jump to the end */
2956 if (fseek(logfp, 0, SEEK_END) < 0)
2957 return error("cannot seek back reflog for %s: %s",
2958 refname, strerror(errno));
2960 while (!ret && 0 < pos) {
2966 /* Fill next block from the end */
2967 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2968 if (fseek(logfp, pos - cnt, SEEK_SET))
2969 return error("cannot seek back reflog for %s: %s",
2970 refname, strerror(errno));
2971 nread = fread(buf, cnt, 1, logfp);
2973 return error("cannot read %d bytes from reflog for %s: %s",
2974 cnt, refname, strerror(errno));
2977 scanp = endp = buf + cnt;
2978 if (at_tail && scanp[-1] == '\n')
2979 /* Looking at the final LF at the end of the file */
2983 while (buf < scanp) {
2985 * terminating LF of the previous line, or the beginning
2990 bp = find_beginning_of_line(buf, scanp);
2994 * The newline is the end of the previous line,
2995 * so we know we have complete line starting
2996 * at (bp + 1). Prefix it onto any prior data
2997 * we collected for the line and process it.
2999 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3002 ret = show_one_reflog_ent(&sb, fn, cb_data);
3008 * We are at the start of the buffer, and the
3009 * start of the file; there is no previous
3010 * line, and we have everything for this one.
3011 * Process it, and we can end the loop.
3013 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3014 ret = show_one_reflog_ent(&sb, fn, cb_data);
3021 * We are at the start of the buffer, and there
3022 * is more file to read backwards. Which means
3023 * we are in the middle of a line. Note that we
3024 * may get here even if *bp was a newline; that
3025 * just means we are at the exact end of the
3026 * previous line, rather than some spot in the
3029 * Save away what we have to be combined with
3030 * the data from the next read.
3032 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3039 die("BUG: reverse reflog parser had leftover data");
3042 strbuf_release(&sb);
3046 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3049 struct strbuf sb = STRBUF_INIT;
3052 logfp = fopen(git_path("logs/%s", refname), "r");
3056 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3057 ret = show_one_reflog_ent(&sb, fn, cb_data);
3059 strbuf_release(&sb);
3063 * Call fn for each reflog in the namespace indicated by name. name
3064 * must be empty or end with '/'. Name will be used as a scratch
3065 * space, but its contents will be restored before return.
3067 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3069 DIR *d = opendir(git_path("logs/%s", name->buf));
3072 int oldlen = name->len;
3075 return name->len ? errno : 0;
3077 while ((de = readdir(d)) != NULL) {
3080 if (de->d_name[0] == '.')
3082 if (ends_with(de->d_name, ".lock"))
3084 strbuf_addstr(name, de->d_name);
3085 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3086 ; /* silently ignore */
3088 if (S_ISDIR(st.st_mode)) {
3089 strbuf_addch(name, '/');
3090 retval = do_for_each_reflog(name, fn, cb_data);
3092 struct object_id oid;
3094 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3095 retval = error("bad ref for %s", name->buf);
3097 retval = fn(name->buf, &oid, 0, cb_data);
3102 strbuf_setlen(name, oldlen);
3108 int for_each_reflog(each_ref_fn fn, void *cb_data)
3112 strbuf_init(&name, PATH_MAX);
3113 retval = do_for_each_reflog(&name, fn, cb_data);
3114 strbuf_release(&name);
3118 static int ref_update_reject_duplicates(struct string_list *refnames,
3121 int i, n = refnames->nr;
3125 for (i = 1; i < n; i++)
3126 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3128 "Multiple updates for ref '%s' not allowed.",
3129 refnames->items[i].string);
3135 int ref_transaction_commit(struct ref_transaction *transaction,
3139 int n = transaction->nr;
3140 struct ref_update **updates = transaction->updates;
3141 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3142 struct string_list_item *ref_to_delete;
3143 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3147 if (transaction->state != REF_TRANSACTION_OPEN)
3148 die("BUG: commit called for transaction that is not open");
3151 transaction->state = REF_TRANSACTION_CLOSED;
3155 /* Fail if a refname appears more than once in the transaction: */
3156 for (i = 0; i < n; i++)
3157 string_list_append(&affected_refnames, updates[i]->refname);
3158 string_list_sort(&affected_refnames);
3159 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3160 ret = TRANSACTION_GENERIC_ERROR;
3165 * Acquire all locks, verify old values if provided, check
3166 * that new values are valid, and write new values to the
3167 * lockfiles, ready to be activated. Only keep one lockfile
3168 * open at a time to avoid running out of file descriptors.
3170 for (i = 0; i < n; i++) {
3171 struct ref_update *update = updates[i];
3173 if ((update->flags & REF_HAVE_NEW) &&
3174 is_null_sha1(update->new_sha1))
3175 update->flags |= REF_DELETING;
3176 update->lock = lock_ref_sha1_basic(
3178 ((update->flags & REF_HAVE_OLD) ?
3179 update->old_sha1 : NULL),
3180 &affected_refnames, NULL,
3184 if (!update->lock) {
3187 ret = (errno == ENOTDIR)
3188 ? TRANSACTION_NAME_CONFLICT
3189 : TRANSACTION_GENERIC_ERROR;
3190 reason = strbuf_detach(err, NULL);
3191 strbuf_addf(err, "cannot lock ref '%s': %s",
3192 update->refname, reason);
3196 if ((update->flags & REF_HAVE_NEW) &&
3197 !(update->flags & REF_DELETING)) {
3198 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3199 (update->flags & REF_NODEREF));
3201 if (!overwriting_symref &&
3202 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3204 * The reference already has the desired
3205 * value, so we don't need to write it.
3207 } else if (write_ref_to_lockfile(update->lock,
3210 char *write_err = strbuf_detach(err, NULL);
3213 * The lock was freed upon failure of
3214 * write_ref_to_lockfile():
3216 update->lock = NULL;
3218 "cannot update the ref '%s': %s",
3219 update->refname, write_err);
3221 ret = TRANSACTION_GENERIC_ERROR;
3224 update->flags |= REF_NEEDS_COMMIT;
3227 if (!(update->flags & REF_NEEDS_COMMIT)) {
3229 * We didn't have to write anything to the lockfile.
3230 * Close it to free up the file descriptor:
3232 if (close_ref(update->lock)) {
3233 strbuf_addf(err, "Couldn't close %s.lock",
3240 /* Perform updates first so live commits remain referenced */
3241 for (i = 0; i < n; i++) {
3242 struct ref_update *update = updates[i];
3244 if (update->flags & REF_NEEDS_COMMIT) {
3245 if (commit_ref_update(update->lock,
3246 update->new_sha1, update->msg,
3247 update->flags, err)) {
3248 /* freed by commit_ref_update(): */
3249 update->lock = NULL;
3250 ret = TRANSACTION_GENERIC_ERROR;
3253 /* freed by commit_ref_update(): */
3254 update->lock = NULL;
3259 /* Perform deletes now that updates are safely completed */
3260 for (i = 0; i < n; i++) {
3261 struct ref_update *update = updates[i];
3263 if (update->flags & REF_DELETING) {
3264 if (delete_ref_loose(update->lock, update->type, err)) {
3265 ret = TRANSACTION_GENERIC_ERROR;
3269 if (!(update->flags & REF_ISPRUNING))
3270 string_list_append(&refs_to_delete,
3271 update->lock->ref_name);
3275 if (repack_without_refs(&refs_to_delete, err)) {
3276 ret = TRANSACTION_GENERIC_ERROR;
3279 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3280 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3281 clear_loose_ref_cache(&ref_cache);
3284 transaction->state = REF_TRANSACTION_CLOSED;
3286 for (i = 0; i < n; i++)
3287 if (updates[i]->lock)
3288 unlock_ref(updates[i]->lock);
3289 string_list_clear(&refs_to_delete, 0);
3290 string_list_clear(&affected_refnames, 0);
3294 static int ref_present(const char *refname,
3295 const struct object_id *oid, int flags, void *cb_data)
3297 struct string_list *affected_refnames = cb_data;
3299 return string_list_has_string(affected_refnames, refname);
3302 int initial_ref_transaction_commit(struct ref_transaction *transaction,
3306 int n = transaction->nr;
3307 struct ref_update **updates = transaction->updates;
3308 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3312 if (transaction->state != REF_TRANSACTION_OPEN)
3313 die("BUG: commit called for transaction that is not open");
3315 /* Fail if a refname appears more than once in the transaction: */
3316 for (i = 0; i < n; i++)
3317 string_list_append(&affected_refnames, updates[i]->refname);
3318 string_list_sort(&affected_refnames);
3319 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3320 ret = TRANSACTION_GENERIC_ERROR;
3325 * It's really undefined to call this function in an active
3326 * repository or when there are existing references: we are
3327 * only locking and changing packed-refs, so (1) any
3328 * simultaneous processes might try to change a reference at
3329 * the same time we do, and (2) any existing loose versions of
3330 * the references that we are setting would have precedence
3331 * over our values. But some remote helpers create the remote
3332 * "HEAD" and "master" branches before calling this function,
3333 * so here we really only check that none of the references
3334 * that we are creating already exists.
3336 if (for_each_rawref(ref_present, &affected_refnames))
3337 die("BUG: initial ref transaction called with existing refs");
3339 for (i = 0; i < n; i++) {
3340 struct ref_update *update = updates[i];
3342 if ((update->flags & REF_HAVE_OLD) &&
3343 !is_null_sha1(update->old_sha1))
3344 die("BUG: initial ref transaction with old_sha1 set");
3345 if (verify_refname_available(update->refname,
3346 &affected_refnames, NULL,
3348 ret = TRANSACTION_NAME_CONFLICT;
3353 if (lock_packed_refs(0)) {
3354 strbuf_addf(err, "unable to lock packed-refs file: %s",
3356 ret = TRANSACTION_GENERIC_ERROR;
3360 for (i = 0; i < n; i++) {
3361 struct ref_update *update = updates[i];
3363 if ((update->flags & REF_HAVE_NEW) &&
3364 !is_null_sha1(update->new_sha1))
3365 add_packed_ref(update->refname, update->new_sha1);
3368 if (commit_packed_refs()) {
3369 strbuf_addf(err, "unable to commit packed-refs file: %s",
3371 ret = TRANSACTION_GENERIC_ERROR;
3376 transaction->state = REF_TRANSACTION_CLOSED;
3377 string_list_clear(&affected_refnames, 0);
3381 struct expire_reflog_cb {
3383 reflog_expiry_should_prune_fn *should_prune_fn;
3386 unsigned char last_kept_sha1[20];
3389 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3390 const char *email, unsigned long timestamp, int tz,
3391 const char *message, void *cb_data)
3393 struct expire_reflog_cb *cb = cb_data;
3394 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3396 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3397 osha1 = cb->last_kept_sha1;
3399 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3400 message, policy_cb)) {
3402 printf("would prune %s", message);
3403 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3404 printf("prune %s", message);
3407 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3408 sha1_to_hex(osha1), sha1_to_hex(nsha1),
3409 email, timestamp, tz, message);
3410 hashcpy(cb->last_kept_sha1, nsha1);
3412 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3413 printf("keep %s", message);
3418 int reflog_expire(const char *refname, const unsigned char *sha1,
3420 reflog_expiry_prepare_fn prepare_fn,
3421 reflog_expiry_should_prune_fn should_prune_fn,
3422 reflog_expiry_cleanup_fn cleanup_fn,
3423 void *policy_cb_data)
3425 static struct lock_file reflog_lock;
3426 struct expire_reflog_cb cb;
3427 struct ref_lock *lock;
3431 struct strbuf err = STRBUF_INIT;
3433 memset(&cb, 0, sizeof(cb));
3435 cb.policy_cb = policy_cb_data;
3436 cb.should_prune_fn = should_prune_fn;
3439 * The reflog file is locked by holding the lock on the
3440 * reference itself, plus we might need to update the
3441 * reference if --updateref was specified:
3443 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3445 error("cannot lock ref '%s': %s", refname, err.buf);
3446 strbuf_release(&err);
3449 if (!reflog_exists(refname)) {
3454 log_file = git_pathdup("logs/%s", refname);
3455 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3457 * Even though holding $GIT_DIR/logs/$reflog.lock has
3458 * no locking implications, we use the lock_file
3459 * machinery here anyway because it does a lot of the
3460 * work we need, including cleaning up if the program
3461 * exits unexpectedly.
3463 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3464 struct strbuf err = STRBUF_INIT;
3465 unable_to_lock_message(log_file, errno, &err);
3466 error("%s", err.buf);
3467 strbuf_release(&err);
3470 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3472 error("cannot fdopen %s (%s)",
3473 get_lock_file_path(&reflog_lock), strerror(errno));
3478 (*prepare_fn)(refname, sha1, cb.policy_cb);
3479 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3480 (*cleanup_fn)(cb.policy_cb);
3482 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3484 * It doesn't make sense to adjust a reference pointed
3485 * to by a symbolic ref based on expiring entries in
3486 * the symbolic reference's reflog. Nor can we update
3487 * a reference if there are no remaining reflog
3490 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3491 !(type & REF_ISSYMREF) &&
3492 !is_null_sha1(cb.last_kept_sha1);
3494 if (close_lock_file(&reflog_lock)) {
3495 status |= error("couldn't write %s: %s", log_file,
3497 } else if (update &&
3498 (write_in_full(get_lock_file_fd(lock->lk),
3499 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3500 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3501 close_ref(lock) < 0)) {
3502 status |= error("couldn't write %s",
3503 get_lock_file_path(lock->lk));
3504 rollback_lock_file(&reflog_lock);
3505 } else if (commit_lock_file(&reflog_lock)) {
3506 status |= error("unable to write reflog '%s' (%s)",
3507 log_file, strerror(errno));
3508 } else if (update && commit_ref(lock)) {
3509 status |= error("couldn't set %s", lock->ref_name);
3517 rollback_lock_file(&reflog_lock);