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);
936 static struct ref_cache *create_ref_cache(const char *submodule)
939 struct ref_cache *refs;
942 len = strlen(submodule) + 1;
943 refs = xcalloc(1, sizeof(struct ref_cache) + len);
944 memcpy(refs->name, submodule, len);
949 * Return a pointer to a ref_cache for the specified submodule. For
950 * the main repository, use submodule==NULL. The returned structure
951 * will be allocated and initialized but not necessarily populated; it
952 * should not be freed.
954 static struct ref_cache *get_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))
965 refs = create_ref_cache(submodule);
966 refs->next = submodule_ref_caches;
967 submodule_ref_caches = refs;
971 /* The length of a peeled reference line in packed-refs, including EOL: */
972 #define PEELED_LINE_LENGTH 42
975 * The packed-refs header line that we write out. Perhaps other
976 * traits will be added later. The trailing space is required.
978 static const char PACKED_REFS_HEADER[] =
979 "# pack-refs with: peeled fully-peeled \n";
982 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
983 * Return a pointer to the refname within the line (null-terminated),
984 * or NULL if there was a problem.
986 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
991 * 42: the answer to everything.
993 * In this case, it happens to be the answer to
994 * 40 (length of sha1 hex representation)
995 * +1 (space in between hex and name)
996 * +1 (newline at the end of the line)
1001 if (get_sha1_hex(line->buf, sha1) < 0)
1003 if (!isspace(line->buf[40]))
1006 ref = line->buf + 41;
1010 if (line->buf[line->len - 1] != '\n')
1012 line->buf[--line->len] = 0;
1018 * Read f, which is a packed-refs file, into dir.
1020 * A comment line of the form "# pack-refs with: " may contain zero or
1021 * more traits. We interpret the traits as follows:
1025 * Probably no references are peeled. But if the file contains a
1026 * peeled value for a reference, we will use it.
1030 * References under "refs/tags/", if they *can* be peeled, *are*
1031 * peeled in this file. References outside of "refs/tags/" are
1032 * probably not peeled even if they could have been, but if we find
1033 * a peeled value for such a reference we will use it.
1037 * All references in the file that can be peeled are peeled.
1038 * Inversely (and this is more important), any references in the
1039 * file for which no peeled value is recorded is not peelable. This
1040 * trait should typically be written alongside "peeled" for
1041 * compatibility with older clients, but we do not require it
1042 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1044 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1046 struct ref_entry *last = NULL;
1047 struct strbuf line = STRBUF_INIT;
1048 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1050 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1051 unsigned char sha1[20];
1052 const char *refname;
1055 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1056 if (strstr(traits, " fully-peeled "))
1057 peeled = PEELED_FULLY;
1058 else if (strstr(traits, " peeled "))
1059 peeled = PEELED_TAGS;
1060 /* perhaps other traits later as well */
1064 refname = parse_ref_line(&line, sha1);
1066 int flag = REF_ISPACKED;
1068 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1069 if (!refname_is_safe(refname))
1070 die("packed refname is dangerous: %s", refname);
1072 flag |= REF_BAD_NAME | REF_ISBROKEN;
1074 last = create_ref_entry(refname, sha1, flag, 0);
1075 if (peeled == PEELED_FULLY ||
1076 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1077 last->flag |= REF_KNOWS_PEELED;
1082 line.buf[0] == '^' &&
1083 line.len == PEELED_LINE_LENGTH &&
1084 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1085 !get_sha1_hex(line.buf + 1, sha1)) {
1086 hashcpy(last->u.value.peeled.hash, sha1);
1088 * Regardless of what the file header said,
1089 * we definitely know the value of *this*
1092 last->flag |= REF_KNOWS_PEELED;
1096 strbuf_release(&line);
1100 * Get the packed_ref_cache for the specified ref_cache, creating it
1103 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1105 char *packed_refs_file;
1108 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1110 packed_refs_file = git_pathdup("packed-refs");
1113 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1114 clear_packed_ref_cache(refs);
1116 if (!refs->packed) {
1119 refs->packed = xcalloc(1, sizeof(*refs->packed));
1120 acquire_packed_ref_cache(refs->packed);
1121 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1122 f = fopen(packed_refs_file, "r");
1124 stat_validity_update(&refs->packed->validity, fileno(f));
1125 read_packed_refs(f, get_ref_dir(refs->packed->root));
1129 free(packed_refs_file);
1130 return refs->packed;
1133 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1135 return get_ref_dir(packed_ref_cache->root);
1138 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1140 return get_packed_ref_dir(get_packed_ref_cache(refs));
1144 * Add a reference to the in-memory packed reference cache. This may
1145 * only be called while the packed-refs file is locked (see
1146 * lock_packed_refs()). To actually write the packed-refs file, call
1147 * commit_packed_refs().
1149 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1151 struct packed_ref_cache *packed_ref_cache =
1152 get_packed_ref_cache(&ref_cache);
1154 if (!packed_ref_cache->lock)
1155 die("internal error: packed refs not locked");
1156 add_ref(get_packed_ref_dir(packed_ref_cache),
1157 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1161 * Read the loose references from the namespace dirname into dir
1162 * (without recursing). dirname must end with '/'. dir must be the
1163 * directory entry corresponding to dirname.
1165 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1167 struct ref_cache *refs = dir->ref_cache;
1170 int dirnamelen = strlen(dirname);
1171 struct strbuf refname;
1172 struct strbuf path = STRBUF_INIT;
1173 size_t path_baselen;
1176 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1178 strbuf_git_path(&path, "%s", dirname);
1179 path_baselen = path.len;
1181 d = opendir(path.buf);
1183 strbuf_release(&path);
1187 strbuf_init(&refname, dirnamelen + 257);
1188 strbuf_add(&refname, dirname, dirnamelen);
1190 while ((de = readdir(d)) != NULL) {
1191 unsigned char sha1[20];
1195 if (de->d_name[0] == '.')
1197 if (ends_with(de->d_name, ".lock"))
1199 strbuf_addstr(&refname, de->d_name);
1200 strbuf_addstr(&path, de->d_name);
1201 if (stat(path.buf, &st) < 0) {
1202 ; /* silently ignore */
1203 } else if (S_ISDIR(st.st_mode)) {
1204 strbuf_addch(&refname, '/');
1205 add_entry_to_dir(dir,
1206 create_dir_entry(refs, refname.buf,
1214 read_ok = !resolve_gitlink_ref(refs->name,
1217 read_ok = !read_ref_full(refname.buf,
1218 RESOLVE_REF_READING,
1224 flag |= REF_ISBROKEN;
1225 } else if (is_null_sha1(sha1)) {
1227 * It is so astronomically unlikely
1228 * that NULL_SHA1 is the SHA-1 of an
1229 * actual object that we consider its
1230 * appearance in a loose reference
1231 * file to be repo corruption
1232 * (probably due to a software bug).
1234 flag |= REF_ISBROKEN;
1237 if (check_refname_format(refname.buf,
1238 REFNAME_ALLOW_ONELEVEL)) {
1239 if (!refname_is_safe(refname.buf))
1240 die("loose refname is dangerous: %s", refname.buf);
1242 flag |= REF_BAD_NAME | REF_ISBROKEN;
1244 add_entry_to_dir(dir,
1245 create_ref_entry(refname.buf, sha1, flag, 0));
1247 strbuf_setlen(&refname, dirnamelen);
1248 strbuf_setlen(&path, path_baselen);
1250 strbuf_release(&refname);
1251 strbuf_release(&path);
1255 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1259 * Mark the top-level directory complete because we
1260 * are about to read the only subdirectory that can
1263 refs->loose = create_dir_entry(refs, "", 0, 0);
1265 * Create an incomplete entry for "refs/":
1267 add_entry_to_dir(get_ref_dir(refs->loose),
1268 create_dir_entry(refs, "refs/", 5, 1));
1270 return get_ref_dir(refs->loose);
1273 /* We allow "recursive" symbolic refs. Only within reason, though */
1275 #define MAXREFLEN (1024)
1278 * Called by resolve_gitlink_ref_recursive() after it failed to read
1279 * from the loose refs in ref_cache refs. Find <refname> in the
1280 * packed-refs file for the submodule.
1282 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1283 const char *refname, unsigned char *sha1)
1285 struct ref_entry *ref;
1286 struct ref_dir *dir = get_packed_refs(refs);
1288 ref = find_ref(dir, refname);
1292 hashcpy(sha1, ref->u.value.oid.hash);
1296 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1297 const char *refname, unsigned char *sha1,
1301 char buffer[128], *p;
1304 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1307 ? git_pathdup_submodule(refs->name, "%s", refname)
1308 : git_pathdup("%s", refname);
1309 fd = open(path, O_RDONLY);
1312 return resolve_gitlink_packed_ref(refs, refname, sha1);
1314 len = read(fd, buffer, sizeof(buffer)-1);
1318 while (len && isspace(buffer[len-1]))
1322 /* Was it a detached head or an old-fashioned symlink? */
1323 if (!get_sha1_hex(buffer, sha1))
1327 if (strncmp(buffer, "ref:", 4))
1333 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1336 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1338 int len = strlen(path), retval;
1340 struct ref_cache *refs;
1342 while (len && path[len-1] == '/')
1346 submodule = xstrndup(path, len);
1347 refs = get_ref_cache(submodule);
1350 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1355 * Return the ref_entry for the given refname from the packed
1356 * references. If it does not exist, return NULL.
1358 static struct ref_entry *get_packed_ref(const char *refname)
1360 return find_ref(get_packed_refs(&ref_cache), refname);
1364 * A loose ref file doesn't exist; check for a packed ref. The
1365 * options are forwarded from resolve_safe_unsafe().
1367 static int resolve_missing_loose_ref(const char *refname,
1369 unsigned char *sha1,
1372 struct ref_entry *entry;
1375 * The loose reference file does not exist; check for a packed
1378 entry = get_packed_ref(refname);
1380 hashcpy(sha1, entry->u.value.oid.hash);
1382 *flags |= REF_ISPACKED;
1385 /* The reference is not a packed reference, either. */
1386 if (resolve_flags & RESOLVE_REF_READING) {
1395 /* This function needs to return a meaningful errno on failure */
1396 static const char *resolve_ref_1(const char *refname,
1398 unsigned char *sha1,
1400 struct strbuf *sb_refname,
1401 struct strbuf *sb_path,
1402 struct strbuf *sb_contents)
1404 int depth = MAXDEPTH;
1410 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1412 *flags |= REF_BAD_NAME;
1414 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1415 !refname_is_safe(refname)) {
1420 * dwim_ref() uses REF_ISBROKEN to distinguish between
1421 * missing refs and refs that were present but invalid,
1422 * to complain about the latter to stderr.
1424 * We don't know whether the ref exists, so don't set
1440 strbuf_reset(sb_path);
1441 strbuf_git_path(sb_path, "%s", refname);
1442 path = sb_path->buf;
1445 * We might have to loop back here to avoid a race
1446 * condition: first we lstat() the file, then we try
1447 * to read it as a link or as a file. But if somebody
1448 * changes the type of the file (file <-> directory
1449 * <-> symlink) between the lstat() and reading, then
1450 * we don't want to report that as an error but rather
1451 * try again starting with the lstat().
1454 if (lstat(path, &st) < 0) {
1455 if (errno != ENOENT)
1457 if (resolve_missing_loose_ref(refname, resolve_flags,
1463 *flags |= REF_ISBROKEN;
1468 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1469 if (S_ISLNK(st.st_mode)) {
1470 strbuf_reset(sb_contents);
1471 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1472 if (errno == ENOENT || errno == EINVAL)
1473 /* inconsistent with lstat; retry */
1478 if (starts_with(sb_contents->buf, "refs/") &&
1479 !check_refname_format(sb_contents->buf, 0)) {
1480 strbuf_swap(sb_refname, sb_contents);
1481 refname = sb_refname->buf;
1483 *flags |= REF_ISSYMREF;
1484 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1492 /* Is it a directory? */
1493 if (S_ISDIR(st.st_mode)) {
1499 * Anything else, just open it and try to use it as
1502 fd = open(path, O_RDONLY);
1504 if (errno == ENOENT)
1505 /* inconsistent with lstat; retry */
1510 strbuf_reset(sb_contents);
1511 if (strbuf_read(sb_contents, fd, 256) < 0) {
1512 int save_errno = errno;
1518 strbuf_rtrim(sb_contents);
1521 * Is it a symbolic ref?
1523 if (!starts_with(sb_contents->buf, "ref:")) {
1525 * Please note that FETCH_HEAD has a second
1526 * line containing other data.
1528 if (get_sha1_hex(sb_contents->buf, sha1) ||
1529 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1531 *flags |= REF_ISBROKEN;
1538 *flags |= REF_ISBROKEN;
1543 *flags |= REF_ISSYMREF;
1544 buf = sb_contents->buf + 4;
1545 while (isspace(*buf))
1547 strbuf_reset(sb_refname);
1548 strbuf_addstr(sb_refname, buf);
1549 refname = sb_refname->buf;
1550 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1554 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1556 *flags |= REF_ISBROKEN;
1558 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1559 !refname_is_safe(buf)) {
1568 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1569 unsigned char *sha1, int *flags)
1571 static struct strbuf sb_refname = STRBUF_INIT;
1572 struct strbuf sb_contents = STRBUF_INIT;
1573 struct strbuf sb_path = STRBUF_INIT;
1576 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1577 &sb_refname, &sb_path, &sb_contents);
1578 strbuf_release(&sb_path);
1579 strbuf_release(&sb_contents);
1584 * Peel the entry (if possible) and return its new peel_status. If
1585 * repeel is true, re-peel the entry even if there is an old peeled
1586 * value that is already stored in it.
1588 * It is OK to call this function with a packed reference entry that
1589 * might be stale and might even refer to an object that has since
1590 * been garbage-collected. In such a case, if the entry has
1591 * REF_KNOWS_PEELED then leave the status unchanged and return
1592 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1594 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1596 enum peel_status status;
1598 if (entry->flag & REF_KNOWS_PEELED) {
1600 entry->flag &= ~REF_KNOWS_PEELED;
1601 oidclr(&entry->u.value.peeled);
1603 return is_null_oid(&entry->u.value.peeled) ?
1604 PEEL_NON_TAG : PEEL_PEELED;
1607 if (entry->flag & REF_ISBROKEN)
1609 if (entry->flag & REF_ISSYMREF)
1610 return PEEL_IS_SYMREF;
1612 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1613 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1614 entry->flag |= REF_KNOWS_PEELED;
1618 int peel_ref(const char *refname, unsigned char *sha1)
1621 unsigned char base[20];
1623 if (current_ref && (current_ref->name == refname
1624 || !strcmp(current_ref->name, refname))) {
1625 if (peel_entry(current_ref, 0))
1627 hashcpy(sha1, current_ref->u.value.peeled.hash);
1631 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1635 * If the reference is packed, read its ref_entry from the
1636 * cache in the hope that we already know its peeled value.
1637 * We only try this optimization on packed references because
1638 * (a) forcing the filling of the loose reference cache could
1639 * be expensive and (b) loose references anyway usually do not
1640 * have REF_KNOWS_PEELED.
1642 if (flag & REF_ISPACKED) {
1643 struct ref_entry *r = get_packed_ref(refname);
1645 if (peel_entry(r, 0))
1647 hashcpy(sha1, r->u.value.peeled.hash);
1652 return peel_object(base, sha1);
1656 * Call fn for each reference in the specified ref_cache, omitting
1657 * references not in the containing_dir of base. fn is called for all
1658 * references, including broken ones. If fn ever returns a non-zero
1659 * value, stop the iteration and return that value; otherwise, return
1662 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1663 each_ref_entry_fn fn, void *cb_data)
1665 struct packed_ref_cache *packed_ref_cache;
1666 struct ref_dir *loose_dir;
1667 struct ref_dir *packed_dir;
1671 * We must make sure that all loose refs are read before accessing the
1672 * packed-refs file; this avoids a race condition in which loose refs
1673 * are migrated to the packed-refs file by a simultaneous process, but
1674 * our in-memory view is from before the migration. get_packed_ref_cache()
1675 * takes care of making sure our view is up to date with what is on
1678 loose_dir = get_loose_refs(refs);
1679 if (base && *base) {
1680 loose_dir = find_containing_dir(loose_dir, base, 0);
1683 prime_ref_dir(loose_dir);
1685 packed_ref_cache = get_packed_ref_cache(refs);
1686 acquire_packed_ref_cache(packed_ref_cache);
1687 packed_dir = get_packed_ref_dir(packed_ref_cache);
1688 if (base && *base) {
1689 packed_dir = find_containing_dir(packed_dir, base, 0);
1692 if (packed_dir && loose_dir) {
1693 sort_ref_dir(packed_dir);
1694 sort_ref_dir(loose_dir);
1695 retval = do_for_each_entry_in_dirs(
1696 packed_dir, loose_dir, fn, cb_data);
1697 } else if (packed_dir) {
1698 sort_ref_dir(packed_dir);
1699 retval = do_for_each_entry_in_dir(
1700 packed_dir, 0, fn, cb_data);
1701 } else if (loose_dir) {
1702 sort_ref_dir(loose_dir);
1703 retval = do_for_each_entry_in_dir(
1704 loose_dir, 0, fn, cb_data);
1707 release_packed_ref_cache(packed_ref_cache);
1712 * Call fn for each reference in the specified ref_cache for which the
1713 * refname begins with base. If trim is non-zero, then trim that many
1714 * characters off the beginning of each refname before passing the
1715 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1716 * broken references in the iteration. If fn ever returns a non-zero
1717 * value, stop the iteration and return that value; otherwise, return
1720 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1721 each_ref_fn fn, int trim, int flags, void *cb_data)
1723 struct ref_entry_cb data;
1728 data.cb_data = cb_data;
1730 if (ref_paranoia < 0)
1731 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1733 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1735 return do_for_each_entry(refs, base, do_one_ref, &data);
1738 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1740 struct object_id oid;
1744 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1745 return fn("HEAD", &oid, 0, cb_data);
1750 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1751 return fn("HEAD", &oid, flag, cb_data);
1756 int head_ref(each_ref_fn fn, void *cb_data)
1758 return do_head_ref(NULL, fn, cb_data);
1761 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1763 return do_head_ref(submodule, fn, cb_data);
1766 int for_each_ref(each_ref_fn fn, void *cb_data)
1768 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1771 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1773 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1776 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1778 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1781 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1783 unsigned int flag = 0;
1786 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1787 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
1790 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1791 each_ref_fn fn, void *cb_data)
1793 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1796 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1798 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
1799 strlen(git_replace_ref_base), 0, cb_data);
1802 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1804 struct strbuf buf = STRBUF_INIT;
1806 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1807 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1808 strbuf_release(&buf);
1812 int for_each_rawref(each_ref_fn fn, void *cb_data)
1814 return do_for_each_ref(&ref_cache, "", fn, 0,
1815 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1818 static void unlock_ref(struct ref_lock *lock)
1820 /* Do not free lock->lk -- atexit() still looks at them */
1822 rollback_lock_file(lock->lk);
1823 free(lock->ref_name);
1824 free(lock->orig_ref_name);
1829 * Verify that the reference locked by lock has the value old_sha1.
1830 * Fail if the reference doesn't exist and mustexist is set. Return 0
1831 * on success. On error, write an error message to err, set errno, and
1832 * return a negative value.
1834 static int verify_lock(struct ref_lock *lock,
1835 const unsigned char *old_sha1, int mustexist,
1840 if (read_ref_full(lock->ref_name,
1841 mustexist ? RESOLVE_REF_READING : 0,
1842 lock->old_oid.hash, NULL)) {
1843 int save_errno = errno;
1844 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1848 if (hashcmp(lock->old_oid.hash, old_sha1)) {
1849 strbuf_addf(err, "ref %s is at %s but expected %s",
1851 sha1_to_hex(lock->old_oid.hash),
1852 sha1_to_hex(old_sha1));
1859 static int remove_empty_directories(struct strbuf *path)
1862 * we want to create a file but there is a directory there;
1863 * if that is an empty directory (or a directory that contains
1864 * only empty directories), remove them.
1866 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1870 * Locks a ref returning the lock on success and NULL on failure.
1871 * On failure errno is set to something meaningful.
1873 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1874 const unsigned char *old_sha1,
1875 const struct string_list *extras,
1876 const struct string_list *skip,
1877 unsigned int flags, int *type_p,
1880 struct strbuf ref_file = STRBUF_INIT;
1881 struct strbuf orig_ref_file = STRBUF_INIT;
1882 const char *orig_refname = refname;
1883 struct ref_lock *lock;
1886 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1887 int resolve_flags = 0;
1888 int attempts_remaining = 3;
1892 lock = xcalloc(1, sizeof(struct ref_lock));
1895 resolve_flags |= RESOLVE_REF_READING;
1896 if (flags & REF_DELETING) {
1897 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1898 if (flags & REF_NODEREF)
1899 resolve_flags |= RESOLVE_REF_NO_RECURSE;
1902 refname = resolve_ref_unsafe(refname, resolve_flags,
1903 lock->old_oid.hash, &type);
1904 if (!refname && errno == EISDIR) {
1906 * we are trying to lock foo but we used to
1907 * have foo/bar which now does not exist;
1908 * it is normal for the empty directory 'foo'
1911 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1912 if (remove_empty_directories(&orig_ref_file)) {
1914 if (!verify_refname_available_dir(orig_refname, extras, skip,
1915 get_loose_refs(&ref_cache), err))
1916 strbuf_addf(err, "there are still refs under '%s'",
1920 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1921 lock->old_oid.hash, &type);
1927 if (last_errno != ENOTDIR ||
1928 !verify_refname_available_dir(orig_refname, extras, skip,
1929 get_loose_refs(&ref_cache), err))
1930 strbuf_addf(err, "unable to resolve reference %s: %s",
1931 orig_refname, strerror(last_errno));
1936 * If the ref did not exist and we are creating it, make sure
1937 * there is no existing packed ref whose name begins with our
1938 * refname, nor a packed ref whose name is a proper prefix of
1941 if (is_null_oid(&lock->old_oid) &&
1942 verify_refname_available_dir(refname, extras, skip,
1943 get_packed_refs(&ref_cache), err)) {
1944 last_errno = ENOTDIR;
1948 lock->lk = xcalloc(1, sizeof(struct lock_file));
1951 if (flags & REF_NODEREF) {
1952 refname = orig_refname;
1953 lflags |= LOCK_NO_DEREF;
1955 lock->ref_name = xstrdup(refname);
1956 lock->orig_ref_name = xstrdup(orig_refname);
1957 strbuf_git_path(&ref_file, "%s", refname);
1960 switch (safe_create_leading_directories_const(ref_file.buf)) {
1962 break; /* success */
1964 if (--attempts_remaining > 0)
1969 strbuf_addf(err, "unable to create directory for %s",
1974 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1976 if (errno == ENOENT && --attempts_remaining > 0)
1978 * Maybe somebody just deleted one of the
1979 * directories leading to ref_file. Try
1984 unable_to_lock_message(ref_file.buf, errno, err);
1988 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
1999 strbuf_release(&ref_file);
2000 strbuf_release(&orig_ref_file);
2006 * Write an entry to the packed-refs file for the specified refname.
2007 * If peeled is non-NULL, write it as the entry's peeled value.
2009 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2010 unsigned char *peeled)
2012 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2014 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2018 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2020 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2022 enum peel_status peel_status = peel_entry(entry, 0);
2024 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2025 error("internal error: %s is not a valid packed reference!",
2027 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2028 peel_status == PEEL_PEELED ?
2029 entry->u.value.peeled.hash : NULL);
2034 * Lock the packed-refs file for writing. Flags is passed to
2035 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2036 * errno appropriately and return a nonzero value.
2038 static int lock_packed_refs(int flags)
2040 static int timeout_configured = 0;
2041 static int timeout_value = 1000;
2043 struct packed_ref_cache *packed_ref_cache;
2045 if (!timeout_configured) {
2046 git_config_get_int("core.packedrefstimeout", &timeout_value);
2047 timeout_configured = 1;
2050 if (hold_lock_file_for_update_timeout(
2051 &packlock, git_path("packed-refs"),
2052 flags, timeout_value) < 0)
2055 * Get the current packed-refs while holding the lock. If the
2056 * packed-refs file has been modified since we last read it,
2057 * this will automatically invalidate the cache and re-read
2058 * the packed-refs file.
2060 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2061 packed_ref_cache->lock = &packlock;
2062 /* Increment the reference count to prevent it from being freed: */
2063 acquire_packed_ref_cache(packed_ref_cache);
2068 * Write the current version of the packed refs cache from memory to
2069 * disk. The packed-refs file must already be locked for writing (see
2070 * lock_packed_refs()). Return zero on success. On errors, set errno
2071 * and return a nonzero value
2073 static int commit_packed_refs(void)
2075 struct packed_ref_cache *packed_ref_cache =
2076 get_packed_ref_cache(&ref_cache);
2081 if (!packed_ref_cache->lock)
2082 die("internal error: packed-refs not locked");
2084 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2086 die_errno("unable to fdopen packed-refs descriptor");
2088 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2089 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2090 0, write_packed_entry_fn, out);
2092 if (commit_lock_file(packed_ref_cache->lock)) {
2096 packed_ref_cache->lock = NULL;
2097 release_packed_ref_cache(packed_ref_cache);
2103 * Rollback the lockfile for the packed-refs file, and discard the
2104 * in-memory packed reference cache. (The packed-refs file will be
2105 * read anew if it is needed again after this function is called.)
2107 static void rollback_packed_refs(void)
2109 struct packed_ref_cache *packed_ref_cache =
2110 get_packed_ref_cache(&ref_cache);
2112 if (!packed_ref_cache->lock)
2113 die("internal error: packed-refs not locked");
2114 rollback_lock_file(packed_ref_cache->lock);
2115 packed_ref_cache->lock = NULL;
2116 release_packed_ref_cache(packed_ref_cache);
2117 clear_packed_ref_cache(&ref_cache);
2120 struct ref_to_prune {
2121 struct ref_to_prune *next;
2122 unsigned char sha1[20];
2123 char name[FLEX_ARRAY];
2126 struct pack_refs_cb_data {
2128 struct ref_dir *packed_refs;
2129 struct ref_to_prune *ref_to_prune;
2133 * An each_ref_entry_fn that is run over loose references only. If
2134 * the loose reference can be packed, add an entry in the packed ref
2135 * cache. If the reference should be pruned, also add it to
2136 * ref_to_prune in the pack_refs_cb_data.
2138 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2140 struct pack_refs_cb_data *cb = cb_data;
2141 enum peel_status peel_status;
2142 struct ref_entry *packed_entry;
2143 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2145 /* Do not pack per-worktree refs: */
2146 if (ref_type(entry->name) != REF_TYPE_NORMAL)
2149 /* ALWAYS pack tags */
2150 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2153 /* Do not pack symbolic or broken refs: */
2154 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2157 /* Add a packed ref cache entry equivalent to the loose entry. */
2158 peel_status = peel_entry(entry, 1);
2159 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2160 die("internal error peeling reference %s (%s)",
2161 entry->name, oid_to_hex(&entry->u.value.oid));
2162 packed_entry = find_ref(cb->packed_refs, entry->name);
2164 /* Overwrite existing packed entry with info from loose entry */
2165 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2166 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2168 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2169 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2170 add_ref(cb->packed_refs, packed_entry);
2172 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2174 /* Schedule the loose reference for pruning if requested. */
2175 if ((cb->flags & PACK_REFS_PRUNE)) {
2176 int namelen = strlen(entry->name) + 1;
2177 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2178 hashcpy(n->sha1, entry->u.value.oid.hash);
2179 memcpy(n->name, entry->name, namelen); /* includes NUL */
2180 n->next = cb->ref_to_prune;
2181 cb->ref_to_prune = n;
2187 * Remove empty parents, but spare refs/ and immediate subdirs.
2188 * Note: munges *name.
2190 static void try_remove_empty_parents(char *name)
2195 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2196 while (*p && *p != '/')
2198 /* tolerate duplicate slashes; see check_refname_format() */
2202 for (q = p; *q; q++)
2205 while (q > p && *q != '/')
2207 while (q > p && *(q-1) == '/')
2212 if (rmdir(git_path("%s", name)))
2217 /* make sure nobody touched the ref, and unlink */
2218 static void prune_ref(struct ref_to_prune *r)
2220 struct ref_transaction *transaction;
2221 struct strbuf err = STRBUF_INIT;
2223 if (check_refname_format(r->name, 0))
2226 transaction = ref_transaction_begin(&err);
2228 ref_transaction_delete(transaction, r->name, r->sha1,
2229 REF_ISPRUNING, NULL, &err) ||
2230 ref_transaction_commit(transaction, &err)) {
2231 ref_transaction_free(transaction);
2232 error("%s", err.buf);
2233 strbuf_release(&err);
2236 ref_transaction_free(transaction);
2237 strbuf_release(&err);
2238 try_remove_empty_parents(r->name);
2241 static void prune_refs(struct ref_to_prune *r)
2249 int pack_refs(unsigned int flags)
2251 struct pack_refs_cb_data cbdata;
2253 memset(&cbdata, 0, sizeof(cbdata));
2254 cbdata.flags = flags;
2256 lock_packed_refs(LOCK_DIE_ON_ERROR);
2257 cbdata.packed_refs = get_packed_refs(&ref_cache);
2259 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2260 pack_if_possible_fn, &cbdata);
2262 if (commit_packed_refs())
2263 die_errno("unable to overwrite old ref-pack file");
2265 prune_refs(cbdata.ref_to_prune);
2270 * Rewrite the packed-refs file, omitting any refs listed in
2271 * 'refnames'. On error, leave packed-refs unchanged, write an error
2272 * message to 'err', and return a nonzero value.
2274 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2276 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2278 struct ref_dir *packed;
2279 struct string_list_item *refname;
2280 int ret, needs_repacking = 0, removed = 0;
2284 /* Look for a packed ref */
2285 for_each_string_list_item(refname, refnames) {
2286 if (get_packed_ref(refname->string)) {
2287 needs_repacking = 1;
2292 /* Avoid locking if we have nothing to do */
2293 if (!needs_repacking)
2294 return 0; /* no refname exists in packed refs */
2296 if (lock_packed_refs(0)) {
2297 unable_to_lock_message(git_path("packed-refs"), errno, err);
2300 packed = get_packed_refs(&ref_cache);
2302 /* Remove refnames from the cache */
2303 for_each_string_list_item(refname, refnames)
2304 if (remove_entry(packed, refname->string) != -1)
2308 * All packed entries disappeared while we were
2309 * acquiring the lock.
2311 rollback_packed_refs();
2315 /* Write what remains */
2316 ret = commit_packed_refs();
2318 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2323 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2327 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2329 * loose. The loose file name is the same as the
2330 * lockfile name, minus ".lock":
2332 char *loose_filename = get_locked_file_path(lock->lk);
2333 int res = unlink_or_msg(loose_filename, err);
2334 free(loose_filename);
2341 int delete_refs(struct string_list *refnames)
2343 struct strbuf err = STRBUF_INIT;
2349 result = repack_without_refs(refnames, &err);
2352 * If we failed to rewrite the packed-refs file, then
2353 * it is unsafe to try to remove loose refs, because
2354 * doing so might expose an obsolete packed value for
2355 * a reference that might even point at an object that
2356 * has been garbage collected.
2358 if (refnames->nr == 1)
2359 error(_("could not delete reference %s: %s"),
2360 refnames->items[0].string, err.buf);
2362 error(_("could not delete references: %s"), err.buf);
2367 for (i = 0; i < refnames->nr; i++) {
2368 const char *refname = refnames->items[i].string;
2370 if (delete_ref(refname, NULL, 0))
2371 result |= error(_("could not remove reference %s"), refname);
2375 strbuf_release(&err);
2380 * People using contrib's git-new-workdir have .git/logs/refs ->
2381 * /some/other/path/.git/logs/refs, and that may live on another device.
2383 * IOW, to avoid cross device rename errors, the temporary renamed log must
2384 * live into logs/refs.
2386 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2388 static int rename_tmp_log(const char *newrefname)
2390 int attempts_remaining = 4;
2391 struct strbuf path = STRBUF_INIT;
2395 strbuf_reset(&path);
2396 strbuf_git_path(&path, "logs/%s", newrefname);
2397 switch (safe_create_leading_directories_const(path.buf)) {
2399 break; /* success */
2401 if (--attempts_remaining > 0)
2405 error("unable to create directory for %s", newrefname);
2409 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2410 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2412 * rename(a, b) when b is an existing
2413 * directory ought to result in ISDIR, but
2414 * Solaris 5.8 gives ENOTDIR. Sheesh.
2416 if (remove_empty_directories(&path)) {
2417 error("Directory not empty: logs/%s", newrefname);
2421 } else if (errno == ENOENT && --attempts_remaining > 0) {
2423 * Maybe another process just deleted one of
2424 * the directories in the path to newrefname.
2425 * Try again from the beginning.
2429 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2430 newrefname, strerror(errno));
2436 strbuf_release(&path);
2440 int verify_refname_available(const char *newname,
2441 struct string_list *extras,
2442 struct string_list *skip,
2445 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2446 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2448 if (verify_refname_available_dir(newname, extras, skip,
2449 packed_refs, err) ||
2450 verify_refname_available_dir(newname, extras, skip,
2457 static int write_ref_to_lockfile(struct ref_lock *lock,
2458 const unsigned char *sha1, struct strbuf *err);
2459 static int commit_ref_update(struct ref_lock *lock,
2460 const unsigned char *sha1, const char *logmsg,
2461 int flags, struct strbuf *err);
2463 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2465 unsigned char sha1[20], orig_sha1[20];
2466 int flag = 0, logmoved = 0;
2467 struct ref_lock *lock;
2468 struct stat loginfo;
2469 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2470 const char *symref = NULL;
2471 struct strbuf err = STRBUF_INIT;
2473 if (log && S_ISLNK(loginfo.st_mode))
2474 return error("reflog for %s is a symlink", oldrefname);
2476 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2478 if (flag & REF_ISSYMREF)
2479 return error("refname %s is a symbolic ref, renaming it is not supported",
2482 return error("refname %s not found", oldrefname);
2484 if (!rename_ref_available(oldrefname, newrefname))
2487 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2488 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2489 oldrefname, strerror(errno));
2491 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2492 error("unable to delete old %s", oldrefname);
2496 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2497 delete_ref(newrefname, sha1, REF_NODEREF)) {
2498 if (errno==EISDIR) {
2499 struct strbuf path = STRBUF_INIT;
2502 strbuf_git_path(&path, "%s", newrefname);
2503 result = remove_empty_directories(&path);
2504 strbuf_release(&path);
2507 error("Directory not empty: %s", newrefname);
2511 error("unable to delete existing %s", newrefname);
2516 if (log && rename_tmp_log(newrefname))
2521 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2523 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2524 strbuf_release(&err);
2527 hashcpy(lock->old_oid.hash, orig_sha1);
2529 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2530 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2531 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2532 strbuf_release(&err);
2539 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2541 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2542 strbuf_release(&err);
2546 flag = log_all_ref_updates;
2547 log_all_ref_updates = 0;
2548 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2549 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2550 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2551 strbuf_release(&err);
2553 log_all_ref_updates = flag;
2556 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2557 error("unable to restore logfile %s from %s: %s",
2558 oldrefname, newrefname, strerror(errno));
2559 if (!logmoved && log &&
2560 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2561 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2562 oldrefname, strerror(errno));
2567 static int close_ref(struct ref_lock *lock)
2569 if (close_lock_file(lock->lk))
2574 static int commit_ref(struct ref_lock *lock)
2576 if (commit_lock_file(lock->lk))
2582 * Create a reflog for a ref. If force_create = 0, the reflog will
2583 * only be created for certain refs (those for which
2584 * should_autocreate_reflog returns non-zero. Otherwise, create it
2585 * regardless of the ref name. Fill in *err and return -1 on failure.
2587 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2589 int logfd, oflags = O_APPEND | O_WRONLY;
2591 strbuf_git_path(logfile, "logs/%s", refname);
2592 if (force_create || should_autocreate_reflog(refname)) {
2593 if (safe_create_leading_directories(logfile->buf) < 0) {
2594 strbuf_addf(err, "unable to create directory for %s: "
2595 "%s", logfile->buf, strerror(errno));
2601 logfd = open(logfile->buf, oflags, 0666);
2603 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2606 if (errno == EISDIR) {
2607 if (remove_empty_directories(logfile)) {
2608 strbuf_addf(err, "There are still logs under "
2609 "'%s'", logfile->buf);
2612 logfd = open(logfile->buf, oflags, 0666);
2616 strbuf_addf(err, "unable to append to %s: %s",
2617 logfile->buf, strerror(errno));
2622 adjust_shared_perm(logfile->buf);
2628 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2631 struct strbuf sb = STRBUF_INIT;
2633 ret = log_ref_setup(refname, &sb, err, force_create);
2634 strbuf_release(&sb);
2638 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2639 const unsigned char *new_sha1,
2640 const char *committer, const char *msg)
2642 int msglen, written;
2643 unsigned maxlen, len;
2646 msglen = msg ? strlen(msg) : 0;
2647 maxlen = strlen(committer) + msglen + 100;
2648 logrec = xmalloc(maxlen);
2649 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2650 sha1_to_hex(old_sha1),
2651 sha1_to_hex(new_sha1),
2654 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2656 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2664 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2665 const unsigned char *new_sha1, const char *msg,
2666 struct strbuf *logfile, int flags,
2669 int logfd, result, oflags = O_APPEND | O_WRONLY;
2671 if (log_all_ref_updates < 0)
2672 log_all_ref_updates = !is_bare_repository();
2674 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2679 logfd = open(logfile->buf, oflags);
2682 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2683 git_committer_info(0), msg);
2685 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2691 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2698 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2699 const unsigned char *new_sha1, const char *msg,
2700 int flags, struct strbuf *err)
2702 return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2706 int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2707 const unsigned char *new_sha1, const char *msg,
2708 int flags, struct strbuf *err)
2710 struct strbuf sb = STRBUF_INIT;
2711 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2713 strbuf_release(&sb);
2718 * Write sha1 into the open lockfile, then close the lockfile. On
2719 * errors, rollback the lockfile, fill in *err and
2722 static int write_ref_to_lockfile(struct ref_lock *lock,
2723 const unsigned char *sha1, struct strbuf *err)
2725 static char term = '\n';
2729 o = parse_object(sha1);
2732 "Trying to write ref %s with nonexistent object %s",
2733 lock->ref_name, sha1_to_hex(sha1));
2737 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2739 "Trying to write non-commit object %s to branch %s",
2740 sha1_to_hex(sha1), lock->ref_name);
2744 fd = get_lock_file_fd(lock->lk);
2745 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2746 write_in_full(fd, &term, 1) != 1 ||
2747 close_ref(lock) < 0) {
2749 "Couldn't write %s", get_lock_file_path(lock->lk));
2757 * Commit a change to a loose reference that has already been written
2758 * to the loose reference lockfile. Also update the reflogs if
2759 * necessary, using the specified lockmsg (which can be NULL).
2761 static int commit_ref_update(struct ref_lock *lock,
2762 const unsigned char *sha1, const char *logmsg,
2763 int flags, struct strbuf *err)
2765 clear_loose_ref_cache(&ref_cache);
2766 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2767 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2768 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2769 char *old_msg = strbuf_detach(err, NULL);
2770 strbuf_addf(err, "Cannot update the ref '%s': %s",
2771 lock->ref_name, old_msg);
2776 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2778 * Special hack: If a branch is updated directly and HEAD
2779 * points to it (may happen on the remote side of a push
2780 * for example) then logically the HEAD reflog should be
2782 * A generic solution implies reverse symref information,
2783 * but finding all symrefs pointing to the given branch
2784 * would be rather costly for this rare event (the direct
2785 * update of a branch) to be worth it. So let's cheat and
2786 * check with HEAD only which should cover 99% of all usage
2787 * scenarios (even 100% of the default ones).
2789 unsigned char head_sha1[20];
2791 const char *head_ref;
2792 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2793 head_sha1, &head_flag);
2794 if (head_ref && (head_flag & REF_ISSYMREF) &&
2795 !strcmp(head_ref, lock->ref_name)) {
2796 struct strbuf log_err = STRBUF_INIT;
2797 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2798 logmsg, 0, &log_err)) {
2799 error("%s", log_err.buf);
2800 strbuf_release(&log_err);
2804 if (commit_ref(lock)) {
2805 error("Couldn't set %s", lock->ref_name);
2814 int create_symref(const char *ref_target, const char *refs_heads_master,
2817 char *lockpath = NULL;
2819 int fd, len, written;
2820 char *git_HEAD = git_pathdup("%s", ref_target);
2821 unsigned char old_sha1[20], new_sha1[20];
2822 struct strbuf err = STRBUF_INIT;
2824 if (logmsg && read_ref(ref_target, old_sha1))
2827 if (safe_create_leading_directories(git_HEAD) < 0)
2828 return error("unable to create directory for %s", git_HEAD);
2830 #ifndef NO_SYMLINK_HEAD
2831 if (prefer_symlink_refs) {
2833 if (!symlink(refs_heads_master, git_HEAD))
2835 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2839 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2840 if (sizeof(ref) <= len) {
2841 error("refname too long: %s", refs_heads_master);
2842 goto error_free_return;
2844 lockpath = mkpathdup("%s.lock", git_HEAD);
2845 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2847 error("Unable to open %s for writing", lockpath);
2848 goto error_free_return;
2850 written = write_in_full(fd, ref, len);
2851 if (close(fd) != 0 || written != len) {
2852 error("Unable to write to %s", lockpath);
2853 goto error_unlink_return;
2855 if (rename(lockpath, git_HEAD) < 0) {
2856 error("Unable to create %s", git_HEAD);
2857 goto error_unlink_return;
2859 if (adjust_shared_perm(git_HEAD)) {
2860 error("Unable to fix permissions on %s", lockpath);
2861 error_unlink_return:
2862 unlink_or_warn(lockpath);
2870 #ifndef NO_SYMLINK_HEAD
2873 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
2874 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
2875 error("%s", err.buf);
2876 strbuf_release(&err);
2883 int reflog_exists(const char *refname)
2887 return !lstat(git_path("logs/%s", refname), &st) &&
2888 S_ISREG(st.st_mode);
2891 int delete_reflog(const char *refname)
2893 return remove_path(git_path("logs/%s", refname));
2896 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2898 unsigned char osha1[20], nsha1[20];
2899 char *email_end, *message;
2900 unsigned long timestamp;
2903 /* old SP new SP name <email> SP time TAB msg LF */
2904 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2905 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2906 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2907 !(email_end = strchr(sb->buf + 82, '>')) ||
2908 email_end[1] != ' ' ||
2909 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2910 !message || message[0] != ' ' ||
2911 (message[1] != '+' && message[1] != '-') ||
2912 !isdigit(message[2]) || !isdigit(message[3]) ||
2913 !isdigit(message[4]) || !isdigit(message[5]))
2914 return 0; /* corrupt? */
2915 email_end[1] = '\0';
2916 tz = strtol(message + 1, NULL, 10);
2917 if (message[6] != '\t')
2921 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2924 static char *find_beginning_of_line(char *bob, char *scan)
2926 while (bob < scan && *(--scan) != '\n')
2927 ; /* keep scanning backwards */
2929 * Return either beginning of the buffer, or LF at the end of
2930 * the previous line.
2935 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2937 struct strbuf sb = STRBUF_INIT;
2940 int ret = 0, at_tail = 1;
2942 logfp = fopen(git_path("logs/%s", refname), "r");
2946 /* Jump to the end */
2947 if (fseek(logfp, 0, SEEK_END) < 0)
2948 return error("cannot seek back reflog for %s: %s",
2949 refname, strerror(errno));
2951 while (!ret && 0 < pos) {
2957 /* Fill next block from the end */
2958 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2959 if (fseek(logfp, pos - cnt, SEEK_SET))
2960 return error("cannot seek back reflog for %s: %s",
2961 refname, strerror(errno));
2962 nread = fread(buf, cnt, 1, logfp);
2964 return error("cannot read %d bytes from reflog for %s: %s",
2965 cnt, refname, strerror(errno));
2968 scanp = endp = buf + cnt;
2969 if (at_tail && scanp[-1] == '\n')
2970 /* Looking at the final LF at the end of the file */
2974 while (buf < scanp) {
2976 * terminating LF of the previous line, or the beginning
2981 bp = find_beginning_of_line(buf, scanp);
2985 * The newline is the end of the previous line,
2986 * so we know we have complete line starting
2987 * at (bp + 1). Prefix it onto any prior data
2988 * we collected for the line and process it.
2990 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2993 ret = show_one_reflog_ent(&sb, fn, cb_data);
2999 * We are at the start of the buffer, and the
3000 * start of the file; there is no previous
3001 * line, and we have everything for this one.
3002 * Process it, and we can end the loop.
3004 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3005 ret = show_one_reflog_ent(&sb, fn, cb_data);
3012 * We are at the start of the buffer, and there
3013 * is more file to read backwards. Which means
3014 * we are in the middle of a line. Note that we
3015 * may get here even if *bp was a newline; that
3016 * just means we are at the exact end of the
3017 * previous line, rather than some spot in the
3020 * Save away what we have to be combined with
3021 * the data from the next read.
3023 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3030 die("BUG: reverse reflog parser had leftover data");
3033 strbuf_release(&sb);
3037 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3040 struct strbuf sb = STRBUF_INIT;
3043 logfp = fopen(git_path("logs/%s", refname), "r");
3047 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3048 ret = show_one_reflog_ent(&sb, fn, cb_data);
3050 strbuf_release(&sb);
3054 * Call fn for each reflog in the namespace indicated by name. name
3055 * must be empty or end with '/'. Name will be used as a scratch
3056 * space, but its contents will be restored before return.
3058 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3060 DIR *d = opendir(git_path("logs/%s", name->buf));
3063 int oldlen = name->len;
3066 return name->len ? errno : 0;
3068 while ((de = readdir(d)) != NULL) {
3071 if (de->d_name[0] == '.')
3073 if (ends_with(de->d_name, ".lock"))
3075 strbuf_addstr(name, de->d_name);
3076 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3077 ; /* silently ignore */
3079 if (S_ISDIR(st.st_mode)) {
3080 strbuf_addch(name, '/');
3081 retval = do_for_each_reflog(name, fn, cb_data);
3083 struct object_id oid;
3085 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3086 retval = error("bad ref for %s", name->buf);
3088 retval = fn(name->buf, &oid, 0, cb_data);
3093 strbuf_setlen(name, oldlen);
3099 int for_each_reflog(each_ref_fn fn, void *cb_data)
3103 strbuf_init(&name, PATH_MAX);
3104 retval = do_for_each_reflog(&name, fn, cb_data);
3105 strbuf_release(&name);
3109 static int ref_update_reject_duplicates(struct string_list *refnames,
3112 int i, n = refnames->nr;
3116 for (i = 1; i < n; i++)
3117 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3119 "Multiple updates for ref '%s' not allowed.",
3120 refnames->items[i].string);
3126 int ref_transaction_commit(struct ref_transaction *transaction,
3130 int n = transaction->nr;
3131 struct ref_update **updates = transaction->updates;
3132 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3133 struct string_list_item *ref_to_delete;
3134 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3138 if (transaction->state != REF_TRANSACTION_OPEN)
3139 die("BUG: commit called for transaction that is not open");
3142 transaction->state = REF_TRANSACTION_CLOSED;
3146 /* Fail if a refname appears more than once in the transaction: */
3147 for (i = 0; i < n; i++)
3148 string_list_append(&affected_refnames, updates[i]->refname);
3149 string_list_sort(&affected_refnames);
3150 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3151 ret = TRANSACTION_GENERIC_ERROR;
3156 * Acquire all locks, verify old values if provided, check
3157 * that new values are valid, and write new values to the
3158 * lockfiles, ready to be activated. Only keep one lockfile
3159 * open at a time to avoid running out of file descriptors.
3161 for (i = 0; i < n; i++) {
3162 struct ref_update *update = updates[i];
3164 if ((update->flags & REF_HAVE_NEW) &&
3165 is_null_sha1(update->new_sha1))
3166 update->flags |= REF_DELETING;
3167 update->lock = lock_ref_sha1_basic(
3169 ((update->flags & REF_HAVE_OLD) ?
3170 update->old_sha1 : NULL),
3171 &affected_refnames, NULL,
3175 if (!update->lock) {
3178 ret = (errno == ENOTDIR)
3179 ? TRANSACTION_NAME_CONFLICT
3180 : TRANSACTION_GENERIC_ERROR;
3181 reason = strbuf_detach(err, NULL);
3182 strbuf_addf(err, "cannot lock ref '%s': %s",
3183 update->refname, reason);
3187 if ((update->flags & REF_HAVE_NEW) &&
3188 !(update->flags & REF_DELETING)) {
3189 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3190 (update->flags & REF_NODEREF));
3192 if (!overwriting_symref &&
3193 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3195 * The reference already has the desired
3196 * value, so we don't need to write it.
3198 } else if (write_ref_to_lockfile(update->lock,
3201 char *write_err = strbuf_detach(err, NULL);
3204 * The lock was freed upon failure of
3205 * write_ref_to_lockfile():
3207 update->lock = NULL;
3209 "cannot update the ref '%s': %s",
3210 update->refname, write_err);
3212 ret = TRANSACTION_GENERIC_ERROR;
3215 update->flags |= REF_NEEDS_COMMIT;
3218 if (!(update->flags & REF_NEEDS_COMMIT)) {
3220 * We didn't have to write anything to the lockfile.
3221 * Close it to free up the file descriptor:
3223 if (close_ref(update->lock)) {
3224 strbuf_addf(err, "Couldn't close %s.lock",
3231 /* Perform updates first so live commits remain referenced */
3232 for (i = 0; i < n; i++) {
3233 struct ref_update *update = updates[i];
3235 if (update->flags & REF_NEEDS_COMMIT) {
3236 if (commit_ref_update(update->lock,
3237 update->new_sha1, update->msg,
3238 update->flags, err)) {
3239 /* freed by commit_ref_update(): */
3240 update->lock = NULL;
3241 ret = TRANSACTION_GENERIC_ERROR;
3244 /* freed by commit_ref_update(): */
3245 update->lock = NULL;
3250 /* Perform deletes now that updates are safely completed */
3251 for (i = 0; i < n; i++) {
3252 struct ref_update *update = updates[i];
3254 if (update->flags & REF_DELETING) {
3255 if (delete_ref_loose(update->lock, update->type, err)) {
3256 ret = TRANSACTION_GENERIC_ERROR;
3260 if (!(update->flags & REF_ISPRUNING))
3261 string_list_append(&refs_to_delete,
3262 update->lock->ref_name);
3266 if (repack_without_refs(&refs_to_delete, err)) {
3267 ret = TRANSACTION_GENERIC_ERROR;
3270 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3271 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3272 clear_loose_ref_cache(&ref_cache);
3275 transaction->state = REF_TRANSACTION_CLOSED;
3277 for (i = 0; i < n; i++)
3278 if (updates[i]->lock)
3279 unlock_ref(updates[i]->lock);
3280 string_list_clear(&refs_to_delete, 0);
3281 string_list_clear(&affected_refnames, 0);
3285 static int ref_present(const char *refname,
3286 const struct object_id *oid, int flags, void *cb_data)
3288 struct string_list *affected_refnames = cb_data;
3290 return string_list_has_string(affected_refnames, refname);
3293 int initial_ref_transaction_commit(struct ref_transaction *transaction,
3297 int n = transaction->nr;
3298 struct ref_update **updates = transaction->updates;
3299 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3303 if (transaction->state != REF_TRANSACTION_OPEN)
3304 die("BUG: commit called for transaction that is not open");
3306 /* Fail if a refname appears more than once in the transaction: */
3307 for (i = 0; i < n; i++)
3308 string_list_append(&affected_refnames, updates[i]->refname);
3309 string_list_sort(&affected_refnames);
3310 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3311 ret = TRANSACTION_GENERIC_ERROR;
3316 * It's really undefined to call this function in an active
3317 * repository or when there are existing references: we are
3318 * only locking and changing packed-refs, so (1) any
3319 * simultaneous processes might try to change a reference at
3320 * the same time we do, and (2) any existing loose versions of
3321 * the references that we are setting would have precedence
3322 * over our values. But some remote helpers create the remote
3323 * "HEAD" and "master" branches before calling this function,
3324 * so here we really only check that none of the references
3325 * that we are creating already exists.
3327 if (for_each_rawref(ref_present, &affected_refnames))
3328 die("BUG: initial ref transaction called with existing refs");
3330 for (i = 0; i < n; i++) {
3331 struct ref_update *update = updates[i];
3333 if ((update->flags & REF_HAVE_OLD) &&
3334 !is_null_sha1(update->old_sha1))
3335 die("BUG: initial ref transaction with old_sha1 set");
3336 if (verify_refname_available(update->refname,
3337 &affected_refnames, NULL,
3339 ret = TRANSACTION_NAME_CONFLICT;
3344 if (lock_packed_refs(0)) {
3345 strbuf_addf(err, "unable to lock packed-refs file: %s",
3347 ret = TRANSACTION_GENERIC_ERROR;
3351 for (i = 0; i < n; i++) {
3352 struct ref_update *update = updates[i];
3354 if ((update->flags & REF_HAVE_NEW) &&
3355 !is_null_sha1(update->new_sha1))
3356 add_packed_ref(update->refname, update->new_sha1);
3359 if (commit_packed_refs()) {
3360 strbuf_addf(err, "unable to commit packed-refs file: %s",
3362 ret = TRANSACTION_GENERIC_ERROR;
3367 transaction->state = REF_TRANSACTION_CLOSED;
3368 string_list_clear(&affected_refnames, 0);
3372 struct expire_reflog_cb {
3374 reflog_expiry_should_prune_fn *should_prune_fn;
3377 unsigned char last_kept_sha1[20];
3380 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3381 const char *email, unsigned long timestamp, int tz,
3382 const char *message, void *cb_data)
3384 struct expire_reflog_cb *cb = cb_data;
3385 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3387 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3388 osha1 = cb->last_kept_sha1;
3390 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3391 message, policy_cb)) {
3393 printf("would prune %s", message);
3394 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3395 printf("prune %s", message);
3398 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3399 sha1_to_hex(osha1), sha1_to_hex(nsha1),
3400 email, timestamp, tz, message);
3401 hashcpy(cb->last_kept_sha1, nsha1);
3403 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3404 printf("keep %s", message);
3409 int reflog_expire(const char *refname, const unsigned char *sha1,
3411 reflog_expiry_prepare_fn prepare_fn,
3412 reflog_expiry_should_prune_fn should_prune_fn,
3413 reflog_expiry_cleanup_fn cleanup_fn,
3414 void *policy_cb_data)
3416 static struct lock_file reflog_lock;
3417 struct expire_reflog_cb cb;
3418 struct ref_lock *lock;
3422 struct strbuf err = STRBUF_INIT;
3424 memset(&cb, 0, sizeof(cb));
3426 cb.policy_cb = policy_cb_data;
3427 cb.should_prune_fn = should_prune_fn;
3430 * The reflog file is locked by holding the lock on the
3431 * reference itself, plus we might need to update the
3432 * reference if --updateref was specified:
3434 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3436 error("cannot lock ref '%s': %s", refname, err.buf);
3437 strbuf_release(&err);
3440 if (!reflog_exists(refname)) {
3445 log_file = git_pathdup("logs/%s", refname);
3446 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3448 * Even though holding $GIT_DIR/logs/$reflog.lock has
3449 * no locking implications, we use the lock_file
3450 * machinery here anyway because it does a lot of the
3451 * work we need, including cleaning up if the program
3452 * exits unexpectedly.
3454 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3455 struct strbuf err = STRBUF_INIT;
3456 unable_to_lock_message(log_file, errno, &err);
3457 error("%s", err.buf);
3458 strbuf_release(&err);
3461 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3463 error("cannot fdopen %s (%s)",
3464 get_lock_file_path(&reflog_lock), strerror(errno));
3469 (*prepare_fn)(refname, sha1, cb.policy_cb);
3470 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3471 (*cleanup_fn)(cb.policy_cb);
3473 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3475 * It doesn't make sense to adjust a reference pointed
3476 * to by a symbolic ref based on expiring entries in
3477 * the symbolic reference's reflog. Nor can we update
3478 * a reference if there are no remaining reflog
3481 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3482 !(type & REF_ISSYMREF) &&
3483 !is_null_sha1(cb.last_kept_sha1);
3485 if (close_lock_file(&reflog_lock)) {
3486 status |= error("couldn't write %s: %s", log_file,
3488 } else if (update &&
3489 (write_in_full(get_lock_file_fd(lock->lk),
3490 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3491 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3492 close_ref(lock) < 0)) {
3493 status |= error("couldn't write %s",
3494 get_lock_file_path(lock->lk));
3495 rollback_lock_file(&reflog_lock);
3496 } else if (commit_lock_file(&reflog_lock)) {
3497 status |= error("unable to write reflog '%s' (%s)",
3498 log_file, strerror(errno));
3499 } else if (update && commit_ref(lock)) {
3500 status |= error("couldn't set %s", lock->ref_name);
3508 rollback_lock_file(&reflog_lock);