3 #include "refs-internal.h"
4 #include "../lockfile.h"
12 struct object_id old_oid
;
18 * Information used (along with the information in ref_entry) to
19 * describe a single cached reference. This data structure only
20 * occurs embedded in a union in struct ref_entry, and only when
21 * (ref_entry->flag & REF_DIR) is zero.
25 * The name of the object to which this reference resolves
26 * (which may be a tag object). If REF_ISBROKEN, this is
27 * null. If REF_ISSYMREF, then this is the name of the object
28 * referred to by the last reference in the symlink chain.
33 * If REF_KNOWS_PEELED, then this field holds the peeled value
34 * of this reference, or null if the reference is known not to
35 * be peelable. See the documentation for peel_ref() for an
36 * exact definition of "peelable".
38 struct object_id peeled
;
44 * Information used (along with the information in ref_entry) to
45 * describe a level in the hierarchy of references. This data
46 * structure only occurs embedded in a union in struct ref_entry, and
47 * only when (ref_entry.flag & REF_DIR) is set. In that case,
48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
49 * in the directory have already been read:
51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
52 * or packed references, already read.
54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
55 * references that hasn't been read yet (nor has any of its
58 * Entries within a directory are stored within a growable array of
59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
60 * sorted are sorted by their component name in strcmp() order and the
61 * remaining entries are unsorted.
63 * Loose references are read lazily, one directory at a time. When a
64 * directory of loose references is read, then all of the references
65 * in that directory are stored, and REF_INCOMPLETE stubs are created
66 * for any subdirectories, but the subdirectories themselves are not
67 * read. The reading is triggered by get_ref_dir().
73 * Entries with index 0 <= i < sorted are sorted by name. New
74 * entries are appended to the list unsorted, and are sorted
75 * only when required; thus we avoid the need to sort the list
76 * after the addition of every reference.
80 /* A pointer to the ref_cache that contains this ref_dir. */
81 struct ref_cache
*ref_cache
;
83 struct ref_entry
**entries
;
87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
89 * public values; see refs.h.
93 * The field ref_entry->u.value.peeled of this value entry contains
94 * the correct peeled value for the reference, which might be
95 * null_sha1 if the reference is not a tag or if it is broken.
97 #define REF_KNOWS_PEELED 0x10
99 /* ref_entry represents a directory of references */
103 * Entry has not yet been read from disk (used only for REF_DIR
104 * entries representing loose references)
106 #define REF_INCOMPLETE 0x40
109 * A ref_entry represents either a reference or a "subdirectory" of
112 * Each directory in the reference namespace is represented by a
113 * ref_entry with (flags & REF_DIR) set and containing a subdir member
114 * that holds the entries in that directory that have been read so
115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
117 * used for loose reference directories.
119 * References are represented by a ref_entry with (flags & REF_DIR)
120 * unset and a value member that describes the reference's value. The
121 * flag member is at the ref_entry level, but it is also needed to
122 * interpret the contents of the value field (in other words, a
123 * ref_value object is not very much use without the enclosing
126 * Reference names cannot end with slash and directories' names are
127 * always stored with a trailing slash (except for the top-level
128 * directory, which is always denoted by ""). This has two nice
129 * consequences: (1) when the entries in each subdir are sorted
130 * lexicographically by name (as they usually are), the references in
131 * a whole tree can be generated in lexicographic order by traversing
132 * the tree in left-to-right, depth-first order; (2) the names of
133 * references and subdirectories cannot conflict, and therefore the
134 * presence of an empty subdirectory does not block the creation of a
135 * similarly-named reference. (The fact that reference names with the
136 * same leading components can conflict *with each other* is a
137 * separate issue that is regulated by verify_refname_available().)
139 * Please note that the name field contains the fully-qualified
140 * reference (or subdirectory) name. Space could be saved by only
141 * storing the relative names. But that would require the full names
142 * to be generated on the fly when iterating in do_for_each_ref(), and
143 * would break callback functions, who have always been able to assume
144 * that the name strings that they are passed will not be freed during
148 unsigned char flag
; /* ISSYMREF? ISPACKED? */
150 struct ref_value value
; /* if not (flags&REF_DIR) */
151 struct ref_dir subdir
; /* if (flags&REF_DIR) */
154 * The full name of the reference (e.g., "refs/heads/master")
155 * or the full name of the directory with a trailing slash
156 * (e.g., "refs/heads/"):
158 char name
[FLEX_ARRAY
];
161 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
162 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
);
163 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
164 const char *dirname
, size_t len
,
166 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
);
168 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
171 assert(entry
->flag
& REF_DIR
);
172 dir
= &entry
->u
.subdir
;
173 if (entry
->flag
& REF_INCOMPLETE
) {
174 read_loose_refs(entry
->name
, dir
);
177 * Manually add refs/bisect, which, being
178 * per-worktree, might not appear in the directory
179 * listing for refs/ in the main repo.
181 if (!strcmp(entry
->name
, "refs/")) {
182 int pos
= search_ref_dir(dir
, "refs/bisect/", 12);
184 struct ref_entry
*child_entry
;
185 child_entry
= create_dir_entry(dir
->ref_cache
,
188 add_entry_to_dir(dir
, child_entry
);
189 read_loose_refs("refs/bisect",
190 &child_entry
->u
.subdir
);
193 entry
->flag
&= ~REF_INCOMPLETE
;
198 static struct ref_entry
*create_ref_entry(const char *refname
,
199 const unsigned char *sha1
, int flag
,
202 struct ref_entry
*ref
;
205 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
206 die("Reference has invalid format: '%s'", refname
);
207 FLEX_ALLOC_STR(ref
, name
, refname
);
208 hashcpy(ref
->u
.value
.oid
.hash
, sha1
);
209 oidclr(&ref
->u
.value
.peeled
);
214 static void clear_ref_dir(struct ref_dir
*dir
);
216 static void free_ref_entry(struct ref_entry
*entry
)
218 if (entry
->flag
& REF_DIR
) {
220 * Do not use get_ref_dir() here, as that might
221 * trigger the reading of loose refs.
223 clear_ref_dir(&entry
->u
.subdir
);
229 * Add a ref_entry to the end of dir (unsorted). Entry is always
230 * stored directly in dir; no recursion into subdirectories is
233 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
235 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
236 dir
->entries
[dir
->nr
++] = entry
;
237 /* optimize for the case that entries are added in order */
239 (dir
->nr
== dir
->sorted
+ 1 &&
240 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
241 dir
->entries
[dir
->nr
- 1]->name
) < 0))
242 dir
->sorted
= dir
->nr
;
246 * Clear and free all entries in dir, recursively.
248 static void clear_ref_dir(struct ref_dir
*dir
)
251 for (i
= 0; i
< dir
->nr
; i
++)
252 free_ref_entry(dir
->entries
[i
]);
254 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
259 * Create a struct ref_entry object for the specified dirname.
260 * dirname is the name of the directory with a trailing slash (e.g.,
261 * "refs/heads/") or "" for the top-level directory.
263 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
264 const char *dirname
, size_t len
,
267 struct ref_entry
*direntry
;
268 FLEX_ALLOC_MEM(direntry
, name
, dirname
, len
);
269 direntry
->u
.subdir
.ref_cache
= ref_cache
;
270 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
274 static int ref_entry_cmp(const void *a
, const void *b
)
276 struct ref_entry
*one
= *(struct ref_entry
**)a
;
277 struct ref_entry
*two
= *(struct ref_entry
**)b
;
278 return strcmp(one
->name
, two
->name
);
281 static void sort_ref_dir(struct ref_dir
*dir
);
283 struct string_slice
{
288 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
290 const struct string_slice
*key
= key_
;
291 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
292 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
295 return '\0' - (unsigned char)ent
->name
[key
->len
];
299 * Return the index of the entry with the given refname from the
300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
301 * no such entry is found. dir must already be complete.
303 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
305 struct ref_entry
**r
;
306 struct string_slice key
;
308 if (refname
== NULL
|| !dir
->nr
)
314 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
315 ref_entry_cmp_sslice
);
320 return r
- dir
->entries
;
324 * Search for a directory entry directly within dir (without
325 * recursing). Sort dir if necessary. subdirname must be a directory
326 * name (i.e., end in '/'). If mkdir is set, then create the
327 * directory if it is missing; otherwise, return NULL if the desired
328 * directory cannot be found. dir must already be complete.
330 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
331 const char *subdirname
, size_t len
,
334 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
335 struct ref_entry
*entry
;
336 if (entry_index
== -1) {
340 * Since dir is complete, the absence of a subdir
341 * means that the subdir really doesn't exist;
342 * therefore, create an empty record for it but mark
343 * the record complete.
345 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
346 add_entry_to_dir(dir
, entry
);
348 entry
= dir
->entries
[entry_index
];
350 return get_ref_dir(entry
);
354 * If refname is a reference name, find the ref_dir within the dir
355 * tree that should hold refname. If refname is a directory name
356 * (i.e., ends in '/'), then return that ref_dir itself. dir must
357 * represent the top-level directory and must already be complete.
358 * Sort ref_dirs and recurse into subdirectories as necessary. If
359 * mkdir is set, then create any missing directories; otherwise,
360 * return NULL if the desired directory cannot be found.
362 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
363 const char *refname
, int mkdir
)
366 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
367 size_t dirnamelen
= slash
- refname
+ 1;
368 struct ref_dir
*subdir
;
369 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
381 * Find the value entry with the given name in dir, sorting ref_dirs
382 * and recursing into subdirectories as necessary. If the name is not
383 * found or it corresponds to a directory entry, return NULL.
385 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
388 struct ref_entry
*entry
;
389 dir
= find_containing_dir(dir
, refname
, 0);
392 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
393 if (entry_index
== -1)
395 entry
= dir
->entries
[entry_index
];
396 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
400 * Remove the entry with the given name from dir, recursing into
401 * subdirectories as necessary. If refname is the name of a directory
402 * (i.e., ends with '/'), then remove the directory and its contents.
403 * If the removal was successful, return the number of entries
404 * remaining in the directory entry that contained the deleted entry.
405 * If the name was not found, return -1. Please note that this
406 * function only deletes the entry from the cache; it does not delete
407 * it from the filesystem or ensure that other cache entries (which
408 * might be symbolic references to the removed entry) are updated.
409 * Nor does it remove any containing dir entries that might be made
410 * empty by the removal. dir must represent the top-level directory
411 * and must already be complete.
413 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
415 int refname_len
= strlen(refname
);
417 struct ref_entry
*entry
;
418 int is_dir
= refname
[refname_len
- 1] == '/';
421 * refname represents a reference directory. Remove
422 * the trailing slash; otherwise we will get the
423 * directory *representing* refname rather than the
424 * one *containing* it.
426 char *dirname
= xmemdupz(refname
, refname_len
- 1);
427 dir
= find_containing_dir(dir
, dirname
, 0);
430 dir
= find_containing_dir(dir
, refname
, 0);
434 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
435 if (entry_index
== -1)
437 entry
= dir
->entries
[entry_index
];
439 memmove(&dir
->entries
[entry_index
],
440 &dir
->entries
[entry_index
+ 1],
441 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
444 if (dir
->sorted
> entry_index
)
446 free_ref_entry(entry
);
451 * Add a ref_entry to the ref_dir (unsorted), recursing into
452 * subdirectories as necessary. dir must represent the top-level
453 * directory. Return 0 on success.
455 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
457 dir
= find_containing_dir(dir
, ref
->name
, 1);
460 add_entry_to_dir(dir
, ref
);
465 * Emit a warning and return true iff ref1 and ref2 have the same name
466 * and the same sha1. Die if they have the same name but different
469 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
471 if (strcmp(ref1
->name
, ref2
->name
))
474 /* Duplicate name; make sure that they don't conflict: */
476 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
477 /* This is impossible by construction */
478 die("Reference directory conflict: %s", ref1
->name
);
480 if (oidcmp(&ref1
->u
.value
.oid
, &ref2
->u
.value
.oid
))
481 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
483 warning("Duplicated ref: %s", ref1
->name
);
488 * Sort the entries in dir non-recursively (if they are not already
489 * sorted) and remove any duplicate entries.
491 static void sort_ref_dir(struct ref_dir
*dir
)
494 struct ref_entry
*last
= NULL
;
497 * This check also prevents passing a zero-length array to qsort(),
498 * which is a problem on some platforms.
500 if (dir
->sorted
== dir
->nr
)
503 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
505 /* Remove any duplicates: */
506 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
507 struct ref_entry
*entry
= dir
->entries
[j
];
508 if (last
&& is_dup_ref(last
, entry
))
509 free_ref_entry(entry
);
511 last
= dir
->entries
[i
++] = entry
;
513 dir
->sorted
= dir
->nr
= i
;
517 * Return true iff the reference described by entry can be resolved to
518 * an object in the database. Emit a warning if the referred-to
519 * object does not exist.
521 static int ref_resolves_to_object(struct ref_entry
*entry
)
523 if (entry
->flag
& REF_ISBROKEN
)
525 if (!has_sha1_file(entry
->u
.value
.oid
.hash
)) {
526 error("%s does not point to a valid object!", entry
->name
);
533 * current_ref is a performance hack: when iterating over references
534 * using the for_each_ref*() functions, current_ref is set to the
535 * current reference's entry before calling the callback function. If
536 * the callback function calls peel_ref(), then peel_ref() first
537 * checks whether the reference to be peeled is the current reference
538 * (it usually is) and if so, returns that reference's peeled version
539 * if it is available. This avoids a refname lookup in a common case.
541 static struct ref_entry
*current_ref
;
543 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
545 struct ref_entry_cb
{
554 * Handle one reference in a do_for_each_ref*()-style iteration,
555 * calling an each_ref_fn for each entry.
557 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
559 struct ref_entry_cb
*data
= cb_data
;
560 struct ref_entry
*old_current_ref
;
563 if (!starts_with(entry
->name
, data
->base
))
566 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
567 !ref_resolves_to_object(entry
))
570 /* Store the old value, in case this is a recursive call: */
571 old_current_ref
= current_ref
;
573 retval
= data
->fn(entry
->name
+ data
->trim
, &entry
->u
.value
.oid
,
574 entry
->flag
, data
->cb_data
);
575 current_ref
= old_current_ref
;
580 * Call fn for each reference in dir that has index in the range
581 * offset <= index < dir->nr. Recurse into subdirectories that are in
582 * that index range, sorting them before iterating. This function
583 * does not sort dir itself; it should be sorted beforehand. fn is
584 * called for all references, including broken ones.
586 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
587 each_ref_entry_fn fn
, void *cb_data
)
590 assert(dir
->sorted
== dir
->nr
);
591 for (i
= offset
; i
< dir
->nr
; i
++) {
592 struct ref_entry
*entry
= dir
->entries
[i
];
594 if (entry
->flag
& REF_DIR
) {
595 struct ref_dir
*subdir
= get_ref_dir(entry
);
596 sort_ref_dir(subdir
);
597 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
599 retval
= fn(entry
, cb_data
);
608 * Call fn for each reference in the union of dir1 and dir2, in order
609 * by refname. Recurse into subdirectories. If a value entry appears
610 * in both dir1 and dir2, then only process the version that is in
611 * dir2. The input dirs must already be sorted, but subdirs will be
612 * sorted as needed. fn is called for all references, including
615 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
616 struct ref_dir
*dir2
,
617 each_ref_entry_fn fn
, void *cb_data
)
622 assert(dir1
->sorted
== dir1
->nr
);
623 assert(dir2
->sorted
== dir2
->nr
);
625 struct ref_entry
*e1
, *e2
;
627 if (i1
== dir1
->nr
) {
628 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
630 if (i2
== dir2
->nr
) {
631 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
633 e1
= dir1
->entries
[i1
];
634 e2
= dir2
->entries
[i2
];
635 cmp
= strcmp(e1
->name
, e2
->name
);
637 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
638 /* Both are directories; descend them in parallel. */
639 struct ref_dir
*subdir1
= get_ref_dir(e1
);
640 struct ref_dir
*subdir2
= get_ref_dir(e2
);
641 sort_ref_dir(subdir1
);
642 sort_ref_dir(subdir2
);
643 retval
= do_for_each_entry_in_dirs(
644 subdir1
, subdir2
, fn
, cb_data
);
647 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
648 /* Both are references; ignore the one from dir1. */
649 retval
= fn(e2
, cb_data
);
653 die("conflict between reference and directory: %s",
665 if (e
->flag
& REF_DIR
) {
666 struct ref_dir
*subdir
= get_ref_dir(e
);
667 sort_ref_dir(subdir
);
668 retval
= do_for_each_entry_in_dir(
669 subdir
, 0, fn
, cb_data
);
671 retval
= fn(e
, cb_data
);
680 * Load all of the refs from the dir into our in-memory cache. The hard work
681 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
682 * through all of the sub-directories. We do not even need to care about
683 * sorting, as traversal order does not matter to us.
685 static void prime_ref_dir(struct ref_dir
*dir
)
688 for (i
= 0; i
< dir
->nr
; i
++) {
689 struct ref_entry
*entry
= dir
->entries
[i
];
690 if (entry
->flag
& REF_DIR
)
691 prime_ref_dir(get_ref_dir(entry
));
695 struct nonmatching_ref_data
{
696 const struct string_list
*skip
;
697 const char *conflicting_refname
;
700 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
702 struct nonmatching_ref_data
*data
= vdata
;
704 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
707 data
->conflicting_refname
= entry
->name
;
712 * Return 0 if a reference named refname could be created without
713 * conflicting with the name of an existing reference in dir.
714 * See verify_refname_available for more information.
716 static int verify_refname_available_dir(const char *refname
,
717 const struct string_list
*extras
,
718 const struct string_list
*skip
,
723 const char *extra_refname
;
725 struct strbuf dirname
= STRBUF_INIT
;
729 * For the sake of comments in this function, suppose that
730 * refname is "refs/foo/bar".
735 strbuf_grow(&dirname
, strlen(refname
) + 1);
736 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
737 /* Expand dirname to the new prefix, not including the trailing slash: */
738 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
741 * We are still at a leading dir of the refname (e.g.,
742 * "refs/foo"; if there is a reference with that name,
743 * it is a conflict, *unless* it is in skip.
746 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
748 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
750 * We found a reference whose name is
751 * a proper prefix of refname; e.g.,
752 * "refs/foo", and is not in skip.
754 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
755 dirname
.buf
, refname
);
760 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
761 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
762 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
763 refname
, dirname
.buf
);
768 * Otherwise, we can try to continue our search with
769 * the next component. So try to look up the
770 * directory, e.g., "refs/foo/". If we come up empty,
771 * we know there is nothing under this whole prefix,
772 * but even in that case we still have to continue the
773 * search for conflicts with extras.
775 strbuf_addch(&dirname
, '/');
777 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
780 * There was no directory "refs/foo/",
781 * so there is nothing under this
782 * whole prefix. So there is no need
783 * to continue looking for conflicting
784 * references. But we need to continue
785 * looking for conflicting extras.
789 dir
= get_ref_dir(dir
->entries
[pos
]);
795 * We are at the leaf of our refname (e.g., "refs/foo/bar").
796 * There is no point in searching for a reference with that
797 * name, because a refname isn't considered to conflict with
798 * itself. But we still need to check for references whose
799 * names are in the "refs/foo/bar/" namespace, because they
802 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
803 strbuf_addch(&dirname
, '/');
806 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
810 * We found a directory named "$refname/"
811 * (e.g., "refs/foo/bar/"). It is a problem
812 * iff it contains any ref that is not in
815 struct nonmatching_ref_data data
;
818 data
.conflicting_refname
= NULL
;
819 dir
= get_ref_dir(dir
->entries
[pos
]);
821 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
822 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
823 data
.conflicting_refname
, refname
);
829 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
831 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
832 refname
, extra_refname
);
837 strbuf_release(&dirname
);
841 struct packed_ref_cache
{
842 struct ref_entry
*root
;
845 * Count of references to the data structure in this instance,
846 * including the pointer from ref_cache::packed if any. The
847 * data will not be freed as long as the reference count is
850 unsigned int referrers
;
853 * Iff the packed-refs file associated with this instance is
854 * currently locked for writing, this points at the associated
855 * lock (which is owned by somebody else). The referrer count
856 * is also incremented when the file is locked and decremented
857 * when it is unlocked.
859 struct lock_file
*lock
;
861 /* The metadata from when this packed-refs cache was read */
862 struct stat_validity validity
;
866 * Future: need to be in "struct repository"
867 * when doing a full libification.
869 static struct ref_cache
{
870 struct ref_cache
*next
;
871 struct ref_entry
*loose
;
872 struct packed_ref_cache
*packed
;
874 * The submodule name, or "" for the main repo. We allocate
875 * length 1 rather than FLEX_ARRAY so that the main ref_cache
876 * is initialized correctly.
879 } ref_cache
, *submodule_ref_caches
;
881 /* Lock used for the main packed-refs file: */
882 static struct lock_file packlock
;
885 * Increment the reference count of *packed_refs.
887 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
889 packed_refs
->referrers
++;
893 * Decrease the reference count of *packed_refs. If it goes to zero,
894 * free *packed_refs and return true; otherwise return false.
896 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
898 if (!--packed_refs
->referrers
) {
899 free_ref_entry(packed_refs
->root
);
900 stat_validity_clear(&packed_refs
->validity
);
908 static void clear_packed_ref_cache(struct ref_cache
*refs
)
911 struct packed_ref_cache
*packed_refs
= refs
->packed
;
913 if (packed_refs
->lock
)
914 die("internal error: packed-ref cache cleared while locked");
916 release_packed_ref_cache(packed_refs
);
920 static void clear_loose_ref_cache(struct ref_cache
*refs
)
923 free_ref_entry(refs
->loose
);
929 * Create a new submodule ref cache and add it to the internal
932 static struct ref_cache
*create_ref_cache(const char *submodule
)
934 struct ref_cache
*refs
;
937 FLEX_ALLOC_STR(refs
, name
, submodule
);
938 refs
->next
= submodule_ref_caches
;
939 submodule_ref_caches
= refs
;
943 static struct ref_cache
*lookup_ref_cache(const char *submodule
)
945 struct ref_cache
*refs
;
947 if (!submodule
|| !*submodule
)
950 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
951 if (!strcmp(submodule
, refs
->name
))
957 * Return a pointer to a ref_cache for the specified submodule. For
958 * the main repository, use submodule==NULL. The returned structure
959 * will be allocated and initialized but not necessarily populated; it
960 * should not be freed.
962 static struct ref_cache
*get_ref_cache(const char *submodule
)
964 struct ref_cache
*refs
= lookup_ref_cache(submodule
);
966 refs
= create_ref_cache(submodule
);
970 /* The length of a peeled reference line in packed-refs, including EOL: */
971 #define PEELED_LINE_LENGTH 42
974 * The packed-refs header line that we write out. Perhaps other
975 * traits will be added later. The trailing space is required.
977 static const char PACKED_REFS_HEADER
[] =
978 "# pack-refs with: peeled fully-peeled \n";
981 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
982 * Return a pointer to the refname within the line (null-terminated),
983 * or NULL if there was a problem.
985 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
990 * 42: the answer to everything.
992 * In this case, it happens to be the answer to
993 * 40 (length of sha1 hex representation)
994 * +1 (space in between hex and name)
995 * +1 (newline at the end of the line)
1000 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1002 if (!isspace(line
->buf
[40]))
1005 ref
= line
->buf
+ 41;
1009 if (line
->buf
[line
->len
- 1] != '\n')
1011 line
->buf
[--line
->len
] = 0;
1017 * Read f, which is a packed-refs file, into dir.
1019 * A comment line of the form "# pack-refs with: " may contain zero or
1020 * more traits. We interpret the traits as follows:
1024 * Probably no references are peeled. But if the file contains a
1025 * peeled value for a reference, we will use it.
1029 * References under "refs/tags/", if they *can* be peeled, *are*
1030 * peeled in this file. References outside of "refs/tags/" are
1031 * probably not peeled even if they could have been, but if we find
1032 * a peeled value for such a reference we will use it.
1036 * All references in the file that can be peeled are peeled.
1037 * Inversely (and this is more important), any references in the
1038 * file for which no peeled value is recorded is not peelable. This
1039 * trait should typically be written alongside "peeled" for
1040 * compatibility with older clients, but we do not require it
1041 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1043 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1045 struct ref_entry
*last
= NULL
;
1046 struct strbuf line
= STRBUF_INIT
;
1047 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1049 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1050 unsigned char sha1
[20];
1051 const char *refname
;
1054 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1055 if (strstr(traits
, " fully-peeled "))
1056 peeled
= PEELED_FULLY
;
1057 else if (strstr(traits
, " peeled "))
1058 peeled
= PEELED_TAGS
;
1059 /* perhaps other traits later as well */
1063 refname
= parse_ref_line(&line
, sha1
);
1065 int flag
= REF_ISPACKED
;
1067 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1068 if (!refname_is_safe(refname
))
1069 die("packed refname is dangerous: %s", refname
);
1071 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1073 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1074 if (peeled
== PEELED_FULLY
||
1075 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1076 last
->flag
|= REF_KNOWS_PEELED
;
1081 line
.buf
[0] == '^' &&
1082 line
.len
== PEELED_LINE_LENGTH
&&
1083 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1084 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1085 hashcpy(last
->u
.value
.peeled
.hash
, sha1
);
1087 * Regardless of what the file header said,
1088 * we definitely know the value of *this*
1091 last
->flag
|= REF_KNOWS_PEELED
;
1095 strbuf_release(&line
);
1099 * Get the packed_ref_cache for the specified ref_cache, creating it
1102 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1104 char *packed_refs_file
;
1107 packed_refs_file
= git_pathdup_submodule(refs
->name
, "packed-refs");
1109 packed_refs_file
= git_pathdup("packed-refs");
1112 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1113 clear_packed_ref_cache(refs
);
1115 if (!refs
->packed
) {
1118 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1119 acquire_packed_ref_cache(refs
->packed
);
1120 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1121 f
= fopen(packed_refs_file
, "r");
1123 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1124 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1128 free(packed_refs_file
);
1129 return refs
->packed
;
1132 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1134 return get_ref_dir(packed_ref_cache
->root
);
1137 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1139 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1143 * Add a reference to the in-memory packed reference cache. This may
1144 * only be called while the packed-refs file is locked (see
1145 * lock_packed_refs()). To actually write the packed-refs file, call
1146 * commit_packed_refs().
1148 static void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1150 struct packed_ref_cache
*packed_ref_cache
=
1151 get_packed_ref_cache(&ref_cache
);
1153 if (!packed_ref_cache
->lock
)
1154 die("internal error: packed refs not locked");
1155 add_ref(get_packed_ref_dir(packed_ref_cache
),
1156 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1160 * Read the loose references from the namespace dirname into dir
1161 * (without recursing). dirname must end with '/'. dir must be the
1162 * directory entry corresponding to dirname.
1164 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1166 struct ref_cache
*refs
= dir
->ref_cache
;
1169 int dirnamelen
= strlen(dirname
);
1170 struct strbuf refname
;
1171 struct strbuf path
= STRBUF_INIT
;
1172 size_t path_baselen
;
1175 strbuf_git_path_submodule(&path
, refs
->name
, "%s", dirname
);
1177 strbuf_git_path(&path
, "%s", dirname
);
1178 path_baselen
= path
.len
;
1180 d
= opendir(path
.buf
);
1182 strbuf_release(&path
);
1186 strbuf_init(&refname
, dirnamelen
+ 257);
1187 strbuf_add(&refname
, dirname
, dirnamelen
);
1189 while ((de
= readdir(d
)) != NULL
) {
1190 unsigned char sha1
[20];
1194 if (de
->d_name
[0] == '.')
1196 if (ends_with(de
->d_name
, ".lock"))
1198 strbuf_addstr(&refname
, de
->d_name
);
1199 strbuf_addstr(&path
, de
->d_name
);
1200 if (stat(path
.buf
, &st
) < 0) {
1201 ; /* silently ignore */
1202 } else if (S_ISDIR(st
.st_mode
)) {
1203 strbuf_addch(&refname
, '/');
1204 add_entry_to_dir(dir
,
1205 create_dir_entry(refs
, refname
.buf
,
1213 read_ok
= !resolve_gitlink_ref(refs
->name
,
1216 read_ok
= !read_ref_full(refname
.buf
,
1217 RESOLVE_REF_READING
,
1223 flag
|= REF_ISBROKEN
;
1224 } else if (is_null_sha1(sha1
)) {
1226 * It is so astronomically unlikely
1227 * that NULL_SHA1 is the SHA-1 of an
1228 * actual object that we consider its
1229 * appearance in a loose reference
1230 * file to be repo corruption
1231 * (probably due to a software bug).
1233 flag
|= REF_ISBROKEN
;
1236 if (check_refname_format(refname
.buf
,
1237 REFNAME_ALLOW_ONELEVEL
)) {
1238 if (!refname_is_safe(refname
.buf
))
1239 die("loose refname is dangerous: %s", refname
.buf
);
1241 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1243 add_entry_to_dir(dir
,
1244 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1246 strbuf_setlen(&refname
, dirnamelen
);
1247 strbuf_setlen(&path
, path_baselen
);
1249 strbuf_release(&refname
);
1250 strbuf_release(&path
);
1254 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1258 * Mark the top-level directory complete because we
1259 * are about to read the only subdirectory that can
1262 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1264 * Create an incomplete entry for "refs/":
1266 add_entry_to_dir(get_ref_dir(refs
->loose
),
1267 create_dir_entry(refs
, "refs/", 5, 1));
1269 return get_ref_dir(refs
->loose
);
1272 #define MAXREFLEN (1024)
1275 * Called by resolve_gitlink_ref_recursive() after it failed to read
1276 * from the loose refs in ref_cache refs. Find <refname> in the
1277 * packed-refs file for the submodule.
1279 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1280 const char *refname
, unsigned char *sha1
)
1282 struct ref_entry
*ref
;
1283 struct ref_dir
*dir
= get_packed_refs(refs
);
1285 ref
= find_ref(dir
, refname
);
1289 hashcpy(sha1
, ref
->u
.value
.oid
.hash
);
1293 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1294 const char *refname
, unsigned char *sha1
,
1298 char buffer
[128], *p
;
1301 if (recursion
> SYMREF_MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1304 ? git_pathdup_submodule(refs
->name
, "%s", refname
)
1305 : git_pathdup("%s", refname
);
1306 fd
= open(path
, O_RDONLY
);
1309 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1311 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1315 while (len
&& isspace(buffer
[len
-1]))
1319 /* Was it a detached head or an old-fashioned symlink? */
1320 if (!get_sha1_hex(buffer
, sha1
))
1324 if (strncmp(buffer
, "ref:", 4))
1330 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1333 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1335 int len
= strlen(path
), retval
;
1336 struct strbuf submodule
= STRBUF_INIT
;
1337 struct ref_cache
*refs
;
1339 while (len
&& path
[len
-1] == '/')
1344 strbuf_add(&submodule
, path
, len
);
1345 refs
= lookup_ref_cache(submodule
.buf
);
1347 if (!is_nonbare_repository_dir(&submodule
)) {
1348 strbuf_release(&submodule
);
1351 refs
= create_ref_cache(submodule
.buf
);
1353 strbuf_release(&submodule
);
1355 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1360 * Return the ref_entry for the given refname from the packed
1361 * references. If it does not exist, return NULL.
1363 static struct ref_entry
*get_packed_ref(const char *refname
)
1365 return find_ref(get_packed_refs(&ref_cache
), refname
);
1369 * A loose ref file doesn't exist; check for a packed ref.
1371 static int resolve_missing_loose_ref(const char *refname
,
1372 unsigned char *sha1
,
1373 unsigned int *flags
)
1375 struct ref_entry
*entry
;
1378 * The loose reference file does not exist; check for a packed
1381 entry
= get_packed_ref(refname
);
1383 hashcpy(sha1
, entry
->u
.value
.oid
.hash
);
1384 *flags
|= REF_ISPACKED
;
1387 /* refname is not a packed reference. */
1391 int read_raw_ref(const char *refname
, unsigned char *sha1
,
1392 struct strbuf
*referent
, unsigned int *type
)
1394 struct strbuf sb_contents
= STRBUF_INIT
;
1395 struct strbuf sb_path
= STRBUF_INIT
;
1404 strbuf_reset(&sb_path
);
1405 strbuf_git_path(&sb_path
, "%s", refname
);
1410 * We might have to loop back here to avoid a race
1411 * condition: first we lstat() the file, then we try
1412 * to read it as a link or as a file. But if somebody
1413 * changes the type of the file (file <-> directory
1414 * <-> symlink) between the lstat() and reading, then
1415 * we don't want to report that as an error but rather
1416 * try again starting with the lstat().
1419 if (lstat(path
, &st
) < 0) {
1420 if (errno
!= ENOENT
)
1422 if (resolve_missing_loose_ref(refname
, sha1
, type
)) {
1430 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1431 if (S_ISLNK(st
.st_mode
)) {
1432 strbuf_reset(&sb_contents
);
1433 if (strbuf_readlink(&sb_contents
, path
, 0) < 0) {
1434 if (errno
== ENOENT
|| errno
== EINVAL
)
1435 /* inconsistent with lstat; retry */
1440 if (starts_with(sb_contents
.buf
, "refs/") &&
1441 !check_refname_format(sb_contents
.buf
, 0)) {
1442 strbuf_swap(&sb_contents
, referent
);
1443 *type
|= REF_ISSYMREF
;
1449 /* Is it a directory? */
1450 if (S_ISDIR(st
.st_mode
)) {
1452 * Even though there is a directory where the loose
1453 * ref is supposed to be, there could still be a
1456 if (resolve_missing_loose_ref(refname
, sha1
, type
)) {
1465 * Anything else, just open it and try to use it as
1468 fd
= open(path
, O_RDONLY
);
1470 if (errno
== ENOENT
)
1471 /* inconsistent with lstat; retry */
1476 strbuf_reset(&sb_contents
);
1477 if (strbuf_read(&sb_contents
, fd
, 256) < 0) {
1478 int save_errno
= errno
;
1484 strbuf_rtrim(&sb_contents
);
1485 buf
= sb_contents
.buf
;
1486 if (starts_with(buf
, "ref:")) {
1488 while (isspace(*buf
))
1491 strbuf_reset(referent
);
1492 strbuf_addstr(referent
, buf
);
1493 *type
|= REF_ISSYMREF
;
1499 * Please note that FETCH_HEAD has additional
1500 * data after the sha.
1502 if (get_sha1_hex(buf
, sha1
) ||
1503 (buf
[40] != '\0' && !isspace(buf
[40]))) {
1504 *type
|= REF_ISBROKEN
;
1513 strbuf_release(&sb_path
);
1514 strbuf_release(&sb_contents
);
1519 static void unlock_ref(struct ref_lock
*lock
)
1521 /* Do not free lock->lk -- atexit() still looks at them */
1523 rollback_lock_file(lock
->lk
);
1524 free(lock
->ref_name
);
1525 free(lock
->orig_ref_name
);
1530 * Lock refname, without following symrefs, and set *lock_p to point
1531 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
1532 * and type similarly to read_raw_ref().
1534 * The caller must verify that refname is a "safe" reference name (in
1535 * the sense of refname_is_safe()) before calling this function.
1537 * If the reference doesn't already exist, verify that refname doesn't
1538 * have a D/F conflict with any existing references. extras and skip
1539 * are passed to verify_refname_available_dir() for this check.
1541 * If mustexist is not set and the reference is not found or is
1542 * broken, lock the reference anyway but clear sha1.
1544 * Return 0 on success. On failure, write an error message to err and
1545 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
1547 * Implementation note: This function is basically
1552 * but it includes a lot more code to
1553 * - Deal with possible races with other processes
1554 * - Avoid calling verify_refname_available_dir() when it can be
1555 * avoided, namely if we were successfully able to read the ref
1556 * - Generate informative error messages in the case of failure
1558 static int lock_raw_ref(const char *refname
, int mustexist
,
1559 const struct string_list
*extras
,
1560 const struct string_list
*skip
,
1561 struct ref_lock
**lock_p
,
1562 struct strbuf
*referent
,
1566 struct ref_lock
*lock
;
1567 struct strbuf ref_file
= STRBUF_INIT
;
1568 int attempts_remaining
= 3;
1569 int ret
= TRANSACTION_GENERIC_ERROR
;
1574 /* First lock the file so it can't change out from under us. */
1576 *lock_p
= lock
= xcalloc(1, sizeof(*lock
));
1578 lock
->ref_name
= xstrdup(refname
);
1579 lock
->orig_ref_name
= xstrdup(refname
);
1580 strbuf_git_path(&ref_file
, "%s", refname
);
1583 switch (safe_create_leading_directories(ref_file
.buf
)) {
1585 break; /* success */
1588 * Suppose refname is "refs/foo/bar". We just failed
1589 * to create the containing directory, "refs/foo",
1590 * because there was a non-directory in the way. This
1591 * indicates a D/F conflict, probably because of
1592 * another reference such as "refs/foo". There is no
1593 * reason to expect this error to be transitory.
1595 if (verify_refname_available(refname
, extras
, skip
, err
)) {
1598 * To the user the relevant error is
1599 * that the "mustexist" reference is
1603 strbuf_addf(err
, "unable to resolve reference '%s'",
1607 * The error message set by
1608 * verify_refname_available_dir() is OK.
1610 ret
= TRANSACTION_NAME_CONFLICT
;
1614 * The file that is in the way isn't a loose
1615 * reference. Report it as a low-level
1618 strbuf_addf(err
, "unable to create lock file %s.lock; "
1619 "non-directory in the way",
1624 /* Maybe another process was tidying up. Try again. */
1625 if (--attempts_remaining
> 0)
1629 strbuf_addf(err
, "unable to create directory for %s",
1635 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
1637 if (hold_lock_file_for_update(lock
->lk
, ref_file
.buf
, LOCK_NO_DEREF
) < 0) {
1638 if (errno
== ENOENT
&& --attempts_remaining
> 0) {
1640 * Maybe somebody just deleted one of the
1641 * directories leading to ref_file. Try
1646 unable_to_lock_message(ref_file
.buf
, errno
, err
);
1652 * Now we hold the lock and can read the reference without
1653 * fear that its value will change.
1656 if (read_raw_ref(refname
, lock
->old_oid
.hash
, referent
, type
)) {
1657 if (errno
== ENOENT
) {
1659 /* Garden variety missing reference. */
1660 strbuf_addf(err
, "unable to resolve reference '%s'",
1665 * Reference is missing, but that's OK. We
1666 * know that there is not a conflict with
1667 * another loose reference because
1668 * (supposing that we are trying to lock
1669 * reference "refs/foo/bar"):
1671 * - We were successfully able to create
1672 * the lockfile refs/foo/bar.lock, so we
1673 * know there cannot be a loose reference
1676 * - We got ENOENT and not EISDIR, so we
1677 * know that there cannot be a loose
1678 * reference named "refs/foo/bar/baz".
1681 } else if (errno
== EISDIR
) {
1683 * There is a directory in the way. It might have
1684 * contained references that have been deleted. If
1685 * we don't require that the reference already
1686 * exists, try to remove the directory so that it
1687 * doesn't cause trouble when we want to rename the
1688 * lockfile into place later.
1691 /* Garden variety missing reference. */
1692 strbuf_addf(err
, "unable to resolve reference '%s'",
1695 } else if (remove_dir_recursively(&ref_file
,
1696 REMOVE_DIR_EMPTY_ONLY
)) {
1697 if (verify_refname_available_dir(
1698 refname
, extras
, skip
,
1699 get_loose_refs(&ref_cache
),
1702 * The error message set by
1703 * verify_refname_available() is OK.
1705 ret
= TRANSACTION_NAME_CONFLICT
;
1709 * We can't delete the directory,
1710 * but we also don't know of any
1711 * references that it should
1714 strbuf_addf(err
, "there is a non-empty directory '%s' "
1715 "blocking reference '%s'",
1716 ref_file
.buf
, refname
);
1720 } else if (errno
== EINVAL
&& (*type
& REF_ISBROKEN
)) {
1721 strbuf_addf(err
, "unable to resolve reference '%s': "
1722 "reference broken", refname
);
1725 strbuf_addf(err
, "unable to resolve reference '%s': %s",
1726 refname
, strerror(errno
));
1731 * If the ref did not exist and we are creating it,
1732 * make sure there is no existing packed ref whose
1733 * name begins with our refname, nor a packed ref
1734 * whose name is a proper prefix of our refname.
1736 if (verify_refname_available_dir(
1737 refname
, extras
, skip
,
1738 get_packed_refs(&ref_cache
),
1752 strbuf_release(&ref_file
);
1757 * Peel the entry (if possible) and return its new peel_status. If
1758 * repeel is true, re-peel the entry even if there is an old peeled
1759 * value that is already stored in it.
1761 * It is OK to call this function with a packed reference entry that
1762 * might be stale and might even refer to an object that has since
1763 * been garbage-collected. In such a case, if the entry has
1764 * REF_KNOWS_PEELED then leave the status unchanged and return
1765 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1767 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1769 enum peel_status status
;
1771 if (entry
->flag
& REF_KNOWS_PEELED
) {
1773 entry
->flag
&= ~REF_KNOWS_PEELED
;
1774 oidclr(&entry
->u
.value
.peeled
);
1776 return is_null_oid(&entry
->u
.value
.peeled
) ?
1777 PEEL_NON_TAG
: PEEL_PEELED
;
1780 if (entry
->flag
& REF_ISBROKEN
)
1782 if (entry
->flag
& REF_ISSYMREF
)
1783 return PEEL_IS_SYMREF
;
1785 status
= peel_object(entry
->u
.value
.oid
.hash
, entry
->u
.value
.peeled
.hash
);
1786 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1787 entry
->flag
|= REF_KNOWS_PEELED
;
1791 int peel_ref(const char *refname
, unsigned char *sha1
)
1794 unsigned char base
[20];
1796 if (current_ref
&& (current_ref
->name
== refname
1797 || !strcmp(current_ref
->name
, refname
))) {
1798 if (peel_entry(current_ref
, 0))
1800 hashcpy(sha1
, current_ref
->u
.value
.peeled
.hash
);
1804 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1808 * If the reference is packed, read its ref_entry from the
1809 * cache in the hope that we already know its peeled value.
1810 * We only try this optimization on packed references because
1811 * (a) forcing the filling of the loose reference cache could
1812 * be expensive and (b) loose references anyway usually do not
1813 * have REF_KNOWS_PEELED.
1815 if (flag
& REF_ISPACKED
) {
1816 struct ref_entry
*r
= get_packed_ref(refname
);
1818 if (peel_entry(r
, 0))
1820 hashcpy(sha1
, r
->u
.value
.peeled
.hash
);
1825 return peel_object(base
, sha1
);
1829 * Call fn for each reference in the specified ref_cache, omitting
1830 * references not in the containing_dir of base. fn is called for all
1831 * references, including broken ones. If fn ever returns a non-zero
1832 * value, stop the iteration and return that value; otherwise, return
1835 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1836 each_ref_entry_fn fn
, void *cb_data
)
1838 struct packed_ref_cache
*packed_ref_cache
;
1839 struct ref_dir
*loose_dir
;
1840 struct ref_dir
*packed_dir
;
1844 * We must make sure that all loose refs are read before accessing the
1845 * packed-refs file; this avoids a race condition in which loose refs
1846 * are migrated to the packed-refs file by a simultaneous process, but
1847 * our in-memory view is from before the migration. get_packed_ref_cache()
1848 * takes care of making sure our view is up to date with what is on
1851 loose_dir
= get_loose_refs(refs
);
1852 if (base
&& *base
) {
1853 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1856 prime_ref_dir(loose_dir
);
1858 packed_ref_cache
= get_packed_ref_cache(refs
);
1859 acquire_packed_ref_cache(packed_ref_cache
);
1860 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1861 if (base
&& *base
) {
1862 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1865 if (packed_dir
&& loose_dir
) {
1866 sort_ref_dir(packed_dir
);
1867 sort_ref_dir(loose_dir
);
1868 retval
= do_for_each_entry_in_dirs(
1869 packed_dir
, loose_dir
, fn
, cb_data
);
1870 } else if (packed_dir
) {
1871 sort_ref_dir(packed_dir
);
1872 retval
= do_for_each_entry_in_dir(
1873 packed_dir
, 0, fn
, cb_data
);
1874 } else if (loose_dir
) {
1875 sort_ref_dir(loose_dir
);
1876 retval
= do_for_each_entry_in_dir(
1877 loose_dir
, 0, fn
, cb_data
);
1880 release_packed_ref_cache(packed_ref_cache
);
1885 * Call fn for each reference in the specified ref_cache for which the
1886 * refname begins with base. If trim is non-zero, then trim that many
1887 * characters off the beginning of each refname before passing the
1888 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1889 * broken references in the iteration. If fn ever returns a non-zero
1890 * value, stop the iteration and return that value; otherwise, return
1893 int do_for_each_ref(const char *submodule
, const char *base
,
1894 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1896 struct ref_entry_cb data
;
1897 struct ref_cache
*refs
;
1899 refs
= get_ref_cache(submodule
);
1904 data
.cb_data
= cb_data
;
1906 if (ref_paranoia
< 0)
1907 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
1909 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1911 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
1915 * Verify that the reference locked by lock has the value old_sha1.
1916 * Fail if the reference doesn't exist and mustexist is set. Return 0
1917 * on success. On error, write an error message to err, set errno, and
1918 * return a negative value.
1920 static int verify_lock(struct ref_lock
*lock
,
1921 const unsigned char *old_sha1
, int mustexist
,
1926 if (read_ref_full(lock
->ref_name
,
1927 mustexist
? RESOLVE_REF_READING
: 0,
1928 lock
->old_oid
.hash
, NULL
)) {
1930 int save_errno
= errno
;
1931 strbuf_addf(err
, "can't verify ref '%s'", lock
->ref_name
);
1935 hashclr(lock
->old_oid
.hash
);
1939 if (old_sha1
&& hashcmp(lock
->old_oid
.hash
, old_sha1
)) {
1940 strbuf_addf(err
, "ref '%s' is at %s but expected %s",
1942 sha1_to_hex(lock
->old_oid
.hash
),
1943 sha1_to_hex(old_sha1
));
1950 static int remove_empty_directories(struct strbuf
*path
)
1953 * we want to create a file but there is a directory there;
1954 * if that is an empty directory (or a directory that contains
1955 * only empty directories), remove them.
1957 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
1961 * Locks a ref returning the lock on success and NULL on failure.
1962 * On failure errno is set to something meaningful.
1964 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
1965 const unsigned char *old_sha1
,
1966 const struct string_list
*extras
,
1967 const struct string_list
*skip
,
1968 unsigned int flags
, int *type
,
1971 struct strbuf ref_file
= STRBUF_INIT
;
1972 struct strbuf orig_ref_file
= STRBUF_INIT
;
1973 const char *orig_refname
= refname
;
1974 struct ref_lock
*lock
;
1977 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
1978 int resolve_flags
= 0;
1979 int attempts_remaining
= 3;
1983 lock
= xcalloc(1, sizeof(struct ref_lock
));
1986 resolve_flags
|= RESOLVE_REF_READING
;
1987 if (flags
& REF_DELETING
)
1988 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
1989 if (flags
& REF_NODEREF
) {
1990 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
1991 lflags
|= LOCK_NO_DEREF
;
1994 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
1995 lock
->old_oid
.hash
, type
);
1996 if (!refname
&& errno
== EISDIR
) {
1998 * we are trying to lock foo but we used to
1999 * have foo/bar which now does not exist;
2000 * it is normal for the empty directory 'foo'
2003 strbuf_git_path(&orig_ref_file
, "%s", orig_refname
);
2004 if (remove_empty_directories(&orig_ref_file
)) {
2006 if (!verify_refname_available_dir(orig_refname
, extras
, skip
,
2007 get_loose_refs(&ref_cache
), err
))
2008 strbuf_addf(err
, "there are still refs under '%s'",
2012 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2013 lock
->old_oid
.hash
, type
);
2017 if (last_errno
!= ENOTDIR
||
2018 !verify_refname_available_dir(orig_refname
, extras
, skip
,
2019 get_loose_refs(&ref_cache
), err
))
2020 strbuf_addf(err
, "unable to resolve reference '%s': %s",
2021 orig_refname
, strerror(last_errno
));
2026 if (flags
& REF_NODEREF
)
2027 refname
= orig_refname
;
2030 * If the ref did not exist and we are creating it, make sure
2031 * there is no existing packed ref whose name begins with our
2032 * refname, nor a packed ref whose name is a proper prefix of
2035 if (is_null_oid(&lock
->old_oid
) &&
2036 verify_refname_available_dir(refname
, extras
, skip
,
2037 get_packed_refs(&ref_cache
), err
)) {
2038 last_errno
= ENOTDIR
;
2042 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2044 lock
->ref_name
= xstrdup(refname
);
2045 lock
->orig_ref_name
= xstrdup(orig_refname
);
2046 strbuf_git_path(&ref_file
, "%s", refname
);
2049 switch (safe_create_leading_directories_const(ref_file
.buf
)) {
2051 break; /* success */
2053 if (--attempts_remaining
> 0)
2058 strbuf_addf(err
, "unable to create directory for '%s'",
2063 if (hold_lock_file_for_update(lock
->lk
, ref_file
.buf
, lflags
) < 0) {
2065 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2067 * Maybe somebody just deleted one of the
2068 * directories leading to ref_file. Try
2073 unable_to_lock_message(ref_file
.buf
, errno
, err
);
2077 if (verify_lock(lock
, old_sha1
, mustexist
, err
)) {
2088 strbuf_release(&ref_file
);
2089 strbuf_release(&orig_ref_file
);
2095 * Write an entry to the packed-refs file for the specified refname.
2096 * If peeled is non-NULL, write it as the entry's peeled value.
2098 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2099 unsigned char *peeled
)
2101 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2103 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2107 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2109 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2111 enum peel_status peel_status
= peel_entry(entry
, 0);
2113 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2114 error("internal error: %s is not a valid packed reference!",
2116 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.oid
.hash
,
2117 peel_status
== PEEL_PEELED
?
2118 entry
->u
.value
.peeled
.hash
: NULL
);
2123 * Lock the packed-refs file for writing. Flags is passed to
2124 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2125 * errno appropriately and return a nonzero value.
2127 static int lock_packed_refs(int flags
)
2129 static int timeout_configured
= 0;
2130 static int timeout_value
= 1000;
2132 struct packed_ref_cache
*packed_ref_cache
;
2134 if (!timeout_configured
) {
2135 git_config_get_int("core.packedrefstimeout", &timeout_value
);
2136 timeout_configured
= 1;
2139 if (hold_lock_file_for_update_timeout(
2140 &packlock
, git_path("packed-refs"),
2141 flags
, timeout_value
) < 0)
2144 * Get the current packed-refs while holding the lock. If the
2145 * packed-refs file has been modified since we last read it,
2146 * this will automatically invalidate the cache and re-read
2147 * the packed-refs file.
2149 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2150 packed_ref_cache
->lock
= &packlock
;
2151 /* Increment the reference count to prevent it from being freed: */
2152 acquire_packed_ref_cache(packed_ref_cache
);
2157 * Write the current version of the packed refs cache from memory to
2158 * disk. The packed-refs file must already be locked for writing (see
2159 * lock_packed_refs()). Return zero on success. On errors, set errno
2160 * and return a nonzero value
2162 static int commit_packed_refs(void)
2164 struct packed_ref_cache
*packed_ref_cache
=
2165 get_packed_ref_cache(&ref_cache
);
2170 if (!packed_ref_cache
->lock
)
2171 die("internal error: packed-refs not locked");
2173 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2175 die_errno("unable to fdopen packed-refs descriptor");
2177 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2178 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2179 0, write_packed_entry_fn
, out
);
2181 if (commit_lock_file(packed_ref_cache
->lock
)) {
2185 packed_ref_cache
->lock
= NULL
;
2186 release_packed_ref_cache(packed_ref_cache
);
2192 * Rollback the lockfile for the packed-refs file, and discard the
2193 * in-memory packed reference cache. (The packed-refs file will be
2194 * read anew if it is needed again after this function is called.)
2196 static void rollback_packed_refs(void)
2198 struct packed_ref_cache
*packed_ref_cache
=
2199 get_packed_ref_cache(&ref_cache
);
2201 if (!packed_ref_cache
->lock
)
2202 die("internal error: packed-refs not locked");
2203 rollback_lock_file(packed_ref_cache
->lock
);
2204 packed_ref_cache
->lock
= NULL
;
2205 release_packed_ref_cache(packed_ref_cache
);
2206 clear_packed_ref_cache(&ref_cache
);
2209 struct ref_to_prune
{
2210 struct ref_to_prune
*next
;
2211 unsigned char sha1
[20];
2212 char name
[FLEX_ARRAY
];
2215 struct pack_refs_cb_data
{
2217 struct ref_dir
*packed_refs
;
2218 struct ref_to_prune
*ref_to_prune
;
2222 * An each_ref_entry_fn that is run over loose references only. If
2223 * the loose reference can be packed, add an entry in the packed ref
2224 * cache. If the reference should be pruned, also add it to
2225 * ref_to_prune in the pack_refs_cb_data.
2227 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2229 struct pack_refs_cb_data
*cb
= cb_data
;
2230 enum peel_status peel_status
;
2231 struct ref_entry
*packed_entry
;
2232 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2234 /* Do not pack per-worktree refs: */
2235 if (ref_type(entry
->name
) != REF_TYPE_NORMAL
)
2238 /* ALWAYS pack tags */
2239 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2242 /* Do not pack symbolic or broken refs: */
2243 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2246 /* Add a packed ref cache entry equivalent to the loose entry. */
2247 peel_status
= peel_entry(entry
, 1);
2248 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2249 die("internal error peeling reference %s (%s)",
2250 entry
->name
, oid_to_hex(&entry
->u
.value
.oid
));
2251 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2253 /* Overwrite existing packed entry with info from loose entry */
2254 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2255 oidcpy(&packed_entry
->u
.value
.oid
, &entry
->u
.value
.oid
);
2257 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.oid
.hash
,
2258 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2259 add_ref(cb
->packed_refs
, packed_entry
);
2261 oidcpy(&packed_entry
->u
.value
.peeled
, &entry
->u
.value
.peeled
);
2263 /* Schedule the loose reference for pruning if requested. */
2264 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2265 struct ref_to_prune
*n
;
2266 FLEX_ALLOC_STR(n
, name
, entry
->name
);
2267 hashcpy(n
->sha1
, entry
->u
.value
.oid
.hash
);
2268 n
->next
= cb
->ref_to_prune
;
2269 cb
->ref_to_prune
= n
;
2275 * Remove empty parents, but spare refs/ and immediate subdirs.
2276 * Note: munges *name.
2278 static void try_remove_empty_parents(char *name
)
2283 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2284 while (*p
&& *p
!= '/')
2286 /* tolerate duplicate slashes; see check_refname_format() */
2290 for (q
= p
; *q
; q
++)
2293 while (q
> p
&& *q
!= '/')
2295 while (q
> p
&& *(q
-1) == '/')
2300 if (rmdir(git_path("%s", name
)))
2305 /* make sure nobody touched the ref, and unlink */
2306 static void prune_ref(struct ref_to_prune
*r
)
2308 struct ref_transaction
*transaction
;
2309 struct strbuf err
= STRBUF_INIT
;
2311 if (check_refname_format(r
->name
, 0))
2314 transaction
= ref_transaction_begin(&err
);
2316 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2317 REF_ISPRUNING
| REF_NODEREF
, NULL
, &err
) ||
2318 ref_transaction_commit(transaction
, &err
)) {
2319 ref_transaction_free(transaction
);
2320 error("%s", err
.buf
);
2321 strbuf_release(&err
);
2324 ref_transaction_free(transaction
);
2325 strbuf_release(&err
);
2326 try_remove_empty_parents(r
->name
);
2329 static void prune_refs(struct ref_to_prune
*r
)
2337 int pack_refs(unsigned int flags
)
2339 struct pack_refs_cb_data cbdata
;
2341 memset(&cbdata
, 0, sizeof(cbdata
));
2342 cbdata
.flags
= flags
;
2344 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2345 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2347 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2348 pack_if_possible_fn
, &cbdata
);
2350 if (commit_packed_refs())
2351 die_errno("unable to overwrite old ref-pack file");
2353 prune_refs(cbdata
.ref_to_prune
);
2358 * Rewrite the packed-refs file, omitting any refs listed in
2359 * 'refnames'. On error, leave packed-refs unchanged, write an error
2360 * message to 'err', and return a nonzero value.
2362 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2364 static int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2366 struct ref_dir
*packed
;
2367 struct string_list_item
*refname
;
2368 int ret
, needs_repacking
= 0, removed
= 0;
2372 /* Look for a packed ref */
2373 for_each_string_list_item(refname
, refnames
) {
2374 if (get_packed_ref(refname
->string
)) {
2375 needs_repacking
= 1;
2380 /* Avoid locking if we have nothing to do */
2381 if (!needs_repacking
)
2382 return 0; /* no refname exists in packed refs */
2384 if (lock_packed_refs(0)) {
2385 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2388 packed
= get_packed_refs(&ref_cache
);
2390 /* Remove refnames from the cache */
2391 for_each_string_list_item(refname
, refnames
)
2392 if (remove_entry(packed
, refname
->string
) != -1)
2396 * All packed entries disappeared while we were
2397 * acquiring the lock.
2399 rollback_packed_refs();
2403 /* Write what remains */
2404 ret
= commit_packed_refs();
2406 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2411 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2415 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2417 * loose. The loose file name is the same as the
2418 * lockfile name, minus ".lock":
2420 char *loose_filename
= get_locked_file_path(lock
->lk
);
2421 int res
= unlink_or_msg(loose_filename
, err
);
2422 free(loose_filename
);
2429 int delete_refs(struct string_list
*refnames
)
2431 struct strbuf err
= STRBUF_INIT
;
2437 result
= repack_without_refs(refnames
, &err
);
2440 * If we failed to rewrite the packed-refs file, then
2441 * it is unsafe to try to remove loose refs, because
2442 * doing so might expose an obsolete packed value for
2443 * a reference that might even point at an object that
2444 * has been garbage collected.
2446 if (refnames
->nr
== 1)
2447 error(_("could not delete reference %s: %s"),
2448 refnames
->items
[0].string
, err
.buf
);
2450 error(_("could not delete references: %s"), err
.buf
);
2455 for (i
= 0; i
< refnames
->nr
; i
++) {
2456 const char *refname
= refnames
->items
[i
].string
;
2458 if (delete_ref(refname
, NULL
, 0))
2459 result
|= error(_("could not remove reference %s"), refname
);
2463 strbuf_release(&err
);
2468 * People using contrib's git-new-workdir have .git/logs/refs ->
2469 * /some/other/path/.git/logs/refs, and that may live on another device.
2471 * IOW, to avoid cross device rename errors, the temporary renamed log must
2472 * live into logs/refs.
2474 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2476 static int rename_tmp_log(const char *newrefname
)
2478 int attempts_remaining
= 4;
2479 struct strbuf path
= STRBUF_INIT
;
2483 strbuf_reset(&path
);
2484 strbuf_git_path(&path
, "logs/%s", newrefname
);
2485 switch (safe_create_leading_directories_const(path
.buf
)) {
2487 break; /* success */
2489 if (--attempts_remaining
> 0)
2493 error("unable to create directory for %s", newrefname
);
2497 if (rename(git_path(TMP_RENAMED_LOG
), path
.buf
)) {
2498 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2500 * rename(a, b) when b is an existing
2501 * directory ought to result in ISDIR, but
2502 * Solaris 5.8 gives ENOTDIR. Sheesh.
2504 if (remove_empty_directories(&path
)) {
2505 error("Directory not empty: logs/%s", newrefname
);
2509 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2511 * Maybe another process just deleted one of
2512 * the directories in the path to newrefname.
2513 * Try again from the beginning.
2517 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2518 newrefname
, strerror(errno
));
2524 strbuf_release(&path
);
2528 int verify_refname_available(const char *newname
,
2529 const struct string_list
*extras
,
2530 const struct string_list
*skip
,
2533 struct ref_dir
*packed_refs
= get_packed_refs(&ref_cache
);
2534 struct ref_dir
*loose_refs
= get_loose_refs(&ref_cache
);
2536 if (verify_refname_available_dir(newname
, extras
, skip
,
2537 packed_refs
, err
) ||
2538 verify_refname_available_dir(newname
, extras
, skip
,
2545 static int write_ref_to_lockfile(struct ref_lock
*lock
,
2546 const unsigned char *sha1
, struct strbuf
*err
);
2547 static int commit_ref_update(struct ref_lock
*lock
,
2548 const unsigned char *sha1
, const char *logmsg
,
2549 int flags
, struct strbuf
*err
);
2551 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2553 unsigned char sha1
[20], orig_sha1
[20];
2554 int flag
= 0, logmoved
= 0;
2555 struct ref_lock
*lock
;
2556 struct stat loginfo
;
2557 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2558 struct strbuf err
= STRBUF_INIT
;
2560 if (log
&& S_ISLNK(loginfo
.st_mode
))
2561 return error("reflog for %s is a symlink", oldrefname
);
2563 if (!resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
2565 return error("refname %s not found", oldrefname
);
2567 if (flag
& REF_ISSYMREF
)
2568 return error("refname %s is a symbolic ref, renaming it is not supported",
2570 if (!rename_ref_available(oldrefname
, newrefname
))
2573 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2574 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2575 oldrefname
, strerror(errno
));
2577 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2578 error("unable to delete old %s", oldrefname
);
2583 * Since we are doing a shallow lookup, sha1 is not the
2584 * correct value to pass to delete_ref as old_sha1. But that
2585 * doesn't matter, because an old_sha1 check wouldn't add to
2586 * the safety anyway; we want to delete the reference whatever
2587 * its current value.
2589 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
,
2591 delete_ref(newrefname
, NULL
, REF_NODEREF
)) {
2592 if (errno
==EISDIR
) {
2593 struct strbuf path
= STRBUF_INIT
;
2596 strbuf_git_path(&path
, "%s", newrefname
);
2597 result
= remove_empty_directories(&path
);
2598 strbuf_release(&path
);
2601 error("Directory not empty: %s", newrefname
);
2605 error("unable to delete existing %s", newrefname
);
2610 if (log
&& rename_tmp_log(newrefname
))
2615 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, REF_NODEREF
,
2618 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
2619 strbuf_release(&err
);
2622 hashcpy(lock
->old_oid
.hash
, orig_sha1
);
2624 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
2625 commit_ref_update(lock
, orig_sha1
, logmsg
, 0, &err
)) {
2626 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
2627 strbuf_release(&err
);
2634 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, REF_NODEREF
,
2637 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
2638 strbuf_release(&err
);
2642 flag
= log_all_ref_updates
;
2643 log_all_ref_updates
= 0;
2644 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
2645 commit_ref_update(lock
, orig_sha1
, NULL
, 0, &err
)) {
2646 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
2647 strbuf_release(&err
);
2649 log_all_ref_updates
= flag
;
2652 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2653 error("unable to restore logfile %s from %s: %s",
2654 oldrefname
, newrefname
, strerror(errno
));
2655 if (!logmoved
&& log
&&
2656 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2657 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2658 oldrefname
, strerror(errno
));
2663 static int close_ref(struct ref_lock
*lock
)
2665 if (close_lock_file(lock
->lk
))
2670 static int commit_ref(struct ref_lock
*lock
)
2672 char *path
= get_locked_file_path(lock
->lk
);
2675 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
)) {
2677 * There is a directory at the path we want to rename
2678 * the lockfile to. Hopefully it is empty; try to
2681 size_t len
= strlen(path
);
2682 struct strbuf sb_path
= STRBUF_INIT
;
2684 strbuf_attach(&sb_path
, path
, len
, len
);
2687 * If this fails, commit_lock_file() will also fail
2688 * and will report the problem.
2690 remove_empty_directories(&sb_path
);
2691 strbuf_release(&sb_path
);
2696 if (commit_lock_file(lock
->lk
))
2702 * Create a reflog for a ref. If force_create = 0, the reflog will
2703 * only be created for certain refs (those for which
2704 * should_autocreate_reflog returns non-zero. Otherwise, create it
2705 * regardless of the ref name. Fill in *err and return -1 on failure.
2707 static int log_ref_setup(const char *refname
, struct strbuf
*logfile
, struct strbuf
*err
, int force_create
)
2709 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2711 strbuf_git_path(logfile
, "logs/%s", refname
);
2712 if (force_create
|| should_autocreate_reflog(refname
)) {
2713 if (safe_create_leading_directories(logfile
->buf
) < 0) {
2714 strbuf_addf(err
, "unable to create directory for '%s': "
2715 "%s", logfile
->buf
, strerror(errno
));
2721 logfd
= open(logfile
->buf
, oflags
, 0666);
2723 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
2726 if (errno
== EISDIR
) {
2727 if (remove_empty_directories(logfile
)) {
2728 strbuf_addf(err
, "there are still logs under "
2729 "'%s'", logfile
->buf
);
2732 logfd
= open(logfile
->buf
, oflags
, 0666);
2736 strbuf_addf(err
, "unable to append to '%s': %s",
2737 logfile
->buf
, strerror(errno
));
2742 adjust_shared_perm(logfile
->buf
);
2748 int safe_create_reflog(const char *refname
, int force_create
, struct strbuf
*err
)
2751 struct strbuf sb
= STRBUF_INIT
;
2753 ret
= log_ref_setup(refname
, &sb
, err
, force_create
);
2754 strbuf_release(&sb
);
2758 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
2759 const unsigned char *new_sha1
,
2760 const char *committer
, const char *msg
)
2762 int msglen
, written
;
2763 unsigned maxlen
, len
;
2766 msglen
= msg
? strlen(msg
) : 0;
2767 maxlen
= strlen(committer
) + msglen
+ 100;
2768 logrec
= xmalloc(maxlen
);
2769 len
= xsnprintf(logrec
, maxlen
, "%s %s %s\n",
2770 sha1_to_hex(old_sha1
),
2771 sha1_to_hex(new_sha1
),
2774 len
+= copy_reflog_msg(logrec
+ len
- 1, msg
) - 1;
2776 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
2784 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
2785 const unsigned char *new_sha1
, const char *msg
,
2786 struct strbuf
*logfile
, int flags
,
2789 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
2791 if (log_all_ref_updates
< 0)
2792 log_all_ref_updates
= !is_bare_repository();
2794 result
= log_ref_setup(refname
, logfile
, err
, flags
& REF_FORCE_CREATE_REFLOG
);
2799 logfd
= open(logfile
->buf
, oflags
);
2802 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
2803 git_committer_info(0), msg
);
2805 strbuf_addf(err
, "unable to append to '%s': %s", logfile
->buf
,
2811 strbuf_addf(err
, "unable to append to '%s': %s", logfile
->buf
,
2818 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
2819 const unsigned char *new_sha1
, const char *msg
,
2820 int flags
, struct strbuf
*err
)
2822 return files_log_ref_write(refname
, old_sha1
, new_sha1
, msg
, flags
,
2826 int files_log_ref_write(const char *refname
, const unsigned char *old_sha1
,
2827 const unsigned char *new_sha1
, const char *msg
,
2828 int flags
, struct strbuf
*err
)
2830 struct strbuf sb
= STRBUF_INIT
;
2831 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
, flags
,
2833 strbuf_release(&sb
);
2838 * Write sha1 into the open lockfile, then close the lockfile. On
2839 * errors, rollback the lockfile, fill in *err and
2842 static int write_ref_to_lockfile(struct ref_lock
*lock
,
2843 const unsigned char *sha1
, struct strbuf
*err
)
2845 static char term
= '\n';
2849 o
= parse_object(sha1
);
2852 "trying to write ref '%s' with nonexistent object %s",
2853 lock
->ref_name
, sha1_to_hex(sha1
));
2857 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
2859 "trying to write non-commit object %s to branch '%s'",
2860 sha1_to_hex(sha1
), lock
->ref_name
);
2864 fd
= get_lock_file_fd(lock
->lk
);
2865 if (write_in_full(fd
, sha1_to_hex(sha1
), 40) != 40 ||
2866 write_in_full(fd
, &term
, 1) != 1 ||
2867 close_ref(lock
) < 0) {
2869 "couldn't write '%s'", get_lock_file_path(lock
->lk
));
2877 * Commit a change to a loose reference that has already been written
2878 * to the loose reference lockfile. Also update the reflogs if
2879 * necessary, using the specified lockmsg (which can be NULL).
2881 static int commit_ref_update(struct ref_lock
*lock
,
2882 const unsigned char *sha1
, const char *logmsg
,
2883 int flags
, struct strbuf
*err
)
2885 clear_loose_ref_cache(&ref_cache
);
2886 if (log_ref_write(lock
->ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, flags
, err
) < 0 ||
2887 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
2888 log_ref_write(lock
->orig_ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, flags
, err
) < 0)) {
2889 char *old_msg
= strbuf_detach(err
, NULL
);
2890 strbuf_addf(err
, "cannot update the ref '%s': %s",
2891 lock
->ref_name
, old_msg
);
2896 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
2898 * Special hack: If a branch is updated directly and HEAD
2899 * points to it (may happen on the remote side of a push
2900 * for example) then logically the HEAD reflog should be
2902 * A generic solution implies reverse symref information,
2903 * but finding all symrefs pointing to the given branch
2904 * would be rather costly for this rare event (the direct
2905 * update of a branch) to be worth it. So let's cheat and
2906 * check with HEAD only which should cover 99% of all usage
2907 * scenarios (even 100% of the default ones).
2909 unsigned char head_sha1
[20];
2911 const char *head_ref
;
2912 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
2913 head_sha1
, &head_flag
);
2914 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
2915 !strcmp(head_ref
, lock
->ref_name
)) {
2916 struct strbuf log_err
= STRBUF_INIT
;
2917 if (log_ref_write("HEAD", lock
->old_oid
.hash
, sha1
,
2918 logmsg
, 0, &log_err
)) {
2919 error("%s", log_err
.buf
);
2920 strbuf_release(&log_err
);
2924 if (!(flags
& REF_LOG_ONLY
) && commit_ref(lock
)) {
2925 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
2934 static int create_ref_symlink(struct ref_lock
*lock
, const char *target
)
2937 #ifndef NO_SYMLINK_HEAD
2938 char *ref_path
= get_locked_file_path(lock
->lk
);
2940 ret
= symlink(target
, ref_path
);
2944 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
2949 static void update_symref_reflog(struct ref_lock
*lock
, const char *refname
,
2950 const char *target
, const char *logmsg
)
2952 struct strbuf err
= STRBUF_INIT
;
2953 unsigned char new_sha1
[20];
2954 if (logmsg
&& !read_ref(target
, new_sha1
) &&
2955 log_ref_write(refname
, lock
->old_oid
.hash
, new_sha1
, logmsg
, 0, &err
)) {
2956 error("%s", err
.buf
);
2957 strbuf_release(&err
);
2961 static int create_symref_locked(struct ref_lock
*lock
, const char *refname
,
2962 const char *target
, const char *logmsg
)
2964 if (prefer_symlink_refs
&& !create_ref_symlink(lock
, target
)) {
2965 update_symref_reflog(lock
, refname
, target
, logmsg
);
2969 if (!fdopen_lock_file(lock
->lk
, "w"))
2970 return error("unable to fdopen %s: %s",
2971 lock
->lk
->tempfile
.filename
.buf
, strerror(errno
));
2973 update_symref_reflog(lock
, refname
, target
, logmsg
);
2975 /* no error check; commit_ref will check ferror */
2976 fprintf(lock
->lk
->tempfile
.fp
, "ref: %s\n", target
);
2977 if (commit_ref(lock
) < 0)
2978 return error("unable to write symref for %s: %s", refname
,
2983 int create_symref(const char *refname
, const char *target
, const char *logmsg
)
2985 struct strbuf err
= STRBUF_INIT
;
2986 struct ref_lock
*lock
;
2989 lock
= lock_ref_sha1_basic(refname
, NULL
, NULL
, NULL
, REF_NODEREF
, NULL
,
2992 error("%s", err
.buf
);
2993 strbuf_release(&err
);
2997 ret
= create_symref_locked(lock
, refname
, target
, logmsg
);
3002 int set_worktree_head_symref(const char *gitdir
, const char *target
)
3004 static struct lock_file head_lock
;
3005 struct ref_lock
*lock
;
3006 struct strbuf head_path
= STRBUF_INIT
;
3007 const char *head_rel
;
3010 strbuf_addf(&head_path
, "%s/HEAD", absolute_path(gitdir
));
3011 if (hold_lock_file_for_update(&head_lock
, head_path
.buf
,
3012 LOCK_NO_DEREF
) < 0) {
3013 struct strbuf err
= STRBUF_INIT
;
3014 unable_to_lock_message(head_path
.buf
, errno
, &err
);
3015 error("%s", err
.buf
);
3016 strbuf_release(&err
);
3017 strbuf_release(&head_path
);
3021 /* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for
3023 head_rel
= remove_leading_path(head_path
.buf
,
3024 absolute_path(get_git_common_dir()));
3025 /* to make use of create_symref_locked(), initialize ref_lock */
3026 lock
= xcalloc(1, sizeof(struct ref_lock
));
3027 lock
->lk
= &head_lock
;
3028 lock
->ref_name
= xstrdup(head_rel
);
3029 lock
->orig_ref_name
= xstrdup(head_rel
);
3031 ret
= create_symref_locked(lock
, head_rel
, target
, NULL
);
3033 unlock_ref(lock
); /* will free lock */
3034 strbuf_release(&head_path
);
3038 int reflog_exists(const char *refname
)
3042 return !lstat(git_path("logs/%s", refname
), &st
) &&
3043 S_ISREG(st
.st_mode
);
3046 int delete_reflog(const char *refname
)
3048 return remove_path(git_path("logs/%s", refname
));
3051 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3053 unsigned char osha1
[20], nsha1
[20];
3054 char *email_end
, *message
;
3055 unsigned long timestamp
;
3058 /* old SP new SP name <email> SP time TAB msg LF */
3059 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3060 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3061 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3062 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3063 email_end
[1] != ' ' ||
3064 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3065 !message
|| message
[0] != ' ' ||
3066 (message
[1] != '+' && message
[1] != '-') ||
3067 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3068 !isdigit(message
[4]) || !isdigit(message
[5]))
3069 return 0; /* corrupt? */
3070 email_end
[1] = '\0';
3071 tz
= strtol(message
+ 1, NULL
, 10);
3072 if (message
[6] != '\t')
3076 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3079 static char *find_beginning_of_line(char *bob
, char *scan
)
3081 while (bob
< scan
&& *(--scan
) != '\n')
3082 ; /* keep scanning backwards */
3084 * Return either beginning of the buffer, or LF at the end of
3085 * the previous line.
3090 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3092 struct strbuf sb
= STRBUF_INIT
;
3095 int ret
= 0, at_tail
= 1;
3097 logfp
= fopen(git_path("logs/%s", refname
), "r");
3101 /* Jump to the end */
3102 if (fseek(logfp
, 0, SEEK_END
) < 0)
3103 return error("cannot seek back reflog for %s: %s",
3104 refname
, strerror(errno
));
3106 while (!ret
&& 0 < pos
) {
3112 /* Fill next block from the end */
3113 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3114 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3115 return error("cannot seek back reflog for %s: %s",
3116 refname
, strerror(errno
));
3117 nread
= fread(buf
, cnt
, 1, logfp
);
3119 return error("cannot read %d bytes from reflog for %s: %s",
3120 cnt
, refname
, strerror(errno
));
3123 scanp
= endp
= buf
+ cnt
;
3124 if (at_tail
&& scanp
[-1] == '\n')
3125 /* Looking at the final LF at the end of the file */
3129 while (buf
< scanp
) {
3131 * terminating LF of the previous line, or the beginning
3136 bp
= find_beginning_of_line(buf
, scanp
);
3140 * The newline is the end of the previous line,
3141 * so we know we have complete line starting
3142 * at (bp + 1). Prefix it onto any prior data
3143 * we collected for the line and process it.
3145 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3148 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3154 * We are at the start of the buffer, and the
3155 * start of the file; there is no previous
3156 * line, and we have everything for this one.
3157 * Process it, and we can end the loop.
3159 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3160 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3167 * We are at the start of the buffer, and there
3168 * is more file to read backwards. Which means
3169 * we are in the middle of a line. Note that we
3170 * may get here even if *bp was a newline; that
3171 * just means we are at the exact end of the
3172 * previous line, rather than some spot in the
3175 * Save away what we have to be combined with
3176 * the data from the next read.
3178 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3185 die("BUG: reverse reflog parser had leftover data");
3188 strbuf_release(&sb
);
3192 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3195 struct strbuf sb
= STRBUF_INIT
;
3198 logfp
= fopen(git_path("logs/%s", refname
), "r");
3202 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3203 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3205 strbuf_release(&sb
);
3209 * Call fn for each reflog in the namespace indicated by name. name
3210 * must be empty or end with '/'. Name will be used as a scratch
3211 * space, but its contents will be restored before return.
3213 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3215 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3218 int oldlen
= name
->len
;
3221 return name
->len
? errno
: 0;
3223 while ((de
= readdir(d
)) != NULL
) {
3226 if (de
->d_name
[0] == '.')
3228 if (ends_with(de
->d_name
, ".lock"))
3230 strbuf_addstr(name
, de
->d_name
);
3231 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3232 ; /* silently ignore */
3234 if (S_ISDIR(st
.st_mode
)) {
3235 strbuf_addch(name
, '/');
3236 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3238 struct object_id oid
;
3240 if (read_ref_full(name
->buf
, 0, oid
.hash
, NULL
))
3241 retval
= error("bad ref for %s", name
->buf
);
3243 retval
= fn(name
->buf
, &oid
, 0, cb_data
);
3248 strbuf_setlen(name
, oldlen
);
3254 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3258 strbuf_init(&name
, PATH_MAX
);
3259 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3260 strbuf_release(&name
);
3264 static int ref_update_reject_duplicates(struct string_list
*refnames
,
3267 int i
, n
= refnames
->nr
;
3271 for (i
= 1; i
< n
; i
++)
3272 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
3274 "multiple updates for ref '%s' not allowed.",
3275 refnames
->items
[i
].string
);
3282 * If update is a direct update of head_ref (the reference pointed to
3283 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
3285 static int split_head_update(struct ref_update
*update
,
3286 struct ref_transaction
*transaction
,
3287 const char *head_ref
,
3288 struct string_list
*affected_refnames
,
3291 struct string_list_item
*item
;
3292 struct ref_update
*new_update
;
3294 if ((update
->flags
& REF_LOG_ONLY
) ||
3295 (update
->flags
& REF_ISPRUNING
) ||
3296 (update
->flags
& REF_UPDATE_VIA_HEAD
))
3299 if (strcmp(update
->refname
, head_ref
))
3303 * First make sure that HEAD is not already in the
3304 * transaction. This insertion is O(N) in the transaction
3305 * size, but it happens at most once per transaction.
3307 item
= string_list_insert(affected_refnames
, "HEAD");
3309 /* An entry already existed */
3311 "multiple updates for 'HEAD' (including one "
3312 "via its referent '%s') are not allowed",
3314 return TRANSACTION_NAME_CONFLICT
;
3317 new_update
= ref_transaction_add_update(
3318 transaction
, "HEAD",
3319 update
->flags
| REF_LOG_ONLY
| REF_NODEREF
,
3320 update
->new_sha1
, update
->old_sha1
,
3323 item
->util
= new_update
;
3329 * update is for a symref that points at referent and doesn't have
3330 * REF_NODEREF set. Split it into two updates:
3331 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
3332 * - A new, separate update for the referent reference
3333 * Note that the new update will itself be subject to splitting when
3334 * the iteration gets to it.
3336 static int split_symref_update(struct ref_update
*update
,
3337 const char *referent
,
3338 struct ref_transaction
*transaction
,
3339 struct string_list
*affected_refnames
,
3342 struct string_list_item
*item
;
3343 struct ref_update
*new_update
;
3344 unsigned int new_flags
;
3347 * First make sure that referent is not already in the
3348 * transaction. This insertion is O(N) in the transaction
3349 * size, but it happens at most once per symref in a
3352 item
= string_list_insert(affected_refnames
, referent
);
3354 /* An entry already existed */
3356 "multiple updates for '%s' (including one "
3357 "via symref '%s') are not allowed",
3358 referent
, update
->refname
);
3359 return TRANSACTION_NAME_CONFLICT
;
3362 new_flags
= update
->flags
;
3363 if (!strcmp(update
->refname
, "HEAD")) {
3365 * Record that the new update came via HEAD, so that
3366 * when we process it, split_head_update() doesn't try
3367 * to add another reflog update for HEAD. Note that
3368 * this bit will be propagated if the new_update
3369 * itself needs to be split.
3371 new_flags
|= REF_UPDATE_VIA_HEAD
;
3374 new_update
= ref_transaction_add_update(
3375 transaction
, referent
, new_flags
,
3376 update
->new_sha1
, update
->old_sha1
,
3379 /* Change the symbolic ref update to log only: */
3380 update
->flags
|= REF_LOG_ONLY
| REF_NODEREF
;
3382 item
->util
= new_update
;
3388 * Prepare for carrying out update:
3389 * - Lock the reference referred to by update.
3390 * - Read the reference under lock.
3391 * - Check that its old SHA-1 value (if specified) is correct, and in
3392 * any case record it in update->lock->old_oid for later use when
3393 * writing the reflog.
3394 * - If it is a symref update without REF_NODEREF, split it up into a
3395 * REF_LOG_ONLY update of the symref and add a separate update for
3396 * the referent to transaction.
3397 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
3400 static int lock_ref_for_update(struct ref_update
*update
,
3401 struct ref_transaction
*transaction
,
3402 const char *head_ref
,
3403 struct string_list
*affected_refnames
,
3406 struct strbuf referent
= STRBUF_INIT
;
3407 int mustexist
= (update
->flags
& REF_HAVE_OLD
) &&
3408 !is_null_sha1(update
->old_sha1
);
3410 struct ref_lock
*lock
;
3412 if ((update
->flags
& REF_HAVE_NEW
) && is_null_sha1(update
->new_sha1
))
3413 update
->flags
|= REF_DELETING
;
3416 ret
= split_head_update(update
, transaction
, head_ref
,
3417 affected_refnames
, err
);
3422 ret
= lock_raw_ref(update
->refname
, mustexist
,
3423 affected_refnames
, NULL
,
3424 &update
->lock
, &referent
,
3425 &update
->type
, err
);
3430 reason
= strbuf_detach(err
, NULL
);
3431 strbuf_addf(err
, "cannot lock ref '%s': %s",
3432 update
->refname
, reason
);
3437 lock
= update
->lock
;
3439 if (read_ref_full(update
->refname
,
3440 mustexist
? RESOLVE_REF_READING
: 0,
3441 lock
->old_oid
.hash
, NULL
)) {
3442 if (update
->flags
& REF_HAVE_OLD
) {
3443 strbuf_addf(err
, "cannot lock ref '%s': can't resolve old value",
3445 return TRANSACTION_GENERIC_ERROR
;
3447 hashclr(lock
->old_oid
.hash
);
3450 if ((update
->flags
& REF_HAVE_OLD
) &&
3451 hashcmp(lock
->old_oid
.hash
, update
->old_sha1
)) {
3452 strbuf_addf(err
, "cannot lock ref '%s': is at %s but expected %s",
3454 sha1_to_hex(lock
->old_oid
.hash
),
3455 sha1_to_hex(update
->old_sha1
));
3456 return TRANSACTION_GENERIC_ERROR
;
3459 if (update
->type
& REF_ISSYMREF
) {
3460 if (!(update
->flags
& REF_NODEREF
)) {
3461 ret
= split_symref_update(update
, referent
.buf
, transaction
,
3462 affected_refnames
, err
);
3468 if ((update
->flags
& REF_HAVE_NEW
) &&
3469 !(update
->flags
& REF_DELETING
) &&
3470 !(update
->flags
& REF_LOG_ONLY
)) {
3471 if (!(update
->type
& REF_ISSYMREF
) &&
3472 !hashcmp(lock
->old_oid
.hash
, update
->new_sha1
)) {
3474 * The reference already has the desired
3475 * value, so we don't need to write it.
3477 } else if (write_ref_to_lockfile(lock
, update
->new_sha1
,
3479 char *write_err
= strbuf_detach(err
, NULL
);
3482 * The lock was freed upon failure of
3483 * write_ref_to_lockfile():
3485 update
->lock
= NULL
;
3487 "cannot update the ref '%s': %s",
3488 update
->refname
, write_err
);
3490 return TRANSACTION_GENERIC_ERROR
;
3492 update
->flags
|= REF_NEEDS_COMMIT
;
3495 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
3497 * We didn't call write_ref_to_lockfile(), so
3498 * the lockfile is still open. Close it to
3499 * free up the file descriptor:
3501 if (close_ref(lock
)) {
3502 strbuf_addf(err
, "couldn't close '%s.lock'",
3504 return TRANSACTION_GENERIC_ERROR
;
3510 int ref_transaction_commit(struct ref_transaction
*transaction
,
3514 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3515 struct string_list_item
*ref_to_delete
;
3516 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3517 char *head_ref
= NULL
;
3519 struct object_id head_oid
;
3523 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3524 die("BUG: commit called for transaction that is not open");
3526 if (!transaction
->nr
) {
3527 transaction
->state
= REF_TRANSACTION_CLOSED
;
3532 * Fail if a refname appears more than once in the
3533 * transaction. (If we end up splitting up any updates using
3534 * split_symref_update() or split_head_update(), those
3535 * functions will check that the new updates don't have the
3536 * same refname as any existing ones.)
3538 for (i
= 0; i
< transaction
->nr
; i
++) {
3539 struct ref_update
*update
= transaction
->updates
[i
];
3540 struct string_list_item
*item
=
3541 string_list_append(&affected_refnames
, update
->refname
);
3544 * We store a pointer to update in item->util, but at
3545 * the moment we never use the value of this field
3546 * except to check whether it is non-NULL.
3548 item
->util
= update
;
3550 string_list_sort(&affected_refnames
);
3551 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
3552 ret
= TRANSACTION_GENERIC_ERROR
;
3557 * Special hack: If a branch is updated directly and HEAD
3558 * points to it (may happen on the remote side of a push
3559 * for example) then logically the HEAD reflog should be
3562 * A generic solution would require reverse symref lookups,
3563 * but finding all symrefs pointing to a given branch would be
3564 * rather costly for this rare event (the direct update of a
3565 * branch) to be worth it. So let's cheat and check with HEAD
3566 * only, which should cover 99% of all usage scenarios (even
3567 * 100% of the default ones).
3569 * So if HEAD is a symbolic reference, then record the name of
3570 * the reference that it points to. If we see an update of
3571 * head_ref within the transaction, then split_head_update()
3572 * arranges for the reflog of HEAD to be updated, too.
3574 head_ref
= resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE
,
3575 head_oid
.hash
, &head_type
);
3577 if (head_ref
&& !(head_type
& REF_ISSYMREF
)) {
3583 * Acquire all locks, verify old values if provided, check
3584 * that new values are valid, and write new values to the
3585 * lockfiles, ready to be activated. Only keep one lockfile
3586 * open at a time to avoid running out of file descriptors.
3588 for (i
= 0; i
< transaction
->nr
; i
++) {
3589 struct ref_update
*update
= transaction
->updates
[i
];
3591 ret
= lock_ref_for_update(update
, transaction
, head_ref
,
3592 &affected_refnames
, err
);
3597 /* Perform updates first so live commits remain referenced */
3598 for (i
= 0; i
< transaction
->nr
; i
++) {
3599 struct ref_update
*update
= transaction
->updates
[i
];
3600 struct ref_lock
*lock
= update
->lock
;
3602 if (update
->flags
& REF_NEEDS_COMMIT
||
3603 update
->flags
& REF_LOG_ONLY
) {
3604 if (log_ref_write(lock
->ref_name
, lock
->old_oid
.hash
,
3606 update
->msg
, update
->flags
, err
)) {
3607 char *old_msg
= strbuf_detach(err
, NULL
);
3609 strbuf_addf(err
, "cannot update the ref '%s': %s",
3610 lock
->ref_name
, old_msg
);
3613 update
->lock
= NULL
;
3614 ret
= TRANSACTION_GENERIC_ERROR
;
3618 if (update
->flags
& REF_NEEDS_COMMIT
) {
3619 clear_loose_ref_cache(&ref_cache
);
3620 if (commit_ref(lock
)) {
3621 strbuf_addf(err
, "couldn't set '%s'", lock
->ref_name
);
3623 update
->lock
= NULL
;
3624 ret
= TRANSACTION_GENERIC_ERROR
;
3629 /* Perform deletes now that updates are safely completed */
3630 for (i
= 0; i
< transaction
->nr
; i
++) {
3631 struct ref_update
*update
= transaction
->updates
[i
];
3633 if (update
->flags
& REF_DELETING
&&
3634 !(update
->flags
& REF_LOG_ONLY
)) {
3635 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3636 ret
= TRANSACTION_GENERIC_ERROR
;
3640 if (!(update
->flags
& REF_ISPRUNING
))
3641 string_list_append(&refs_to_delete
,
3642 update
->lock
->ref_name
);
3646 if (repack_without_refs(&refs_to_delete
, err
)) {
3647 ret
= TRANSACTION_GENERIC_ERROR
;
3650 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3651 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3652 clear_loose_ref_cache(&ref_cache
);
3655 transaction
->state
= REF_TRANSACTION_CLOSED
;
3657 for (i
= 0; i
< transaction
->nr
; i
++)
3658 if (transaction
->updates
[i
]->lock
)
3659 unlock_ref(transaction
->updates
[i
]->lock
);
3660 string_list_clear(&refs_to_delete
, 0);
3662 string_list_clear(&affected_refnames
, 0);
3667 static int ref_present(const char *refname
,
3668 const struct object_id
*oid
, int flags
, void *cb_data
)
3670 struct string_list
*affected_refnames
= cb_data
;
3672 return string_list_has_string(affected_refnames
, refname
);
3675 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
3679 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3683 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3684 die("BUG: commit called for transaction that is not open");
3686 /* Fail if a refname appears more than once in the transaction: */
3687 for (i
= 0; i
< transaction
->nr
; i
++)
3688 string_list_append(&affected_refnames
,
3689 transaction
->updates
[i
]->refname
);
3690 string_list_sort(&affected_refnames
);
3691 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
3692 ret
= TRANSACTION_GENERIC_ERROR
;
3697 * It's really undefined to call this function in an active
3698 * repository or when there are existing references: we are
3699 * only locking and changing packed-refs, so (1) any
3700 * simultaneous processes might try to change a reference at
3701 * the same time we do, and (2) any existing loose versions of
3702 * the references that we are setting would have precedence
3703 * over our values. But some remote helpers create the remote
3704 * "HEAD" and "master" branches before calling this function,
3705 * so here we really only check that none of the references
3706 * that we are creating already exists.
3708 if (for_each_rawref(ref_present
, &affected_refnames
))
3709 die("BUG: initial ref transaction called with existing refs");
3711 for (i
= 0; i
< transaction
->nr
; i
++) {
3712 struct ref_update
*update
= transaction
->updates
[i
];
3714 if ((update
->flags
& REF_HAVE_OLD
) &&
3715 !is_null_sha1(update
->old_sha1
))
3716 die("BUG: initial ref transaction with old_sha1 set");
3717 if (verify_refname_available(update
->refname
,
3718 &affected_refnames
, NULL
,
3720 ret
= TRANSACTION_NAME_CONFLICT
;
3725 if (lock_packed_refs(0)) {
3726 strbuf_addf(err
, "unable to lock packed-refs file: %s",
3728 ret
= TRANSACTION_GENERIC_ERROR
;
3732 for (i
= 0; i
< transaction
->nr
; i
++) {
3733 struct ref_update
*update
= transaction
->updates
[i
];
3735 if ((update
->flags
& REF_HAVE_NEW
) &&
3736 !is_null_sha1(update
->new_sha1
))
3737 add_packed_ref(update
->refname
, update
->new_sha1
);
3740 if (commit_packed_refs()) {
3741 strbuf_addf(err
, "unable to commit packed-refs file: %s",
3743 ret
= TRANSACTION_GENERIC_ERROR
;
3748 transaction
->state
= REF_TRANSACTION_CLOSED
;
3749 string_list_clear(&affected_refnames
, 0);
3753 struct expire_reflog_cb
{
3755 reflog_expiry_should_prune_fn
*should_prune_fn
;
3758 unsigned char last_kept_sha1
[20];
3761 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
3762 const char *email
, unsigned long timestamp
, int tz
,
3763 const char *message
, void *cb_data
)
3765 struct expire_reflog_cb
*cb
= cb_data
;
3766 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
3768 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
3769 osha1
= cb
->last_kept_sha1
;
3771 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
3772 message
, policy_cb
)) {
3774 printf("would prune %s", message
);
3775 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3776 printf("prune %s", message
);
3779 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
3780 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
3781 email
, timestamp
, tz
, message
);
3782 hashcpy(cb
->last_kept_sha1
, nsha1
);
3784 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
3785 printf("keep %s", message
);
3790 int reflog_expire(const char *refname
, const unsigned char *sha1
,
3792 reflog_expiry_prepare_fn prepare_fn
,
3793 reflog_expiry_should_prune_fn should_prune_fn
,
3794 reflog_expiry_cleanup_fn cleanup_fn
,
3795 void *policy_cb_data
)
3797 static struct lock_file reflog_lock
;
3798 struct expire_reflog_cb cb
;
3799 struct ref_lock
*lock
;
3803 struct strbuf err
= STRBUF_INIT
;
3805 memset(&cb
, 0, sizeof(cb
));
3807 cb
.policy_cb
= policy_cb_data
;
3808 cb
.should_prune_fn
= should_prune_fn
;
3811 * The reflog file is locked by holding the lock on the
3812 * reference itself, plus we might need to update the
3813 * reference if --updateref was specified:
3815 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, REF_NODEREF
,
3818 error("cannot lock ref '%s': %s", refname
, err
.buf
);
3819 strbuf_release(&err
);
3822 if (!reflog_exists(refname
)) {
3827 log_file
= git_pathdup("logs/%s", refname
);
3828 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3830 * Even though holding $GIT_DIR/logs/$reflog.lock has
3831 * no locking implications, we use the lock_file
3832 * machinery here anyway because it does a lot of the
3833 * work we need, including cleaning up if the program
3834 * exits unexpectedly.
3836 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
3837 struct strbuf err
= STRBUF_INIT
;
3838 unable_to_lock_message(log_file
, errno
, &err
);
3839 error("%s", err
.buf
);
3840 strbuf_release(&err
);
3843 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
3845 error("cannot fdopen %s (%s)",
3846 get_lock_file_path(&reflog_lock
), strerror(errno
));
3851 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
3852 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
3853 (*cleanup_fn
)(cb
.policy_cb
);
3855 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
3857 * It doesn't make sense to adjust a reference pointed
3858 * to by a symbolic ref based on expiring entries in
3859 * the symbolic reference's reflog. Nor can we update
3860 * a reference if there are no remaining reflog
3863 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
3864 !(type
& REF_ISSYMREF
) &&
3865 !is_null_sha1(cb
.last_kept_sha1
);
3867 if (close_lock_file(&reflog_lock
)) {
3868 status
|= error("couldn't write %s: %s", log_file
,
3870 } else if (update
&&
3871 (write_in_full(get_lock_file_fd(lock
->lk
),
3872 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
3873 write_str_in_full(get_lock_file_fd(lock
->lk
), "\n") != 1 ||
3874 close_ref(lock
) < 0)) {
3875 status
|= error("couldn't write %s",
3876 get_lock_file_path(lock
->lk
));
3877 rollback_lock_file(&reflog_lock
);
3878 } else if (commit_lock_file(&reflog_lock
)) {
3879 status
|= error("unable to write reflog '%s' (%s)",
3880 log_file
, strerror(errno
));
3881 } else if (update
&& commit_ref(lock
)) {
3882 status
|= error("couldn't set %s", lock
->ref_name
);
3890 rollback_lock_file(&reflog_lock
);