3 #include "refs-internal.h"
4 #include "../iterator.h"
5 #include "../lockfile.h"
12 struct object_id old_oid
;
18 * Information used (along with the information in ref_entry) to
19 * describe a single cached reference. This data structure only
20 * occurs embedded in a union in struct ref_entry, and only when
21 * (ref_entry->flag & REF_DIR) is zero.
25 * The name of the object to which this reference resolves
26 * (which may be a tag object). If REF_ISBROKEN, this is
27 * null. If REF_ISSYMREF, then this is the name of the object
28 * referred to by the last reference in the symlink chain.
33 * If REF_KNOWS_PEELED, then this field holds the peeled value
34 * of this reference, or null if the reference is known not to
35 * be peelable. See the documentation for peel_ref() for an
36 * exact definition of "peelable".
38 struct object_id peeled
;
44 * Information used (along with the information in ref_entry) to
45 * describe a level in the hierarchy of references. This data
46 * structure only occurs embedded in a union in struct ref_entry, and
47 * only when (ref_entry.flag & REF_DIR) is set. In that case,
48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
49 * in the directory have already been read:
51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
52 * or packed references, already read.
54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
55 * references that hasn't been read yet (nor has any of its
58 * Entries within a directory are stored within a growable array of
59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
60 * sorted are sorted by their component name in strcmp() order and the
61 * remaining entries are unsorted.
63 * Loose references are read lazily, one directory at a time. When a
64 * directory of loose references is read, then all of the references
65 * in that directory are stored, and REF_INCOMPLETE stubs are created
66 * for any subdirectories, but the subdirectories themselves are not
67 * read. The reading is triggered by get_ref_dir().
73 * Entries with index 0 <= i < sorted are sorted by name. New
74 * entries are appended to the list unsorted, and are sorted
75 * only when required; thus we avoid the need to sort the list
76 * after the addition of every reference.
80 /* A pointer to the ref_cache that contains this ref_dir. */
81 struct ref_cache
*ref_cache
;
83 struct ref_entry
**entries
;
87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
89 * public values; see refs.h.
93 * The field ref_entry->u.value.peeled of this value entry contains
94 * the correct peeled value for the reference, which might be
95 * null_sha1 if the reference is not a tag or if it is broken.
97 #define REF_KNOWS_PEELED 0x10
99 /* ref_entry represents a directory of references */
103 * Entry has not yet been read from disk (used only for REF_DIR
104 * entries representing loose references)
106 #define REF_INCOMPLETE 0x40
109 * A ref_entry represents either a reference or a "subdirectory" of
112 * Each directory in the reference namespace is represented by a
113 * ref_entry with (flags & REF_DIR) set and containing a subdir member
114 * that holds the entries in that directory that have been read so
115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
117 * used for loose reference directories.
119 * References are represented by a ref_entry with (flags & REF_DIR)
120 * unset and a value member that describes the reference's value. The
121 * flag member is at the ref_entry level, but it is also needed to
122 * interpret the contents of the value field (in other words, a
123 * ref_value object is not very much use without the enclosing
126 * Reference names cannot end with slash and directories' names are
127 * always stored with a trailing slash (except for the top-level
128 * directory, which is always denoted by ""). This has two nice
129 * consequences: (1) when the entries in each subdir are sorted
130 * lexicographically by name (as they usually are), the references in
131 * a whole tree can be generated in lexicographic order by traversing
132 * the tree in left-to-right, depth-first order; (2) the names of
133 * references and subdirectories cannot conflict, and therefore the
134 * presence of an empty subdirectory does not block the creation of a
135 * similarly-named reference. (The fact that reference names with the
136 * same leading components can conflict *with each other* is a
137 * separate issue that is regulated by verify_refname_available().)
139 * Please note that the name field contains the fully-qualified
140 * reference (or subdirectory) name. Space could be saved by only
141 * storing the relative names. But that would require the full names
142 * to be generated on the fly when iterating in do_for_each_ref(), and
143 * would break callback functions, who have always been able to assume
144 * that the name strings that they are passed will not be freed during
148 unsigned char flag
; /* ISSYMREF? ISPACKED? */
150 struct ref_value value
; /* if not (flags&REF_DIR) */
151 struct ref_dir subdir
; /* if (flags&REF_DIR) */
154 * The full name of the reference (e.g., "refs/heads/master")
155 * or the full name of the directory with a trailing slash
156 * (e.g., "refs/heads/"):
158 char name
[FLEX_ARRAY
];
161 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
162 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
);
163 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
164 const char *dirname
, size_t len
,
166 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
);
168 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
171 assert(entry
->flag
& REF_DIR
);
172 dir
= &entry
->u
.subdir
;
173 if (entry
->flag
& REF_INCOMPLETE
) {
174 read_loose_refs(entry
->name
, dir
);
177 * Manually add refs/bisect, which, being
178 * per-worktree, might not appear in the directory
179 * listing for refs/ in the main repo.
181 if (!strcmp(entry
->name
, "refs/")) {
182 int pos
= search_ref_dir(dir
, "refs/bisect/", 12);
184 struct ref_entry
*child_entry
;
185 child_entry
= create_dir_entry(dir
->ref_cache
,
188 add_entry_to_dir(dir
, child_entry
);
189 read_loose_refs("refs/bisect",
190 &child_entry
->u
.subdir
);
193 entry
->flag
&= ~REF_INCOMPLETE
;
198 static struct ref_entry
*create_ref_entry(const char *refname
,
199 const unsigned char *sha1
, int flag
,
202 struct ref_entry
*ref
;
205 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
206 die("Reference has invalid format: '%s'", refname
);
207 FLEX_ALLOC_STR(ref
, name
, refname
);
208 hashcpy(ref
->u
.value
.oid
.hash
, sha1
);
209 oidclr(&ref
->u
.value
.peeled
);
214 static void clear_ref_dir(struct ref_dir
*dir
);
216 static void free_ref_entry(struct ref_entry
*entry
)
218 if (entry
->flag
& REF_DIR
) {
220 * Do not use get_ref_dir() here, as that might
221 * trigger the reading of loose refs.
223 clear_ref_dir(&entry
->u
.subdir
);
229 * Add a ref_entry to the end of dir (unsorted). Entry is always
230 * stored directly in dir; no recursion into subdirectories is
233 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
235 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
236 dir
->entries
[dir
->nr
++] = entry
;
237 /* optimize for the case that entries are added in order */
239 (dir
->nr
== dir
->sorted
+ 1 &&
240 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
241 dir
->entries
[dir
->nr
- 1]->name
) < 0))
242 dir
->sorted
= dir
->nr
;
246 * Clear and free all entries in dir, recursively.
248 static void clear_ref_dir(struct ref_dir
*dir
)
251 for (i
= 0; i
< dir
->nr
; i
++)
252 free_ref_entry(dir
->entries
[i
]);
254 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
259 * Create a struct ref_entry object for the specified dirname.
260 * dirname is the name of the directory with a trailing slash (e.g.,
261 * "refs/heads/") or "" for the top-level directory.
263 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
264 const char *dirname
, size_t len
,
267 struct ref_entry
*direntry
;
268 FLEX_ALLOC_MEM(direntry
, name
, dirname
, len
);
269 direntry
->u
.subdir
.ref_cache
= ref_cache
;
270 direntry
->flag
= REF_DIR
| (incomplete ? REF_INCOMPLETE
: 0);
274 static int ref_entry_cmp(const void *a
, const void *b
)
276 struct ref_entry
*one
= *(struct ref_entry
**)a
;
277 struct ref_entry
*two
= *(struct ref_entry
**)b
;
278 return strcmp(one
->name
, two
->name
);
281 static void sort_ref_dir(struct ref_dir
*dir
);
283 struct string_slice
{
288 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
290 const struct string_slice
*key
= key_
;
291 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
292 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
295 return '\0' - (unsigned char)ent
->name
[key
->len
];
299 * Return the index of the entry with the given refname from the
300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
301 * no such entry is found. dir must already be complete.
303 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
305 struct ref_entry
**r
;
306 struct string_slice key
;
308 if (refname
== NULL
|| !dir
->nr
)
314 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
315 ref_entry_cmp_sslice
);
320 return r
- dir
->entries
;
324 * Search for a directory entry directly within dir (without
325 * recursing). Sort dir if necessary. subdirname must be a directory
326 * name (i.e., end in '/'). If mkdir is set, then create the
327 * directory if it is missing; otherwise, return NULL if the desired
328 * directory cannot be found. dir must already be complete.
330 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
331 const char *subdirname
, size_t len
,
334 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
335 struct ref_entry
*entry
;
336 if (entry_index
== -1) {
340 * Since dir is complete, the absence of a subdir
341 * means that the subdir really doesn't exist;
342 * therefore, create an empty record for it but mark
343 * the record complete.
345 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
346 add_entry_to_dir(dir
, entry
);
348 entry
= dir
->entries
[entry_index
];
350 return get_ref_dir(entry
);
354 * If refname is a reference name, find the ref_dir within the dir
355 * tree that should hold refname. If refname is a directory name
356 * (i.e., ends in '/'), then return that ref_dir itself. dir must
357 * represent the top-level directory and must already be complete.
358 * Sort ref_dirs and recurse into subdirectories as necessary. If
359 * mkdir is set, then create any missing directories; otherwise,
360 * return NULL if the desired directory cannot be found.
362 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
363 const char *refname
, int mkdir
)
366 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
367 size_t dirnamelen
= slash
- refname
+ 1;
368 struct ref_dir
*subdir
;
369 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
381 * Find the value entry with the given name in dir, sorting ref_dirs
382 * and recursing into subdirectories as necessary. If the name is not
383 * found or it corresponds to a directory entry, return NULL.
385 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
388 struct ref_entry
*entry
;
389 dir
= find_containing_dir(dir
, refname
, 0);
392 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
393 if (entry_index
== -1)
395 entry
= dir
->entries
[entry_index
];
396 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
400 * Remove the entry with the given name from dir, recursing into
401 * subdirectories as necessary. If refname is the name of a directory
402 * (i.e., ends with '/'), then remove the directory and its contents.
403 * If the removal was successful, return the number of entries
404 * remaining in the directory entry that contained the deleted entry.
405 * If the name was not found, return -1. Please note that this
406 * function only deletes the entry from the cache; it does not delete
407 * it from the filesystem or ensure that other cache entries (which
408 * might be symbolic references to the removed entry) are updated.
409 * Nor does it remove any containing dir entries that might be made
410 * empty by the removal. dir must represent the top-level directory
411 * and must already be complete.
413 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
415 int refname_len
= strlen(refname
);
417 struct ref_entry
*entry
;
418 int is_dir
= refname
[refname_len
- 1] == '/';
421 * refname represents a reference directory. Remove
422 * the trailing slash; otherwise we will get the
423 * directory *representing* refname rather than the
424 * one *containing* it.
426 char *dirname
= xmemdupz(refname
, refname_len
- 1);
427 dir
= find_containing_dir(dir
, dirname
, 0);
430 dir
= find_containing_dir(dir
, refname
, 0);
434 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
435 if (entry_index
== -1)
437 entry
= dir
->entries
[entry_index
];
439 memmove(&dir
->entries
[entry_index
],
440 &dir
->entries
[entry_index
+ 1],
441 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
444 if (dir
->sorted
> entry_index
)
446 free_ref_entry(entry
);
451 * Add a ref_entry to the ref_dir (unsorted), recursing into
452 * subdirectories as necessary. dir must represent the top-level
453 * directory. Return 0 on success.
455 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
457 dir
= find_containing_dir(dir
, ref
->name
, 1);
460 add_entry_to_dir(dir
, ref
);
465 * Emit a warning and return true iff ref1 and ref2 have the same name
466 * and the same sha1. Die if they have the same name but different
469 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
471 if (strcmp(ref1
->name
, ref2
->name
))
474 /* Duplicate name; make sure that they don't conflict: */
476 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
477 /* This is impossible by construction */
478 die("Reference directory conflict: %s", ref1
->name
);
480 if (oidcmp(&ref1
->u
.value
.oid
, &ref2
->u
.value
.oid
))
481 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
483 warning("Duplicated ref: %s", ref1
->name
);
488 * Sort the entries in dir non-recursively (if they are not already
489 * sorted) and remove any duplicate entries.
491 static void sort_ref_dir(struct ref_dir
*dir
)
494 struct ref_entry
*last
= NULL
;
497 * This check also prevents passing a zero-length array to qsort(),
498 * which is a problem on some platforms.
500 if (dir
->sorted
== dir
->nr
)
503 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
505 /* Remove any duplicates: */
506 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
507 struct ref_entry
*entry
= dir
->entries
[j
];
508 if (last
&& is_dup_ref(last
, entry
))
509 free_ref_entry(entry
);
511 last
= dir
->entries
[i
++] = entry
;
513 dir
->sorted
= dir
->nr
= i
;
517 * Return true if refname, which has the specified oid and flags, can
518 * be resolved to an object in the database. If the referred-to object
519 * does not exist, emit a warning and return false.
521 static int ref_resolves_to_object(const char *refname
,
522 const struct object_id
*oid
,
525 if (flags
& REF_ISBROKEN
)
527 if (!has_sha1_file(oid
->hash
)) {
528 error("%s does not point to a valid object!", refname
);
535 * Return true if the reference described by entry can be resolved to
536 * an object in the database; otherwise, emit a warning and return
539 static int entry_resolves_to_object(struct ref_entry
*entry
)
541 return ref_resolves_to_object(entry
->name
,
542 &entry
->u
.value
.oid
, entry
->flag
);
546 * current_ref is a performance hack: when iterating over references
547 * using the for_each_ref*() functions, current_ref is set to the
548 * current reference's entry before calling the callback function. If
549 * the callback function calls peel_ref(), then peel_ref() first
550 * checks whether the reference to be peeled is the current reference
551 * (it usually is) and if so, returns that reference's peeled version
552 * if it is available. This avoids a refname lookup in a common case.
554 static struct ref_entry
*current_ref
;
556 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
558 struct ref_entry_cb
{
567 * Handle one reference in a do_for_each_ref*()-style iteration,
568 * calling an each_ref_fn for each entry.
570 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
572 struct ref_entry_cb
*data
= cb_data
;
573 struct ref_entry
*old_current_ref
;
576 if (!starts_with(entry
->name
, data
->prefix
))
579 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
580 !entry_resolves_to_object(entry
))
583 /* Store the old value, in case this is a recursive call: */
584 old_current_ref
= current_ref
;
586 retval
= data
->fn(entry
->name
+ data
->trim
, &entry
->u
.value
.oid
,
587 entry
->flag
, data
->cb_data
);
588 current_ref
= old_current_ref
;
593 * Call fn for each reference in dir that has index in the range
594 * offset <= index < dir->nr. Recurse into subdirectories that are in
595 * that index range, sorting them before iterating. This function
596 * does not sort dir itself; it should be sorted beforehand. fn is
597 * called for all references, including broken ones.
599 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
600 each_ref_entry_fn fn
, void *cb_data
)
603 assert(dir
->sorted
== dir
->nr
);
604 for (i
= offset
; i
< dir
->nr
; i
++) {
605 struct ref_entry
*entry
= dir
->entries
[i
];
607 if (entry
->flag
& REF_DIR
) {
608 struct ref_dir
*subdir
= get_ref_dir(entry
);
609 sort_ref_dir(subdir
);
610 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
612 retval
= fn(entry
, cb_data
);
621 * Call fn for each reference in the union of dir1 and dir2, in order
622 * by refname. Recurse into subdirectories. If a value entry appears
623 * in both dir1 and dir2, then only process the version that is in
624 * dir2. The input dirs must already be sorted, but subdirs will be
625 * sorted as needed. fn is called for all references, including
628 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
629 struct ref_dir
*dir2
,
630 each_ref_entry_fn fn
, void *cb_data
)
635 assert(dir1
->sorted
== dir1
->nr
);
636 assert(dir2
->sorted
== dir2
->nr
);
638 struct ref_entry
*e1
, *e2
;
640 if (i1
== dir1
->nr
) {
641 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
643 if (i2
== dir2
->nr
) {
644 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
646 e1
= dir1
->entries
[i1
];
647 e2
= dir2
->entries
[i2
];
648 cmp
= strcmp(e1
->name
, e2
->name
);
650 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
651 /* Both are directories; descend them in parallel. */
652 struct ref_dir
*subdir1
= get_ref_dir(e1
);
653 struct ref_dir
*subdir2
= get_ref_dir(e2
);
654 sort_ref_dir(subdir1
);
655 sort_ref_dir(subdir2
);
656 retval
= do_for_each_entry_in_dirs(
657 subdir1
, subdir2
, fn
, cb_data
);
660 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
661 /* Both are references; ignore the one from dir1. */
662 retval
= fn(e2
, cb_data
);
666 die("conflict between reference and directory: %s",
678 if (e
->flag
& REF_DIR
) {
679 struct ref_dir
*subdir
= get_ref_dir(e
);
680 sort_ref_dir(subdir
);
681 retval
= do_for_each_entry_in_dir(
682 subdir
, 0, fn
, cb_data
);
684 retval
= fn(e
, cb_data
);
693 * Load all of the refs from the dir into our in-memory cache. The hard work
694 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
695 * through all of the sub-directories. We do not even need to care about
696 * sorting, as traversal order does not matter to us.
698 static void prime_ref_dir(struct ref_dir
*dir
)
701 for (i
= 0; i
< dir
->nr
; i
++) {
702 struct ref_entry
*entry
= dir
->entries
[i
];
703 if (entry
->flag
& REF_DIR
)
704 prime_ref_dir(get_ref_dir(entry
));
709 * A level in the reference hierarchy that is currently being iterated
712 struct cache_ref_iterator_level
{
714 * The ref_dir being iterated over at this level. The ref_dir
715 * is sorted before being stored here.
720 * The index of the current entry within dir (which might
721 * itself be a directory). If index == -1, then the iteration
722 * hasn't yet begun. If index == dir->nr, then the iteration
723 * through this level is over.
729 * Represent an iteration through a ref_dir in the memory cache. The
730 * iteration recurses through subdirectories.
732 struct cache_ref_iterator
{
733 struct ref_iterator base
;
736 * The number of levels currently on the stack. This is always
737 * at least 1, because when it becomes zero the iteration is
738 * ended and this struct is freed.
742 /* The number of levels that have been allocated on the stack */
746 * A stack of levels. levels[0] is the uppermost level that is
747 * being iterated over in this iteration. (This is not
748 * necessary the top level in the references hierarchy. If we
749 * are iterating through a subtree, then levels[0] will hold
750 * the ref_dir for that subtree, and subsequent levels will go
753 struct cache_ref_iterator_level
*levels
;
756 static int cache_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
758 struct cache_ref_iterator
*iter
=
759 (struct cache_ref_iterator
*)ref_iterator
;
762 struct cache_ref_iterator_level
*level
=
763 &iter
->levels
[iter
->levels_nr
- 1];
764 struct ref_dir
*dir
= level
->dir
;
765 struct ref_entry
*entry
;
767 if (level
->index
== -1)
770 if (++level
->index
== level
->dir
->nr
) {
771 /* This level is exhausted; pop up a level */
772 if (--iter
->levels_nr
== 0)
773 return ref_iterator_abort(ref_iterator
);
778 entry
= dir
->entries
[level
->index
];
780 if (entry
->flag
& REF_DIR
) {
781 /* push down a level */
782 ALLOC_GROW(iter
->levels
, iter
->levels_nr
+ 1,
785 level
= &iter
->levels
[iter
->levels_nr
++];
786 level
->dir
= get_ref_dir(entry
);
789 iter
->base
.refname
= entry
->name
;
790 iter
->base
.oid
= &entry
->u
.value
.oid
;
791 iter
->base
.flags
= entry
->flag
;
797 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
);
799 static int cache_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
800 struct object_id
*peeled
)
802 struct cache_ref_iterator
*iter
=
803 (struct cache_ref_iterator
*)ref_iterator
;
804 struct cache_ref_iterator_level
*level
;
805 struct ref_entry
*entry
;
807 level
= &iter
->levels
[iter
->levels_nr
- 1];
809 if (level
->index
== -1)
810 die("BUG: peel called before advance for cache iterator");
812 entry
= level
->dir
->entries
[level
->index
];
814 if (peel_entry(entry
, 0))
816 hashcpy(peeled
->hash
, entry
->u
.value
.peeled
.hash
);
820 static int cache_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
822 struct cache_ref_iterator
*iter
=
823 (struct cache_ref_iterator
*)ref_iterator
;
826 base_ref_iterator_free(ref_iterator
);
830 static struct ref_iterator_vtable cache_ref_iterator_vtable
= {
831 cache_ref_iterator_advance
,
832 cache_ref_iterator_peel
,
833 cache_ref_iterator_abort
836 static struct ref_iterator
*cache_ref_iterator_begin(struct ref_dir
*dir
)
838 struct cache_ref_iterator
*iter
;
839 struct ref_iterator
*ref_iterator
;
840 struct cache_ref_iterator_level
*level
;
842 iter
= xcalloc(1, sizeof(*iter
));
843 ref_iterator
= &iter
->base
;
844 base_ref_iterator_init(ref_iterator
, &cache_ref_iterator_vtable
);
845 ALLOC_GROW(iter
->levels
, 10, iter
->levels_alloc
);
848 level
= &iter
->levels
[0];
855 struct nonmatching_ref_data
{
856 const struct string_list
*skip
;
857 const char *conflicting_refname
;
860 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
862 struct nonmatching_ref_data
*data
= vdata
;
864 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
867 data
->conflicting_refname
= entry
->name
;
872 * Return 0 if a reference named refname could be created without
873 * conflicting with the name of an existing reference in dir.
874 * See verify_refname_available for more information.
876 static int verify_refname_available_dir(const char *refname
,
877 const struct string_list
*extras
,
878 const struct string_list
*skip
,
883 const char *extra_refname
;
885 struct strbuf dirname
= STRBUF_INIT
;
889 * For the sake of comments in this function, suppose that
890 * refname is "refs/foo/bar".
895 strbuf_grow(&dirname
, strlen(refname
) + 1);
896 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
897 /* Expand dirname to the new prefix, not including the trailing slash: */
898 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
901 * We are still at a leading dir of the refname (e.g.,
902 * "refs/foo"; if there is a reference with that name,
903 * it is a conflict, *unless* it is in skip.
906 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
908 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
910 * We found a reference whose name is
911 * a proper prefix of refname; e.g.,
912 * "refs/foo", and is not in skip.
914 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
915 dirname
.buf
, refname
);
920 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
921 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
922 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
923 refname
, dirname
.buf
);
928 * Otherwise, we can try to continue our search with
929 * the next component. So try to look up the
930 * directory, e.g., "refs/foo/". If we come up empty,
931 * we know there is nothing under this whole prefix,
932 * but even in that case we still have to continue the
933 * search for conflicts with extras.
935 strbuf_addch(&dirname
, '/');
937 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
940 * There was no directory "refs/foo/",
941 * so there is nothing under this
942 * whole prefix. So there is no need
943 * to continue looking for conflicting
944 * references. But we need to continue
945 * looking for conflicting extras.
949 dir
= get_ref_dir(dir
->entries
[pos
]);
955 * We are at the leaf of our refname (e.g., "refs/foo/bar").
956 * There is no point in searching for a reference with that
957 * name, because a refname isn't considered to conflict with
958 * itself. But we still need to check for references whose
959 * names are in the "refs/foo/bar/" namespace, because they
962 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
963 strbuf_addch(&dirname
, '/');
966 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
970 * We found a directory named "$refname/"
971 * (e.g., "refs/foo/bar/"). It is a problem
972 * iff it contains any ref that is not in
975 struct nonmatching_ref_data data
;
978 data
.conflicting_refname
= NULL
;
979 dir
= get_ref_dir(dir
->entries
[pos
]);
981 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
982 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
983 data
.conflicting_refname
, refname
);
989 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
991 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
992 refname
, extra_refname
);
997 strbuf_release(&dirname
);
1001 struct packed_ref_cache
{
1002 struct ref_entry
*root
;
1005 * Count of references to the data structure in this instance,
1006 * including the pointer from ref_cache::packed if any. The
1007 * data will not be freed as long as the reference count is
1010 unsigned int referrers
;
1013 * Iff the packed-refs file associated with this instance is
1014 * currently locked for writing, this points at the associated
1015 * lock (which is owned by somebody else). The referrer count
1016 * is also incremented when the file is locked and decremented
1017 * when it is unlocked.
1019 struct lock_file
*lock
;
1021 /* The metadata from when this packed-refs cache was read */
1022 struct stat_validity validity
;
1026 * Future: need to be in "struct repository"
1027 * when doing a full libification.
1029 static struct ref_cache
{
1030 struct ref_cache
*next
;
1031 struct ref_entry
*loose
;
1032 struct packed_ref_cache
*packed
;
1034 * The submodule name, or "" for the main repo. We allocate
1035 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1036 * is initialized correctly.
1039 } ref_cache
, *submodule_ref_caches
;
1041 /* Lock used for the main packed-refs file: */
1042 static struct lock_file packlock
;
1045 * Increment the reference count of *packed_refs.
1047 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1049 packed_refs
->referrers
++;
1053 * Decrease the reference count of *packed_refs. If it goes to zero,
1054 * free *packed_refs and return true; otherwise return false.
1056 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1058 if (!--packed_refs
->referrers
) {
1059 free_ref_entry(packed_refs
->root
);
1060 stat_validity_clear(&packed_refs
->validity
);
1068 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1071 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1073 if (packed_refs
->lock
)
1074 die("internal error: packed-ref cache cleared while locked");
1075 refs
->packed
= NULL
;
1076 release_packed_ref_cache(packed_refs
);
1080 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1083 free_ref_entry(refs
->loose
);
1089 * Create a new submodule ref cache and add it to the internal
1092 static struct ref_cache
*create_ref_cache(const char *submodule
)
1094 struct ref_cache
*refs
;
1097 FLEX_ALLOC_STR(refs
, name
, submodule
);
1098 refs
->next
= submodule_ref_caches
;
1099 submodule_ref_caches
= refs
;
1103 static struct ref_cache
*lookup_ref_cache(const char *submodule
)
1105 struct ref_cache
*refs
;
1107 if (!submodule
|| !*submodule
)
1110 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1111 if (!strcmp(submodule
, refs
->name
))
1117 * Return a pointer to a ref_cache for the specified submodule. For
1118 * the main repository, use submodule==NULL; such a call cannot fail.
1119 * For a submodule, the submodule must exist and be a nonbare
1120 * repository, otherwise return NULL.
1122 * The returned structure will be allocated and initialized but not
1123 * necessarily populated; it should not be freed.
1125 static struct ref_cache
*get_ref_cache(const char *submodule
)
1127 struct ref_cache
*refs
= lookup_ref_cache(submodule
);
1130 struct strbuf submodule_sb
= STRBUF_INIT
;
1132 strbuf_addstr(&submodule_sb
, submodule
);
1133 if (is_nonbare_repository_dir(&submodule_sb
))
1134 refs
= create_ref_cache(submodule
);
1135 strbuf_release(&submodule_sb
);
1141 /* The length of a peeled reference line in packed-refs, including EOL: */
1142 #define PEELED_LINE_LENGTH 42
1145 * The packed-refs header line that we write out. Perhaps other
1146 * traits will be added later. The trailing space is required.
1148 static const char PACKED_REFS_HEADER
[] =
1149 "# pack-refs with: peeled fully-peeled \n";
1152 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1153 * Return a pointer to the refname within the line (null-terminated),
1154 * or NULL if there was a problem.
1156 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1161 * 42: the answer to everything.
1163 * In this case, it happens to be the answer to
1164 * 40 (length of sha1 hex representation)
1165 * +1 (space in between hex and name)
1166 * +1 (newline at the end of the line)
1168 if (line
->len
<= 42)
1171 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1173 if (!isspace(line
->buf
[40]))
1176 ref
= line
->buf
+ 41;
1180 if (line
->buf
[line
->len
- 1] != '\n')
1182 line
->buf
[--line
->len
] = 0;
1188 * Read f, which is a packed-refs file, into dir.
1190 * A comment line of the form "# pack-refs with: " may contain zero or
1191 * more traits. We interpret the traits as follows:
1195 * Probably no references are peeled. But if the file contains a
1196 * peeled value for a reference, we will use it.
1200 * References under "refs/tags/", if they *can* be peeled, *are*
1201 * peeled in this file. References outside of "refs/tags/" are
1202 * probably not peeled even if they could have been, but if we find
1203 * a peeled value for such a reference we will use it.
1207 * All references in the file that can be peeled are peeled.
1208 * Inversely (and this is more important), any references in the
1209 * file for which no peeled value is recorded is not peelable. This
1210 * trait should typically be written alongside "peeled" for
1211 * compatibility with older clients, but we do not require it
1212 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1214 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1216 struct ref_entry
*last
= NULL
;
1217 struct strbuf line
= STRBUF_INIT
;
1218 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1220 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1221 unsigned char sha1
[20];
1222 const char *refname
;
1225 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1226 if (strstr(traits
, " fully-peeled "))
1227 peeled
= PEELED_FULLY
;
1228 else if (strstr(traits
, " peeled "))
1229 peeled
= PEELED_TAGS
;
1230 /* perhaps other traits later as well */
1234 refname
= parse_ref_line(&line
, sha1
);
1236 int flag
= REF_ISPACKED
;
1238 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1239 if (!refname_is_safe(refname
))
1240 die("packed refname is dangerous: %s", refname
);
1242 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1244 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1245 if (peeled
== PEELED_FULLY
||
1246 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1247 last
->flag
|= REF_KNOWS_PEELED
;
1252 line
.buf
[0] == '^' &&
1253 line
.len
== PEELED_LINE_LENGTH
&&
1254 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1255 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1256 hashcpy(last
->u
.value
.peeled
.hash
, sha1
);
1258 * Regardless of what the file header said,
1259 * we definitely know the value of *this*
1262 last
->flag
|= REF_KNOWS_PEELED
;
1266 strbuf_release(&line
);
1270 * Get the packed_ref_cache for the specified ref_cache, creating it
1273 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1275 char *packed_refs_file
;
1278 packed_refs_file
= git_pathdup_submodule(refs
->name
, "packed-refs");
1280 packed_refs_file
= git_pathdup("packed-refs");
1283 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1284 clear_packed_ref_cache(refs
);
1286 if (!refs
->packed
) {
1289 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1290 acquire_packed_ref_cache(refs
->packed
);
1291 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1292 f
= fopen(packed_refs_file
, "r");
1294 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1295 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1299 free(packed_refs_file
);
1300 return refs
->packed
;
1303 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1305 return get_ref_dir(packed_ref_cache
->root
);
1308 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1310 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1314 * Add a reference to the in-memory packed reference cache. This may
1315 * only be called while the packed-refs file is locked (see
1316 * lock_packed_refs()). To actually write the packed-refs file, call
1317 * commit_packed_refs().
1319 static void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1321 struct packed_ref_cache
*packed_ref_cache
=
1322 get_packed_ref_cache(&ref_cache
);
1324 if (!packed_ref_cache
->lock
)
1325 die("internal error: packed refs not locked");
1326 add_ref(get_packed_ref_dir(packed_ref_cache
),
1327 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1331 * Read the loose references from the namespace dirname into dir
1332 * (without recursing). dirname must end with '/'. dir must be the
1333 * directory entry corresponding to dirname.
1335 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1337 struct ref_cache
*refs
= dir
->ref_cache
;
1340 int dirnamelen
= strlen(dirname
);
1341 struct strbuf refname
;
1342 struct strbuf path
= STRBUF_INIT
;
1343 size_t path_baselen
;
1346 strbuf_git_path_submodule(&path
, refs
->name
, "%s", dirname
);
1348 strbuf_git_path(&path
, "%s", dirname
);
1349 path_baselen
= path
.len
;
1351 d
= opendir(path
.buf
);
1353 strbuf_release(&path
);
1357 strbuf_init(&refname
, dirnamelen
+ 257);
1358 strbuf_add(&refname
, dirname
, dirnamelen
);
1360 while ((de
= readdir(d
)) != NULL
) {
1361 unsigned char sha1
[20];
1365 if (de
->d_name
[0] == '.')
1367 if (ends_with(de
->d_name
, ".lock"))
1369 strbuf_addstr(&refname
, de
->d_name
);
1370 strbuf_addstr(&path
, de
->d_name
);
1371 if (stat(path
.buf
, &st
) < 0) {
1372 ; /* silently ignore */
1373 } else if (S_ISDIR(st
.st_mode
)) {
1374 strbuf_addch(&refname
, '/');
1375 add_entry_to_dir(dir
,
1376 create_dir_entry(refs
, refname
.buf
,
1384 read_ok
= !resolve_gitlink_ref(refs
->name
,
1387 read_ok
= !read_ref_full(refname
.buf
,
1388 RESOLVE_REF_READING
,
1394 flag
|= REF_ISBROKEN
;
1395 } else if (is_null_sha1(sha1
)) {
1397 * It is so astronomically unlikely
1398 * that NULL_SHA1 is the SHA-1 of an
1399 * actual object that we consider its
1400 * appearance in a loose reference
1401 * file to be repo corruption
1402 * (probably due to a software bug).
1404 flag
|= REF_ISBROKEN
;
1407 if (check_refname_format(refname
.buf
,
1408 REFNAME_ALLOW_ONELEVEL
)) {
1409 if (!refname_is_safe(refname
.buf
))
1410 die("loose refname is dangerous: %s", refname
.buf
);
1412 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1414 add_entry_to_dir(dir
,
1415 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1417 strbuf_setlen(&refname
, dirnamelen
);
1418 strbuf_setlen(&path
, path_baselen
);
1420 strbuf_release(&refname
);
1421 strbuf_release(&path
);
1425 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1429 * Mark the top-level directory complete because we
1430 * are about to read the only subdirectory that can
1433 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1435 * Create an incomplete entry for "refs/":
1437 add_entry_to_dir(get_ref_dir(refs
->loose
),
1438 create_dir_entry(refs
, "refs/", 5, 1));
1440 return get_ref_dir(refs
->loose
);
1443 #define MAXREFLEN (1024)
1446 * Called by resolve_gitlink_ref_recursive() after it failed to read
1447 * from the loose refs in ref_cache refs. Find <refname> in the
1448 * packed-refs file for the submodule.
1450 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1451 const char *refname
, unsigned char *sha1
)
1453 struct ref_entry
*ref
;
1454 struct ref_dir
*dir
= get_packed_refs(refs
);
1456 ref
= find_ref(dir
, refname
);
1460 hashcpy(sha1
, ref
->u
.value
.oid
.hash
);
1464 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1465 const char *refname
, unsigned char *sha1
,
1469 char buffer
[128], *p
;
1472 if (recursion
> SYMREF_MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1475 ?
git_pathdup_submodule(refs
->name
, "%s", refname
)
1476 : git_pathdup("%s", refname
);
1477 fd
= open(path
, O_RDONLY
);
1480 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1482 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1486 while (len
&& isspace(buffer
[len
-1]))
1490 /* Was it a detached head or an old-fashioned symlink? */
1491 if (!get_sha1_hex(buffer
, sha1
))
1495 if (strncmp(buffer
, "ref:", 4))
1501 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1504 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1506 int len
= strlen(path
), retval
;
1507 struct strbuf submodule
= STRBUF_INIT
;
1508 struct ref_cache
*refs
;
1510 while (len
&& path
[len
-1] == '/')
1515 strbuf_add(&submodule
, path
, len
);
1516 refs
= get_ref_cache(submodule
.buf
);
1518 strbuf_release(&submodule
);
1521 strbuf_release(&submodule
);
1523 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1528 * Return the ref_entry for the given refname from the packed
1529 * references. If it does not exist, return NULL.
1531 static struct ref_entry
*get_packed_ref(const char *refname
)
1533 return find_ref(get_packed_refs(&ref_cache
), refname
);
1537 * A loose ref file doesn't exist; check for a packed ref.
1539 static int resolve_missing_loose_ref(const char *refname
,
1540 unsigned char *sha1
,
1541 unsigned int *flags
)
1543 struct ref_entry
*entry
;
1546 * The loose reference file does not exist; check for a packed
1549 entry
= get_packed_ref(refname
);
1551 hashcpy(sha1
, entry
->u
.value
.oid
.hash
);
1552 *flags
|= REF_ISPACKED
;
1555 /* refname is not a packed reference. */
1559 int read_raw_ref(const char *refname
, unsigned char *sha1
,
1560 struct strbuf
*referent
, unsigned int *type
)
1562 struct strbuf sb_contents
= STRBUF_INIT
;
1563 struct strbuf sb_path
= STRBUF_INIT
;
1572 strbuf_reset(&sb_path
);
1573 strbuf_git_path(&sb_path
, "%s", refname
);
1578 * We might have to loop back here to avoid a race
1579 * condition: first we lstat() the file, then we try
1580 * to read it as a link or as a file. But if somebody
1581 * changes the type of the file (file <-> directory
1582 * <-> symlink) between the lstat() and reading, then
1583 * we don't want to report that as an error but rather
1584 * try again starting with the lstat().
1587 if (lstat(path
, &st
) < 0) {
1588 if (errno
!= ENOENT
)
1590 if (resolve_missing_loose_ref(refname
, sha1
, type
)) {
1598 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1599 if (S_ISLNK(st
.st_mode
)) {
1600 strbuf_reset(&sb_contents
);
1601 if (strbuf_readlink(&sb_contents
, path
, 0) < 0) {
1602 if (errno
== ENOENT
|| errno
== EINVAL
)
1603 /* inconsistent with lstat; retry */
1608 if (starts_with(sb_contents
.buf
, "refs/") &&
1609 !check_refname_format(sb_contents
.buf
, 0)) {
1610 strbuf_swap(&sb_contents
, referent
);
1611 *type
|= REF_ISSYMREF
;
1617 /* Is it a directory? */
1618 if (S_ISDIR(st
.st_mode
)) {
1620 * Even though there is a directory where the loose
1621 * ref is supposed to be, there could still be a
1624 if (resolve_missing_loose_ref(refname
, sha1
, type
)) {
1633 * Anything else, just open it and try to use it as
1636 fd
= open(path
, O_RDONLY
);
1638 if (errno
== ENOENT
)
1639 /* inconsistent with lstat; retry */
1644 strbuf_reset(&sb_contents
);
1645 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
1646 int save_errno
= errno
;
1652 strbuf_rtrim(&sb_contents
);
1653 buf
= sb_contents
.buf
;
1654 if (starts_with(buf
, "ref:")) {
1656 while (isspace(*buf
))
1659 strbuf_reset(referent
);
1660 strbuf_addstr(referent
, buf
);
1661 *type
|= REF_ISSYMREF
;
1667 * Please note that FETCH_HEAD has additional
1668 * data after the sha.
1670 if (get_sha1_hex(buf
, sha1
) ||
1671 (buf
[40] != '\0' && !isspace(buf
[40]))) {
1672 *type
|= REF_ISBROKEN
;
1681 strbuf_release(&sb_path
);
1682 strbuf_release(&sb_contents
);
1687 static void unlock_ref(struct ref_lock
*lock
)
1689 /* Do not free lock->lk -- atexit() still looks at them */
1691 rollback_lock_file(lock
->lk
);
1692 free(lock
->ref_name
);
1697 * Lock refname, without following symrefs, and set *lock_p to point
1698 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
1699 * and type similarly to read_raw_ref().
1701 * The caller must verify that refname is a "safe" reference name (in
1702 * the sense of refname_is_safe()) before calling this function.
1704 * If the reference doesn't already exist, verify that refname doesn't
1705 * have a D/F conflict with any existing references. extras and skip
1706 * are passed to verify_refname_available_dir() for this check.
1708 * If mustexist is not set and the reference is not found or is
1709 * broken, lock the reference anyway but clear sha1.
1711 * Return 0 on success. On failure, write an error message to err and
1712 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
1714 * Implementation note: This function is basically
1719 * but it includes a lot more code to
1720 * - Deal with possible races with other processes
1721 * - Avoid calling verify_refname_available_dir() when it can be
1722 * avoided, namely if we were successfully able to read the ref
1723 * - Generate informative error messages in the case of failure
1725 static int lock_raw_ref(const char *refname
, int mustexist
,
1726 const struct string_list
*extras
,
1727 const struct string_list
*skip
,
1728 struct ref_lock
**lock_p
,
1729 struct strbuf
*referent
,
1733 struct ref_lock
*lock
;
1734 struct strbuf ref_file
= STRBUF_INIT
;
1735 int attempts_remaining
= 3;
1736 int ret
= TRANSACTION_GENERIC_ERROR
;
1741 /* First lock the file so it can't change out from under us. */
1743 *lock_p
= lock
= xcalloc(1, sizeof(*lock
));
1745 lock
->ref_name
= xstrdup(refname
);
1746 strbuf_git_path(&ref_file
, "%s", refname
);
1749 switch (safe_create_leading_directories(ref_file
.buf
)) {
1751 break; /* success */
1754 * Suppose refname is "refs/foo/bar". We just failed
1755 * to create the containing directory, "refs/foo",
1756 * because there was a non-directory in the way. This
1757 * indicates a D/F conflict, probably because of
1758 * another reference such as "refs/foo". There is no
1759 * reason to expect this error to be transitory.
1761 if (verify_refname_available(refname
, extras
, skip
, err
)) {
1764 * To the user the relevant error is
1765 * that the "mustexist" reference is
1769 strbuf_addf(err
, "unable to resolve reference '%s'",
1773 * The error message set by
1774 * verify_refname_available_dir() is OK.
1776 ret
= TRANSACTION_NAME_CONFLICT
;
1780 * The file that is in the way isn't a loose
1781 * reference. Report it as a low-level
1784 strbuf_addf(err
, "unable to create lock file %s.lock; "
1785 "non-directory in the way",
1790 /* Maybe another process was tidying up. Try again. */
1791 if (--attempts_remaining
> 0)
1795 strbuf_addf(err
, "unable to create directory for %s",
1801 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
1803 if (hold_lock_file_for_update(lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
) < 0) {
1804 if (errno
== ENOENT
&& --attempts_remaining
> 0) {
1806 * Maybe somebody just deleted one of the
1807 * directories leading to ref_file. Try
1812 unable_to_lock_message(ref_file
.buf
, errno
, err
);
1818 * Now we hold the lock and can read the reference without
1819 * fear that its value will change.
1822 if (read_raw_ref(refname
, lock
->old_oid
.hash
, referent
, type
)) {
1823 if (errno
== ENOENT
) {
1825 /* Garden variety missing reference. */
1826 strbuf_addf(err
, "unable to resolve reference '%s'",
1831 * Reference is missing, but that's OK. We
1832 * know that there is not a conflict with
1833 * another loose reference because
1834 * (supposing that we are trying to lock
1835 * reference "refs/foo/bar"):
1837 * - We were successfully able to create
1838 * the lockfile refs/foo/bar.lock, so we
1839 * know there cannot be a loose reference
1842 * - We got ENOENT and not EISDIR, so we
1843 * know that there cannot be a loose
1844 * reference named "refs/foo/bar/baz".
1847 } else if (errno
== EISDIR
) {
1849 * There is a directory in the way. It might have
1850 * contained references that have been deleted. If
1851 * we don't require that the reference already
1852 * exists, try to remove the directory so that it
1853 * doesn't cause trouble when we want to rename the
1854 * lockfile into place later.
1857 /* Garden variety missing reference. */
1858 strbuf_addf(err
, "unable to resolve reference '%s'",
1861 } else if (remove_dir_recursively(&ref_file
,
1862 REMOVE_DIR_EMPTY_ONLY
)) {
1863 if (verify_refname_available_dir(
1864 refname
, extras
, skip
,
1865 get_loose_refs(&ref_cache
),
1868 * The error message set by
1869 * verify_refname_available() is OK.
1871 ret
= TRANSACTION_NAME_CONFLICT
;
1875 * We can't delete the directory,
1876 * but we also don't know of any
1877 * references that it should
1880 strbuf_addf(err
, "there is a non-empty directory '%s' "
1881 "blocking reference '%s'",
1882 ref_file
.buf
, refname
);
1886 } else if (errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
1887 strbuf_addf(err
, "unable to resolve reference '%s': "
1888 "reference broken", refname
);
1891 strbuf_addf(err
, "unable to resolve reference '%s': %s",
1892 refname
, strerror(errno
));
1897 * If the ref did not exist and we are creating it,
1898 * make sure there is no existing packed ref whose
1899 * name begins with our refname, nor a packed ref
1900 * whose name is a proper prefix of our refname.
1902 if (verify_refname_available_dir(
1903 refname
, extras
, skip
,
1904 get_packed_refs(&ref_cache
),
1918 strbuf_release(&ref_file
);
1923 * Peel the entry (if possible) and return its new peel_status. If
1924 * repeel is true, re-peel the entry even if there is an old peeled
1925 * value that is already stored in it.
1927 * It is OK to call this function with a packed reference entry that
1928 * might be stale and might even refer to an object that has since
1929 * been garbage-collected. In such a case, if the entry has
1930 * REF_KNOWS_PEELED then leave the status unchanged and return
1931 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1933 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1935 enum peel_status status
;
1937 if (entry
->flag
& REF_KNOWS_PEELED
) {
1939 entry
->flag
&= ~REF_KNOWS_PEELED
;
1940 oidclr(&entry
->u
.value
.peeled
);
1942 return is_null_oid(&entry
->u
.value
.peeled
) ?
1943 PEEL_NON_TAG
: PEEL_PEELED
;
1946 if (entry
->flag
& REF_ISBROKEN
)
1948 if (entry
->flag
& REF_ISSYMREF
)
1949 return PEEL_IS_SYMREF
;
1951 status
= peel_object(entry
->u
.value
.oid
.hash
, entry
->u
.value
.peeled
.hash
);
1952 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1953 entry
->flag
|= REF_KNOWS_PEELED
;
1957 int peel_ref(const char *refname
, unsigned char *sha1
)
1960 unsigned char base
[20];
1962 if (current_ref
&& (current_ref
->name
== refname
1963 || !strcmp(current_ref
->name
, refname
))) {
1964 if (peel_entry(current_ref
, 0))
1966 hashcpy(sha1
, current_ref
->u
.value
.peeled
.hash
);
1970 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1974 * If the reference is packed, read its ref_entry from the
1975 * cache in the hope that we already know its peeled value.
1976 * We only try this optimization on packed references because
1977 * (a) forcing the filling of the loose reference cache could
1978 * be expensive and (b) loose references anyway usually do not
1979 * have REF_KNOWS_PEELED.
1981 if (flag
& REF_ISPACKED
) {
1982 struct ref_entry
*r
= get_packed_ref(refname
);
1984 if (peel_entry(r
, 0))
1986 hashcpy(sha1
, r
->u
.value
.peeled
.hash
);
1991 return peel_object(base
, sha1
);
1994 struct files_ref_iterator
{
1995 struct ref_iterator base
;
1997 struct packed_ref_cache
*packed_ref_cache
;
1998 struct ref_iterator
*iter0
;
2002 static int files_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
2004 struct files_ref_iterator
*iter
=
2005 (struct files_ref_iterator
*)ref_iterator
;
2008 while ((ok
= ref_iterator_advance(iter
->iter0
)) == ITER_OK
) {
2009 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
2010 !ref_resolves_to_object(iter
->iter0
->refname
,
2012 iter
->iter0
->flags
))
2015 iter
->base
.refname
= iter
->iter0
->refname
;
2016 iter
->base
.oid
= iter
->iter0
->oid
;
2017 iter
->base
.flags
= iter
->iter0
->flags
;
2022 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
2028 static int files_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
2029 struct object_id
*peeled
)
2031 struct files_ref_iterator
*iter
=
2032 (struct files_ref_iterator
*)ref_iterator
;
2034 return ref_iterator_peel(iter
->iter0
, peeled
);
2037 static int files_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
2039 struct files_ref_iterator
*iter
=
2040 (struct files_ref_iterator
*)ref_iterator
;
2044 ok
= ref_iterator_abort(iter
->iter0
);
2046 release_packed_ref_cache(iter
->packed_ref_cache
);
2047 base_ref_iterator_free(ref_iterator
);
2051 static struct ref_iterator_vtable files_ref_iterator_vtable
= {
2052 files_ref_iterator_advance
,
2053 files_ref_iterator_peel
,
2054 files_ref_iterator_abort
2057 struct ref_iterator
*files_ref_iterator_begin(
2058 const char *submodule
,
2059 const char *prefix
, unsigned int flags
)
2061 struct ref_cache
*refs
= get_ref_cache(submodule
);
2062 struct ref_dir
*loose_dir
, *packed_dir
;
2063 struct ref_iterator
*loose_iter
, *packed_iter
;
2064 struct files_ref_iterator
*iter
;
2065 struct ref_iterator
*ref_iterator
;
2068 return empty_ref_iterator_begin();
2070 if (ref_paranoia
< 0)
2071 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2073 flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2075 iter
= xcalloc(1, sizeof(*iter
));
2076 ref_iterator
= &iter
->base
;
2077 base_ref_iterator_init(ref_iterator
, &files_ref_iterator_vtable
);
2080 * We must make sure that all loose refs are read before
2081 * accessing the packed-refs file; this avoids a race
2082 * condition if loose refs are migrated to the packed-refs
2083 * file by a simultaneous process, but our in-memory view is
2084 * from before the migration. We ensure this as follows:
2085 * First, we call prime_ref_dir(), which pre-reads the loose
2086 * references for the subtree into the cache. (If they've
2087 * already been read, that's OK; we only need to guarantee
2088 * that they're read before the packed refs, not *how much*
2089 * before.) After that, we call get_packed_ref_cache(), which
2090 * internally checks whether the packed-ref cache is up to
2091 * date with what is on disk, and re-reads it if not.
2094 loose_dir
= get_loose_refs(refs
);
2096 if (prefix
&& *prefix
)
2097 loose_dir
= find_containing_dir(loose_dir
, prefix
, 0);
2100 prime_ref_dir(loose_dir
);
2101 loose_iter
= cache_ref_iterator_begin(loose_dir
);
2103 /* There's nothing to iterate over. */
2104 loose_iter
= empty_ref_iterator_begin();
2107 iter
->packed_ref_cache
= get_packed_ref_cache(refs
);
2108 acquire_packed_ref_cache(iter
->packed_ref_cache
);
2109 packed_dir
= get_packed_ref_dir(iter
->packed_ref_cache
);
2111 if (prefix
&& *prefix
)
2112 packed_dir
= find_containing_dir(packed_dir
, prefix
, 0);
2115 packed_iter
= cache_ref_iterator_begin(packed_dir
);
2117 /* There's nothing to iterate over. */
2118 packed_iter
= empty_ref_iterator_begin();
2121 iter
->iter0
= overlay_ref_iterator_begin(loose_iter
, packed_iter
);
2122 iter
->flags
= flags
;
2124 return ref_iterator
;
2128 * Call fn for each reference in the specified ref_cache, omitting
2129 * references not in the containing_dir of prefix. Call fn for all
2130 * references, including broken ones. If fn ever returns a non-zero
2131 * value, stop the iteration and return that value; otherwise, return
2134 static int do_for_each_entry(struct ref_cache
*refs
, const char *prefix
,
2135 each_ref_entry_fn fn
, void *cb_data
)
2137 struct packed_ref_cache
*packed_ref_cache
;
2138 struct ref_dir
*loose_dir
;
2139 struct ref_dir
*packed_dir
;
2143 * We must make sure that all loose refs are read before accessing the
2144 * packed-refs file; this avoids a race condition in which loose refs
2145 * are migrated to the packed-refs file by a simultaneous process, but
2146 * our in-memory view is from before the migration. get_packed_ref_cache()
2147 * takes care of making sure our view is up to date with what is on
2150 loose_dir
= get_loose_refs(refs
);
2151 if (prefix
&& *prefix
) {
2152 loose_dir
= find_containing_dir(loose_dir
, prefix
, 0);
2155 prime_ref_dir(loose_dir
);
2157 packed_ref_cache
= get_packed_ref_cache(refs
);
2158 acquire_packed_ref_cache(packed_ref_cache
);
2159 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
2160 if (prefix
&& *prefix
) {
2161 packed_dir
= find_containing_dir(packed_dir
, prefix
, 0);
2164 if (packed_dir
&& loose_dir
) {
2165 sort_ref_dir(packed_dir
);
2166 sort_ref_dir(loose_dir
);
2167 retval
= do_for_each_entry_in_dirs(
2168 packed_dir
, loose_dir
, fn
, cb_data
);
2169 } else if (packed_dir
) {
2170 sort_ref_dir(packed_dir
);
2171 retval
= do_for_each_entry_in_dir(
2172 packed_dir
, 0, fn
, cb_data
);
2173 } else if (loose_dir
) {
2174 sort_ref_dir(loose_dir
);
2175 retval
= do_for_each_entry_in_dir(
2176 loose_dir
, 0, fn
, cb_data
);
2179 release_packed_ref_cache(packed_ref_cache
);
2183 int do_for_each_ref(const char *submodule
, const char *prefix
,
2184 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
2186 struct ref_entry_cb data
;
2187 struct ref_cache
*refs
;
2189 refs
= get_ref_cache(submodule
);
2193 data
.prefix
= prefix
;
2197 data
.cb_data
= cb_data
;
2199 if (ref_paranoia
< 0)
2200 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2202 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2204 return do_for_each_entry(refs
, prefix
, do_one_ref
, &data
);
2208 * Verify that the reference locked by lock has the value old_sha1.
2209 * Fail if the reference doesn't exist and mustexist is set. Return 0
2210 * on success. On error, write an error message to err, set errno, and
2211 * return a negative value.
2213 static int verify_lock(struct ref_lock
*lock
,
2214 const unsigned char *old_sha1
, int mustexist
,
2219 if (read_ref_full(lock
->ref_name
,
2220 mustexist ? RESOLVE_REF_READING
: 0,
2221 lock
->old_oid
.hash
, NULL
)) {
2223 int save_errno
= errno
;
2224 strbuf_addf(err
, "can't verify ref '%s'", lock
->ref_name
);
2228 hashclr(lock
->old_oid
.hash
);
2232 if (old_sha1
&& hashcmp(lock
->old_oid
.hash
, old_sha1
)) {
2233 strbuf_addf(err
, "ref '%s' is at %s but expected %s",
2235 sha1_to_hex(lock
->old_oid
.hash
),
2236 sha1_to_hex(old_sha1
));
2243 static int remove_empty_directories(struct strbuf
*path
)
2246 * we want to create a file but there is a directory there;
2247 * if that is an empty directory (or a directory that contains
2248 * only empty directories), remove them.
2250 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
2254 * Locks a ref returning the lock on success and NULL on failure.
2255 * On failure errno is set to something meaningful.
2257 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2258 const unsigned char *old_sha1
,
2259 const struct string_list
*extras
,
2260 const struct string_list
*skip
,
2261 unsigned int flags
, int *type
,
2264 struct strbuf ref_file
= STRBUF_INIT
;
2265 struct ref_lock
*lock
;
2267 int lflags
= LOCK_NO_DEREF
;
2268 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2269 int resolve_flags
= RESOLVE_REF_NO_RECURSE
;
2270 int attempts_remaining
= 3;
2275 lock
= xcalloc(1, sizeof(struct ref_lock
));
2278 resolve_flags
|= RESOLVE_REF_READING
;
2279 if (flags
& REF_DELETING
)
2280 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2282 strbuf_git_path(&ref_file
, "%s", refname
);
2283 resolved
= !!resolve_ref_unsafe(refname
, resolve_flags
,
2284 lock
->old_oid
.hash
, type
);
2285 if (!resolved
&& errno
== EISDIR
) {
2287 * we are trying to lock foo but we used to
2288 * have foo/bar which now does not exist;
2289 * it is normal for the empty directory 'foo'
2292 if (remove_empty_directories(&ref_file
)) {
2294 if (!verify_refname_available_dir(refname
, extras
, skip
,
2295 get_loose_refs(&ref_cache
), err
))
2296 strbuf_addf(err
, "there are still refs under '%s'",
2300 resolved
= !!resolve_ref_unsafe(refname
, resolve_flags
,
2301 lock
->old_oid
.hash
, type
);
2305 if (last_errno
!= ENOTDIR
||
2306 !verify_refname_available_dir(refname
, extras
, skip
,
2307 get_loose_refs(&ref_cache
), err
))
2308 strbuf_addf(err
, "unable to resolve reference '%s': %s",
2309 refname
, strerror(last_errno
));
2315 * If the ref did not exist and we are creating it, make sure
2316 * there is no existing packed ref whose name begins with our
2317 * refname, nor a packed ref whose name is a proper prefix of
2320 if (is_null_oid(&lock
->old_oid
) &&
2321 verify_refname_available_dir(refname
, extras
, skip
,
2322 get_packed_refs(&ref_cache
), err
)) {
2323 last_errno
= ENOTDIR
;
2327 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2329 lock
->ref_name
= xstrdup(refname
);
2332 switch (safe_create_leading_directories_const(ref_file
.buf
)) {
2334 break; /* success */
2336 if (--attempts_remaining
> 0)
2341 strbuf_addf(err
, "unable to create directory for '%s'",
2346 if (hold_lock_file_for_update(lock
->lk
, ref_file
.buf
, lflags
) < 0) {
2348 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2350 * Maybe somebody just deleted one of the
2351 * directories leading to ref_file. Try
2356 unable_to_lock_message(ref_file
.buf
, errno
, err
);
2360 if (verify_lock(lock
, old_sha1
, mustexist
, err
)) {
2371 strbuf_release(&ref_file
);
2377 * Write an entry to the packed-refs file for the specified refname.
2378 * If peeled is non-NULL, write it as the entry's peeled value.
2380 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2381 unsigned char *peeled
)
2383 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2385 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2389 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2391 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2393 enum peel_status peel_status
= peel_entry(entry
, 0);
2395 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2396 error("internal error: %s is not a valid packed reference!",
2398 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.oid
.hash
,
2399 peel_status
== PEEL_PEELED ?
2400 entry
->u
.value
.peeled
.hash
: NULL
);
2405 * Lock the packed-refs file for writing. Flags is passed to
2406 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2407 * errno appropriately and return a nonzero value.
2409 static int lock_packed_refs(int flags
)
2411 static int timeout_configured
= 0;
2412 static int timeout_value
= 1000;
2414 struct packed_ref_cache
*packed_ref_cache
;
2416 if (!timeout_configured
) {
2417 git_config_get_int("core.packedrefstimeout", &timeout_value
);
2418 timeout_configured
= 1;
2421 if (hold_lock_file_for_update_timeout(
2422 &packlock
, git_path("packed-refs"),
2423 flags
, timeout_value
) < 0)
2426 * Get the current packed-refs while holding the lock. If the
2427 * packed-refs file has been modified since we last read it,
2428 * this will automatically invalidate the cache and re-read
2429 * the packed-refs file.
2431 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2432 packed_ref_cache
->lock
= &packlock
;
2433 /* Increment the reference count to prevent it from being freed: */
2434 acquire_packed_ref_cache(packed_ref_cache
);
2439 * Write the current version of the packed refs cache from memory to
2440 * disk. The packed-refs file must already be locked for writing (see
2441 * lock_packed_refs()). Return zero on success. On errors, set errno
2442 * and return a nonzero value
2444 static int commit_packed_refs(void)
2446 struct packed_ref_cache
*packed_ref_cache
=
2447 get_packed_ref_cache(&ref_cache
);
2452 if (!packed_ref_cache
->lock
)
2453 die("internal error: packed-refs not locked");
2455 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2457 die_errno("unable to fdopen packed-refs descriptor");
2459 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2460 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2461 0, write_packed_entry_fn
, out
);
2463 if (commit_lock_file(packed_ref_cache
->lock
)) {
2467 packed_ref_cache
->lock
= NULL
;
2468 release_packed_ref_cache(packed_ref_cache
);
2474 * Rollback the lockfile for the packed-refs file, and discard the
2475 * in-memory packed reference cache. (The packed-refs file will be
2476 * read anew if it is needed again after this function is called.)
2478 static void rollback_packed_refs(void)
2480 struct packed_ref_cache
*packed_ref_cache
=
2481 get_packed_ref_cache(&ref_cache
);
2483 if (!packed_ref_cache
->lock
)
2484 die("internal error: packed-refs not locked");
2485 rollback_lock_file(packed_ref_cache
->lock
);
2486 packed_ref_cache
->lock
= NULL
;
2487 release_packed_ref_cache(packed_ref_cache
);
2488 clear_packed_ref_cache(&ref_cache
);
2491 struct ref_to_prune
{
2492 struct ref_to_prune
*next
;
2493 unsigned char sha1
[20];
2494 char name
[FLEX_ARRAY
];
2497 struct pack_refs_cb_data
{
2499 struct ref_dir
*packed_refs
;
2500 struct ref_to_prune
*ref_to_prune
;
2504 * An each_ref_entry_fn that is run over loose references only. If
2505 * the loose reference can be packed, add an entry in the packed ref
2506 * cache. If the reference should be pruned, also add it to
2507 * ref_to_prune in the pack_refs_cb_data.
2509 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2511 struct pack_refs_cb_data
*cb
= cb_data
;
2512 enum peel_status peel_status
;
2513 struct ref_entry
*packed_entry
;
2514 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2516 /* Do not pack per-worktree refs: */
2517 if (ref_type(entry
->name
) != REF_TYPE_NORMAL
)
2520 /* ALWAYS pack tags */
2521 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2524 /* Do not pack symbolic or broken refs: */
2525 if ((entry
->flag
& REF_ISSYMREF
) || !entry_resolves_to_object(entry
))
2528 /* Add a packed ref cache entry equivalent to the loose entry. */
2529 peel_status
= peel_entry(entry
, 1);
2530 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2531 die("internal error peeling reference %s (%s)",
2532 entry
->name
, oid_to_hex(&entry
->u
.value
.oid
));
2533 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2535 /* Overwrite existing packed entry with info from loose entry */
2536 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2537 oidcpy(&packed_entry
->u
.value
.oid
, &entry
->u
.value
.oid
);
2539 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.oid
.hash
,
2540 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2541 add_ref(cb
->packed_refs
, packed_entry
);
2543 oidcpy(&packed_entry
->u
.value
.peeled
, &entry
->u
.value
.peeled
);
2545 /* Schedule the loose reference for pruning if requested. */
2546 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2547 struct ref_to_prune
*n
;
2548 FLEX_ALLOC_STR(n
, name
, entry
->name
);
2549 hashcpy(n
->sha1
, entry
->u
.value
.oid
.hash
);
2550 n
->next
= cb
->ref_to_prune
;
2551 cb
->ref_to_prune
= n
;
2557 * Remove empty parents, but spare refs/ and immediate subdirs.
2558 * Note: munges *name.
2560 static void try_remove_empty_parents(char *name
)
2565 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2566 while (*p
&& *p
!= '/')
2568 /* tolerate duplicate slashes; see check_refname_format() */
2572 for (q
= p
; *q
; q
++)
2575 while (q
> p
&& *q
!= '/')
2577 while (q
> p
&& *(q
-1) == '/')
2582 if (rmdir(git_path("%s", name
)))
2587 /* make sure nobody touched the ref, and unlink */
2588 static void prune_ref(struct ref_to_prune
*r
)
2590 struct ref_transaction
*transaction
;
2591 struct strbuf err
= STRBUF_INIT
;
2593 if (check_refname_format(r
->name
, 0))
2596 transaction
= ref_transaction_begin(&err
);
2598 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2599 REF_ISPRUNING
| REF_NODEREF
, NULL
, &err
) ||
2600 ref_transaction_commit(transaction
, &err
)) {
2601 ref_transaction_free(transaction
);
2602 error("%s", err
.buf
);
2603 strbuf_release(&err
);
2606 ref_transaction_free(transaction
);
2607 strbuf_release(&err
);
2608 try_remove_empty_parents(r
->name
);
2611 static void prune_refs(struct ref_to_prune
*r
)
2619 int pack_refs(unsigned int flags
)
2621 struct pack_refs_cb_data cbdata
;
2623 memset(&cbdata
, 0, sizeof(cbdata
));
2624 cbdata
.flags
= flags
;
2626 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2627 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2629 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2630 pack_if_possible_fn
, &cbdata
);
2632 if (commit_packed_refs())
2633 die_errno("unable to overwrite old ref-pack file");
2635 prune_refs(cbdata
.ref_to_prune
);
2640 * Rewrite the packed-refs file, omitting any refs listed in
2641 * 'refnames'. On error, leave packed-refs unchanged, write an error
2642 * message to 'err', and return a nonzero value.
2644 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2646 static int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2648 struct ref_dir
*packed
;
2649 struct string_list_item
*refname
;
2650 int ret
, needs_repacking
= 0, removed
= 0;
2654 /* Look for a packed ref */
2655 for_each_string_list_item(refname
, refnames
) {
2656 if (get_packed_ref(refname
->string
)) {
2657 needs_repacking
= 1;
2662 /* Avoid locking if we have nothing to do */
2663 if (!needs_repacking
)
2664 return 0; /* no refname exists in packed refs */
2666 if (lock_packed_refs(0)) {
2667 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2670 packed
= get_packed_refs(&ref_cache
);
2672 /* Remove refnames from the cache */
2673 for_each_string_list_item(refname
, refnames
)
2674 if (remove_entry(packed
, refname
->string
) != -1)
2678 * All packed entries disappeared while we were
2679 * acquiring the lock.
2681 rollback_packed_refs();
2685 /* Write what remains */
2686 ret
= commit_packed_refs();
2688 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2693 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2697 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2699 * loose. The loose file name is the same as the
2700 * lockfile name, minus ".lock":
2702 char *loose_filename
= get_locked_file_path(lock
->lk
);
2703 int res
= unlink_or_msg(loose_filename
, err
);
2704 free(loose_filename
);
2711 int delete_refs(struct string_list
*refnames
, unsigned int flags
)
2713 struct strbuf err
= STRBUF_INIT
;
2719 result
= repack_without_refs(refnames
, &err
);
2722 * If we failed to rewrite the packed-refs file, then
2723 * it is unsafe to try to remove loose refs, because
2724 * doing so might expose an obsolete packed value for
2725 * a reference that might even point at an object that
2726 * has been garbage collected.
2728 if (refnames
->nr
== 1)
2729 error(_("could not delete reference %s: %s"),
2730 refnames
->items
[0].string
, err
.buf
);
2732 error(_("could not delete references: %s"), err
.buf
);
2737 for (i
= 0; i
< refnames
->nr
; i
++) {
2738 const char *refname
= refnames
->items
[i
].string
;
2740 if (delete_ref(refname
, NULL
, flags
))
2741 result
|= error(_("could not remove reference %s"), refname
);
2745 strbuf_release(&err
);
2750 * People using contrib's git-new-workdir have .git/logs/refs ->
2751 * /some/other/path/.git/logs/refs, and that may live on another device.
2753 * IOW, to avoid cross device rename errors, the temporary renamed log must
2754 * live into logs/refs.
2756 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2758 static int rename_tmp_log(const char *newrefname
)
2760 int attempts_remaining
= 4;
2761 struct strbuf path
= STRBUF_INIT
;
2765 strbuf_reset(&path
);
2766 strbuf_git_path(&path
, "logs/%s", newrefname
);
2767 switch (safe_create_leading_directories_const(path
.buf
)) {
2769 break; /* success */
2771 if (--attempts_remaining
> 0)
2775 error("unable to create directory for %s", newrefname
);
2779 if (rename(git_path(TMP_RENAMED_LOG
), path
.buf
)) {
2780 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2782 * rename(a, b) when b is an existing
2783 * directory ought to result in ISDIR, but
2784 * Solaris 5.8 gives ENOTDIR. Sheesh.
2786 if (remove_empty_directories(&path
)) {
2787 error("Directory not empty: logs/%s", newrefname
);
2791 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2793 * Maybe another process just deleted one of
2794 * the directories in the path to newrefname.
2795 * Try again from the beginning.
2799 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2800 newrefname
, strerror(errno
));
2806 strbuf_release(&path
);
2810 int verify_refname_available(const char *newname
,
2811 const struct string_list
*extras
,
2812 const struct string_list
*skip
,
2815 struct ref_dir
*packed_refs
= get_packed_refs(&ref_cache
);
2816 struct ref_dir
*loose_refs
= get_loose_refs(&ref_cache
);
2818 if (verify_refname_available_dir(newname
, extras
, skip
,
2819 packed_refs
, err
) ||
2820 verify_refname_available_dir(newname
, extras
, skip
,
2827 static int write_ref_to_lockfile(struct ref_lock
*lock
,
2828 const unsigned char *sha1
, struct strbuf
*err
);
2829 static int commit_ref_update(struct ref_lock
*lock
,
2830 const unsigned char *sha1
, const char *logmsg
,
2831 struct strbuf
*err
);
2833 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2835 unsigned char sha1
[20], orig_sha1
[20];
2836 int flag
= 0, logmoved
= 0;
2837 struct ref_lock
*lock
;
2838 struct stat loginfo
;
2839 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2840 struct strbuf err
= STRBUF_INIT
;
2842 if (log
&& S_ISLNK(loginfo
.st_mode
))
2843 return error("reflog for %s is a symlink", oldrefname
);
2845 if (!resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
2847 return error("refname %s not found", oldrefname
);
2849 if (flag
& REF_ISSYMREF
)
2850 return error("refname %s is a symbolic ref, renaming it is not supported",
2852 if (!rename_ref_available(oldrefname
, newrefname
))
2855 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2856 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2857 oldrefname
, strerror(errno
));
2859 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2860 error("unable to delete old %s", oldrefname
);
2865 * Since we are doing a shallow lookup, sha1 is not the
2866 * correct value to pass to delete_ref as old_sha1. But that
2867 * doesn't matter, because an old_sha1 check wouldn't add to
2868 * the safety anyway; we want to delete the reference whatever
2869 * its current value.
2871 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
2873 delete_ref(newrefname
, NULL
, REF_NODEREF
)) {
2874 if (errno
==EISDIR
) {
2875 struct strbuf path
= STRBUF_INIT
;
2878 strbuf_git_path(&path
, "%s", newrefname
);
2879 result
= remove_empty_directories(&path
);
2880 strbuf_release(&path
);
2883 error("Directory not empty: %s", newrefname
);
2887 error("unable to delete existing %s", newrefname
);
2892 if (log
&& rename_tmp_log(newrefname
))
2897 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, REF_NODEREF
,
2900 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
2901 strbuf_release(&err
);
2904 hashcpy(lock
->old_oid
.hash
, orig_sha1
);
2906 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
2907 commit_ref_update(lock
, orig_sha1
, logmsg
, &err
)) {
2908 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
2909 strbuf_release(&err
);
2916 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, REF_NODEREF
,
2919 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
2920 strbuf_release(&err
);
2924 flag
= log_all_ref_updates
;
2925 log_all_ref_updates
= 0;
2926 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
2927 commit_ref_update(lock
, orig_sha1
, NULL
, &err
)) {
2928 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
2929 strbuf_release(&err
);
2931 log_all_ref_updates
= flag
;
2934 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2935 error("unable to restore logfile %s from %s: %s",
2936 oldrefname
, newrefname
, strerror(errno
));
2937 if (!logmoved
&& log
&&
2938 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2939 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2940 oldrefname
, strerror(errno
));
2945 static int close_ref(struct ref_lock
*lock
)
2947 if (close_lock_file(lock
->lk
))
2952 static int commit_ref(struct ref_lock
*lock
)
2954 char *path
= get_locked_file_path(lock
->lk
);
2957 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
2959 * There is a directory at the path we want to rename
2960 * the lockfile to. Hopefully it is empty; try to
2963 size_t len
= strlen(path
);
2964 struct strbuf sb_path
= STRBUF_INIT
;
2966 strbuf_attach(&sb_path
, path
, len
, len
);
2969 * If this fails, commit_lock_file() will also fail
2970 * and will report the problem.
2972 remove_empty_directories(&sb_path
);
2973 strbuf_release(&sb_path
);
2978 if (commit_lock_file(lock
->lk
))
2984 * Create a reflog for a ref. If force_create = 0, the reflog will
2985 * only be created for certain refs (those for which
2986 * should_autocreate_reflog returns non-zero. Otherwise, create it
2987 * regardless of the ref name. Fill in *err and return -1 on failure.
2989 static int log_ref_setup(const char *refname
, struct strbuf
*logfile
, struct strbuf
*err
, int force_create
)
2991 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2993 strbuf_git_path(logfile
, "logs/%s", refname
);
2994 if (force_create
|| should_autocreate_reflog(refname
)) {
2995 if (safe_create_leading_directories(logfile
->buf
) < 0) {
2996 strbuf_addf(err
, "unable to create directory for '%s': "
2997 "%s", logfile
->buf
, strerror(errno
));
3003 logfd
= open(logfile
->buf
, oflags
, 0666);
3005 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3008 if (errno
== EISDIR
) {
3009 if (remove_empty_directories(logfile
)) {
3010 strbuf_addf(err
, "there are still logs under "
3011 "'%s'", logfile
->buf
);
3014 logfd
= open(logfile
->buf
, oflags
, 0666);
3018 strbuf_addf(err
, "unable to append to '%s': %s",
3019 logfile
->buf
, strerror(errno
));
3024 adjust_shared_perm(logfile
->buf
);
3030 int safe_create_reflog(const char *refname
, int force_create
, struct strbuf
*err
)
3033 struct strbuf sb
= STRBUF_INIT
;
3035 ret
= log_ref_setup(refname
, &sb
, err
, force_create
);
3036 strbuf_release(&sb
);
3040 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3041 const unsigned char *new_sha1
,
3042 const char *committer
, const char *msg
)
3044 int msglen
, written
;
3045 unsigned maxlen
, len
;
3048 msglen
= msg ?
strlen(msg
) : 0;
3049 maxlen
= strlen(committer
) + msglen
+ 100;
3050 logrec
= xmalloc(maxlen
);
3051 len
= xsnprintf(logrec
, maxlen
, "%s %s %s\n",
3052 sha1_to_hex(old_sha1
),
3053 sha1_to_hex(new_sha1
),
3056 len
+= copy_reflog_msg(logrec
+ len
- 1, msg
) - 1;
3058 written
= len
<= maxlen ?
write_in_full(fd
, logrec
, len
) : -1;
3066 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
3067 const unsigned char *new_sha1
, const char *msg
,
3068 struct strbuf
*logfile
, int flags
,
3071 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3073 if (log_all_ref_updates
< 0)
3074 log_all_ref_updates
= !is_bare_repository();
3076 result
= log_ref_setup(refname
, logfile
, err
, flags
& REF_FORCE_CREATE_REFLOG
);
3081 logfd
= open(logfile
->buf
, oflags
);
3084 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3085 git_committer_info(0), msg
);
3087 strbuf_addf(err
, "unable to append to '%s': %s", logfile
->buf
,
3093 strbuf_addf(err
, "unable to append to '%s': %s", logfile
->buf
,
3100 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3101 const unsigned char *new_sha1
, const char *msg
,
3102 int flags
, struct strbuf
*err
)
3104 return files_log_ref_write(refname
, old_sha1
, new_sha1
, msg
, flags
,
3108 int files_log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3109 const unsigned char *new_sha1
, const char *msg
,
3110 int flags
, struct strbuf
*err
)
3112 struct strbuf sb
= STRBUF_INIT
;
3113 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
, flags
,
3115 strbuf_release(&sb
);
3120 * Write sha1 into the open lockfile, then close the lockfile. On
3121 * errors, rollback the lockfile, fill in *err and
3124 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3125 const unsigned char *sha1
, struct strbuf
*err
)
3127 static char term
= '\n';
3131 o
= parse_object(sha1
);
3134 "trying to write ref '%s' with nonexistent object %s",
3135 lock
->ref_name
, sha1_to_hex(sha1
));
3139 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3141 "trying to write non-commit object %s to branch '%s'",
3142 sha1_to_hex(sha1
), lock
->ref_name
);
3146 fd
= get_lock_file_fd(lock
->lk
);
3147 if (write_in_full(fd
, sha1_to_hex(sha1
), 40) != 40 ||
3148 write_in_full(fd
, &term
, 1) != 1 ||
3149 close_ref(lock
) < 0) {
3151 "couldn't write '%s'", get_lock_file_path(lock
->lk
));
3159 * Commit a change to a loose reference that has already been written
3160 * to the loose reference lockfile. Also update the reflogs if
3161 * necessary, using the specified lockmsg (which can be NULL).
3163 static int commit_ref_update(struct ref_lock
*lock
,
3164 const unsigned char *sha1
, const char *logmsg
,
3167 clear_loose_ref_cache(&ref_cache
);
3168 if (log_ref_write(lock
->ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, 0, err
)) {
3169 char *old_msg
= strbuf_detach(err
, NULL
);
3170 strbuf_addf(err
, "cannot update the ref '%s': %s",
3171 lock
->ref_name
, old_msg
);
3177 if (strcmp(lock
->ref_name
, "HEAD") != 0) {
3179 * Special hack: If a branch is updated directly and HEAD
3180 * points to it (may happen on the remote side of a push
3181 * for example) then logically the HEAD reflog should be
3183 * A generic solution implies reverse symref information,
3184 * but finding all symrefs pointing to the given branch
3185 * would be rather costly for this rare event (the direct
3186 * update of a branch) to be worth it. So let's cheat and
3187 * check with HEAD only which should cover 99% of all usage
3188 * scenarios (even 100% of the default ones).
3190 unsigned char head_sha1
[20];
3192 const char *head_ref
;
3194 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3195 head_sha1
, &head_flag
);
3196 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3197 !strcmp(head_ref
, lock
->ref_name
)) {
3198 struct strbuf log_err
= STRBUF_INIT
;
3199 if (log_ref_write("HEAD", lock
->old_oid
.hash
, sha1
,
3200 logmsg
, 0, &log_err
)) {
3201 error("%s", log_err
.buf
);
3202 strbuf_release(&log_err
);
3207 if (commit_ref(lock
)) {
3208 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
3217 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
3220 #ifndef NO_SYMLINK_HEAD
3221 char *ref_path
= get_locked_file_path(lock
->lk
);
3223 ret
= symlink(target
, ref_path
);
3227 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3232 static void update_symref_reflog(struct ref_lock
*lock
, const char *refname
,
3233 const char *target
, const char *logmsg
)
3235 struct strbuf err
= STRBUF_INIT
;
3236 unsigned char new_sha1
[20];
3237 if (logmsg
&& !read_ref(target
, new_sha1
) &&
3238 log_ref_write(refname
, lock
->old_oid
.hash
, new_sha1
, logmsg
, 0, &err
)) {
3239 error("%s", err
.buf
);
3240 strbuf_release(&err
);
3244 static int create_symref_locked(struct ref_lock
*lock
, const char *refname
,
3245 const char *target
, const char *logmsg
)
3247 if (prefer_symlink_refs
&& !create_ref_symlink(lock
, target
)) {
3248 update_symref_reflog(lock
, refname
, target
, logmsg
);
3252 if (!fdopen_lock_file(lock
->lk
, "w"))
3253 return error("unable to fdopen %s: %s",
3254 lock
->lk
->tempfile
.filename
.buf
, strerror(errno
));
3256 update_symref_reflog(lock
, refname
, target
, logmsg
);
3258 /* no error check; commit_ref will check ferror */
3259 fprintf(lock
->lk
->tempfile
.fp
, "ref: %s\n", target
);
3260 if (commit_ref(lock
) < 0)
3261 return error("unable to write symref for %s: %s", refname
,
3266 int create_symref(const char *refname
, const char *target
, const char *logmsg
)
3268 struct strbuf err
= STRBUF_INIT
;
3269 struct ref_lock
*lock
;
3272 lock
= lock_ref_sha1_basic(refname
, NULL
, NULL
, NULL
, REF_NODEREF
, NULL
,
3275 error("%s", err
.buf
);
3276 strbuf_release(&err
);
3280 ret
= create_symref_locked(lock
, refname
, target
, logmsg
);
3285 int set_worktree_head_symref(const char *gitdir
, const char *target
)
3287 static struct lock_file head_lock
;
3288 struct ref_lock
*lock
;
3289 struct strbuf head_path
= STRBUF_INIT
;
3290 const char *head_rel
;
3293 strbuf_addf(&head_path
, "%s/HEAD", absolute_path(gitdir
));
3294 if (hold_lock_file_for_update(&head_lock
, head_path
.buf
,
3295 LOCK_NO_DEREF
) < 0) {
3296 struct strbuf err
= STRBUF_INIT
;
3297 unable_to_lock_message(head_path
.buf
, errno
, &err
);
3298 error("%s", err
.buf
);
3299 strbuf_release(&err
);
3300 strbuf_release(&head_path
);
3304 /* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for
3306 head_rel
= remove_leading_path(head_path
.buf
,
3307 absolute_path(get_git_common_dir()));
3308 /* to make use of create_symref_locked(), initialize ref_lock */
3309 lock
= xcalloc(1, sizeof(struct ref_lock
));
3310 lock
->lk
= &head_lock
;
3311 lock
->ref_name
= xstrdup(head_rel
);
3313 ret
= create_symref_locked(lock
, head_rel
, target
, NULL
);
3315 unlock_ref(lock
); /* will free lock */
3316 strbuf_release(&head_path
);
3320 int reflog_exists(const char *refname
)
3324 return !lstat(git_path("logs/%s", refname
), &st
) &&
3325 S_ISREG(st
.st_mode
);
3328 int delete_reflog(const char *refname
)
3330 return remove_path(git_path("logs/%s", refname
));
3333 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3335 unsigned char osha1
[20], nsha1
[20];
3336 char *email_end
, *message
;
3337 unsigned long timestamp
;
3340 /* old SP new SP name <email> SP time TAB msg LF */
3341 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3342 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3343 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3344 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3345 email_end
[1] != ' ' ||
3346 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3347 !message
|| message
[0] != ' ' ||
3348 (message
[1] != '+' && message
[1] != '-') ||
3349 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3350 !isdigit(message
[4]) || !isdigit(message
[5]))
3351 return 0; /* corrupt? */
3352 email_end
[1] = '\0';
3353 tz
= strtol(message
+ 1, NULL
, 10);
3354 if (message
[6] != '\t')
3358 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3361 static char *find_beginning_of_line(char *bob
, char *scan
)
3363 while (bob
< scan
&& *(--scan
) != '\n')
3364 ; /* keep scanning backwards */
3366 * Return either beginning of the buffer, or LF at the end of
3367 * the previous line.
3372 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3374 struct strbuf sb
= STRBUF_INIT
;
3377 int ret
= 0, at_tail
= 1;
3379 logfp
= fopen(git_path("logs/%s", refname
), "r");
3383 /* Jump to the end */
3384 if (fseek(logfp
, 0, SEEK_END
) < 0)
3385 return error("cannot seek back reflog for %s: %s",
3386 refname
, strerror(errno
));
3388 while (!ret
&& 0 < pos
) {
3394 /* Fill next block from the end */
3395 cnt
= (sizeof(buf
) < pos
) ?
sizeof(buf
) : pos
;
3396 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3397 return error("cannot seek back reflog for %s: %s",
3398 refname
, strerror(errno
));
3399 nread
= fread(buf
, cnt
, 1, logfp
);
3401 return error("cannot read %d bytes from reflog for %s: %s",
3402 cnt
, refname
, strerror(errno
));
3405 scanp
= endp
= buf
+ cnt
;
3406 if (at_tail
&& scanp
[-1] == '\n')
3407 /* Looking at the final LF at the end of the file */
3411 while (buf
< scanp
) {
3413 * terminating LF of the previous line, or the beginning
3418 bp
= find_beginning_of_line(buf
, scanp
);
3422 * The newline is the end of the previous line,
3423 * so we know we have complete line starting
3424 * at (bp + 1). Prefix it onto any prior data
3425 * we collected for the line and process it.
3427 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3430 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3436 * We are at the start of the buffer, and the
3437 * start of the file; there is no previous
3438 * line, and we have everything for this one.
3439 * Process it, and we can end the loop.
3441 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3442 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3449 * We are at the start of the buffer, and there
3450 * is more file to read backwards. Which means
3451 * we are in the middle of a line. Note that we
3452 * may get here even if *bp was a newline; that
3453 * just means we are at the exact end of the
3454 * previous line, rather than some spot in the
3457 * Save away what we have to be combined with
3458 * the data from the next read.
3460 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3467 die("BUG: reverse reflog parser had leftover data");
3470 strbuf_release(&sb
);
3474 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3477 struct strbuf sb
= STRBUF_INIT
;
3480 logfp
= fopen(git_path("logs/%s", refname
), "r");
3484 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3485 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3487 strbuf_release(&sb
);
3491 * Call fn for each reflog in the namespace indicated by name. name
3492 * must be empty or end with '/'. Name will be used as a scratch
3493 * space, but its contents will be restored before return.
3495 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3497 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3500 int oldlen
= name
->len
;
3503 return name
->len ? errno
: 0;
3505 while ((de
= readdir(d
)) != NULL
) {
3508 if (de
->d_name
[0] == '.')
3510 if (ends_with(de
->d_name
, ".lock"))
3512 strbuf_addstr(name
, de
->d_name
);
3513 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3514 ; /* silently ignore */
3516 if (S_ISDIR(st
.st_mode
)) {
3517 strbuf_addch(name
, '/');
3518 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3520 struct object_id oid
;
3522 if (read_ref_full(name
->buf
, 0, oid
.hash
, NULL
))
3523 retval
= error("bad ref for %s", name
->buf
);
3525 retval
= fn(name
->buf
, &oid
, 0, cb_data
);
3530 strbuf_setlen(name
, oldlen
);
3536 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3540 strbuf_init(&name
, PATH_MAX
);
3541 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3542 strbuf_release(&name
);
3546 static int ref_update_reject_duplicates(struct string_list
*refnames
,
3549 int i
, n
= refnames
->nr
;
3553 for (i
= 1; i
< n
; i
++)
3554 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
3556 "multiple updates for ref '%s' not allowed.",
3557 refnames
->items
[i
].string
);
3564 * If update is a direct update of head_ref (the reference pointed to
3565 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
3567 static int split_head_update(struct ref_update
*update
,
3568 struct ref_transaction
*transaction
,
3569 const char *head_ref
,
3570 struct string_list
*affected_refnames
,
3573 struct string_list_item
*item
;
3574 struct ref_update
*new_update
;
3576 if ((update
->flags
& REF_LOG_ONLY
) ||
3577 (update
->flags
& REF_ISPRUNING
) ||
3578 (update
->flags
& REF_UPDATE_VIA_HEAD
))
3581 if (strcmp(update
->refname
, head_ref
))
3585 * First make sure that HEAD is not already in the
3586 * transaction. This insertion is O(N) in the transaction
3587 * size, but it happens at most once per transaction.
3589 item
= string_list_insert(affected_refnames
, "HEAD");
3591 /* An entry already existed */
3593 "multiple updates for 'HEAD' (including one "
3594 "via its referent '%s') are not allowed",
3596 return TRANSACTION_NAME_CONFLICT
;
3599 new_update
= ref_transaction_add_update(
3600 transaction
, "HEAD",
3601 update
->flags
| REF_LOG_ONLY
| REF_NODEREF
,
3602 update
->new_sha1
, update
->old_sha1
,
3605 item
->util
= new_update
;
3611 * update is for a symref that points at referent and doesn't have
3612 * REF_NODEREF set. Split it into two updates:
3613 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
3614 * - A new, separate update for the referent reference
3615 * Note that the new update will itself be subject to splitting when
3616 * the iteration gets to it.
3618 static int split_symref_update(struct ref_update
*update
,
3619 const char *referent
,
3620 struct ref_transaction
*transaction
,
3621 struct string_list
*affected_refnames
,
3624 struct string_list_item
*item
;
3625 struct ref_update
*new_update
;
3626 unsigned int new_flags
;
3629 * First make sure that referent is not already in the
3630 * transaction. This insertion is O(N) in the transaction
3631 * size, but it happens at most once per symref in a
3634 item
= string_list_insert(affected_refnames
, referent
);
3636 /* An entry already existed */
3638 "multiple updates for '%s' (including one "
3639 "via symref '%s') are not allowed",
3640 referent
, update
->refname
);
3641 return TRANSACTION_NAME_CONFLICT
;
3644 new_flags
= update
->flags
;
3645 if (!strcmp(update
->refname
, "HEAD")) {
3647 * Record that the new update came via HEAD, so that
3648 * when we process it, split_head_update() doesn't try
3649 * to add another reflog update for HEAD. Note that
3650 * this bit will be propagated if the new_update
3651 * itself needs to be split.
3653 new_flags
|= REF_UPDATE_VIA_HEAD
;
3656 new_update
= ref_transaction_add_update(
3657 transaction
, referent
, new_flags
,
3658 update
->new_sha1
, update
->old_sha1
,
3661 new_update
->parent_update
= update
;
3664 * Change the symbolic ref update to log only. Also, it
3665 * doesn't need to check its old SHA-1 value, as that will be
3666 * done when new_update is processed.
3668 update
->flags
|= REF_LOG_ONLY
| REF_NODEREF
;
3669 update
->flags
&= ~REF_HAVE_OLD
;
3671 item
->util
= new_update
;
3677 * Return the refname under which update was originally requested.
3679 static const char *original_update_refname(struct ref_update
*update
)
3681 while (update
->parent_update
)
3682 update
= update
->parent_update
;
3684 return update
->refname
;
3688 * Prepare for carrying out update:
3689 * - Lock the reference referred to by update.
3690 * - Read the reference under lock.
3691 * - Check that its old SHA-1 value (if specified) is correct, and in
3692 * any case record it in update->lock->old_oid for later use when
3693 * writing the reflog.
3694 * - If it is a symref update without REF_NODEREF, split it up into a
3695 * REF_LOG_ONLY update of the symref and add a separate update for
3696 * the referent to transaction.
3697 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
3700 static int lock_ref_for_update(struct ref_update
*update
,
3701 struct ref_transaction
*transaction
,
3702 const char *head_ref
,
3703 struct string_list
*affected_refnames
,
3706 struct strbuf referent
= STRBUF_INIT
;
3707 int mustexist
= (update
->flags
& REF_HAVE_OLD
) &&
3708 !is_null_sha1(update
->old_sha1
);
3710 struct ref_lock
*lock
;
3712 if ((update
->flags
& REF_HAVE_NEW
) && is_null_sha1(update
->new_sha1
))
3713 update
->flags
|= REF_DELETING
;
3716 ret
= split_head_update(update
, transaction
, head_ref
,
3717 affected_refnames
, err
);
3722 ret
= lock_raw_ref(update
->refname
, mustexist
,
3723 affected_refnames
, NULL
,
3724 &update
->lock
, &referent
,
3725 &update
->type
, err
);
3730 reason
= strbuf_detach(err
, NULL
);
3731 strbuf_addf(err
, "cannot lock ref '%s': %s",
3732 update
->refname
, reason
);
3737 lock
= update
->lock
;
3739 if (update
->type
& REF_ISSYMREF
) {
3740 if (update
->flags
& REF_NODEREF
) {
3742 * We won't be reading the referent as part of
3743 * the transaction, so we have to read it here
3744 * to record and possibly check old_sha1:
3746 if (read_ref_full(update
->refname
,
3747 mustexist ? RESOLVE_REF_READING
: 0,
3748 lock
->old_oid
.hash
, NULL
)) {
3749 if (update
->flags
& REF_HAVE_OLD
) {
3750 strbuf_addf(err
, "cannot lock ref '%s': "
3751 "can't resolve old value",
3753 return TRANSACTION_GENERIC_ERROR
;
3755 hashclr(lock
->old_oid
.hash
);
3758 if ((update
->flags
& REF_HAVE_OLD
) &&
3759 hashcmp(lock
->old_oid
.hash
, update
->old_sha1
)) {
3760 strbuf_addf(err
, "cannot lock ref '%s': "
3761 "is at %s but expected %s",
3763 sha1_to_hex(lock
->old_oid
.hash
),
3764 sha1_to_hex(update
->old_sha1
));
3765 return TRANSACTION_GENERIC_ERROR
;
3770 * Create a new update for the reference this
3771 * symref is pointing at. Also, we will record
3772 * and verify old_sha1 for this update as part
3773 * of processing the split-off update, so we
3774 * don't have to do it here.
3776 ret
= split_symref_update(update
, referent
.buf
, transaction
,
3777 affected_refnames
, err
);
3782 struct ref_update
*parent_update
;
3785 * If this update is happening indirectly because of a
3786 * symref update, record the old SHA-1 in the parent
3789 for (parent_update
= update
->parent_update
;
3791 parent_update
= parent_update
->parent_update
) {
3792 oidcpy(&parent_update
->lock
->old_oid
, &lock
->old_oid
);
3795 if ((update
->flags
& REF_HAVE_OLD
) &&
3796 hashcmp(lock
->old_oid
.hash
, update
->old_sha1
)) {
3797 if (is_null_sha1(update
->old_sha1
))
3798 strbuf_addf(err
, "cannot lock ref '%s': reference already exists",
3799 original_update_refname(update
));
3801 strbuf_addf(err
, "cannot lock ref '%s': is at %s but expected %s",
3802 original_update_refname(update
),
3803 sha1_to_hex(lock
->old_oid
.hash
),
3804 sha1_to_hex(update
->old_sha1
));
3806 return TRANSACTION_GENERIC_ERROR
;
3810 if ((update
->flags
& REF_HAVE_NEW
) &&
3811 !(update
->flags
& REF_DELETING
) &&