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,
732 struct strbuf dirname = STRBUF_INIT;
736 * For the sake of comments in this function, suppose that
737 * refname is "refs/foo/bar".
742 strbuf_grow(&dirname, strlen(refname) + 1);
743 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
744 /* Expand dirname to the new prefix, not including the trailing slash: */
745 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
748 * We are still at a leading dir of the refname (e.g.,
749 * "refs/foo"; if there is a reference with that name,
750 * it is a conflict, *unless* it is in skip.
753 pos = search_ref_dir(dir, dirname.buf, dirname.len);
755 (!skip || !string_list_has_string(skip, dirname.buf))) {
757 * We found a reference whose name is
758 * a proper prefix of refname; e.g.,
759 * "refs/foo", and is not in skip.
761 strbuf_addf(err, "'%s' exists; cannot create '%s'",
762 dirname.buf, refname);
767 if (extras && string_list_has_string(extras, dirname.buf) &&
768 (!skip || !string_list_has_string(skip, dirname.buf))) {
769 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
770 refname, dirname.buf);
775 * Otherwise, we can try to continue our search with
776 * the next component. So try to look up the
777 * directory, e.g., "refs/foo/". If we come up empty,
778 * we know there is nothing under this whole prefix,
779 * but even in that case we still have to continue the
780 * search for conflicts with extras.
782 strbuf_addch(&dirname, '/');
784 pos = search_ref_dir(dir, dirname.buf, dirname.len);
787 * There was no directory "refs/foo/",
788 * so there is nothing under this
789 * whole prefix. So there is no need
790 * to continue looking for conflicting
791 * references. But we need to continue
792 * looking for conflicting extras.
796 dir = get_ref_dir(dir->entries[pos]);
802 * We are at the leaf of our refname (e.g., "refs/foo/bar").
803 * There is no point in searching for a reference with that
804 * name, because a refname isn't considered to conflict with
805 * itself. But we still need to check for references whose
806 * names are in the "refs/foo/bar/" namespace, because they
809 strbuf_addstr(&dirname, refname + dirname.len);
810 strbuf_addch(&dirname, '/');
813 pos = search_ref_dir(dir, dirname.buf, dirname.len);
817 * We found a directory named "$refname/"
818 * (e.g., "refs/foo/bar/"). It is a problem
819 * iff it contains any ref that is not in
822 struct nonmatching_ref_data data;
825 data.conflicting_refname = NULL;
826 dir = get_ref_dir(dir->entries[pos]);
828 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
829 strbuf_addf(err, "'%s' exists; cannot create '%s'",
830 data.conflicting_refname, refname);
838 * Check for entries in extras that start with
839 * "$refname/". We do that by looking for the place
840 * where "$refname/" would be inserted in extras. If
841 * there is an entry at that position that starts with
842 * "$refname/" and is not in skip, then we have a
845 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
846 pos < extras->nr; pos++) {
847 const char *extra_refname = extras->items[pos].string;
849 if (!starts_with(extra_refname, dirname.buf))
852 if (!skip || !string_list_has_string(skip, extra_refname)) {
853 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
854 refname, extra_refname);
860 /* No conflicts were found */
864 strbuf_release(&dirname);
868 struct packed_ref_cache {
869 struct ref_entry *root;
872 * Count of references to the data structure in this instance,
873 * including the pointer from ref_cache::packed if any. The
874 * data will not be freed as long as the reference count is
877 unsigned int referrers;
880 * Iff the packed-refs file associated with this instance is
881 * currently locked for writing, this points at the associated
882 * lock (which is owned by somebody else). The referrer count
883 * is also incremented when the file is locked and decremented
884 * when it is unlocked.
886 struct lock_file *lock;
888 /* The metadata from when this packed-refs cache was read */
889 struct stat_validity validity;
893 * Future: need to be in "struct repository"
894 * when doing a full libification.
896 static struct ref_cache {
897 struct ref_cache *next;
898 struct ref_entry *loose;
899 struct packed_ref_cache *packed;
901 * The submodule name, or "" for the main repo. We allocate
902 * length 1 rather than FLEX_ARRAY so that the main ref_cache
903 * is initialized correctly.
906 } ref_cache, *submodule_ref_caches;
908 /* Lock used for the main packed-refs file: */
909 static struct lock_file packlock;
912 * Increment the reference count of *packed_refs.
914 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
916 packed_refs->referrers++;
920 * Decrease the reference count of *packed_refs. If it goes to zero,
921 * free *packed_refs and return true; otherwise return false.
923 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
925 if (!--packed_refs->referrers) {
926 free_ref_entry(packed_refs->root);
927 stat_validity_clear(&packed_refs->validity);
935 static void clear_packed_ref_cache(struct ref_cache *refs)
938 struct packed_ref_cache *packed_refs = refs->packed;
940 if (packed_refs->lock)
941 die("internal error: packed-ref cache cleared while locked");
943 release_packed_ref_cache(packed_refs);
947 static void clear_loose_ref_cache(struct ref_cache *refs)
950 free_ref_entry(refs->loose);
955 static struct ref_cache *create_ref_cache(const char *submodule)
958 struct ref_cache *refs;
961 len = strlen(submodule) + 1;
962 refs = xcalloc(1, sizeof(struct ref_cache) + len);
963 memcpy(refs->name, submodule, len);
968 * Return a pointer to a ref_cache for the specified submodule. For
969 * the main repository, use submodule==NULL. The returned structure
970 * will be allocated and initialized but not necessarily populated; it
971 * should not be freed.
973 static struct ref_cache *get_ref_cache(const char *submodule)
975 struct ref_cache *refs;
977 if (!submodule || !*submodule)
980 for (refs = submodule_ref_caches; refs; refs = refs->next)
981 if (!strcmp(submodule, refs->name))
984 refs = create_ref_cache(submodule);
985 refs->next = submodule_ref_caches;
986 submodule_ref_caches = refs;
990 /* The length of a peeled reference line in packed-refs, including EOL: */
991 #define PEELED_LINE_LENGTH 42
994 * The packed-refs header line that we write out. Perhaps other
995 * traits will be added later. The trailing space is required.
997 static const char PACKED_REFS_HEADER[] =
998 "# pack-refs with: peeled fully-peeled \n";
1001 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1002 * Return a pointer to the refname within the line (null-terminated),
1003 * or NULL if there was a problem.
1005 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1010 * 42: the answer to everything.
1012 * In this case, it happens to be the answer to
1013 * 40 (length of sha1 hex representation)
1014 * +1 (space in between hex and name)
1015 * +1 (newline at the end of the line)
1017 if (line->len <= 42)
1020 if (get_sha1_hex(line->buf, sha1) < 0)
1022 if (!isspace(line->buf[40]))
1025 ref = line->buf + 41;
1029 if (line->buf[line->len - 1] != '\n')
1031 line->buf[--line->len] = 0;
1037 * Read f, which is a packed-refs file, into dir.
1039 * A comment line of the form "# pack-refs with: " may contain zero or
1040 * more traits. We interpret the traits as follows:
1044 * Probably no references are peeled. But if the file contains a
1045 * peeled value for a reference, we will use it.
1049 * References under "refs/tags/", if they *can* be peeled, *are*
1050 * peeled in this file. References outside of "refs/tags/" are
1051 * probably not peeled even if they could have been, but if we find
1052 * a peeled value for such a reference we will use it.
1056 * All references in the file that can be peeled are peeled.
1057 * Inversely (and this is more important), any references in the
1058 * file for which no peeled value is recorded is not peelable. This
1059 * trait should typically be written alongside "peeled" for
1060 * compatibility with older clients, but we do not require it
1061 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1063 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1065 struct ref_entry *last = NULL;
1066 struct strbuf line = STRBUF_INIT;
1067 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1069 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1070 unsigned char sha1[20];
1071 const char *refname;
1074 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1075 if (strstr(traits, " fully-peeled "))
1076 peeled = PEELED_FULLY;
1077 else if (strstr(traits, " peeled "))
1078 peeled = PEELED_TAGS;
1079 /* perhaps other traits later as well */
1083 refname = parse_ref_line(&line, sha1);
1085 int flag = REF_ISPACKED;
1087 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1088 if (!refname_is_safe(refname))
1089 die("packed refname is dangerous: %s", refname);
1091 flag |= REF_BAD_NAME | REF_ISBROKEN;
1093 last = create_ref_entry(refname, sha1, flag, 0);
1094 if (peeled == PEELED_FULLY ||
1095 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1096 last->flag |= REF_KNOWS_PEELED;
1101 line.buf[0] == '^' &&
1102 line.len == PEELED_LINE_LENGTH &&
1103 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1104 !get_sha1_hex(line.buf + 1, sha1)) {
1105 hashcpy(last->u.value.peeled.hash, sha1);
1107 * Regardless of what the file header said,
1108 * we definitely know the value of *this*
1111 last->flag |= REF_KNOWS_PEELED;
1115 strbuf_release(&line);
1119 * Get the packed_ref_cache for the specified ref_cache, creating it
1122 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1124 char *packed_refs_file;
1127 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1129 packed_refs_file = git_pathdup("packed-refs");
1132 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1133 clear_packed_ref_cache(refs);
1135 if (!refs->packed) {
1138 refs->packed = xcalloc(1, sizeof(*refs->packed));
1139 acquire_packed_ref_cache(refs->packed);
1140 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1141 f = fopen(packed_refs_file, "r");
1143 stat_validity_update(&refs->packed->validity, fileno(f));
1144 read_packed_refs(f, get_ref_dir(refs->packed->root));
1148 free(packed_refs_file);
1149 return refs->packed;
1152 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1154 return get_ref_dir(packed_ref_cache->root);
1157 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1159 return get_packed_ref_dir(get_packed_ref_cache(refs));
1163 * Add a reference to the in-memory packed reference cache. This may
1164 * only be called while the packed-refs file is locked (see
1165 * lock_packed_refs()). To actually write the packed-refs file, call
1166 * commit_packed_refs().
1168 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1170 struct packed_ref_cache *packed_ref_cache =
1171 get_packed_ref_cache(&ref_cache);
1173 if (!packed_ref_cache->lock)
1174 die("internal error: packed refs not locked");
1175 add_ref(get_packed_ref_dir(packed_ref_cache),
1176 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1180 * Read the loose references from the namespace dirname into dir
1181 * (without recursing). dirname must end with '/'. dir must be the
1182 * directory entry corresponding to dirname.
1184 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1186 struct ref_cache *refs = dir->ref_cache;
1189 int dirnamelen = strlen(dirname);
1190 struct strbuf refname;
1191 struct strbuf path = STRBUF_INIT;
1192 size_t path_baselen;
1195 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1197 strbuf_git_path(&path, "%s", dirname);
1198 path_baselen = path.len;
1200 d = opendir(path.buf);
1202 strbuf_release(&path);
1206 strbuf_init(&refname, dirnamelen + 257);
1207 strbuf_add(&refname, dirname, dirnamelen);
1209 while ((de = readdir(d)) != NULL) {
1210 unsigned char sha1[20];
1214 if (de->d_name[0] == '.')
1216 if (ends_with(de->d_name, ".lock"))
1218 strbuf_addstr(&refname, de->d_name);
1219 strbuf_addstr(&path, de->d_name);
1220 if (stat(path.buf, &st) < 0) {
1221 ; /* silently ignore */
1222 } else if (S_ISDIR(st.st_mode)) {
1223 strbuf_addch(&refname, '/');
1224 add_entry_to_dir(dir,
1225 create_dir_entry(refs, refname.buf,
1233 read_ok = !resolve_gitlink_ref(refs->name,
1236 read_ok = !read_ref_full(refname.buf,
1237 RESOLVE_REF_READING,
1243 flag |= REF_ISBROKEN;
1244 } else if (is_null_sha1(sha1)) {
1246 * It is so astronomically unlikely
1247 * that NULL_SHA1 is the SHA-1 of an
1248 * actual object that we consider its
1249 * appearance in a loose reference
1250 * file to be repo corruption
1251 * (probably due to a software bug).
1253 flag |= REF_ISBROKEN;
1256 if (check_refname_format(refname.buf,
1257 REFNAME_ALLOW_ONELEVEL)) {
1258 if (!refname_is_safe(refname.buf))
1259 die("loose refname is dangerous: %s", refname.buf);
1261 flag |= REF_BAD_NAME | REF_ISBROKEN;
1263 add_entry_to_dir(dir,
1264 create_ref_entry(refname.buf, sha1, flag, 0));
1266 strbuf_setlen(&refname, dirnamelen);
1267 strbuf_setlen(&path, path_baselen);
1269 strbuf_release(&refname);
1270 strbuf_release(&path);
1274 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1278 * Mark the top-level directory complete because we
1279 * are about to read the only subdirectory that can
1282 refs->loose = create_dir_entry(refs, "", 0, 0);
1284 * Create an incomplete entry for "refs/":
1286 add_entry_to_dir(get_ref_dir(refs->loose),
1287 create_dir_entry(refs, "refs/", 5, 1));
1289 return get_ref_dir(refs->loose);
1292 /* We allow "recursive" symbolic refs. Only within reason, though */
1294 #define MAXREFLEN (1024)
1297 * Called by resolve_gitlink_ref_recursive() after it failed to read
1298 * from the loose refs in ref_cache refs. Find <refname> in the
1299 * packed-refs file for the submodule.
1301 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1302 const char *refname, unsigned char *sha1)
1304 struct ref_entry *ref;
1305 struct ref_dir *dir = get_packed_refs(refs);
1307 ref = find_ref(dir, refname);
1311 hashcpy(sha1, ref->u.value.oid.hash);
1315 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1316 const char *refname, unsigned char *sha1,
1320 char buffer[128], *p;
1323 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1326 ? git_pathdup_submodule(refs->name, "%s", refname)
1327 : git_pathdup("%s", refname);
1328 fd = open(path, O_RDONLY);
1331 return resolve_gitlink_packed_ref(refs, refname, sha1);
1333 len = read(fd, buffer, sizeof(buffer)-1);
1337 while (len && isspace(buffer[len-1]))
1341 /* Was it a detached head or an old-fashioned symlink? */
1342 if (!get_sha1_hex(buffer, sha1))
1346 if (strncmp(buffer, "ref:", 4))
1352 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1355 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1357 int len = strlen(path), retval;
1359 struct ref_cache *refs;
1361 while (len && path[len-1] == '/')
1365 submodule = xstrndup(path, len);
1366 refs = get_ref_cache(submodule);
1369 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1374 * Return the ref_entry for the given refname from the packed
1375 * references. If it does not exist, return NULL.
1377 static struct ref_entry *get_packed_ref(const char *refname)
1379 return find_ref(get_packed_refs(&ref_cache), refname);
1383 * A loose ref file doesn't exist; check for a packed ref. The
1384 * options are forwarded from resolve_safe_unsafe().
1386 static int resolve_missing_loose_ref(const char *refname,
1388 unsigned char *sha1,
1391 struct ref_entry *entry;
1394 * The loose reference file does not exist; check for a packed
1397 entry = get_packed_ref(refname);
1399 hashcpy(sha1, entry->u.value.oid.hash);
1401 *flags |= REF_ISPACKED;
1404 /* The reference is not a packed reference, either. */
1405 if (resolve_flags & RESOLVE_REF_READING) {
1414 /* This function needs to return a meaningful errno on failure */
1415 static const char *resolve_ref_1(const char *refname,
1417 unsigned char *sha1,
1419 struct strbuf *sb_refname,
1420 struct strbuf *sb_path,
1421 struct strbuf *sb_contents)
1423 int depth = MAXDEPTH;
1429 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1431 *flags |= REF_BAD_NAME;
1433 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1434 !refname_is_safe(refname)) {
1439 * dwim_ref() uses REF_ISBROKEN to distinguish between
1440 * missing refs and refs that were present but invalid,
1441 * to complain about the latter to stderr.
1443 * We don't know whether the ref exists, so don't set
1459 strbuf_reset(sb_path);
1460 strbuf_git_path(sb_path, "%s", refname);
1461 path = sb_path->buf;
1464 * We might have to loop back here to avoid a race
1465 * condition: first we lstat() the file, then we try
1466 * to read it as a link or as a file. But if somebody
1467 * changes the type of the file (file <-> directory
1468 * <-> symlink) between the lstat() and reading, then
1469 * we don't want to report that as an error but rather
1470 * try again starting with the lstat().
1473 if (lstat(path, &st) < 0) {
1474 if (errno != ENOENT)
1476 if (resolve_missing_loose_ref(refname, resolve_flags,
1482 *flags |= REF_ISBROKEN;
1487 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1488 if (S_ISLNK(st.st_mode)) {
1489 strbuf_reset(sb_contents);
1490 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1491 if (errno == ENOENT || errno == EINVAL)
1492 /* inconsistent with lstat; retry */
1497 if (starts_with(sb_contents->buf, "refs/") &&
1498 !check_refname_format(sb_contents->buf, 0)) {
1499 strbuf_swap(sb_refname, sb_contents);
1500 refname = sb_refname->buf;
1502 *flags |= REF_ISSYMREF;
1503 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1511 /* Is it a directory? */
1512 if (S_ISDIR(st.st_mode)) {
1518 * Anything else, just open it and try to use it as
1521 fd = open(path, O_RDONLY);
1523 if (errno == ENOENT)
1524 /* inconsistent with lstat; retry */
1529 strbuf_reset(sb_contents);
1530 if (strbuf_read(sb_contents, fd, 256) < 0) {
1531 int save_errno = errno;
1537 strbuf_rtrim(sb_contents);
1540 * Is it a symbolic ref?
1542 if (!starts_with(sb_contents->buf, "ref:")) {
1544 * Please note that FETCH_HEAD has a second
1545 * line containing other data.
1547 if (get_sha1_hex(sb_contents->buf, sha1) ||
1548 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1550 *flags |= REF_ISBROKEN;
1557 *flags |= REF_ISBROKEN;
1562 *flags |= REF_ISSYMREF;
1563 buf = sb_contents->buf + 4;
1564 while (isspace(*buf))
1566 strbuf_reset(sb_refname);
1567 strbuf_addstr(sb_refname, buf);
1568 refname = sb_refname->buf;
1569 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1573 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1575 *flags |= REF_ISBROKEN;
1577 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1578 !refname_is_safe(buf)) {
1587 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1588 unsigned char *sha1, int *flags)
1590 static struct strbuf sb_refname = STRBUF_INIT;
1591 struct strbuf sb_contents = STRBUF_INIT;
1592 struct strbuf sb_path = STRBUF_INIT;
1595 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1596 &sb_refname, &sb_path, &sb_contents);
1597 strbuf_release(&sb_path);
1598 strbuf_release(&sb_contents);
1603 * Peel the entry (if possible) and return its new peel_status. If
1604 * repeel is true, re-peel the entry even if there is an old peeled
1605 * value that is already stored in it.
1607 * It is OK to call this function with a packed reference entry that
1608 * might be stale and might even refer to an object that has since
1609 * been garbage-collected. In such a case, if the entry has
1610 * REF_KNOWS_PEELED then leave the status unchanged and return
1611 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1613 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1615 enum peel_status status;
1617 if (entry->flag & REF_KNOWS_PEELED) {
1619 entry->flag &= ~REF_KNOWS_PEELED;
1620 oidclr(&entry->u.value.peeled);
1622 return is_null_oid(&entry->u.value.peeled) ?
1623 PEEL_NON_TAG : PEEL_PEELED;
1626 if (entry->flag & REF_ISBROKEN)
1628 if (entry->flag & REF_ISSYMREF)
1629 return PEEL_IS_SYMREF;
1631 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1632 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1633 entry->flag |= REF_KNOWS_PEELED;
1637 int peel_ref(const char *refname, unsigned char *sha1)
1640 unsigned char base[20];
1642 if (current_ref && (current_ref->name == refname
1643 || !strcmp(current_ref->name, refname))) {
1644 if (peel_entry(current_ref, 0))
1646 hashcpy(sha1, current_ref->u.value.peeled.hash);
1650 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1654 * If the reference is packed, read its ref_entry from the
1655 * cache in the hope that we already know its peeled value.
1656 * We only try this optimization on packed references because
1657 * (a) forcing the filling of the loose reference cache could
1658 * be expensive and (b) loose references anyway usually do not
1659 * have REF_KNOWS_PEELED.
1661 if (flag & REF_ISPACKED) {
1662 struct ref_entry *r = get_packed_ref(refname);
1664 if (peel_entry(r, 0))
1666 hashcpy(sha1, r->u.value.peeled.hash);
1671 return peel_object(base, sha1);
1675 * Call fn for each reference in the specified ref_cache, omitting
1676 * references not in the containing_dir of base. fn is called for all
1677 * references, including broken ones. If fn ever returns a non-zero
1678 * value, stop the iteration and return that value; otherwise, return
1681 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1682 each_ref_entry_fn fn, void *cb_data)
1684 struct packed_ref_cache *packed_ref_cache;
1685 struct ref_dir *loose_dir;
1686 struct ref_dir *packed_dir;
1690 * We must make sure that all loose refs are read before accessing the
1691 * packed-refs file; this avoids a race condition in which loose refs
1692 * are migrated to the packed-refs file by a simultaneous process, but
1693 * our in-memory view is from before the migration. get_packed_ref_cache()
1694 * takes care of making sure our view is up to date with what is on
1697 loose_dir = get_loose_refs(refs);
1698 if (base && *base) {
1699 loose_dir = find_containing_dir(loose_dir, base, 0);
1702 prime_ref_dir(loose_dir);
1704 packed_ref_cache = get_packed_ref_cache(refs);
1705 acquire_packed_ref_cache(packed_ref_cache);
1706 packed_dir = get_packed_ref_dir(packed_ref_cache);
1707 if (base && *base) {
1708 packed_dir = find_containing_dir(packed_dir, base, 0);
1711 if (packed_dir && loose_dir) {
1712 sort_ref_dir(packed_dir);
1713 sort_ref_dir(loose_dir);
1714 retval = do_for_each_entry_in_dirs(
1715 packed_dir, loose_dir, fn, cb_data);
1716 } else if (packed_dir) {
1717 sort_ref_dir(packed_dir);
1718 retval = do_for_each_entry_in_dir(
1719 packed_dir, 0, fn, cb_data);
1720 } else if (loose_dir) {
1721 sort_ref_dir(loose_dir);
1722 retval = do_for_each_entry_in_dir(
1723 loose_dir, 0, fn, cb_data);
1726 release_packed_ref_cache(packed_ref_cache);
1731 * Call fn for each reference in the specified ref_cache for which the
1732 * refname begins with base. If trim is non-zero, then trim that many
1733 * characters off the beginning of each refname before passing the
1734 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1735 * broken references in the iteration. If fn ever returns a non-zero
1736 * value, stop the iteration and return that value; otherwise, return
1739 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1740 each_ref_fn fn, int trim, int flags, void *cb_data)
1742 struct ref_entry_cb data;
1747 data.cb_data = cb_data;
1749 if (ref_paranoia < 0)
1750 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1752 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1754 return do_for_each_entry(refs, base, do_one_ref, &data);
1757 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1759 struct object_id oid;
1763 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1764 return fn("HEAD", &oid, 0, cb_data);
1769 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1770 return fn("HEAD", &oid, flag, cb_data);
1775 int head_ref(each_ref_fn fn, void *cb_data)
1777 return do_head_ref(NULL, fn, cb_data);
1780 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1782 return do_head_ref(submodule, fn, cb_data);
1785 int for_each_ref(each_ref_fn fn, void *cb_data)
1787 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1790 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1792 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1795 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1797 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1800 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1802 unsigned int flag = 0;
1805 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1806 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
1809 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1810 each_ref_fn fn, void *cb_data)
1812 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1815 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1817 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
1818 strlen(git_replace_ref_base), 0, cb_data);
1821 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1823 struct strbuf buf = STRBUF_INIT;
1825 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1826 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1827 strbuf_release(&buf);
1831 int for_each_rawref(each_ref_fn fn, void *cb_data)
1833 return do_for_each_ref(&ref_cache, "", fn, 0,
1834 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1837 static void unlock_ref(struct ref_lock *lock)
1839 /* Do not free lock->lk -- atexit() still looks at them */
1841 rollback_lock_file(lock->lk);
1842 free(lock->ref_name);
1843 free(lock->orig_ref_name);
1848 * Verify that the reference locked by lock has the value old_sha1.
1849 * Fail if the reference doesn't exist and mustexist is set. Return 0
1850 * on success. On error, write an error message to err, set errno, and
1851 * return a negative value.
1853 static int verify_lock(struct ref_lock *lock,
1854 const unsigned char *old_sha1, int mustexist,
1859 if (read_ref_full(lock->ref_name,
1860 mustexist ? RESOLVE_REF_READING : 0,
1861 lock->old_oid.hash, NULL)) {
1862 int save_errno = errno;
1863 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
1867 if (hashcmp(lock->old_oid.hash, old_sha1)) {
1868 strbuf_addf(err, "ref %s is at %s but expected %s",
1870 sha1_to_hex(lock->old_oid.hash),
1871 sha1_to_hex(old_sha1));
1878 static int remove_empty_directories(struct strbuf *path)
1881 * we want to create a file but there is a directory there;
1882 * if that is an empty directory (or a directory that contains
1883 * only empty directories), remove them.
1885 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1889 * Locks a ref returning the lock on success and NULL on failure.
1890 * On failure errno is set to something meaningful.
1892 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1893 const unsigned char *old_sha1,
1894 const struct string_list *extras,
1895 const struct string_list *skip,
1896 unsigned int flags, int *type_p,
1899 struct strbuf ref_file = STRBUF_INIT;
1900 struct strbuf orig_ref_file = STRBUF_INIT;
1901 const char *orig_refname = refname;
1902 struct ref_lock *lock;
1905 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1906 int resolve_flags = 0;
1907 int attempts_remaining = 3;
1911 lock = xcalloc(1, sizeof(struct ref_lock));
1914 resolve_flags |= RESOLVE_REF_READING;
1915 if (flags & REF_DELETING) {
1916 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1917 if (flags & REF_NODEREF)
1918 resolve_flags |= RESOLVE_REF_NO_RECURSE;
1921 refname = resolve_ref_unsafe(refname, resolve_flags,
1922 lock->old_oid.hash, &type);
1923 if (!refname && errno == EISDIR) {
1925 * we are trying to lock foo but we used to
1926 * have foo/bar which now does not exist;
1927 * it is normal for the empty directory 'foo'
1930 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
1931 if (remove_empty_directories(&orig_ref_file)) {
1933 if (!verify_refname_available_dir(orig_refname, extras, skip,
1934 get_loose_refs(&ref_cache), err))
1935 strbuf_addf(err, "there are still refs under '%s'",
1939 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
1940 lock->old_oid.hash, &type);
1946 if (last_errno != ENOTDIR ||
1947 !verify_refname_available_dir(orig_refname, extras, skip,
1948 get_loose_refs(&ref_cache), err))
1949 strbuf_addf(err, "unable to resolve reference %s: %s",
1950 orig_refname, strerror(last_errno));
1955 * If the ref did not exist and we are creating it, make sure
1956 * there is no existing packed ref whose name begins with our
1957 * refname, nor a packed ref whose name is a proper prefix of
1960 if (is_null_oid(&lock->old_oid) &&
1961 verify_refname_available_dir(refname, extras, skip,
1962 get_packed_refs(&ref_cache), err)) {
1963 last_errno = ENOTDIR;
1967 lock->lk = xcalloc(1, sizeof(struct lock_file));
1970 if (flags & REF_NODEREF) {
1971 refname = orig_refname;
1972 lflags |= LOCK_NO_DEREF;
1974 lock->ref_name = xstrdup(refname);
1975 lock->orig_ref_name = xstrdup(orig_refname);
1976 strbuf_git_path(&ref_file, "%s", refname);
1979 switch (safe_create_leading_directories_const(ref_file.buf)) {
1981 break; /* success */
1983 if (--attempts_remaining > 0)
1988 strbuf_addf(err, "unable to create directory for %s",
1993 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
1995 if (errno == ENOENT && --attempts_remaining > 0)
1997 * Maybe somebody just deleted one of the
1998 * directories leading to ref_file. Try
2003 unable_to_lock_message(ref_file.buf, errno, err);
2007 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2018 strbuf_release(&ref_file);
2019 strbuf_release(&orig_ref_file);
2025 * Write an entry to the packed-refs file for the specified refname.
2026 * If peeled is non-NULL, write it as the entry's peeled value.
2028 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2029 unsigned char *peeled)
2031 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2033 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2037 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2039 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2041 enum peel_status peel_status = peel_entry(entry, 0);
2043 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2044 error("internal error: %s is not a valid packed reference!",
2046 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2047 peel_status == PEEL_PEELED ?
2048 entry->u.value.peeled.hash : NULL);
2053 * Lock the packed-refs file for writing. Flags is passed to
2054 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2055 * errno appropriately and return a nonzero value.
2057 static int lock_packed_refs(int flags)
2059 static int timeout_configured = 0;
2060 static int timeout_value = 1000;
2062 struct packed_ref_cache *packed_ref_cache;
2064 if (!timeout_configured) {
2065 git_config_get_int("core.packedrefstimeout", &timeout_value);
2066 timeout_configured = 1;
2069 if (hold_lock_file_for_update_timeout(
2070 &packlock, git_path("packed-refs"),
2071 flags, timeout_value) < 0)
2074 * Get the current packed-refs while holding the lock. If the
2075 * packed-refs file has been modified since we last read it,
2076 * this will automatically invalidate the cache and re-read
2077 * the packed-refs file.
2079 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2080 packed_ref_cache->lock = &packlock;
2081 /* Increment the reference count to prevent it from being freed: */
2082 acquire_packed_ref_cache(packed_ref_cache);
2087 * Write the current version of the packed refs cache from memory to
2088 * disk. The packed-refs file must already be locked for writing (see
2089 * lock_packed_refs()). Return zero on success. On errors, set errno
2090 * and return a nonzero value
2092 static int commit_packed_refs(void)
2094 struct packed_ref_cache *packed_ref_cache =
2095 get_packed_ref_cache(&ref_cache);
2100 if (!packed_ref_cache->lock)
2101 die("internal error: packed-refs not locked");
2103 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2105 die_errno("unable to fdopen packed-refs descriptor");
2107 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2108 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2109 0, write_packed_entry_fn, out);
2111 if (commit_lock_file(packed_ref_cache->lock)) {
2115 packed_ref_cache->lock = NULL;
2116 release_packed_ref_cache(packed_ref_cache);
2122 * Rollback the lockfile for the packed-refs file, and discard the
2123 * in-memory packed reference cache. (The packed-refs file will be
2124 * read anew if it is needed again after this function is called.)
2126 static void rollback_packed_refs(void)
2128 struct packed_ref_cache *packed_ref_cache =
2129 get_packed_ref_cache(&ref_cache);
2131 if (!packed_ref_cache->lock)
2132 die("internal error: packed-refs not locked");
2133 rollback_lock_file(packed_ref_cache->lock);
2134 packed_ref_cache->lock = NULL;
2135 release_packed_ref_cache(packed_ref_cache);
2136 clear_packed_ref_cache(&ref_cache);
2139 struct ref_to_prune {
2140 struct ref_to_prune *next;
2141 unsigned char sha1[20];
2142 char name[FLEX_ARRAY];
2145 struct pack_refs_cb_data {
2147 struct ref_dir *packed_refs;
2148 struct ref_to_prune *ref_to_prune;
2152 * An each_ref_entry_fn that is run over loose references only. If
2153 * the loose reference can be packed, add an entry in the packed ref
2154 * cache. If the reference should be pruned, also add it to
2155 * ref_to_prune in the pack_refs_cb_data.
2157 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2159 struct pack_refs_cb_data *cb = cb_data;
2160 enum peel_status peel_status;
2161 struct ref_entry *packed_entry;
2162 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2164 /* Do not pack per-worktree refs: */
2165 if (ref_type(entry->name) != REF_TYPE_NORMAL)
2168 /* ALWAYS pack tags */
2169 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2172 /* Do not pack symbolic or broken refs: */
2173 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2176 /* Add a packed ref cache entry equivalent to the loose entry. */
2177 peel_status = peel_entry(entry, 1);
2178 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2179 die("internal error peeling reference %s (%s)",
2180 entry->name, oid_to_hex(&entry->u.value.oid));
2181 packed_entry = find_ref(cb->packed_refs, entry->name);
2183 /* Overwrite existing packed entry with info from loose entry */
2184 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2185 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2187 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2188 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2189 add_ref(cb->packed_refs, packed_entry);
2191 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2193 /* Schedule the loose reference for pruning if requested. */
2194 if ((cb->flags & PACK_REFS_PRUNE)) {
2195 int namelen = strlen(entry->name) + 1;
2196 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2197 hashcpy(n->sha1, entry->u.value.oid.hash);
2198 memcpy(n->name, entry->name, namelen); /* includes NUL */
2199 n->next = cb->ref_to_prune;
2200 cb->ref_to_prune = n;
2206 * Remove empty parents, but spare refs/ and immediate subdirs.
2207 * Note: munges *name.
2209 static void try_remove_empty_parents(char *name)
2214 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2215 while (*p && *p != '/')
2217 /* tolerate duplicate slashes; see check_refname_format() */
2221 for (q = p; *q; q++)
2224 while (q > p && *q != '/')
2226 while (q > p && *(q-1) == '/')
2231 if (rmdir(git_path("%s", name)))
2236 /* make sure nobody touched the ref, and unlink */
2237 static void prune_ref(struct ref_to_prune *r)
2239 struct ref_transaction *transaction;
2240 struct strbuf err = STRBUF_INIT;
2242 if (check_refname_format(r->name, 0))
2245 transaction = ref_transaction_begin(&err);
2247 ref_transaction_delete(transaction, r->name, r->sha1,
2248 REF_ISPRUNING, NULL, &err) ||
2249 ref_transaction_commit(transaction, &err)) {
2250 ref_transaction_free(transaction);
2251 error("%s", err.buf);
2252 strbuf_release(&err);
2255 ref_transaction_free(transaction);
2256 strbuf_release(&err);
2257 try_remove_empty_parents(r->name);
2260 static void prune_refs(struct ref_to_prune *r)
2268 int pack_refs(unsigned int flags)
2270 struct pack_refs_cb_data cbdata;
2272 memset(&cbdata, 0, sizeof(cbdata));
2273 cbdata.flags = flags;
2275 lock_packed_refs(LOCK_DIE_ON_ERROR);
2276 cbdata.packed_refs = get_packed_refs(&ref_cache);
2278 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2279 pack_if_possible_fn, &cbdata);
2281 if (commit_packed_refs())
2282 die_errno("unable to overwrite old ref-pack file");
2284 prune_refs(cbdata.ref_to_prune);
2289 * Rewrite the packed-refs file, omitting any refs listed in
2290 * 'refnames'. On error, leave packed-refs unchanged, write an error
2291 * message to 'err', and return a nonzero value.
2293 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2295 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2297 struct ref_dir *packed;
2298 struct string_list_item *refname;
2299 int ret, needs_repacking = 0, removed = 0;
2303 /* Look for a packed ref */
2304 for_each_string_list_item(refname, refnames) {
2305 if (get_packed_ref(refname->string)) {
2306 needs_repacking = 1;
2311 /* Avoid locking if we have nothing to do */
2312 if (!needs_repacking)
2313 return 0; /* no refname exists in packed refs */
2315 if (lock_packed_refs(0)) {
2316 unable_to_lock_message(git_path("packed-refs"), errno, err);
2319 packed = get_packed_refs(&ref_cache);
2321 /* Remove refnames from the cache */
2322 for_each_string_list_item(refname, refnames)
2323 if (remove_entry(packed, refname->string) != -1)
2327 * All packed entries disappeared while we were
2328 * acquiring the lock.
2330 rollback_packed_refs();
2334 /* Write what remains */
2335 ret = commit_packed_refs();
2337 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2342 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2346 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2348 * loose. The loose file name is the same as the
2349 * lockfile name, minus ".lock":
2351 char *loose_filename = get_locked_file_path(lock->lk);
2352 int res = unlink_or_msg(loose_filename, err);
2353 free(loose_filename);
2360 int delete_refs(struct string_list *refnames)
2362 struct strbuf err = STRBUF_INIT;
2368 result = repack_without_refs(refnames, &err);
2371 * If we failed to rewrite the packed-refs file, then
2372 * it is unsafe to try to remove loose refs, because
2373 * doing so might expose an obsolete packed value for
2374 * a reference that might even point at an object that
2375 * has been garbage collected.
2377 if (refnames->nr == 1)
2378 error(_("could not delete reference %s: %s"),
2379 refnames->items[0].string, err.buf);
2381 error(_("could not delete references: %s"), err.buf);
2386 for (i = 0; i < refnames->nr; i++) {
2387 const char *refname = refnames->items[i].string;
2389 if (delete_ref(refname, NULL, 0))
2390 result |= error(_("could not remove reference %s"), refname);
2394 strbuf_release(&err);
2399 * People using contrib's git-new-workdir have .git/logs/refs ->
2400 * /some/other/path/.git/logs/refs, and that may live on another device.
2402 * IOW, to avoid cross device rename errors, the temporary renamed log must
2403 * live into logs/refs.
2405 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2407 static int rename_tmp_log(const char *newrefname)
2409 int attempts_remaining = 4;
2410 struct strbuf path = STRBUF_INIT;
2414 strbuf_reset(&path);
2415 strbuf_git_path(&path, "logs/%s", newrefname);
2416 switch (safe_create_leading_directories_const(path.buf)) {
2418 break; /* success */
2420 if (--attempts_remaining > 0)
2424 error("unable to create directory for %s", newrefname);
2428 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2429 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2431 * rename(a, b) when b is an existing
2432 * directory ought to result in ISDIR, but
2433 * Solaris 5.8 gives ENOTDIR. Sheesh.
2435 if (remove_empty_directories(&path)) {
2436 error("Directory not empty: logs/%s", newrefname);
2440 } else if (errno == ENOENT && --attempts_remaining > 0) {
2442 * Maybe another process just deleted one of
2443 * the directories in the path to newrefname.
2444 * Try again from the beginning.
2448 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2449 newrefname, strerror(errno));
2455 strbuf_release(&path);
2459 int verify_refname_available(const char *newname,
2460 struct string_list *extras,
2461 struct string_list *skip,
2464 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
2465 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
2467 if (verify_refname_available_dir(newname, extras, skip,
2468 packed_refs, err) ||
2469 verify_refname_available_dir(newname, extras, skip,
2476 static int rename_ref_available(const char *oldname, const char *newname)
2478 struct string_list skip = STRING_LIST_INIT_NODUP;
2479 struct strbuf err = STRBUF_INIT;
2482 string_list_insert(&skip, oldname);
2483 ret = !verify_refname_available(newname, NULL, &skip, &err);
2485 error("%s", err.buf);
2487 string_list_clear(&skip, 0);
2488 strbuf_release(&err);
2492 static int write_ref_to_lockfile(struct ref_lock *lock,
2493 const unsigned char *sha1, struct strbuf *err);
2494 static int commit_ref_update(struct ref_lock *lock,
2495 const unsigned char *sha1, const char *logmsg,
2496 int flags, struct strbuf *err);
2498 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2500 unsigned char sha1[20], orig_sha1[20];
2501 int flag = 0, logmoved = 0;
2502 struct ref_lock *lock;
2503 struct stat loginfo;
2504 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2505 const char *symref = NULL;
2506 struct strbuf err = STRBUF_INIT;
2508 if (log && S_ISLNK(loginfo.st_mode))
2509 return error("reflog for %s is a symlink", oldrefname);
2511 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2513 if (flag & REF_ISSYMREF)
2514 return error("refname %s is a symbolic ref, renaming it is not supported",
2517 return error("refname %s not found", oldrefname);
2519 if (!rename_ref_available(oldrefname, newrefname))
2522 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2523 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2524 oldrefname, strerror(errno));
2526 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2527 error("unable to delete old %s", oldrefname);
2531 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2532 delete_ref(newrefname, sha1, REF_NODEREF)) {
2533 if (errno==EISDIR) {
2534 struct strbuf path = STRBUF_INIT;
2537 strbuf_git_path(&path, "%s", newrefname);
2538 result = remove_empty_directories(&path);
2539 strbuf_release(&path);
2542 error("Directory not empty: %s", newrefname);
2546 error("unable to delete existing %s", newrefname);
2551 if (log && rename_tmp_log(newrefname))
2556 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2558 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2559 strbuf_release(&err);
2562 hashcpy(lock->old_oid.hash, orig_sha1);
2564 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2565 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
2566 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2567 strbuf_release(&err);
2574 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2576 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2577 strbuf_release(&err);
2581 flag = log_all_ref_updates;
2582 log_all_ref_updates = 0;
2583 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2584 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
2585 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2586 strbuf_release(&err);
2588 log_all_ref_updates = flag;
2591 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2592 error("unable to restore logfile %s from %s: %s",
2593 oldrefname, newrefname, strerror(errno));
2594 if (!logmoved && log &&
2595 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2596 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2597 oldrefname, strerror(errno));
2602 static int close_ref(struct ref_lock *lock)
2604 if (close_lock_file(lock->lk))
2609 static int commit_ref(struct ref_lock *lock)
2611 if (commit_lock_file(lock->lk))
2617 * Create a reflog for a ref. If force_create = 0, the reflog will
2618 * only be created for certain refs (those for which
2619 * should_autocreate_reflog returns non-zero. Otherwise, create it
2620 * regardless of the ref name. Fill in *err and return -1 on failure.
2622 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2624 int logfd, oflags = O_APPEND | O_WRONLY;
2626 strbuf_git_path(logfile, "logs/%s", refname);
2627 if (force_create || should_autocreate_reflog(refname)) {
2628 if (safe_create_leading_directories(logfile->buf) < 0) {
2629 strbuf_addf(err, "unable to create directory for %s: "
2630 "%s", logfile->buf, strerror(errno));
2636 logfd = open(logfile->buf, oflags, 0666);
2638 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2641 if (errno == EISDIR) {
2642 if (remove_empty_directories(logfile)) {
2643 strbuf_addf(err, "There are still logs under "
2644 "'%s'", logfile->buf);
2647 logfd = open(logfile->buf, oflags, 0666);
2651 strbuf_addf(err, "unable to append to %s: %s",
2652 logfile->buf, strerror(errno));
2657 adjust_shared_perm(logfile->buf);
2663 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2666 struct strbuf sb = STRBUF_INIT;
2668 ret = log_ref_setup(refname, &sb, err, force_create);
2669 strbuf_release(&sb);
2673 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2674 const unsigned char *new_sha1,
2675 const char *committer, const char *msg)
2677 int msglen, written;
2678 unsigned maxlen, len;
2681 msglen = msg ? strlen(msg) : 0;
2682 maxlen = strlen(committer) + msglen + 100;
2683 logrec = xmalloc(maxlen);
2684 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2685 sha1_to_hex(old_sha1),
2686 sha1_to_hex(new_sha1),
2689 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2691 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2699 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2700 const unsigned char *new_sha1, const char *msg,
2701 struct strbuf *logfile, int flags,
2704 int logfd, result, oflags = O_APPEND | O_WRONLY;
2706 if (log_all_ref_updates < 0)
2707 log_all_ref_updates = !is_bare_repository();
2709 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2714 logfd = open(logfile->buf, oflags);
2717 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2718 git_committer_info(0), msg);
2720 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2726 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
2733 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2734 const unsigned char *new_sha1, const char *msg,
2735 int flags, struct strbuf *err)
2737 return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2741 int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2742 const unsigned char *new_sha1, const char *msg,
2743 int flags, struct strbuf *err)
2745 struct strbuf sb = STRBUF_INIT;
2746 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2748 strbuf_release(&sb);
2753 * Write sha1 into the open lockfile, then close the lockfile. On
2754 * errors, rollback the lockfile, fill in *err and
2757 static int write_ref_to_lockfile(struct ref_lock *lock,
2758 const unsigned char *sha1, struct strbuf *err)
2760 static char term = '\n';
2764 o = parse_object(sha1);
2767 "Trying to write ref %s with nonexistent object %s",
2768 lock->ref_name, sha1_to_hex(sha1));
2772 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2774 "Trying to write non-commit object %s to branch %s",
2775 sha1_to_hex(sha1), lock->ref_name);
2779 fd = get_lock_file_fd(lock->lk);
2780 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2781 write_in_full(fd, &term, 1) != 1 ||
2782 close_ref(lock) < 0) {
2784 "Couldn't write %s", get_lock_file_path(lock->lk));
2792 * Commit a change to a loose reference that has already been written
2793 * to the loose reference lockfile. Also update the reflogs if
2794 * necessary, using the specified lockmsg (which can be NULL).
2796 static int commit_ref_update(struct ref_lock *lock,
2797 const unsigned char *sha1, const char *logmsg,
2798 int flags, struct strbuf *err)
2800 clear_loose_ref_cache(&ref_cache);
2801 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
2802 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2803 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
2804 char *old_msg = strbuf_detach(err, NULL);
2805 strbuf_addf(err, "Cannot update the ref '%s': %s",
2806 lock->ref_name, old_msg);
2811 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2813 * Special hack: If a branch is updated directly and HEAD
2814 * points to it (may happen on the remote side of a push
2815 * for example) then logically the HEAD reflog should be
2817 * A generic solution implies reverse symref information,
2818 * but finding all symrefs pointing to the given branch
2819 * would be rather costly for this rare event (the direct
2820 * update of a branch) to be worth it. So let's cheat and
2821 * check with HEAD only which should cover 99% of all usage
2822 * scenarios (even 100% of the default ones).
2824 unsigned char head_sha1[20];
2826 const char *head_ref;
2827 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2828 head_sha1, &head_flag);
2829 if (head_ref && (head_flag & REF_ISSYMREF) &&
2830 !strcmp(head_ref, lock->ref_name)) {
2831 struct strbuf log_err = STRBUF_INIT;
2832 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2833 logmsg, 0, &log_err)) {
2834 error("%s", log_err.buf);
2835 strbuf_release(&log_err);
2839 if (commit_ref(lock)) {
2840 error("Couldn't set %s", lock->ref_name);
2849 int create_symref(const char *ref_target, const char *refs_heads_master,
2852 char *lockpath = NULL;
2854 int fd, len, written;
2855 char *git_HEAD = git_pathdup("%s", ref_target);
2856 unsigned char old_sha1[20], new_sha1[20];
2857 struct strbuf err = STRBUF_INIT;
2859 if (logmsg && read_ref(ref_target, old_sha1))
2862 if (safe_create_leading_directories(git_HEAD) < 0)
2863 return error("unable to create directory for %s", git_HEAD);
2865 #ifndef NO_SYMLINK_HEAD
2866 if (prefer_symlink_refs) {
2868 if (!symlink(refs_heads_master, git_HEAD))
2870 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2874 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2875 if (sizeof(ref) <= len) {
2876 error("refname too long: %s", refs_heads_master);
2877 goto error_free_return;
2879 lockpath = mkpathdup("%s.lock", git_HEAD);
2880 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2882 error("Unable to open %s for writing", lockpath);
2883 goto error_free_return;
2885 written = write_in_full(fd, ref, len);
2886 if (close(fd) != 0 || written != len) {
2887 error("Unable to write to %s", lockpath);
2888 goto error_unlink_return;
2890 if (rename(lockpath, git_HEAD) < 0) {
2891 error("Unable to create %s", git_HEAD);
2892 goto error_unlink_return;
2894 if (adjust_shared_perm(git_HEAD)) {
2895 error("Unable to fix permissions on %s", lockpath);
2896 error_unlink_return:
2897 unlink_or_warn(lockpath);
2905 #ifndef NO_SYMLINK_HEAD
2908 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
2909 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
2910 error("%s", err.buf);
2911 strbuf_release(&err);
2918 int reflog_exists(const char *refname)
2922 return !lstat(git_path("logs/%s", refname), &st) &&
2923 S_ISREG(st.st_mode);
2926 int delete_reflog(const char *refname)
2928 return remove_path(git_path("logs/%s", refname));
2931 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2933 unsigned char osha1[20], nsha1[20];
2934 char *email_end, *message;
2935 unsigned long timestamp;
2938 /* old SP new SP name <email> SP time TAB msg LF */
2939 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2940 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2941 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2942 !(email_end = strchr(sb->buf + 82, '>')) ||
2943 email_end[1] != ' ' ||
2944 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2945 !message || message[0] != ' ' ||
2946 (message[1] != '+' && message[1] != '-') ||
2947 !isdigit(message[2]) || !isdigit(message[3]) ||
2948 !isdigit(message[4]) || !isdigit(message[5]))
2949 return 0; /* corrupt? */
2950 email_end[1] = '\0';
2951 tz = strtol(message + 1, NULL, 10);
2952 if (message[6] != '\t')
2956 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
2959 static char *find_beginning_of_line(char *bob, char *scan)
2961 while (bob < scan && *(--scan) != '\n')
2962 ; /* keep scanning backwards */
2964 * Return either beginning of the buffer, or LF at the end of
2965 * the previous line.
2970 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2972 struct strbuf sb = STRBUF_INIT;
2975 int ret = 0, at_tail = 1;
2977 logfp = fopen(git_path("logs/%s", refname), "r");
2981 /* Jump to the end */
2982 if (fseek(logfp, 0, SEEK_END) < 0)
2983 return error("cannot seek back reflog for %s: %s",
2984 refname, strerror(errno));
2986 while (!ret && 0 < pos) {
2992 /* Fill next block from the end */
2993 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2994 if (fseek(logfp, pos - cnt, SEEK_SET))
2995 return error("cannot seek back reflog for %s: %s",
2996 refname, strerror(errno));
2997 nread = fread(buf, cnt, 1, logfp);
2999 return error("cannot read %d bytes from reflog for %s: %s",
3000 cnt, refname, strerror(errno));
3003 scanp = endp = buf + cnt;
3004 if (at_tail && scanp[-1] == '\n')
3005 /* Looking at the final LF at the end of the file */
3009 while (buf < scanp) {
3011 * terminating LF of the previous line, or the beginning
3016 bp = find_beginning_of_line(buf, scanp);
3020 * The newline is the end of the previous line,
3021 * so we know we have complete line starting
3022 * at (bp + 1). Prefix it onto any prior data
3023 * we collected for the line and process it.
3025 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3028 ret = show_one_reflog_ent(&sb, fn, cb_data);
3034 * We are at the start of the buffer, and the
3035 * start of the file; there is no previous
3036 * line, and we have everything for this one.
3037 * Process it, and we can end the loop.
3039 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3040 ret = show_one_reflog_ent(&sb, fn, cb_data);
3047 * We are at the start of the buffer, and there
3048 * is more file to read backwards. Which means
3049 * we are in the middle of a line. Note that we
3050 * may get here even if *bp was a newline; that
3051 * just means we are at the exact end of the
3052 * previous line, rather than some spot in the
3055 * Save away what we have to be combined with
3056 * the data from the next read.
3058 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3065 die("BUG: reverse reflog parser had leftover data");
3068 strbuf_release(&sb);
3072 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3075 struct strbuf sb = STRBUF_INIT;
3078 logfp = fopen(git_path("logs/%s", refname), "r");
3082 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3083 ret = show_one_reflog_ent(&sb, fn, cb_data);
3085 strbuf_release(&sb);
3089 * Call fn for each reflog in the namespace indicated by name. name
3090 * must be empty or end with '/'. Name will be used as a scratch
3091 * space, but its contents will be restored before return.
3093 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3095 DIR *d = opendir(git_path("logs/%s", name->buf));
3098 int oldlen = name->len;
3101 return name->len ? errno : 0;
3103 while ((de = readdir(d)) != NULL) {
3106 if (de->d_name[0] == '.')
3108 if (ends_with(de->d_name, ".lock"))
3110 strbuf_addstr(name, de->d_name);
3111 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3112 ; /* silently ignore */
3114 if (S_ISDIR(st.st_mode)) {
3115 strbuf_addch(name, '/');
3116 retval = do_for_each_reflog(name, fn, cb_data);
3118 struct object_id oid;
3120 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3121 retval = error("bad ref for %s", name->buf);
3123 retval = fn(name->buf, &oid, 0, cb_data);
3128 strbuf_setlen(name, oldlen);
3134 int for_each_reflog(each_ref_fn fn, void *cb_data)
3138 strbuf_init(&name, PATH_MAX);
3139 retval = do_for_each_reflog(&name, fn, cb_data);
3140 strbuf_release(&name);
3144 static int ref_update_reject_duplicates(struct string_list *refnames,
3147 int i, n = refnames->nr;
3151 for (i = 1; i < n; i++)
3152 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3154 "Multiple updates for ref '%s' not allowed.",
3155 refnames->items[i].string);
3161 int ref_transaction_commit(struct ref_transaction *transaction,
3165 int n = transaction->nr;
3166 struct ref_update **updates = transaction->updates;
3167 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3168 struct string_list_item *ref_to_delete;
3169 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3173 if (transaction->state != REF_TRANSACTION_OPEN)
3174 die("BUG: commit called for transaction that is not open");
3177 transaction->state = REF_TRANSACTION_CLOSED;
3181 /* Fail if a refname appears more than once in the transaction: */
3182 for (i = 0; i < n; i++)
3183 string_list_append(&affected_refnames, updates[i]->refname);
3184 string_list_sort(&affected_refnames);
3185 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3186 ret = TRANSACTION_GENERIC_ERROR;
3191 * Acquire all locks, verify old values if provided, check
3192 * that new values are valid, and write new values to the
3193 * lockfiles, ready to be activated. Only keep one lockfile
3194 * open at a time to avoid running out of file descriptors.
3196 for (i = 0; i < n; i++) {
3197 struct ref_update *update = updates[i];
3199 if ((update->flags & REF_HAVE_NEW) &&
3200 is_null_sha1(update->new_sha1))
3201 update->flags |= REF_DELETING;
3202 update->lock = lock_ref_sha1_basic(
3204 ((update->flags & REF_HAVE_OLD) ?
3205 update->old_sha1 : NULL),
3206 &affected_refnames, NULL,
3210 if (!update->lock) {
3213 ret = (errno == ENOTDIR)
3214 ? TRANSACTION_NAME_CONFLICT
3215 : TRANSACTION_GENERIC_ERROR;
3216 reason = strbuf_detach(err, NULL);
3217 strbuf_addf(err, "cannot lock ref '%s': %s",
3218 update->refname, reason);
3222 if ((update->flags & REF_HAVE_NEW) &&
3223 !(update->flags & REF_DELETING)) {
3224 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3225 (update->flags & REF_NODEREF));
3227 if (!overwriting_symref &&
3228 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
3230 * The reference already has the desired
3231 * value, so we don't need to write it.
3233 } else if (write_ref_to_lockfile(update->lock,
3236 char *write_err = strbuf_detach(err, NULL);
3239 * The lock was freed upon failure of
3240 * write_ref_to_lockfile():
3242 update->lock = NULL;
3244 "cannot update the ref '%s': %s",
3245 update->refname, write_err);
3247 ret = TRANSACTION_GENERIC_ERROR;
3250 update->flags |= REF_NEEDS_COMMIT;
3253 if (!(update->flags & REF_NEEDS_COMMIT)) {
3255 * We didn't have to write anything to the lockfile.
3256 * Close it to free up the file descriptor:
3258 if (close_ref(update->lock)) {
3259 strbuf_addf(err, "Couldn't close %s.lock",
3266 /* Perform updates first so live commits remain referenced */
3267 for (i = 0; i < n; i++) {
3268 struct ref_update *update = updates[i];
3270 if (update->flags & REF_NEEDS_COMMIT) {
3271 if (commit_ref_update(update->lock,
3272 update->new_sha1, update->msg,
3273 update->flags, err)) {
3274 /* freed by commit_ref_update(): */
3275 update->lock = NULL;
3276 ret = TRANSACTION_GENERIC_ERROR;
3279 /* freed by commit_ref_update(): */
3280 update->lock = NULL;
3285 /* Perform deletes now that updates are safely completed */
3286 for (i = 0; i < n; i++) {
3287 struct ref_update *update = updates[i];
3289 if (update->flags & REF_DELETING) {
3290 if (delete_ref_loose(update->lock, update->type, err)) {
3291 ret = TRANSACTION_GENERIC_ERROR;
3295 if (!(update->flags & REF_ISPRUNING))
3296 string_list_append(&refs_to_delete,
3297 update->lock->ref_name);
3301 if (repack_without_refs(&refs_to_delete, err)) {
3302 ret = TRANSACTION_GENERIC_ERROR;
3305 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3306 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3307 clear_loose_ref_cache(&ref_cache);
3310 transaction->state = REF_TRANSACTION_CLOSED;
3312 for (i = 0; i < n; i++)
3313 if (updates[i]->lock)
3314 unlock_ref(updates[i]->lock);
3315 string_list_clear(&refs_to_delete, 0);
3316 string_list_clear(&affected_refnames, 0);
3320 static int ref_present(const char *refname,
3321 const struct object_id *oid, int flags, void *cb_data)
3323 struct string_list *affected_refnames = cb_data;
3325 return string_list_has_string(affected_refnames, refname);
3328 int initial_ref_transaction_commit(struct ref_transaction *transaction,
3332 int n = transaction->nr;
3333 struct ref_update **updates = transaction->updates;
3334 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3338 if (transaction->state != REF_TRANSACTION_OPEN)
3339 die("BUG: commit called for transaction that is not open");
3341 /* Fail if a refname appears more than once in the transaction: */
3342 for (i = 0; i < n; i++)
3343 string_list_append(&affected_refnames, updates[i]->refname);
3344 string_list_sort(&affected_refnames);
3345 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3346 ret = TRANSACTION_GENERIC_ERROR;
3351 * It's really undefined to call this function in an active
3352 * repository or when there are existing references: we are
3353 * only locking and changing packed-refs, so (1) any
3354 * simultaneous processes might try to change a reference at
3355 * the same time we do, and (2) any existing loose versions of
3356 * the references that we are setting would have precedence
3357 * over our values. But some remote helpers create the remote
3358 * "HEAD" and "master" branches before calling this function,
3359 * so here we really only check that none of the references
3360 * that we are creating already exists.
3362 if (for_each_rawref(ref_present, &affected_refnames))
3363 die("BUG: initial ref transaction called with existing refs");
3365 for (i = 0; i < n; i++) {
3366 struct ref_update *update = updates[i];
3368 if ((update->flags & REF_HAVE_OLD) &&
3369 !is_null_sha1(update->old_sha1))
3370 die("BUG: initial ref transaction with old_sha1 set");
3371 if (verify_refname_available(update->refname,
3372 &affected_refnames, NULL,
3374 ret = TRANSACTION_NAME_CONFLICT;
3379 if (lock_packed_refs(0)) {
3380 strbuf_addf(err, "unable to lock packed-refs file: %s",
3382 ret = TRANSACTION_GENERIC_ERROR;
3386 for (i = 0; i < n; i++) {
3387 struct ref_update *update = updates[i];
3389 if ((update->flags & REF_HAVE_NEW) &&
3390 !is_null_sha1(update->new_sha1))
3391 add_packed_ref(update->refname, update->new_sha1);
3394 if (commit_packed_refs()) {
3395 strbuf_addf(err, "unable to commit packed-refs file: %s",
3397 ret = TRANSACTION_GENERIC_ERROR;
3402 transaction->state = REF_TRANSACTION_CLOSED;
3403 string_list_clear(&affected_refnames, 0);
3407 struct expire_reflog_cb {
3409 reflog_expiry_should_prune_fn *should_prune_fn;
3412 unsigned char last_kept_sha1[20];
3415 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3416 const char *email, unsigned long timestamp, int tz,
3417 const char *message, void *cb_data)
3419 struct expire_reflog_cb *cb = cb_data;
3420 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3422 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3423 osha1 = cb->last_kept_sha1;
3425 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3426 message, policy_cb)) {
3428 printf("would prune %s", message);
3429 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3430 printf("prune %s", message);
3433 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3434 sha1_to_hex(osha1), sha1_to_hex(nsha1),
3435 email, timestamp, tz, message);
3436 hashcpy(cb->last_kept_sha1, nsha1);
3438 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3439 printf("keep %s", message);
3444 int reflog_expire(const char *refname, const unsigned char *sha1,
3446 reflog_expiry_prepare_fn prepare_fn,
3447 reflog_expiry_should_prune_fn should_prune_fn,
3448 reflog_expiry_cleanup_fn cleanup_fn,
3449 void *policy_cb_data)
3451 static struct lock_file reflog_lock;
3452 struct expire_reflog_cb cb;
3453 struct ref_lock *lock;
3457 struct strbuf err = STRBUF_INIT;
3459 memset(&cb, 0, sizeof(cb));
3461 cb.policy_cb = policy_cb_data;
3462 cb.should_prune_fn = should_prune_fn;
3465 * The reflog file is locked by holding the lock on the
3466 * reference itself, plus we might need to update the
3467 * reference if --updateref was specified:
3469 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
3471 error("cannot lock ref '%s': %s", refname, err.buf);
3472 strbuf_release(&err);
3475 if (!reflog_exists(refname)) {
3480 log_file = git_pathdup("logs/%s", refname);
3481 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3483 * Even though holding $GIT_DIR/logs/$reflog.lock has
3484 * no locking implications, we use the lock_file
3485 * machinery here anyway because it does a lot of the
3486 * work we need, including cleaning up if the program
3487 * exits unexpectedly.
3489 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3490 struct strbuf err = STRBUF_INIT;
3491 unable_to_lock_message(log_file, errno, &err);
3492 error("%s", err.buf);
3493 strbuf_release(&err);
3496 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3498 error("cannot fdopen %s (%s)",
3499 get_lock_file_path(&reflog_lock), strerror(errno));
3504 (*prepare_fn)(refname, sha1, cb.policy_cb);
3505 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3506 (*cleanup_fn)(cb.policy_cb);
3508 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3510 * It doesn't make sense to adjust a reference pointed
3511 * to by a symbolic ref based on expiring entries in
3512 * the symbolic reference's reflog. Nor can we update
3513 * a reference if there are no remaining reflog
3516 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3517 !(type & REF_ISSYMREF) &&
3518 !is_null_sha1(cb.last_kept_sha1);
3520 if (close_lock_file(&reflog_lock)) {
3521 status |= error("couldn't write %s: %s", log_file,
3523 } else if (update &&
3524 (write_in_full(get_lock_file_fd(lock->lk),
3525 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
3526 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3527 close_ref(lock) < 0)) {
3528 status |= error("couldn't write %s",
3529 get_lock_file_path(lock->lk));
3530 rollback_lock_file(&reflog_lock);
3531 } else if (commit_lock_file(&reflog_lock)) {
3532 status |= error("unable to commit reflog '%s' (%s)",
3533 log_file, strerror(errno));
3534 } else if (update && commit_ref(lock)) {
3535 status |= error("couldn't set %s", lock->ref_name);
3543 rollback_lock_file(&reflog_lock);