7 #include "string-list.h"
10 * How to handle various characters in refnames:
11 * 0: An acceptable character for refs
13 * 2: ., look for a preceding . to reject .. in refs
14 * 3: {, look for a preceding @ to reject @{ in refs
15 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
17 static unsigned char refname_disposition
[256] = {
18 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
19 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
20 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
25 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
29 * Used as a flag to ref_transaction_delete when a loose ref is being
32 #define REF_ISPRUNING 0x0100
34 * Try to read one refname component from the front of refname.
35 * Return the length of the component found, or -1 if the component is
36 * not legal. It is legal if it is something reasonable to have under
37 * ".git/refs/"; We do not like it if:
39 * - any path component of it begins with ".", or
40 * - it has double dots "..", or
41 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
42 * - it ends with a "/".
43 * - it ends with ".lock"
44 * - it contains a "\" (backslash)
46 static int check_refname_component(const char *refname
, int flags
)
51 for (cp
= refname
; ; cp
++) {
53 unsigned char disp
= refname_disposition
[ch
];
59 return -1; /* Refname contains "..". */
63 return -1; /* Refname contains "@{". */
72 return 0; /* Component has zero length. */
73 if (refname
[0] == '.')
74 return -1; /* Component starts with '.'. */
75 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
76 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
77 return -1; /* Refname ends with ".lock". */
81 int check_refname_format(const char *refname
, int flags
)
83 int component_len
, component_count
= 0;
85 if (!strcmp(refname
, "@"))
86 /* Refname is a single character '@'. */
90 /* We are at the start of a path component. */
91 component_len
= check_refname_component(refname
, flags
);
92 if (component_len
<= 0) {
93 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
95 (refname
[1] == '\0' || refname
[1] == '/')) {
96 /* Accept one wildcard as a full refname component. */
97 flags
&= ~REFNAME_REFSPEC_PATTERN
;
104 if (refname
[component_len
] == '\0')
106 /* Skip to next component. */
107 refname
+= component_len
+ 1;
110 if (refname
[component_len
- 1] == '.')
111 return -1; /* Refname ends with '.'. */
112 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
113 return -1; /* Refname has only one component. */
120 * Information used (along with the information in ref_entry) to
121 * describe a single cached reference. This data structure only
122 * occurs embedded in a union in struct ref_entry, and only when
123 * (ref_entry->flag & REF_DIR) is zero.
127 * The name of the object to which this reference resolves
128 * (which may be a tag object). If REF_ISBROKEN, this is
129 * null. If REF_ISSYMREF, then this is the name of the object
130 * referred to by the last reference in the symlink chain.
132 unsigned char sha1
[20];
135 * If REF_KNOWS_PEELED, then this field holds the peeled value
136 * of this reference, or null if the reference is known not to
137 * be peelable. See the documentation for peel_ref() for an
138 * exact definition of "peelable".
140 unsigned char peeled
[20];
146 * Information used (along with the information in ref_entry) to
147 * describe a level in the hierarchy of references. This data
148 * structure only occurs embedded in a union in struct ref_entry, and
149 * only when (ref_entry.flag & REF_DIR) is set. In that case,
150 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
151 * in the directory have already been read:
153 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
154 * or packed references, already read.
156 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
157 * references that hasn't been read yet (nor has any of its
160 * Entries within a directory are stored within a growable array of
161 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
162 * sorted are sorted by their component name in strcmp() order and the
163 * remaining entries are unsorted.
165 * Loose references are read lazily, one directory at a time. When a
166 * directory of loose references is read, then all of the references
167 * in that directory are stored, and REF_INCOMPLETE stubs are created
168 * for any subdirectories, but the subdirectories themselves are not
169 * read. The reading is triggered by get_ref_dir().
175 * Entries with index 0 <= i < sorted are sorted by name. New
176 * entries are appended to the list unsorted, and are sorted
177 * only when required; thus we avoid the need to sort the list
178 * after the addition of every reference.
182 /* A pointer to the ref_cache that contains this ref_dir. */
183 struct ref_cache
*ref_cache
;
185 struct ref_entry
**entries
;
189 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
190 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see
195 * The field ref_entry->u.value.peeled of this value entry contains
196 * the correct peeled value for the reference, which might be
197 * null_sha1 if the reference is not a tag or if it is broken.
199 #define REF_KNOWS_PEELED 0x08
201 /* ref_entry represents a directory of references */
205 * Entry has not yet been read from disk (used only for REF_DIR
206 * entries representing loose references)
208 #define REF_INCOMPLETE 0x20
211 * A ref_entry represents either a reference or a "subdirectory" of
214 * Each directory in the reference namespace is represented by a
215 * ref_entry with (flags & REF_DIR) set and containing a subdir member
216 * that holds the entries in that directory that have been read so
217 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
218 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
219 * used for loose reference directories.
221 * References are represented by a ref_entry with (flags & REF_DIR)
222 * unset and a value member that describes the reference's value. The
223 * flag member is at the ref_entry level, but it is also needed to
224 * interpret the contents of the value field (in other words, a
225 * ref_value object is not very much use without the enclosing
228 * Reference names cannot end with slash and directories' names are
229 * always stored with a trailing slash (except for the top-level
230 * directory, which is always denoted by ""). This has two nice
231 * consequences: (1) when the entries in each subdir are sorted
232 * lexicographically by name (as they usually are), the references in
233 * a whole tree can be generated in lexicographic order by traversing
234 * the tree in left-to-right, depth-first order; (2) the names of
235 * references and subdirectories cannot conflict, and therefore the
236 * presence of an empty subdirectory does not block the creation of a
237 * similarly-named reference. (The fact that reference names with the
238 * same leading components can conflict *with each other* is a
239 * separate issue that is regulated by is_refname_available().)
241 * Please note that the name field contains the fully-qualified
242 * reference (or subdirectory) name. Space could be saved by only
243 * storing the relative names. But that would require the full names
244 * to be generated on the fly when iterating in do_for_each_ref(), and
245 * would break callback functions, who have always been able to assume
246 * that the name strings that they are passed will not be freed during
250 unsigned char flag
; /* ISSYMREF? ISPACKED? */
252 struct ref_value value
; /* if not (flags&REF_DIR) */
253 struct ref_dir subdir
; /* if (flags&REF_DIR) */
256 * The full name of the reference (e.g., "refs/heads/master")
257 * or the full name of the directory with a trailing slash
258 * (e.g., "refs/heads/"):
260 char name
[FLEX_ARRAY
];
263 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
265 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
268 assert(entry
->flag
& REF_DIR
);
269 dir
= &entry
->u
.subdir
;
270 if (entry
->flag
& REF_INCOMPLETE
) {
271 read_loose_refs(entry
->name
, dir
);
272 entry
->flag
&= ~REF_INCOMPLETE
;
277 static struct ref_entry
*create_ref_entry(const char *refname
,
278 const unsigned char *sha1
, int flag
,
282 struct ref_entry
*ref
;
285 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
286 die("Reference has invalid format: '%s'", refname
);
287 len
= strlen(refname
) + 1;
288 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
289 hashcpy(ref
->u
.value
.sha1
, sha1
);
290 hashclr(ref
->u
.value
.peeled
);
291 memcpy(ref
->name
, refname
, len
);
296 static void clear_ref_dir(struct ref_dir
*dir
);
298 static void free_ref_entry(struct ref_entry
*entry
)
300 if (entry
->flag
& REF_DIR
) {
302 * Do not use get_ref_dir() here, as that might
303 * trigger the reading of loose refs.
305 clear_ref_dir(&entry
->u
.subdir
);
311 * Add a ref_entry to the end of dir (unsorted). Entry is always
312 * stored directly in dir; no recursion into subdirectories is
315 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
317 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
318 dir
->entries
[dir
->nr
++] = entry
;
319 /* optimize for the case that entries are added in order */
321 (dir
->nr
== dir
->sorted
+ 1 &&
322 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
323 dir
->entries
[dir
->nr
- 1]->name
) < 0))
324 dir
->sorted
= dir
->nr
;
328 * Clear and free all entries in dir, recursively.
330 static void clear_ref_dir(struct ref_dir
*dir
)
333 for (i
= 0; i
< dir
->nr
; i
++)
334 free_ref_entry(dir
->entries
[i
]);
336 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
341 * Create a struct ref_entry object for the specified dirname.
342 * dirname is the name of the directory with a trailing slash (e.g.,
343 * "refs/heads/") or "" for the top-level directory.
345 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
346 const char *dirname
, size_t len
,
349 struct ref_entry
*direntry
;
350 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
351 memcpy(direntry
->name
, dirname
, len
);
352 direntry
->name
[len
] = '\0';
353 direntry
->u
.subdir
.ref_cache
= ref_cache
;
354 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
358 static int ref_entry_cmp(const void *a
, const void *b
)
360 struct ref_entry
*one
= *(struct ref_entry
**)a
;
361 struct ref_entry
*two
= *(struct ref_entry
**)b
;
362 return strcmp(one
->name
, two
->name
);
365 static void sort_ref_dir(struct ref_dir
*dir
);
367 struct string_slice
{
372 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
374 const struct string_slice
*key
= key_
;
375 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
376 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
379 return '\0' - (unsigned char)ent
->name
[key
->len
];
383 * Return the index of the entry with the given refname from the
384 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
385 * no such entry is found. dir must already be complete.
387 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
389 struct ref_entry
**r
;
390 struct string_slice key
;
392 if (refname
== NULL
|| !dir
->nr
)
398 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
399 ref_entry_cmp_sslice
);
404 return r
- dir
->entries
;
408 * Search for a directory entry directly within dir (without
409 * recursing). Sort dir if necessary. subdirname must be a directory
410 * name (i.e., end in '/'). If mkdir is set, then create the
411 * directory if it is missing; otherwise, return NULL if the desired
412 * directory cannot be found. dir must already be complete.
414 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
415 const char *subdirname
, size_t len
,
418 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
419 struct ref_entry
*entry
;
420 if (entry_index
== -1) {
424 * Since dir is complete, the absence of a subdir
425 * means that the subdir really doesn't exist;
426 * therefore, create an empty record for it but mark
427 * the record complete.
429 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
430 add_entry_to_dir(dir
, entry
);
432 entry
= dir
->entries
[entry_index
];
434 return get_ref_dir(entry
);
438 * If refname is a reference name, find the ref_dir within the dir
439 * tree that should hold refname. If refname is a directory name
440 * (i.e., ends in '/'), then return that ref_dir itself. dir must
441 * represent the top-level directory and must already be complete.
442 * Sort ref_dirs and recurse into subdirectories as necessary. If
443 * mkdir is set, then create any missing directories; otherwise,
444 * return NULL if the desired directory cannot be found.
446 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
447 const char *refname
, int mkdir
)
450 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
451 size_t dirnamelen
= slash
- refname
+ 1;
452 struct ref_dir
*subdir
;
453 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
465 * Find the value entry with the given name in dir, sorting ref_dirs
466 * and recursing into subdirectories as necessary. If the name is not
467 * found or it corresponds to a directory entry, return NULL.
469 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
472 struct ref_entry
*entry
;
473 dir
= find_containing_dir(dir
, refname
, 0);
476 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
477 if (entry_index
== -1)
479 entry
= dir
->entries
[entry_index
];
480 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
484 * Remove the entry with the given name from dir, recursing into
485 * subdirectories as necessary. If refname is the name of a directory
486 * (i.e., ends with '/'), then remove the directory and its contents.
487 * If the removal was successful, return the number of entries
488 * remaining in the directory entry that contained the deleted entry.
489 * If the name was not found, return -1. Please note that this
490 * function only deletes the entry from the cache; it does not delete
491 * it from the filesystem or ensure that other cache entries (which
492 * might be symbolic references to the removed entry) are updated.
493 * Nor does it remove any containing dir entries that might be made
494 * empty by the removal. dir must represent the top-level directory
495 * and must already be complete.
497 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
499 int refname_len
= strlen(refname
);
501 struct ref_entry
*entry
;
502 int is_dir
= refname
[refname_len
- 1] == '/';
505 * refname represents a reference directory. Remove
506 * the trailing slash; otherwise we will get the
507 * directory *representing* refname rather than the
508 * one *containing* it.
510 char *dirname
= xmemdupz(refname
, refname_len
- 1);
511 dir
= find_containing_dir(dir
, dirname
, 0);
514 dir
= find_containing_dir(dir
, refname
, 0);
518 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
519 if (entry_index
== -1)
521 entry
= dir
->entries
[entry_index
];
523 memmove(&dir
->entries
[entry_index
],
524 &dir
->entries
[entry_index
+ 1],
525 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
528 if (dir
->sorted
> entry_index
)
530 free_ref_entry(entry
);
535 * Add a ref_entry to the ref_dir (unsorted), recursing into
536 * subdirectories as necessary. dir must represent the top-level
537 * directory. Return 0 on success.
539 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
541 dir
= find_containing_dir(dir
, ref
->name
, 1);
544 add_entry_to_dir(dir
, ref
);
549 * Emit a warning and return true iff ref1 and ref2 have the same name
550 * and the same sha1. Die if they have the same name but different
553 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
555 if (strcmp(ref1
->name
, ref2
->name
))
558 /* Duplicate name; make sure that they don't conflict: */
560 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
561 /* This is impossible by construction */
562 die("Reference directory conflict: %s", ref1
->name
);
564 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
565 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
567 warning("Duplicated ref: %s", ref1
->name
);
572 * Sort the entries in dir non-recursively (if they are not already
573 * sorted) and remove any duplicate entries.
575 static void sort_ref_dir(struct ref_dir
*dir
)
578 struct ref_entry
*last
= NULL
;
581 * This check also prevents passing a zero-length array to qsort(),
582 * which is a problem on some platforms.
584 if (dir
->sorted
== dir
->nr
)
587 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
589 /* Remove any duplicates: */
590 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
591 struct ref_entry
*entry
= dir
->entries
[j
];
592 if (last
&& is_dup_ref(last
, entry
))
593 free_ref_entry(entry
);
595 last
= dir
->entries
[i
++] = entry
;
597 dir
->sorted
= dir
->nr
= i
;
600 /* Include broken references in a do_for_each_ref*() iteration: */
601 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
604 * Return true iff the reference described by entry can be resolved to
605 * an object in the database. Emit a warning if the referred-to
606 * object does not exist.
608 static int ref_resolves_to_object(struct ref_entry
*entry
)
610 if (entry
->flag
& REF_ISBROKEN
)
612 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
613 error("%s does not point to a valid object!", entry
->name
);
620 * current_ref is a performance hack: when iterating over references
621 * using the for_each_ref*() functions, current_ref is set to the
622 * current reference's entry before calling the callback function. If
623 * the callback function calls peel_ref(), then peel_ref() first
624 * checks whether the reference to be peeled is the current reference
625 * (it usually is) and if so, returns that reference's peeled version
626 * if it is available. This avoids a refname lookup in a common case.
628 static struct ref_entry
*current_ref
;
630 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
632 struct ref_entry_cb
{
641 * Handle one reference in a do_for_each_ref*()-style iteration,
642 * calling an each_ref_fn for each entry.
644 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
646 struct ref_entry_cb
*data
= cb_data
;
647 struct ref_entry
*old_current_ref
;
650 if (!starts_with(entry
->name
, data
->base
))
653 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
654 !ref_resolves_to_object(entry
))
657 /* Store the old value, in case this is a recursive call: */
658 old_current_ref
= current_ref
;
660 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
661 entry
->flag
, data
->cb_data
);
662 current_ref
= old_current_ref
;
667 * Call fn for each reference in dir that has index in the range
668 * offset <= index < dir->nr. Recurse into subdirectories that are in
669 * that index range, sorting them before iterating. This function
670 * does not sort dir itself; it should be sorted beforehand. fn is
671 * called for all references, including broken ones.
673 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
674 each_ref_entry_fn fn
, void *cb_data
)
677 assert(dir
->sorted
== dir
->nr
);
678 for (i
= offset
; i
< dir
->nr
; i
++) {
679 struct ref_entry
*entry
= dir
->entries
[i
];
681 if (entry
->flag
& REF_DIR
) {
682 struct ref_dir
*subdir
= get_ref_dir(entry
);
683 sort_ref_dir(subdir
);
684 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
686 retval
= fn(entry
, cb_data
);
695 * Call fn for each reference in the union of dir1 and dir2, in order
696 * by refname. Recurse into subdirectories. If a value entry appears
697 * in both dir1 and dir2, then only process the version that is in
698 * dir2. The input dirs must already be sorted, but subdirs will be
699 * sorted as needed. fn is called for all references, including
702 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
703 struct ref_dir
*dir2
,
704 each_ref_entry_fn fn
, void *cb_data
)
709 assert(dir1
->sorted
== dir1
->nr
);
710 assert(dir2
->sorted
== dir2
->nr
);
712 struct ref_entry
*e1
, *e2
;
714 if (i1
== dir1
->nr
) {
715 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
717 if (i2
== dir2
->nr
) {
718 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
720 e1
= dir1
->entries
[i1
];
721 e2
= dir2
->entries
[i2
];
722 cmp
= strcmp(e1
->name
, e2
->name
);
724 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
725 /* Both are directories; descend them in parallel. */
726 struct ref_dir
*subdir1
= get_ref_dir(e1
);
727 struct ref_dir
*subdir2
= get_ref_dir(e2
);
728 sort_ref_dir(subdir1
);
729 sort_ref_dir(subdir2
);
730 retval
= do_for_each_entry_in_dirs(
731 subdir1
, subdir2
, fn
, cb_data
);
734 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
735 /* Both are references; ignore the one from dir1. */
736 retval
= fn(e2
, cb_data
);
740 die("conflict between reference and directory: %s",
752 if (e
->flag
& REF_DIR
) {
753 struct ref_dir
*subdir
= get_ref_dir(e
);
754 sort_ref_dir(subdir
);
755 retval
= do_for_each_entry_in_dir(
756 subdir
, 0, fn
, cb_data
);
758 retval
= fn(e
, cb_data
);
767 * Load all of the refs from the dir into our in-memory cache. The hard work
768 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
769 * through all of the sub-directories. We do not even need to care about
770 * sorting, as traversal order does not matter to us.
772 static void prime_ref_dir(struct ref_dir
*dir
)
775 for (i
= 0; i
< dir
->nr
; i
++) {
776 struct ref_entry
*entry
= dir
->entries
[i
];
777 if (entry
->flag
& REF_DIR
)
778 prime_ref_dir(get_ref_dir(entry
));
782 static int entry_matches(struct ref_entry
*entry
, const struct string_list
*list
)
784 return list
&& string_list_has_string(list
, entry
->name
);
787 struct nonmatching_ref_data
{
788 const struct string_list
*skip
;
789 struct ref_entry
*found
;
792 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
794 struct nonmatching_ref_data
*data
= vdata
;
796 if (entry_matches(entry
, data
->skip
))
803 static void report_refname_conflict(struct ref_entry
*entry
,
806 error("'%s' exists; cannot create '%s'", entry
->name
, refname
);
810 * Return true iff a reference named refname could be created without
811 * conflicting with the name of an existing reference in dir. If
812 * skip is non-NULL, ignore potential conflicts with refs in skip
813 * (e.g., because they are scheduled for deletion in the same
816 * Two reference names conflict if one of them exactly matches the
817 * leading components of the other; e.g., "foo/bar" conflicts with
818 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
821 * skip must be sorted.
823 static int is_refname_available(const char *refname
,
824 const struct string_list
*skip
,
832 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
834 * We are still at a leading dir of the refname; we are
835 * looking for a conflict with a leaf entry.
837 * If we find one, we still must make sure it is
840 pos
= search_ref_dir(dir
, refname
, slash
- refname
);
842 struct ref_entry
*entry
= dir
->entries
[pos
];
843 if (entry_matches(entry
, skip
))
845 report_refname_conflict(entry
, refname
);
851 * Otherwise, we can try to continue our search with
852 * the next component; if we come up empty, we know
853 * there is nothing under this whole prefix.
855 pos
= search_ref_dir(dir
, refname
, slash
+ 1 - refname
);
859 dir
= get_ref_dir(dir
->entries
[pos
]);
863 * We are at the leaf of our refname; we want to
864 * make sure there are no directories which match it.
866 len
= strlen(refname
);
867 dirname
= xmallocz(len
+ 1);
868 sprintf(dirname
, "%s/", refname
);
869 pos
= search_ref_dir(dir
, dirname
, len
+ 1);
874 * We found a directory named "refname". It is a
875 * problem iff it contains any ref that is not
878 struct ref_entry
*entry
= dir
->entries
[pos
];
879 struct ref_dir
*dir
= get_ref_dir(entry
);
880 struct nonmatching_ref_data data
;
884 if (!do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
))
887 report_refname_conflict(data
.found
, refname
);
892 * There is no point in searching for another leaf
893 * node which matches it; such an entry would be the
894 * ref we are looking for, not a conflict.
899 struct packed_ref_cache
{
900 struct ref_entry
*root
;
903 * Count of references to the data structure in this instance,
904 * including the pointer from ref_cache::packed if any. The
905 * data will not be freed as long as the reference count is
908 unsigned int referrers
;
911 * Iff the packed-refs file associated with this instance is
912 * currently locked for writing, this points at the associated
913 * lock (which is owned by somebody else). The referrer count
914 * is also incremented when the file is locked and decremented
915 * when it is unlocked.
917 struct lock_file
*lock
;
919 /* The metadata from when this packed-refs cache was read */
920 struct stat_validity validity
;
924 * Future: need to be in "struct repository"
925 * when doing a full libification.
927 static struct ref_cache
{
928 struct ref_cache
*next
;
929 struct ref_entry
*loose
;
930 struct packed_ref_cache
*packed
;
932 * The submodule name, or "" for the main repo. We allocate
933 * length 1 rather than FLEX_ARRAY so that the main ref_cache
934 * is initialized correctly.
937 } ref_cache
, *submodule_ref_caches
;
939 /* Lock used for the main packed-refs file: */
940 static struct lock_file packlock
;
943 * Increment the reference count of *packed_refs.
945 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
947 packed_refs
->referrers
++;
951 * Decrease the reference count of *packed_refs. If it goes to zero,
952 * free *packed_refs and return true; otherwise return false.
954 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
956 if (!--packed_refs
->referrers
) {
957 free_ref_entry(packed_refs
->root
);
958 stat_validity_clear(&packed_refs
->validity
);
966 static void clear_packed_ref_cache(struct ref_cache
*refs
)
969 struct packed_ref_cache
*packed_refs
= refs
->packed
;
971 if (packed_refs
->lock
)
972 die("internal error: packed-ref cache cleared while locked");
974 release_packed_ref_cache(packed_refs
);
978 static void clear_loose_ref_cache(struct ref_cache
*refs
)
981 free_ref_entry(refs
->loose
);
986 static struct ref_cache
*create_ref_cache(const char *submodule
)
989 struct ref_cache
*refs
;
992 len
= strlen(submodule
) + 1;
993 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
994 memcpy(refs
->name
, submodule
, len
);
999 * Return a pointer to a ref_cache for the specified submodule. For
1000 * the main repository, use submodule==NULL. The returned structure
1001 * will be allocated and initialized but not necessarily populated; it
1002 * should not be freed.
1004 static struct ref_cache
*get_ref_cache(const char *submodule
)
1006 struct ref_cache
*refs
;
1008 if (!submodule
|| !*submodule
)
1011 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1012 if (!strcmp(submodule
, refs
->name
))
1015 refs
= create_ref_cache(submodule
);
1016 refs
->next
= submodule_ref_caches
;
1017 submodule_ref_caches
= refs
;
1021 /* The length of a peeled reference line in packed-refs, including EOL: */
1022 #define PEELED_LINE_LENGTH 42
1025 * The packed-refs header line that we write out. Perhaps other
1026 * traits will be added later. The trailing space is required.
1028 static const char PACKED_REFS_HEADER
[] =
1029 "# pack-refs with: peeled fully-peeled \n";
1032 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1033 * Return a pointer to the refname within the line (null-terminated),
1034 * or NULL if there was a problem.
1036 static const char *parse_ref_line(char *line
, unsigned char *sha1
)
1039 * 42: the answer to everything.
1041 * In this case, it happens to be the answer to
1042 * 40 (length of sha1 hex representation)
1043 * +1 (space in between hex and name)
1044 * +1 (newline at the end of the line)
1046 int len
= strlen(line
) - 42;
1050 if (get_sha1_hex(line
, sha1
) < 0)
1052 if (!isspace(line
[40]))
1057 if (line
[len
] != '\n')
1065 * Read f, which is a packed-refs file, into dir.
1067 * A comment line of the form "# pack-refs with: " may contain zero or
1068 * more traits. We interpret the traits as follows:
1072 * Probably no references are peeled. But if the file contains a
1073 * peeled value for a reference, we will use it.
1077 * References under "refs/tags/", if they *can* be peeled, *are*
1078 * peeled in this file. References outside of "refs/tags/" are
1079 * probably not peeled even if they could have been, but if we find
1080 * a peeled value for such a reference we will use it.
1084 * All references in the file that can be peeled are peeled.
1085 * Inversely (and this is more important), any references in the
1086 * file for which no peeled value is recorded is not peelable. This
1087 * trait should typically be written alongside "peeled" for
1088 * compatibility with older clients, but we do not require it
1089 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1091 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1093 struct ref_entry
*last
= NULL
;
1094 char refline
[PATH_MAX
];
1095 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1097 while (fgets(refline
, sizeof(refline
), f
)) {
1098 unsigned char sha1
[20];
1099 const char *refname
;
1100 static const char header
[] = "# pack-refs with:";
1102 if (!strncmp(refline
, header
, sizeof(header
)-1)) {
1103 const char *traits
= refline
+ sizeof(header
) - 1;
1104 if (strstr(traits
, " fully-peeled "))
1105 peeled
= PEELED_FULLY
;
1106 else if (strstr(traits
, " peeled "))
1107 peeled
= PEELED_TAGS
;
1108 /* perhaps other traits later as well */
1112 refname
= parse_ref_line(refline
, sha1
);
1114 last
= create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1);
1115 if (peeled
== PEELED_FULLY
||
1116 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1117 last
->flag
|= REF_KNOWS_PEELED
;
1122 refline
[0] == '^' &&
1123 strlen(refline
) == PEELED_LINE_LENGTH
&&
1124 refline
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1125 !get_sha1_hex(refline
+ 1, sha1
)) {
1126 hashcpy(last
->u
.value
.peeled
, sha1
);
1128 * Regardless of what the file header said,
1129 * we definitely know the value of *this*
1132 last
->flag
|= REF_KNOWS_PEELED
;
1138 * Get the packed_ref_cache for the specified ref_cache, creating it
1141 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1143 const char *packed_refs_file
;
1146 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1148 packed_refs_file
= git_path("packed-refs");
1151 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1152 clear_packed_ref_cache(refs
);
1154 if (!refs
->packed
) {
1157 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1158 acquire_packed_ref_cache(refs
->packed
);
1159 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1160 f
= fopen(packed_refs_file
, "r");
1162 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1163 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1167 return refs
->packed
;
1170 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1172 return get_ref_dir(packed_ref_cache
->root
);
1175 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1177 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1180 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1182 struct packed_ref_cache
*packed_ref_cache
=
1183 get_packed_ref_cache(&ref_cache
);
1185 if (!packed_ref_cache
->lock
)
1186 die("internal error: packed refs not locked");
1187 add_ref(get_packed_ref_dir(packed_ref_cache
),
1188 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1192 * Read the loose references from the namespace dirname into dir
1193 * (without recursing). dirname must end with '/'. dir must be the
1194 * directory entry corresponding to dirname.
1196 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1198 struct ref_cache
*refs
= dir
->ref_cache
;
1202 int dirnamelen
= strlen(dirname
);
1203 struct strbuf refname
;
1206 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1208 path
= git_path("%s", dirname
);
1214 strbuf_init(&refname
, dirnamelen
+ 257);
1215 strbuf_add(&refname
, dirname
, dirnamelen
);
1217 while ((de
= readdir(d
)) != NULL
) {
1218 unsigned char sha1
[20];
1223 if (de
->d_name
[0] == '.')
1225 if (ends_with(de
->d_name
, ".lock"))
1227 strbuf_addstr(&refname
, de
->d_name
);
1228 refdir
= *refs
->name
1229 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1230 : git_path("%s", refname
.buf
);
1231 if (stat(refdir
, &st
) < 0) {
1232 ; /* silently ignore */
1233 } else if (S_ISDIR(st
.st_mode
)) {
1234 strbuf_addch(&refname
, '/');
1235 add_entry_to_dir(dir
,
1236 create_dir_entry(refs
, refname
.buf
,
1242 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1244 flag
|= REF_ISBROKEN
;
1246 } else if (read_ref_full(refname
.buf
,
1247 RESOLVE_REF_READING
,
1250 flag
|= REF_ISBROKEN
;
1252 add_entry_to_dir(dir
,
1253 create_ref_entry(refname
.buf
, sha1
, flag
, 1));
1255 strbuf_setlen(&refname
, dirnamelen
);
1257 strbuf_release(&refname
);
1261 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1265 * Mark the top-level directory complete because we
1266 * are about to read the only subdirectory that can
1269 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1271 * Create an incomplete entry for "refs/":
1273 add_entry_to_dir(get_ref_dir(refs
->loose
),
1274 create_dir_entry(refs
, "refs/", 5, 1));
1276 return get_ref_dir(refs
->loose
);
1279 /* We allow "recursive" symbolic refs. Only within reason, though */
1281 #define MAXREFLEN (1024)
1284 * Called by resolve_gitlink_ref_recursive() after it failed to read
1285 * from the loose refs in ref_cache refs. Find <refname> in the
1286 * packed-refs file for the submodule.
1288 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1289 const char *refname
, unsigned char *sha1
)
1291 struct ref_entry
*ref
;
1292 struct ref_dir
*dir
= get_packed_refs(refs
);
1294 ref
= find_ref(dir
, refname
);
1298 hashcpy(sha1
, ref
->u
.value
.sha1
);
1302 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1303 const char *refname
, unsigned char *sha1
,
1307 char buffer
[128], *p
;
1310 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1313 ? git_path_submodule(refs
->name
, "%s", refname
)
1314 : git_path("%s", refname
);
1315 fd
= open(path
, O_RDONLY
);
1317 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1319 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1323 while (len
&& isspace(buffer
[len
-1]))
1327 /* Was it a detached head or an old-fashioned symlink? */
1328 if (!get_sha1_hex(buffer
, sha1
))
1332 if (strncmp(buffer
, "ref:", 4))
1338 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1341 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1343 int len
= strlen(path
), retval
;
1345 struct ref_cache
*refs
;
1347 while (len
&& path
[len
-1] == '/')
1351 submodule
= xstrndup(path
, len
);
1352 refs
= get_ref_cache(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. The
1370 * options are forwarded from resolve_safe_unsafe().
1372 static const char *handle_missing_loose_ref(const char *refname
,
1374 unsigned char *sha1
,
1377 struct ref_entry
*entry
;
1380 * The loose reference file does not exist; check for a packed
1383 entry
= get_packed_ref(refname
);
1385 hashcpy(sha1
, entry
->u
.value
.sha1
);
1387 *flags
|= REF_ISPACKED
;
1390 /* The reference is not a packed reference, either. */
1391 if (resolve_flags
& RESOLVE_REF_READING
) {
1399 /* This function needs to return a meaningful errno on failure */
1400 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1402 int depth
= MAXDEPTH
;
1405 static char refname_buffer
[256];
1410 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1415 char path
[PATH_MAX
];
1425 git_snpath(path
, sizeof(path
), "%s", refname
);
1428 * We might have to loop back here to avoid a race
1429 * condition: first we lstat() the file, then we try
1430 * to read it as a link or as a file. But if somebody
1431 * changes the type of the file (file <-> directory
1432 * <-> symlink) between the lstat() and reading, then
1433 * we don't want to report that as an error but rather
1434 * try again starting with the lstat().
1437 if (lstat(path
, &st
) < 0) {
1438 if (errno
== ENOENT
)
1439 return handle_missing_loose_ref(refname
,
1440 resolve_flags
, sha1
, flags
);
1445 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1446 if (S_ISLNK(st
.st_mode
)) {
1447 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1449 if (errno
== ENOENT
|| errno
== EINVAL
)
1450 /* inconsistent with lstat; retry */
1456 if (starts_with(buffer
, "refs/") &&
1457 !check_refname_format(buffer
, 0)) {
1458 strcpy(refname_buffer
, buffer
);
1459 refname
= refname_buffer
;
1461 *flags
|= REF_ISSYMREF
;
1462 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1470 /* Is it a directory? */
1471 if (S_ISDIR(st
.st_mode
)) {
1477 * Anything else, just open it and try to use it as
1480 fd
= open(path
, O_RDONLY
);
1482 if (errno
== ENOENT
)
1483 /* inconsistent with lstat; retry */
1488 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1490 int save_errno
= errno
;
1496 while (len
&& isspace(buffer
[len
-1]))
1501 * Is it a symbolic ref?
1503 if (!starts_with(buffer
, "ref:")) {
1505 * Please note that FETCH_HEAD has a second
1506 * line containing other data.
1508 if (get_sha1_hex(buffer
, sha1
) ||
1509 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1511 *flags
|= REF_ISBROKEN
;
1518 *flags
|= REF_ISSYMREF
;
1520 while (isspace(*buf
))
1522 refname
= strcpy(refname_buffer
, buf
);
1523 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1527 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1529 *flags
|= REF_ISBROKEN
;
1536 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1538 const char *ret
= resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
);
1539 return ret
? xstrdup(ret
) : NULL
;
1542 /* The argument to filter_refs */
1544 const char *pattern
;
1549 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1551 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1556 int read_ref(const char *refname
, unsigned char *sha1
)
1558 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1561 int ref_exists(const char *refname
)
1563 unsigned char sha1
[20];
1564 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1567 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1570 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1571 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1573 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1577 /* object was peeled successfully: */
1581 * object cannot be peeled because the named object (or an
1582 * object referred to by a tag in the peel chain), does not
1587 /* object cannot be peeled because it is not a tag: */
1590 /* ref_entry contains no peeled value because it is a symref: */
1591 PEEL_IS_SYMREF
= -3,
1594 * ref_entry cannot be peeled because it is broken (i.e., the
1595 * symbolic reference cannot even be resolved to an object
1602 * Peel the named object; i.e., if the object is a tag, resolve the
1603 * tag recursively until a non-tag is found. If successful, store the
1604 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1605 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1606 * and leave sha1 unchanged.
1608 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1610 struct object
*o
= lookup_unknown_object(name
);
1612 if (o
->type
== OBJ_NONE
) {
1613 int type
= sha1_object_info(name
, NULL
);
1614 if (type
< 0 || !object_as_type(o
, type
, 0))
1615 return PEEL_INVALID
;
1618 if (o
->type
!= OBJ_TAG
)
1619 return PEEL_NON_TAG
;
1621 o
= deref_tag_noverify(o
);
1623 return PEEL_INVALID
;
1625 hashcpy(sha1
, o
->sha1
);
1630 * Peel the entry (if possible) and return its new peel_status. If
1631 * repeel is true, re-peel the entry even if there is an old peeled
1632 * value that is already stored in it.
1634 * It is OK to call this function with a packed reference entry that
1635 * might be stale and might even refer to an object that has since
1636 * been garbage-collected. In such a case, if the entry has
1637 * REF_KNOWS_PEELED then leave the status unchanged and return
1638 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1640 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1642 enum peel_status status
;
1644 if (entry
->flag
& REF_KNOWS_PEELED
) {
1646 entry
->flag
&= ~REF_KNOWS_PEELED
;
1647 hashclr(entry
->u
.value
.peeled
);
1649 return is_null_sha1(entry
->u
.value
.peeled
) ?
1650 PEEL_NON_TAG
: PEEL_PEELED
;
1653 if (entry
->flag
& REF_ISBROKEN
)
1655 if (entry
->flag
& REF_ISSYMREF
)
1656 return PEEL_IS_SYMREF
;
1658 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1659 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1660 entry
->flag
|= REF_KNOWS_PEELED
;
1664 int peel_ref(const char *refname
, unsigned char *sha1
)
1667 unsigned char base
[20];
1669 if (current_ref
&& (current_ref
->name
== refname
1670 || !strcmp(current_ref
->name
, refname
))) {
1671 if (peel_entry(current_ref
, 0))
1673 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1677 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1681 * If the reference is packed, read its ref_entry from the
1682 * cache in the hope that we already know its peeled value.
1683 * We only try this optimization on packed references because
1684 * (a) forcing the filling of the loose reference cache could
1685 * be expensive and (b) loose references anyway usually do not
1686 * have REF_KNOWS_PEELED.
1688 if (flag
& REF_ISPACKED
) {
1689 struct ref_entry
*r
= get_packed_ref(refname
);
1691 if (peel_entry(r
, 0))
1693 hashcpy(sha1
, r
->u
.value
.peeled
);
1698 return peel_object(base
, sha1
);
1701 struct warn_if_dangling_data
{
1703 const char *refname
;
1704 const struct string_list
*refnames
;
1705 const char *msg_fmt
;
1708 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1709 int flags
, void *cb_data
)
1711 struct warn_if_dangling_data
*d
= cb_data
;
1712 const char *resolves_to
;
1713 unsigned char junk
[20];
1715 if (!(flags
& REF_ISSYMREF
))
1718 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1721 ? strcmp(resolves_to
, d
->refname
)
1722 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1726 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1731 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1733 struct warn_if_dangling_data data
;
1736 data
.refname
= refname
;
1737 data
.refnames
= NULL
;
1738 data
.msg_fmt
= msg_fmt
;
1739 for_each_rawref(warn_if_dangling_symref
, &data
);
1742 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1744 struct warn_if_dangling_data data
;
1747 data
.refname
= NULL
;
1748 data
.refnames
= refnames
;
1749 data
.msg_fmt
= msg_fmt
;
1750 for_each_rawref(warn_if_dangling_symref
, &data
);
1754 * Call fn for each reference in the specified ref_cache, omitting
1755 * references not in the containing_dir of base. fn is called for all
1756 * references, including broken ones. If fn ever returns a non-zero
1757 * value, stop the iteration and return that value; otherwise, return
1760 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1761 each_ref_entry_fn fn
, void *cb_data
)
1763 struct packed_ref_cache
*packed_ref_cache
;
1764 struct ref_dir
*loose_dir
;
1765 struct ref_dir
*packed_dir
;
1769 * We must make sure that all loose refs are read before accessing the
1770 * packed-refs file; this avoids a race condition in which loose refs
1771 * are migrated to the packed-refs file by a simultaneous process, but
1772 * our in-memory view is from before the migration. get_packed_ref_cache()
1773 * takes care of making sure our view is up to date with what is on
1776 loose_dir
= get_loose_refs(refs
);
1777 if (base
&& *base
) {
1778 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1781 prime_ref_dir(loose_dir
);
1783 packed_ref_cache
= get_packed_ref_cache(refs
);
1784 acquire_packed_ref_cache(packed_ref_cache
);
1785 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1786 if (base
&& *base
) {
1787 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1790 if (packed_dir
&& loose_dir
) {
1791 sort_ref_dir(packed_dir
);
1792 sort_ref_dir(loose_dir
);
1793 retval
= do_for_each_entry_in_dirs(
1794 packed_dir
, loose_dir
, fn
, cb_data
);
1795 } else if (packed_dir
) {
1796 sort_ref_dir(packed_dir
);
1797 retval
= do_for_each_entry_in_dir(
1798 packed_dir
, 0, fn
, cb_data
);
1799 } else if (loose_dir
) {
1800 sort_ref_dir(loose_dir
);
1801 retval
= do_for_each_entry_in_dir(
1802 loose_dir
, 0, fn
, cb_data
);
1805 release_packed_ref_cache(packed_ref_cache
);
1810 * Call fn for each reference in the specified ref_cache for which the
1811 * refname begins with base. If trim is non-zero, then trim that many
1812 * characters off the beginning of each refname before passing the
1813 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1814 * broken references in the iteration. If fn ever returns a non-zero
1815 * value, stop the iteration and return that value; otherwise, return
1818 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
1819 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1821 struct ref_entry_cb data
;
1826 data
.cb_data
= cb_data
;
1828 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
1831 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1833 unsigned char sha1
[20];
1837 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
1838 return fn("HEAD", sha1
, 0, cb_data
);
1843 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
1844 return fn("HEAD", sha1
, flag
, cb_data
);
1849 int head_ref(each_ref_fn fn
, void *cb_data
)
1851 return do_head_ref(NULL
, fn
, cb_data
);
1854 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1856 return do_head_ref(submodule
, fn
, cb_data
);
1859 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1861 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
1864 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1866 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
1869 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1871 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
1874 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
1875 each_ref_fn fn
, void *cb_data
)
1877 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
1880 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
1882 return for_each_ref_in("refs/tags/", fn
, cb_data
);
1885 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1887 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
1890 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
1892 return for_each_ref_in("refs/heads/", fn
, cb_data
);
1895 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1897 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
1900 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
1902 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
1905 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1907 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
1910 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
1912 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
1915 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
1917 struct strbuf buf
= STRBUF_INIT
;
1919 unsigned char sha1
[20];
1922 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
1923 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
1924 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
1925 strbuf_release(&buf
);
1930 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
1932 struct strbuf buf
= STRBUF_INIT
;
1934 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
1935 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
1936 strbuf_release(&buf
);
1940 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
1941 const char *prefix
, void *cb_data
)
1943 struct strbuf real_pattern
= STRBUF_INIT
;
1944 struct ref_filter filter
;
1947 if (!prefix
&& !starts_with(pattern
, "refs/"))
1948 strbuf_addstr(&real_pattern
, "refs/");
1950 strbuf_addstr(&real_pattern
, prefix
);
1951 strbuf_addstr(&real_pattern
, pattern
);
1953 if (!has_glob_specials(pattern
)) {
1954 /* Append implied '/' '*' if not present. */
1955 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
1956 strbuf_addch(&real_pattern
, '/');
1957 /* No need to check for '*', there is none. */
1958 strbuf_addch(&real_pattern
, '*');
1961 filter
.pattern
= real_pattern
.buf
;
1963 filter
.cb_data
= cb_data
;
1964 ret
= for_each_ref(filter_refs
, &filter
);
1966 strbuf_release(&real_pattern
);
1970 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
1972 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
1975 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
1977 return do_for_each_ref(&ref_cache
, "", fn
, 0,
1978 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1981 const char *prettify_refname(const char *name
)
1984 starts_with(name
, "refs/heads/") ? 11 :
1985 starts_with(name
, "refs/tags/") ? 10 :
1986 starts_with(name
, "refs/remotes/") ? 13 :
1990 static const char *ref_rev_parse_rules
[] = {
1995 "refs/remotes/%.*s",
1996 "refs/remotes/%.*s/HEAD",
2000 int refname_match(const char *abbrev_name
, const char *full_name
)
2003 const int abbrev_name_len
= strlen(abbrev_name
);
2005 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2006 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2014 /* This function should make sure errno is meaningful on error */
2015 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2016 const unsigned char *old_sha1
, int mustexist
)
2018 if (read_ref_full(lock
->ref_name
,
2019 mustexist
? RESOLVE_REF_READING
: 0,
2020 lock
->old_sha1
, NULL
)) {
2021 int save_errno
= errno
;
2022 error("Can't verify ref %s", lock
->ref_name
);
2027 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2028 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2029 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2037 static int remove_empty_directories(const char *file
)
2039 /* we want to create a file but there is a directory there;
2040 * if that is an empty directory (or a directory that contains
2041 * only empty directories), remove them.
2044 int result
, save_errno
;
2046 strbuf_init(&path
, 20);
2047 strbuf_addstr(&path
, file
);
2049 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2052 strbuf_release(&path
);
2059 * *string and *len will only be substituted, and *string returned (for
2060 * later free()ing) if the string passed in is a magic short-hand form
2063 static char *substitute_branch_name(const char **string
, int *len
)
2065 struct strbuf buf
= STRBUF_INIT
;
2066 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2070 *string
= strbuf_detach(&buf
, &size
);
2072 return (char *)*string
;
2078 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2080 char *last_branch
= substitute_branch_name(&str
, &len
);
2085 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2086 char fullref
[PATH_MAX
];
2087 unsigned char sha1_from_ref
[20];
2088 unsigned char *this_result
;
2091 this_result
= refs_found
? sha1_from_ref
: sha1
;
2092 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2093 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2094 this_result
, &flag
);
2098 if (!warn_ambiguous_refs
)
2100 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2101 warning("ignoring dangling symref %s.", fullref
);
2102 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2103 warning("ignoring broken ref %s.", fullref
);
2110 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2112 char *last_branch
= substitute_branch_name(&str
, &len
);
2117 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2118 unsigned char hash
[20];
2119 char path
[PATH_MAX
];
2120 const char *ref
, *it
;
2122 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2123 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2127 if (reflog_exists(path
))
2129 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2133 if (!logs_found
++) {
2135 hashcpy(sha1
, hash
);
2137 if (!warn_ambiguous_refs
)
2145 * Locks a ref returning the lock on success and NULL on failure.
2146 * On failure errno is set to something meaningful.
2148 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2149 const unsigned char *old_sha1
,
2150 const struct string_list
*skip
,
2151 int flags
, int *type_p
)
2154 const char *orig_refname
= refname
;
2155 struct ref_lock
*lock
;
2158 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2159 int resolve_flags
= 0;
2161 int attempts_remaining
= 3;
2163 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
2168 lock
= xcalloc(1, sizeof(struct ref_lock
));
2172 resolve_flags
|= RESOLVE_REF_READING
;
2173 if (flags
& REF_NODEREF
&& flags
& REF_DELETING
)
2174 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2176 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2177 lock
->old_sha1
, &type
);
2178 if (!refname
&& errno
== EISDIR
) {
2179 /* we are trying to lock foo but we used to
2180 * have foo/bar which now does not exist;
2181 * it is normal for the empty directory 'foo'
2184 ref_file
= git_path("%s", orig_refname
);
2185 if (remove_empty_directories(ref_file
)) {
2187 error("there are still refs under '%s'", orig_refname
);
2190 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2191 lock
->old_sha1
, &type
);
2197 error("unable to resolve reference %s: %s",
2198 orig_refname
, strerror(errno
));
2201 missing
= is_null_sha1(lock
->old_sha1
);
2202 /* When the ref did not exist and we are creating it,
2203 * make sure there is no existing ref that is packed
2204 * whose name begins with our refname, nor a ref whose
2205 * name is a proper prefix of our refname.
2208 !is_refname_available(refname
, skip
, get_packed_refs(&ref_cache
))) {
2209 last_errno
= ENOTDIR
;
2213 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2216 if (flags
& REF_NODEREF
) {
2217 refname
= orig_refname
;
2218 lflags
|= LOCK_NO_DEREF
;
2220 lock
->ref_name
= xstrdup(refname
);
2221 lock
->orig_ref_name
= xstrdup(orig_refname
);
2222 ref_file
= git_path("%s", refname
);
2224 lock
->force_write
= 1;
2225 if ((flags
& REF_NODEREF
) && (type
& REF_ISSYMREF
))
2226 lock
->force_write
= 1;
2229 switch (safe_create_leading_directories(ref_file
)) {
2231 break; /* success */
2233 if (--attempts_remaining
> 0)
2238 error("unable to create directory for %s", ref_file
);
2242 lock
->lock_fd
= hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
);
2243 if (lock
->lock_fd
< 0) {
2244 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2246 * Maybe somebody just deleted one of the
2247 * directories leading to ref_file. Try
2252 unable_to_lock_die(ref_file
, errno
);
2254 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2262 struct ref_lock
*lock_any_ref_for_update(const char *refname
,
2263 const unsigned char *old_sha1
,
2264 int flags
, int *type_p
)
2266 return lock_ref_sha1_basic(refname
, old_sha1
, NULL
, flags
, type_p
);
2270 * Write an entry to the packed-refs file for the specified refname.
2271 * If peeled is non-NULL, write it as the entry's peeled value.
2273 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2274 unsigned char *peeled
)
2276 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2278 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2282 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2284 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2286 enum peel_status peel_status
= peel_entry(entry
, 0);
2288 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2289 error("internal error: %s is not a valid packed reference!",
2291 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2292 peel_status
== PEEL_PEELED
?
2293 entry
->u
.value
.peeled
: NULL
);
2297 /* This should return a meaningful errno on failure */
2298 int lock_packed_refs(int flags
)
2300 struct packed_ref_cache
*packed_ref_cache
;
2302 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2305 * Get the current packed-refs while holding the lock. If the
2306 * packed-refs file has been modified since we last read it,
2307 * this will automatically invalidate the cache and re-read
2308 * the packed-refs file.
2310 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2311 packed_ref_cache
->lock
= &packlock
;
2312 /* Increment the reference count to prevent it from being freed: */
2313 acquire_packed_ref_cache(packed_ref_cache
);
2318 * Commit the packed refs changes.
2319 * On error we must make sure that errno contains a meaningful value.
2321 int commit_packed_refs(void)
2323 struct packed_ref_cache
*packed_ref_cache
=
2324 get_packed_ref_cache(&ref_cache
);
2329 if (!packed_ref_cache
->lock
)
2330 die("internal error: packed-refs not locked");
2332 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2334 die_errno("unable to fdopen packed-refs descriptor");
2336 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2337 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2338 0, write_packed_entry_fn
, out
);
2340 if (commit_lock_file(packed_ref_cache
->lock
)) {
2344 packed_ref_cache
->lock
= NULL
;
2345 release_packed_ref_cache(packed_ref_cache
);
2350 void rollback_packed_refs(void)
2352 struct packed_ref_cache
*packed_ref_cache
=
2353 get_packed_ref_cache(&ref_cache
);
2355 if (!packed_ref_cache
->lock
)
2356 die("internal error: packed-refs not locked");
2357 rollback_lock_file(packed_ref_cache
->lock
);
2358 packed_ref_cache
->lock
= NULL
;
2359 release_packed_ref_cache(packed_ref_cache
);
2360 clear_packed_ref_cache(&ref_cache
);
2363 struct ref_to_prune
{
2364 struct ref_to_prune
*next
;
2365 unsigned char sha1
[20];
2366 char name
[FLEX_ARRAY
];
2369 struct pack_refs_cb_data
{
2371 struct ref_dir
*packed_refs
;
2372 struct ref_to_prune
*ref_to_prune
;
2376 * An each_ref_entry_fn that is run over loose references only. If
2377 * the loose reference can be packed, add an entry in the packed ref
2378 * cache. If the reference should be pruned, also add it to
2379 * ref_to_prune in the pack_refs_cb_data.
2381 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2383 struct pack_refs_cb_data
*cb
= cb_data
;
2384 enum peel_status peel_status
;
2385 struct ref_entry
*packed_entry
;
2386 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2388 /* ALWAYS pack tags */
2389 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2392 /* Do not pack symbolic or broken refs: */
2393 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2396 /* Add a packed ref cache entry equivalent to the loose entry. */
2397 peel_status
= peel_entry(entry
, 1);
2398 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2399 die("internal error peeling reference %s (%s)",
2400 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2401 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2403 /* Overwrite existing packed entry with info from loose entry */
2404 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2405 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2407 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2408 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2409 add_ref(cb
->packed_refs
, packed_entry
);
2411 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2413 /* Schedule the loose reference for pruning if requested. */
2414 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2415 int namelen
= strlen(entry
->name
) + 1;
2416 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2417 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2418 strcpy(n
->name
, entry
->name
);
2419 n
->next
= cb
->ref_to_prune
;
2420 cb
->ref_to_prune
= n
;
2426 * Remove empty parents, but spare refs/ and immediate subdirs.
2427 * Note: munges *name.
2429 static void try_remove_empty_parents(char *name
)
2434 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2435 while (*p
&& *p
!= '/')
2437 /* tolerate duplicate slashes; see check_refname_format() */
2441 for (q
= p
; *q
; q
++)
2444 while (q
> p
&& *q
!= '/')
2446 while (q
> p
&& *(q
-1) == '/')
2451 if (rmdir(git_path("%s", name
)))
2456 /* make sure nobody touched the ref, and unlink */
2457 static void prune_ref(struct ref_to_prune
*r
)
2459 struct ref_transaction
*transaction
;
2460 struct strbuf err
= STRBUF_INIT
;
2462 if (check_refname_format(r
->name
, 0))
2465 transaction
= ref_transaction_begin(&err
);
2467 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2468 REF_ISPRUNING
, 1, NULL
, &err
) ||
2469 ref_transaction_commit(transaction
, &err
)) {
2470 ref_transaction_free(transaction
);
2471 error("%s", err
.buf
);
2472 strbuf_release(&err
);
2475 ref_transaction_free(transaction
);
2476 strbuf_release(&err
);
2477 try_remove_empty_parents(r
->name
);
2480 static void prune_refs(struct ref_to_prune
*r
)
2488 int pack_refs(unsigned int flags
)
2490 struct pack_refs_cb_data cbdata
;
2492 memset(&cbdata
, 0, sizeof(cbdata
));
2493 cbdata
.flags
= flags
;
2495 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2496 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2498 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2499 pack_if_possible_fn
, &cbdata
);
2501 if (commit_packed_refs())
2502 die_errno("unable to overwrite old ref-pack file");
2504 prune_refs(cbdata
.ref_to_prune
);
2509 * If entry is no longer needed in packed-refs, add it to the string
2510 * list pointed to by cb_data. Reasons for deleting entries:
2512 * - Entry is broken.
2513 * - Entry is overridden by a loose ref.
2514 * - Entry does not point at a valid object.
2516 * In the first and third cases, also emit an error message because these
2517 * are indications of repository corruption.
2519 static int curate_packed_ref_fn(struct ref_entry
*entry
, void *cb_data
)
2521 struct string_list
*refs_to_delete
= cb_data
;
2523 if (entry
->flag
& REF_ISBROKEN
) {
2524 /* This shouldn't happen to packed refs. */
2525 error("%s is broken!", entry
->name
);
2526 string_list_append(refs_to_delete
, entry
->name
);
2529 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
2530 unsigned char sha1
[20];
2533 if (read_ref_full(entry
->name
, 0, sha1
, &flags
))
2534 /* We should at least have found the packed ref. */
2535 die("Internal error");
2536 if ((flags
& REF_ISSYMREF
) || !(flags
& REF_ISPACKED
)) {
2538 * This packed reference is overridden by a
2539 * loose reference, so it is OK that its value
2540 * is no longer valid; for example, it might
2541 * refer to an object that has been garbage
2542 * collected. For this purpose we don't even
2543 * care whether the loose reference itself is
2544 * invalid, broken, symbolic, etc. Silently
2545 * remove the packed reference.
2547 string_list_append(refs_to_delete
, entry
->name
);
2551 * There is no overriding loose reference, so the fact
2552 * that this reference doesn't refer to a valid object
2553 * indicates some kind of repository corruption.
2554 * Report the problem, then omit the reference from
2557 error("%s does not point to a valid object!", entry
->name
);
2558 string_list_append(refs_to_delete
, entry
->name
);
2565 int repack_without_refs(const char **refnames
, int n
, struct strbuf
*err
)
2567 struct ref_dir
*packed
;
2568 struct string_list refs_to_delete
= STRING_LIST_INIT_DUP
;
2569 struct string_list_item
*ref_to_delete
;
2570 int i
, ret
, removed
= 0;
2572 /* Look for a packed ref */
2573 for (i
= 0; i
< n
; i
++)
2574 if (get_packed_ref(refnames
[i
]))
2577 /* Avoid locking if we have nothing to do */
2579 return 0; /* no refname exists in packed refs */
2581 if (lock_packed_refs(0)) {
2583 unable_to_lock_message(git_path("packed-refs"), errno
,
2587 unable_to_lock_error(git_path("packed-refs"), errno
);
2588 return error("cannot delete '%s' from packed refs", refnames
[i
]);
2590 packed
= get_packed_refs(&ref_cache
);
2592 /* Remove refnames from the cache */
2593 for (i
= 0; i
< n
; i
++)
2594 if (remove_entry(packed
, refnames
[i
]) != -1)
2598 * All packed entries disappeared while we were
2599 * acquiring the lock.
2601 rollback_packed_refs();
2605 /* Remove any other accumulated cruft */
2606 do_for_each_entry_in_dir(packed
, 0, curate_packed_ref_fn
, &refs_to_delete
);
2607 for_each_string_list_item(ref_to_delete
, &refs_to_delete
) {
2608 if (remove_entry(packed
, ref_to_delete
->string
) == -1)
2609 die("internal error");
2612 /* Write what remains */
2613 ret
= commit_packed_refs();
2615 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2620 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2622 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2624 * loose. The loose file name is the same as the
2625 * lockfile name, minus ".lock":
2627 char *loose_filename
= get_locked_file_path(lock
->lk
);
2628 int res
= unlink_or_msg(loose_filename
, err
);
2629 free(loose_filename
);
2636 int delete_ref(const char *refname
, const unsigned char *sha1
, int delopt
)
2638 struct ref_transaction
*transaction
;
2639 struct strbuf err
= STRBUF_INIT
;
2641 transaction
= ref_transaction_begin(&err
);
2643 ref_transaction_delete(transaction
, refname
, sha1
, delopt
,
2644 sha1
&& !is_null_sha1(sha1
), NULL
, &err
) ||
2645 ref_transaction_commit(transaction
, &err
)) {
2646 error("%s", err
.buf
);
2647 ref_transaction_free(transaction
);
2648 strbuf_release(&err
);
2651 ref_transaction_free(transaction
);
2652 strbuf_release(&err
);
2657 * People using contrib's git-new-workdir have .git/logs/refs ->
2658 * /some/other/path/.git/logs/refs, and that may live on another device.
2660 * IOW, to avoid cross device rename errors, the temporary renamed log must
2661 * live into logs/refs.
2663 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2665 static int rename_tmp_log(const char *newrefname
)
2667 int attempts_remaining
= 4;
2670 switch (safe_create_leading_directories(git_path("logs/%s", newrefname
))) {
2672 break; /* success */
2674 if (--attempts_remaining
> 0)
2678 error("unable to create directory for %s", newrefname
);
2682 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2683 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2685 * rename(a, b) when b is an existing
2686 * directory ought to result in ISDIR, but
2687 * Solaris 5.8 gives ENOTDIR. Sheesh.
2689 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2690 error("Directory not empty: logs/%s", newrefname
);
2694 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2696 * Maybe another process just deleted one of
2697 * the directories in the path to newrefname.
2698 * Try again from the beginning.
2702 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2703 newrefname
, strerror(errno
));
2710 static int rename_ref_available(const char *oldname
, const char *newname
)
2712 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2715 string_list_insert(&skip
, oldname
);
2716 ret
= is_refname_available(newname
, &skip
, get_packed_refs(&ref_cache
))
2717 && is_refname_available(newname
, &skip
, get_loose_refs(&ref_cache
));
2718 string_list_clear(&skip
, 0);
2722 static int write_ref_sha1(struct ref_lock
*lock
, const unsigned char *sha1
,
2723 const char *logmsg
);
2725 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2727 unsigned char sha1
[20], orig_sha1
[20];
2728 int flag
= 0, logmoved
= 0;
2729 struct ref_lock
*lock
;
2730 struct stat loginfo
;
2731 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2732 const char *symref
= NULL
;
2734 if (log
&& S_ISLNK(loginfo
.st_mode
))
2735 return error("reflog for %s is a symlink", oldrefname
);
2737 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2739 if (flag
& REF_ISSYMREF
)
2740 return error("refname %s is a symbolic ref, renaming it is not supported",
2743 return error("refname %s not found", oldrefname
);
2745 if (!rename_ref_available(oldrefname
, newrefname
))
2748 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2749 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2750 oldrefname
, strerror(errno
));
2752 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2753 error("unable to delete old %s", oldrefname
);
2757 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2758 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2759 if (errno
==EISDIR
) {
2760 if (remove_empty_directories(git_path("%s", newrefname
))) {
2761 error("Directory not empty: %s", newrefname
);
2765 error("unable to delete existing %s", newrefname
);
2770 if (log
&& rename_tmp_log(newrefname
))
2775 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, 0, NULL
);
2777 error("unable to lock %s for update", newrefname
);
2780 lock
->force_write
= 1;
2781 hashcpy(lock
->old_sha1
, orig_sha1
);
2782 if (write_ref_sha1(lock
, orig_sha1
, logmsg
)) {
2783 error("unable to write current sha1 into %s", newrefname
);
2790 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, 0, NULL
);
2792 error("unable to lock %s for rollback", oldrefname
);
2796 lock
->force_write
= 1;
2797 flag
= log_all_ref_updates
;
2798 log_all_ref_updates
= 0;
2799 if (write_ref_sha1(lock
, orig_sha1
, NULL
))
2800 error("unable to write current sha1 into %s", oldrefname
);
2801 log_all_ref_updates
= flag
;
2804 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2805 error("unable to restore logfile %s from %s: %s",
2806 oldrefname
, newrefname
, strerror(errno
));
2807 if (!logmoved
&& log
&&
2808 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2809 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2810 oldrefname
, strerror(errno
));
2815 int close_ref(struct ref_lock
*lock
)
2817 if (close_lock_file(lock
->lk
))
2823 int commit_ref(struct ref_lock
*lock
)
2825 if (commit_lock_file(lock
->lk
))
2831 void unlock_ref(struct ref_lock
*lock
)
2833 /* Do not free lock->lk -- atexit() still looks at them */
2835 rollback_lock_file(lock
->lk
);
2836 free(lock
->ref_name
);
2837 free(lock
->orig_ref_name
);
2842 * copy the reflog message msg to buf, which has been allocated sufficiently
2843 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2844 * because reflog file is one line per entry.
2846 static int copy_msg(char *buf
, const char *msg
)
2853 while ((c
= *msg
++)) {
2854 if (wasspace
&& isspace(c
))
2856 wasspace
= isspace(c
);
2861 while (buf
< cp
&& isspace(cp
[-1]))
2867 /* This function must set a meaningful errno on failure */
2868 int log_ref_setup(const char *refname
, char *logfile
, int bufsize
)
2870 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2872 git_snpath(logfile
, bufsize
, "logs/%s", refname
);
2873 if (log_all_ref_updates
&&
2874 (starts_with(refname
, "refs/heads/") ||
2875 starts_with(refname
, "refs/remotes/") ||
2876 starts_with(refname
, "refs/notes/") ||
2877 !strcmp(refname
, "HEAD"))) {
2878 if (safe_create_leading_directories(logfile
) < 0) {
2879 int save_errno
= errno
;
2880 error("unable to create directory for %s", logfile
);
2887 logfd
= open(logfile
, oflags
, 0666);
2889 if (!(oflags
& O_CREAT
) && errno
== ENOENT
)
2892 if ((oflags
& O_CREAT
) && errno
== EISDIR
) {
2893 if (remove_empty_directories(logfile
)) {
2894 int save_errno
= errno
;
2895 error("There are still logs under '%s'",
2900 logfd
= open(logfile
, oflags
, 0666);
2904 int save_errno
= errno
;
2905 error("Unable to append to %s: %s", logfile
,
2912 adjust_shared_perm(logfile
);
2917 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
2918 const unsigned char *new_sha1
, const char *msg
)
2920 int logfd
, result
, written
, oflags
= O_APPEND
| O_WRONLY
;
2921 unsigned maxlen
, len
;
2923 char log_file
[PATH_MAX
];
2925 const char *committer
;
2927 if (log_all_ref_updates
< 0)
2928 log_all_ref_updates
= !is_bare_repository();
2930 result
= log_ref_setup(refname
, log_file
, sizeof(log_file
));
2934 logfd
= open(log_file
, oflags
);
2937 msglen
= msg
? strlen(msg
) : 0;
2938 committer
= git_committer_info(0);
2939 maxlen
= strlen(committer
) + msglen
+ 100;
2940 logrec
= xmalloc(maxlen
);
2941 len
= sprintf(logrec
, "%s %s %s\n",
2942 sha1_to_hex(old_sha1
),
2943 sha1_to_hex(new_sha1
),
2946 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
2947 written
= len
<= maxlen
? write_in_full(logfd
, logrec
, len
) : -1;
2949 if (written
!= len
) {
2950 int save_errno
= errno
;
2952 error("Unable to append to %s", log_file
);
2957 int save_errno
= errno
;
2958 error("Unable to append to %s", log_file
);
2965 int is_branch(const char *refname
)
2967 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
2971 * Write sha1 into the ref specified by the lock. Make sure that errno
2974 static int write_ref_sha1(struct ref_lock
*lock
,
2975 const unsigned char *sha1
, const char *logmsg
)
2977 static char term
= '\n';
2984 if (!lock
->force_write
&& !hashcmp(lock
->old_sha1
, sha1
)) {
2988 o
= parse_object(sha1
);
2990 error("Trying to write ref %s with nonexistent object %s",
2991 lock
->ref_name
, sha1_to_hex(sha1
));
2996 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
2997 error("Trying to write non-commit object %s to branch %s",
2998 sha1_to_hex(sha1
), lock
->ref_name
);
3003 if (write_in_full(lock
->lock_fd
, sha1_to_hex(sha1
), 40) != 40 ||
3004 write_in_full(lock
->lock_fd
, &term
, 1) != 1 ||
3005 close_ref(lock
) < 0) {
3006 int save_errno
= errno
;
3007 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3012 clear_loose_ref_cache(&ref_cache
);
3013 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3014 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3015 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3019 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3021 * Special hack: If a branch is updated directly and HEAD
3022 * points to it (may happen on the remote side of a push
3023 * for example) then logically the HEAD reflog should be
3025 * A generic solution implies reverse symref information,
3026 * but finding all symrefs pointing to the given branch
3027 * would be rather costly for this rare event (the direct
3028 * update of a branch) to be worth it. So let's cheat and
3029 * check with HEAD only which should cover 99% of all usage
3030 * scenarios (even 100% of the default ones).
3032 unsigned char head_sha1
[20];
3034 const char *head_ref
;
3035 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3036 head_sha1
, &head_flag
);
3037 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3038 !strcmp(head_ref
, lock
->ref_name
))
3039 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3041 if (commit_ref(lock
)) {
3042 error("Couldn't set %s", lock
->ref_name
);
3050 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3053 const char *lockpath
;
3055 int fd
, len
, written
;
3056 char *git_HEAD
= git_pathdup("%s", ref_target
);
3057 unsigned char old_sha1
[20], new_sha1
[20];
3059 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3062 if (safe_create_leading_directories(git_HEAD
) < 0)
3063 return error("unable to create directory for %s", git_HEAD
);
3065 #ifndef NO_SYMLINK_HEAD
3066 if (prefer_symlink_refs
) {
3068 if (!symlink(refs_heads_master
, git_HEAD
))
3070 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3074 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3075 if (sizeof(ref
) <= len
) {
3076 error("refname too long: %s", refs_heads_master
);
3077 goto error_free_return
;
3079 lockpath
= mkpath("%s.lock", git_HEAD
);
3080 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3082 error("Unable to open %s for writing", lockpath
);
3083 goto error_free_return
;
3085 written
= write_in_full(fd
, ref
, len
);
3086 if (close(fd
) != 0 || written
!= len
) {
3087 error("Unable to write to %s", lockpath
);
3088 goto error_unlink_return
;
3090 if (rename(lockpath
, git_HEAD
) < 0) {
3091 error("Unable to create %s", git_HEAD
);
3092 goto error_unlink_return
;
3094 if (adjust_shared_perm(git_HEAD
)) {
3095 error("Unable to fix permissions on %s", lockpath
);
3096 error_unlink_return
:
3097 unlink_or_warn(lockpath
);
3103 #ifndef NO_SYMLINK_HEAD
3106 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3107 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3113 struct read_ref_at_cb
{
3114 const char *refname
;
3115 unsigned long at_time
;
3118 unsigned char *sha1
;
3121 unsigned char osha1
[20];
3122 unsigned char nsha1
[20];
3126 unsigned long *cutoff_time
;
3131 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3132 const char *email
, unsigned long timestamp
, int tz
,
3133 const char *message
, void *cb_data
)
3135 struct read_ref_at_cb
*cb
= cb_data
;
3139 cb
->date
= timestamp
;
3141 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3143 *cb
->msg
= xstrdup(message
);
3144 if (cb
->cutoff_time
)
3145 *cb
->cutoff_time
= timestamp
;
3147 *cb
->cutoff_tz
= tz
;
3149 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3151 * we have not yet updated cb->[n|o]sha1 so they still
3152 * hold the values for the previous record.
3154 if (!is_null_sha1(cb
->osha1
)) {
3155 hashcpy(cb
->sha1
, nsha1
);
3156 if (hashcmp(cb
->osha1
, nsha1
))
3157 warning("Log for ref %s has gap after %s.",
3158 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3160 else if (cb
->date
== cb
->at_time
)
3161 hashcpy(cb
->sha1
, nsha1
);
3162 else if (hashcmp(nsha1
, cb
->sha1
))
3163 warning("Log for ref %s unexpectedly ended on %s.",
3164 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3166 hashcpy(cb
->osha1
, osha1
);
3167 hashcpy(cb
->nsha1
, nsha1
);
3171 hashcpy(cb
->osha1
, osha1
);
3172 hashcpy(cb
->nsha1
, nsha1
);
3178 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3179 const char *email
, unsigned long timestamp
,
3180 int tz
, const char *message
, void *cb_data
)
3182 struct read_ref_at_cb
*cb
= cb_data
;
3185 *cb
->msg
= xstrdup(message
);
3186 if (cb
->cutoff_time
)
3187 *cb
->cutoff_time
= timestamp
;
3189 *cb
->cutoff_tz
= tz
;
3191 *cb
->cutoff_cnt
= cb
->reccnt
;
3192 hashcpy(cb
->sha1
, osha1
);
3193 if (is_null_sha1(cb
->sha1
))
3194 hashcpy(cb
->sha1
, nsha1
);
3195 /* We just want the first entry */
3199 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3200 unsigned char *sha1
, char **msg
,
3201 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3203 struct read_ref_at_cb cb
;
3205 memset(&cb
, 0, sizeof(cb
));
3206 cb
.refname
= refname
;
3207 cb
.at_time
= at_time
;
3210 cb
.cutoff_time
= cutoff_time
;
3211 cb
.cutoff_tz
= cutoff_tz
;
3212 cb
.cutoff_cnt
= cutoff_cnt
;
3215 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3218 if (flags
& GET_SHA1_QUIETLY
)
3221 die("Log for %s is empty.", refname
);
3226 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3231 int reflog_exists(const char *refname
)
3235 return !lstat(git_path("logs/%s", refname
), &st
) &&
3236 S_ISREG(st
.st_mode
);
3239 int delete_reflog(const char *refname
)
3241 return remove_path(git_path("logs/%s", refname
));
3244 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3246 unsigned char osha1
[20], nsha1
[20];
3247 char *email_end
, *message
;
3248 unsigned long timestamp
;
3251 /* old SP new SP name <email> SP time TAB msg LF */
3252 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3253 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3254 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3255 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3256 email_end
[1] != ' ' ||
3257 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3258 !message
|| message
[0] != ' ' ||
3259 (message
[1] != '+' && message
[1] != '-') ||
3260 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3261 !isdigit(message
[4]) || !isdigit(message
[5]))
3262 return 0; /* corrupt? */
3263 email_end
[1] = '\0';
3264 tz
= strtol(message
+ 1, NULL
, 10);
3265 if (message
[6] != '\t')
3269 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3272 static char *find_beginning_of_line(char *bob
, char *scan
)
3274 while (bob
< scan
&& *(--scan
) != '\n')
3275 ; /* keep scanning backwards */
3277 * Return either beginning of the buffer, or LF at the end of
3278 * the previous line.
3283 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3285 struct strbuf sb
= STRBUF_INIT
;
3288 int ret
= 0, at_tail
= 1;
3290 logfp
= fopen(git_path("logs/%s", refname
), "r");
3294 /* Jump to the end */
3295 if (fseek(logfp
, 0, SEEK_END
) < 0)
3296 return error("cannot seek back reflog for %s: %s",
3297 refname
, strerror(errno
));
3299 while (!ret
&& 0 < pos
) {
3305 /* Fill next block from the end */
3306 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3307 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3308 return error("cannot seek back reflog for %s: %s",
3309 refname
, strerror(errno
));
3310 nread
= fread(buf
, cnt
, 1, logfp
);
3312 return error("cannot read %d bytes from reflog for %s: %s",
3313 cnt
, refname
, strerror(errno
));
3316 scanp
= endp
= buf
+ cnt
;
3317 if (at_tail
&& scanp
[-1] == '\n')
3318 /* Looking at the final LF at the end of the file */
3322 while (buf
< scanp
) {
3324 * terminating LF of the previous line, or the beginning
3329 bp
= find_beginning_of_line(buf
, scanp
);
3332 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3334 break; /* need to fill another block */
3335 scanp
= buf
- 1; /* leave loop */
3338 * (bp + 1) thru endp is the beginning of the
3339 * current line we have in sb
3341 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3345 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3353 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3356 strbuf_release(&sb
);
3360 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3363 struct strbuf sb
= STRBUF_INIT
;
3366 logfp
= fopen(git_path("logs/%s", refname
), "r");
3370 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3371 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3373 strbuf_release(&sb
);
3377 * Call fn for each reflog in the namespace indicated by name. name
3378 * must be empty or end with '/'. Name will be used as a scratch
3379 * space, but its contents will be restored before return.
3381 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3383 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3386 int oldlen
= name
->len
;
3389 return name
->len
? errno
: 0;
3391 while ((de
= readdir(d
)) != NULL
) {
3394 if (de
->d_name
[0] == '.')
3396 if (ends_with(de
->d_name
, ".lock"))
3398 strbuf_addstr(name
, de
->d_name
);
3399 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3400 ; /* silently ignore */
3402 if (S_ISDIR(st
.st_mode
)) {
3403 strbuf_addch(name
, '/');
3404 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3406 unsigned char sha1
[20];
3407 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3408 retval
= error("bad ref for %s", name
->buf
);
3410 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3415 strbuf_setlen(name
, oldlen
);
3421 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3425 strbuf_init(&name
, PATH_MAX
);
3426 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3427 strbuf_release(&name
);
3432 * Information needed for a single ref update. Set new_sha1 to the
3433 * new value or to zero to delete the ref. To check the old value
3434 * while locking the ref, set have_old to 1 and set old_sha1 to the
3435 * value or to zero to ensure the ref does not exist before update.
3438 unsigned char new_sha1
[20];
3439 unsigned char old_sha1
[20];
3440 int flags
; /* REF_NODEREF? */
3441 int have_old
; /* 1 if old_sha1 is valid, 0 otherwise */
3442 struct ref_lock
*lock
;
3445 const char refname
[FLEX_ARRAY
];
3449 * Transaction states.
3450 * OPEN: The transaction is in a valid state and can accept new updates.
3451 * An OPEN transaction can be committed.
3452 * CLOSED: A closed transaction is no longer active and no other operations
3453 * than free can be used on it in this state.
3454 * A transaction can either become closed by successfully committing
3455 * an active transaction or if there is a failure while building
3456 * the transaction thus rendering it failed/inactive.
3458 enum ref_transaction_state
{
3459 REF_TRANSACTION_OPEN
= 0,
3460 REF_TRANSACTION_CLOSED
= 1
3464 * Data structure for holding a reference transaction, which can
3465 * consist of checks and updates to multiple references, carried out
3466 * as atomically as possible. This structure is opaque to callers.
3468 struct ref_transaction
{
3469 struct ref_update
**updates
;
3472 enum ref_transaction_state state
;
3475 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3477 return xcalloc(1, sizeof(struct ref_transaction
));
3480 void ref_transaction_free(struct ref_transaction
*transaction
)
3487 for (i
= 0; i
< transaction
->nr
; i
++) {
3488 free(transaction
->updates
[i
]->msg
);
3489 free(transaction
->updates
[i
]);
3491 free(transaction
->updates
);
3495 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3496 const char *refname
)
3498 size_t len
= strlen(refname
);
3499 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3501 strcpy((char *)update
->refname
, refname
);
3502 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3503 transaction
->updates
[transaction
->nr
++] = update
;
3507 int ref_transaction_update(struct ref_transaction
*transaction
,
3508 const char *refname
,
3509 const unsigned char *new_sha1
,
3510 const unsigned char *old_sha1
,
3511 int flags
, int have_old
, const char *msg
,
3514 struct ref_update
*update
;
3516 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3517 die("BUG: update called for transaction that is not open");
3519 if (have_old
&& !old_sha1
)
3520 die("BUG: have_old is true but old_sha1 is NULL");
3522 update
= add_update(transaction
, refname
);
3523 hashcpy(update
->new_sha1
, new_sha1
);
3524 update
->flags
= flags
;
3525 update
->have_old
= have_old
;
3527 hashcpy(update
->old_sha1
, old_sha1
);
3529 update
->msg
= xstrdup(msg
);
3533 int ref_transaction_create(struct ref_transaction
*transaction
,
3534 const char *refname
,
3535 const unsigned char *new_sha1
,
3536 int flags
, const char *msg
,
3539 struct ref_update
*update
;
3541 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3542 die("BUG: create called for transaction that is not open");
3544 if (!new_sha1
|| is_null_sha1(new_sha1
))
3545 die("BUG: create ref with null new_sha1");
3547 update
= add_update(transaction
, refname
);
3549 hashcpy(update
->new_sha1
, new_sha1
);
3550 hashclr(update
->old_sha1
);
3551 update
->flags
= flags
;
3552 update
->have_old
= 1;
3554 update
->msg
= xstrdup(msg
);
3558 int ref_transaction_delete(struct ref_transaction
*transaction
,
3559 const char *refname
,
3560 const unsigned char *old_sha1
,
3561 int flags
, int have_old
, const char *msg
,
3564 struct ref_update
*update
;
3566 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3567 die("BUG: delete called for transaction that is not open");
3569 if (have_old
&& !old_sha1
)
3570 die("BUG: have_old is true but old_sha1 is NULL");
3572 update
= add_update(transaction
, refname
);
3573 update
->flags
= flags
;
3574 update
->have_old
= have_old
;
3576 assert(!is_null_sha1(old_sha1
));
3577 hashcpy(update
->old_sha1
, old_sha1
);
3580 update
->msg
= xstrdup(msg
);
3584 int update_ref(const char *action
, const char *refname
,
3585 const unsigned char *sha1
, const unsigned char *oldval
,
3586 int flags
, enum action_on_err onerr
)
3588 struct ref_transaction
*t
;
3589 struct strbuf err
= STRBUF_INIT
;
3591 t
= ref_transaction_begin(&err
);
3593 ref_transaction_update(t
, refname
, sha1
, oldval
, flags
,
3594 !!oldval
, action
, &err
) ||
3595 ref_transaction_commit(t
, &err
)) {
3596 const char *str
= "update_ref failed for ref '%s': %s";
3598 ref_transaction_free(t
);
3600 case UPDATE_REFS_MSG_ON_ERR
:
3601 error(str
, refname
, err
.buf
);
3603 case UPDATE_REFS_DIE_ON_ERR
:
3604 die(str
, refname
, err
.buf
);
3606 case UPDATE_REFS_QUIET_ON_ERR
:
3609 strbuf_release(&err
);
3612 strbuf_release(&err
);
3613 ref_transaction_free(t
);
3617 static int ref_update_compare(const void *r1
, const void *r2
)
3619 const struct ref_update
* const *u1
= r1
;
3620 const struct ref_update
* const *u2
= r2
;
3621 return strcmp((*u1
)->refname
, (*u2
)->refname
);
3624 static int ref_update_reject_duplicates(struct ref_update
**updates
, int n
,
3628 for (i
= 1; i
< n
; i
++)
3629 if (!strcmp(updates
[i
- 1]->refname
, updates
[i
]->refname
)) {
3631 "Multiple updates for ref '%s' not allowed.";
3633 strbuf_addf(err
, str
, updates
[i
]->refname
);
3640 int ref_transaction_commit(struct ref_transaction
*transaction
,
3643 int ret
= 0, delnum
= 0, i
;
3644 const char **delnames
;
3645 int n
= transaction
->nr
;
3646 struct ref_update
**updates
= transaction
->updates
;
3648 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3649 die("BUG: commit called for transaction that is not open");
3652 transaction
->state
= REF_TRANSACTION_CLOSED
;
3656 /* Allocate work space */
3657 delnames
= xmalloc(sizeof(*delnames
) * n
);
3659 /* Copy, sort, and reject duplicate refs */
3660 qsort(updates
, n
, sizeof(*updates
), ref_update_compare
);
3661 if (ref_update_reject_duplicates(updates
, n
, err
)) {
3662 ret
= TRANSACTION_GENERIC_ERROR
;
3666 /* Acquire all locks while verifying old values */
3667 for (i
= 0; i
< n
; i
++) {
3668 struct ref_update
*update
= updates
[i
];
3669 int flags
= update
->flags
;
3671 if (is_null_sha1(update
->new_sha1
))
3672 flags
|= REF_DELETING
;
3673 update
->lock
= lock_ref_sha1_basic(update
->refname
,
3680 if (!update
->lock
) {
3681 ret
= (errno
== ENOTDIR
)
3682 ? TRANSACTION_NAME_CONFLICT
3683 : TRANSACTION_GENERIC_ERROR
;
3685 strbuf_addf(err
, "Cannot lock the ref '%s'.",
3691 /* Perform updates first so live commits remain referenced */
3692 for (i
= 0; i
< n
; i
++) {
3693 struct ref_update
*update
= updates
[i
];
3695 if (!is_null_sha1(update
->new_sha1
)) {
3696 if (write_ref_sha1(update
->lock
, update
->new_sha1
,
3698 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3700 strbuf_addf(err
, "Cannot update the ref '%s'.",
3702 ret
= TRANSACTION_GENERIC_ERROR
;
3705 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3709 /* Perform deletes now that updates are safely completed */
3710 for (i
= 0; i
< n
; i
++) {
3711 struct ref_update
*update
= updates
[i
];
3714 if (delete_ref_loose(update
->lock
, update
->type
, err
))
3715 ret
= TRANSACTION_GENERIC_ERROR
;
3717 if (!(update
->flags
& REF_ISPRUNING
))
3718 delnames
[delnum
++] = update
->lock
->ref_name
;
3722 if (repack_without_refs(delnames
, delnum
, err
))
3723 ret
= TRANSACTION_GENERIC_ERROR
;
3724 for (i
= 0; i
< delnum
; i
++)
3725 unlink_or_warn(git_path("logs/%s", delnames
[i
]));
3726 clear_loose_ref_cache(&ref_cache
);
3729 transaction
->state
= REF_TRANSACTION_CLOSED
;
3731 for (i
= 0; i
< n
; i
++)
3732 if (updates
[i
]->lock
)
3733 unlock_ref(updates
[i
]->lock
);
3738 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3741 static char **scanf_fmts
;
3742 static int nr_rules
;
3747 * Pre-generate scanf formats from ref_rev_parse_rules[].
3748 * Generate a format suitable for scanf from a
3749 * ref_rev_parse_rules rule by interpolating "%s" at the
3750 * location of the "%.*s".
3752 size_t total_len
= 0;
3755 /* the rule list is NULL terminated, count them first */
3756 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3757 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3758 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3760 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3763 for (i
= 0; i
< nr_rules
; i
++) {
3764 assert(offset
< total_len
);
3765 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
3766 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
3767 ref_rev_parse_rules
[i
], 2, "%s") + 1;
3771 /* bail out if there are no rules */
3773 return xstrdup(refname
);
3775 /* buffer for scanf result, at most refname must fit */
3776 short_name
= xstrdup(refname
);
3778 /* skip first rule, it will always match */
3779 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
3781 int rules_to_fail
= i
;
3784 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
3787 short_name_len
= strlen(short_name
);
3790 * in strict mode, all (except the matched one) rules
3791 * must fail to resolve to a valid non-ambiguous ref
3794 rules_to_fail
= nr_rules
;
3797 * check if the short name resolves to a valid ref,
3798 * but use only rules prior to the matched one
3800 for (j
= 0; j
< rules_to_fail
; j
++) {
3801 const char *rule
= ref_rev_parse_rules
[j
];
3802 char refname
[PATH_MAX
];
3804 /* skip matched rule */
3809 * the short name is ambiguous, if it resolves
3810 * (with this previous rule) to a valid ref
3811 * read_ref() returns 0 on success
3813 mksnpath(refname
, sizeof(refname
),
3814 rule
, short_name_len
, short_name
);
3815 if (ref_exists(refname
))
3820 * short name is non-ambiguous if all previous rules
3821 * haven't resolved to a valid ref
3823 if (j
== rules_to_fail
)
3828 return xstrdup(refname
);
3831 static struct string_list
*hide_refs
;
3833 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
3835 if (!strcmp("transfer.hiderefs", var
) ||
3836 /* NEEDSWORK: use parse_config_key() once both are merged */
3837 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
3838 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
3843 return config_error_nonbool(var
);
3844 ref
= xstrdup(value
);
3846 while (len
&& ref
[len
- 1] == '/')
3849 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
3850 hide_refs
->strdup_strings
= 1;
3852 string_list_append(hide_refs
, ref
);
3857 int ref_is_hidden(const char *refname
)
3859 struct string_list_item
*item
;
3863 for_each_string_list_item(item
, hide_refs
) {
3865 if (!starts_with(refname
, item
->string
))
3867 len
= strlen(item
->string
);
3868 if (!refname
[len
] || refname
[len
] == '/')