7 #include "string-list.h"
13 unsigned char old_sha1
[20];
19 * How to handle various characters in refnames:
20 * 0: An acceptable character for refs
22 * 2: ., look for a preceding . to reject .. in refs
23 * 3: {, look for a preceding @ to reject @{ in refs
24 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
26 static unsigned char refname_disposition
[256] = {
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
41 #define REF_DELETING 0x02
44 * Used as a flag to ref_transaction_delete when a loose ref is being
47 #define REF_ISPRUNING 0x04
50 * Try to read one refname component from the front of refname.
51 * Return the length of the component found, or -1 if the component is
52 * not legal. It is legal if it is something reasonable to have under
53 * ".git/refs/"; We do not like it if:
55 * - any path component of it begins with ".", or
56 * - it has double dots "..", or
57 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
58 * - it ends with a "/".
59 * - it ends with ".lock"
60 * - it contains a "\" (backslash)
62 static int check_refname_component(const char *refname
, int flags
)
67 for (cp
= refname
; ; cp
++) {
69 unsigned char disp
= refname_disposition
[ch
];
75 return -1; /* Refname contains "..". */
79 return -1; /* Refname contains "@{". */
88 return 0; /* Component has zero length. */
89 if (refname
[0] == '.')
90 return -1; /* Component starts with '.'. */
91 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
92 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
93 return -1; /* Refname ends with ".lock". */
97 int check_refname_format(const char *refname
, int flags
)
99 int component_len
, component_count
= 0;
101 if (!strcmp(refname
, "@"))
102 /* Refname is a single character '@'. */
106 /* We are at the start of a path component. */
107 component_len
= check_refname_component(refname
, flags
);
108 if (component_len
<= 0) {
109 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
111 (refname
[1] == '\0' || refname
[1] == '/')) {
112 /* Accept one wildcard as a full refname component. */
113 flags
&= ~REFNAME_REFSPEC_PATTERN
;
120 if (refname
[component_len
] == '\0')
122 /* Skip to next component. */
123 refname
+= component_len
+ 1;
126 if (refname
[component_len
- 1] == '.')
127 return -1; /* Refname ends with '.'. */
128 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
129 return -1; /* Refname has only one component. */
136 * Information used (along with the information in ref_entry) to
137 * describe a single cached reference. This data structure only
138 * occurs embedded in a union in struct ref_entry, and only when
139 * (ref_entry->flag & REF_DIR) is zero.
143 * The name of the object to which this reference resolves
144 * (which may be a tag object). If REF_ISBROKEN, this is
145 * null. If REF_ISSYMREF, then this is the name of the object
146 * referred to by the last reference in the symlink chain.
148 unsigned char sha1
[20];
151 * If REF_KNOWS_PEELED, then this field holds the peeled value
152 * of this reference, or null if the reference is known not to
153 * be peelable. See the documentation for peel_ref() for an
154 * exact definition of "peelable".
156 unsigned char peeled
[20];
162 * Information used (along with the information in ref_entry) to
163 * describe a level in the hierarchy of references. This data
164 * structure only occurs embedded in a union in struct ref_entry, and
165 * only when (ref_entry.flag & REF_DIR) is set. In that case,
166 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
167 * in the directory have already been read:
169 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
170 * or packed references, already read.
172 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
173 * references that hasn't been read yet (nor has any of its
176 * Entries within a directory are stored within a growable array of
177 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
178 * sorted are sorted by their component name in strcmp() order and the
179 * remaining entries are unsorted.
181 * Loose references are read lazily, one directory at a time. When a
182 * directory of loose references is read, then all of the references
183 * in that directory are stored, and REF_INCOMPLETE stubs are created
184 * for any subdirectories, but the subdirectories themselves are not
185 * read. The reading is triggered by get_ref_dir().
191 * Entries with index 0 <= i < sorted are sorted by name. New
192 * entries are appended to the list unsorted, and are sorted
193 * only when required; thus we avoid the need to sort the list
194 * after the addition of every reference.
198 /* A pointer to the ref_cache that contains this ref_dir. */
199 struct ref_cache
*ref_cache
;
201 struct ref_entry
**entries
;
205 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
206 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
207 * public values; see refs.h.
211 * The field ref_entry->u.value.peeled of this value entry contains
212 * the correct peeled value for the reference, which might be
213 * null_sha1 if the reference is not a tag or if it is broken.
215 #define REF_KNOWS_PEELED 0x10
217 /* ref_entry represents a directory of references */
221 * Entry has not yet been read from disk (used only for REF_DIR
222 * entries representing loose references)
224 #define REF_INCOMPLETE 0x40
227 * A ref_entry represents either a reference or a "subdirectory" of
230 * Each directory in the reference namespace is represented by a
231 * ref_entry with (flags & REF_DIR) set and containing a subdir member
232 * that holds the entries in that directory that have been read so
233 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
234 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
235 * used for loose reference directories.
237 * References are represented by a ref_entry with (flags & REF_DIR)
238 * unset and a value member that describes the reference's value. The
239 * flag member is at the ref_entry level, but it is also needed to
240 * interpret the contents of the value field (in other words, a
241 * ref_value object is not very much use without the enclosing
244 * Reference names cannot end with slash and directories' names are
245 * always stored with a trailing slash (except for the top-level
246 * directory, which is always denoted by ""). This has two nice
247 * consequences: (1) when the entries in each subdir are sorted
248 * lexicographically by name (as they usually are), the references in
249 * a whole tree can be generated in lexicographic order by traversing
250 * the tree in left-to-right, depth-first order; (2) the names of
251 * references and subdirectories cannot conflict, and therefore the
252 * presence of an empty subdirectory does not block the creation of a
253 * similarly-named reference. (The fact that reference names with the
254 * same leading components can conflict *with each other* is a
255 * separate issue that is regulated by is_refname_available().)
257 * Please note that the name field contains the fully-qualified
258 * reference (or subdirectory) name. Space could be saved by only
259 * storing the relative names. But that would require the full names
260 * to be generated on the fly when iterating in do_for_each_ref(), and
261 * would break callback functions, who have always been able to assume
262 * that the name strings that they are passed will not be freed during
266 unsigned char flag
; /* ISSYMREF? ISPACKED? */
268 struct ref_value value
; /* if not (flags&REF_DIR) */
269 struct ref_dir subdir
; /* if (flags&REF_DIR) */
272 * The full name of the reference (e.g., "refs/heads/master")
273 * or the full name of the directory with a trailing slash
274 * (e.g., "refs/heads/"):
276 char name
[FLEX_ARRAY
];
279 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
281 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
284 assert(entry
->flag
& REF_DIR
);
285 dir
= &entry
->u
.subdir
;
286 if (entry
->flag
& REF_INCOMPLETE
) {
287 read_loose_refs(entry
->name
, dir
);
288 entry
->flag
&= ~REF_INCOMPLETE
;
294 * Check if a refname is safe.
295 * For refs that start with "refs/" we consider it safe as long they do
296 * not try to resolve to outside of refs/.
298 * For all other refs we only consider them safe iff they only contain
299 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
302 static int refname_is_safe(const char *refname
)
304 if (starts_with(refname
, "refs/")) {
308 buf
= xmalloc(strlen(refname
) + 1);
310 * Does the refname try to escape refs/?
311 * For example: refs/foo/../bar is safe but refs/foo/../../bar
314 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
319 if (!isupper(*refname
) && *refname
!= '_')
326 static struct ref_entry
*create_ref_entry(const char *refname
,
327 const unsigned char *sha1
, int flag
,
331 struct ref_entry
*ref
;
334 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
335 die("Reference has invalid format: '%s'", refname
);
336 if (!check_name
&& !refname_is_safe(refname
))
337 die("Reference has invalid name: '%s'", refname
);
338 len
= strlen(refname
) + 1;
339 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
340 hashcpy(ref
->u
.value
.sha1
, sha1
);
341 hashclr(ref
->u
.value
.peeled
);
342 memcpy(ref
->name
, refname
, len
);
347 static void clear_ref_dir(struct ref_dir
*dir
);
349 static void free_ref_entry(struct ref_entry
*entry
)
351 if (entry
->flag
& REF_DIR
) {
353 * Do not use get_ref_dir() here, as that might
354 * trigger the reading of loose refs.
356 clear_ref_dir(&entry
->u
.subdir
);
362 * Add a ref_entry to the end of dir (unsorted). Entry is always
363 * stored directly in dir; no recursion into subdirectories is
366 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
368 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
369 dir
->entries
[dir
->nr
++] = entry
;
370 /* optimize for the case that entries are added in order */
372 (dir
->nr
== dir
->sorted
+ 1 &&
373 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
374 dir
->entries
[dir
->nr
- 1]->name
) < 0))
375 dir
->sorted
= dir
->nr
;
379 * Clear and free all entries in dir, recursively.
381 static void clear_ref_dir(struct ref_dir
*dir
)
384 for (i
= 0; i
< dir
->nr
; i
++)
385 free_ref_entry(dir
->entries
[i
]);
387 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
392 * Create a struct ref_entry object for the specified dirname.
393 * dirname is the name of the directory with a trailing slash (e.g.,
394 * "refs/heads/") or "" for the top-level directory.
396 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
397 const char *dirname
, size_t len
,
400 struct ref_entry
*direntry
;
401 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
402 memcpy(direntry
->name
, dirname
, len
);
403 direntry
->name
[len
] = '\0';
404 direntry
->u
.subdir
.ref_cache
= ref_cache
;
405 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
409 static int ref_entry_cmp(const void *a
, const void *b
)
411 struct ref_entry
*one
= *(struct ref_entry
**)a
;
412 struct ref_entry
*two
= *(struct ref_entry
**)b
;
413 return strcmp(one
->name
, two
->name
);
416 static void sort_ref_dir(struct ref_dir
*dir
);
418 struct string_slice
{
423 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
425 const struct string_slice
*key
= key_
;
426 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
427 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
430 return '\0' - (unsigned char)ent
->name
[key
->len
];
434 * Return the index of the entry with the given refname from the
435 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
436 * no such entry is found. dir must already be complete.
438 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
440 struct ref_entry
**r
;
441 struct string_slice key
;
443 if (refname
== NULL
|| !dir
->nr
)
449 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
450 ref_entry_cmp_sslice
);
455 return r
- dir
->entries
;
459 * Search for a directory entry directly within dir (without
460 * recursing). Sort dir if necessary. subdirname must be a directory
461 * name (i.e., end in '/'). If mkdir is set, then create the
462 * directory if it is missing; otherwise, return NULL if the desired
463 * directory cannot be found. dir must already be complete.
465 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
466 const char *subdirname
, size_t len
,
469 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
470 struct ref_entry
*entry
;
471 if (entry_index
== -1) {
475 * Since dir is complete, the absence of a subdir
476 * means that the subdir really doesn't exist;
477 * therefore, create an empty record for it but mark
478 * the record complete.
480 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
481 add_entry_to_dir(dir
, entry
);
483 entry
= dir
->entries
[entry_index
];
485 return get_ref_dir(entry
);
489 * If refname is a reference name, find the ref_dir within the dir
490 * tree that should hold refname. If refname is a directory name
491 * (i.e., ends in '/'), then return that ref_dir itself. dir must
492 * represent the top-level directory and must already be complete.
493 * Sort ref_dirs and recurse into subdirectories as necessary. If
494 * mkdir is set, then create any missing directories; otherwise,
495 * return NULL if the desired directory cannot be found.
497 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
498 const char *refname
, int mkdir
)
501 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
502 size_t dirnamelen
= slash
- refname
+ 1;
503 struct ref_dir
*subdir
;
504 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
516 * Find the value entry with the given name in dir, sorting ref_dirs
517 * and recursing into subdirectories as necessary. If the name is not
518 * found or it corresponds to a directory entry, return NULL.
520 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
523 struct ref_entry
*entry
;
524 dir
= find_containing_dir(dir
, refname
, 0);
527 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
528 if (entry_index
== -1)
530 entry
= dir
->entries
[entry_index
];
531 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
535 * Remove the entry with the given name from dir, recursing into
536 * subdirectories as necessary. If refname is the name of a directory
537 * (i.e., ends with '/'), then remove the directory and its contents.
538 * If the removal was successful, return the number of entries
539 * remaining in the directory entry that contained the deleted entry.
540 * If the name was not found, return -1. Please note that this
541 * function only deletes the entry from the cache; it does not delete
542 * it from the filesystem or ensure that other cache entries (which
543 * might be symbolic references to the removed entry) are updated.
544 * Nor does it remove any containing dir entries that might be made
545 * empty by the removal. dir must represent the top-level directory
546 * and must already be complete.
548 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
550 int refname_len
= strlen(refname
);
552 struct ref_entry
*entry
;
553 int is_dir
= refname
[refname_len
- 1] == '/';
556 * refname represents a reference directory. Remove
557 * the trailing slash; otherwise we will get the
558 * directory *representing* refname rather than the
559 * one *containing* it.
561 char *dirname
= xmemdupz(refname
, refname_len
- 1);
562 dir
= find_containing_dir(dir
, dirname
, 0);
565 dir
= find_containing_dir(dir
, refname
, 0);
569 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
570 if (entry_index
== -1)
572 entry
= dir
->entries
[entry_index
];
574 memmove(&dir
->entries
[entry_index
],
575 &dir
->entries
[entry_index
+ 1],
576 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
579 if (dir
->sorted
> entry_index
)
581 free_ref_entry(entry
);
586 * Add a ref_entry to the ref_dir (unsorted), recursing into
587 * subdirectories as necessary. dir must represent the top-level
588 * directory. Return 0 on success.
590 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
592 dir
= find_containing_dir(dir
, ref
->name
, 1);
595 add_entry_to_dir(dir
, ref
);
600 * Emit a warning and return true iff ref1 and ref2 have the same name
601 * and the same sha1. Die if they have the same name but different
604 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
606 if (strcmp(ref1
->name
, ref2
->name
))
609 /* Duplicate name; make sure that they don't conflict: */
611 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
612 /* This is impossible by construction */
613 die("Reference directory conflict: %s", ref1
->name
);
615 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
616 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
618 warning("Duplicated ref: %s", ref1
->name
);
623 * Sort the entries in dir non-recursively (if they are not already
624 * sorted) and remove any duplicate entries.
626 static void sort_ref_dir(struct ref_dir
*dir
)
629 struct ref_entry
*last
= NULL
;
632 * This check also prevents passing a zero-length array to qsort(),
633 * which is a problem on some platforms.
635 if (dir
->sorted
== dir
->nr
)
638 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
640 /* Remove any duplicates: */
641 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
642 struct ref_entry
*entry
= dir
->entries
[j
];
643 if (last
&& is_dup_ref(last
, entry
))
644 free_ref_entry(entry
);
646 last
= dir
->entries
[i
++] = entry
;
648 dir
->sorted
= dir
->nr
= i
;
651 /* Include broken references in a do_for_each_ref*() iteration: */
652 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
655 * Return true iff the reference described by entry can be resolved to
656 * an object in the database. Emit a warning if the referred-to
657 * object does not exist.
659 static int ref_resolves_to_object(struct ref_entry
*entry
)
661 if (entry
->flag
& REF_ISBROKEN
)
663 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
664 error("%s does not point to a valid object!", entry
->name
);
671 * current_ref is a performance hack: when iterating over references
672 * using the for_each_ref*() functions, current_ref is set to the
673 * current reference's entry before calling the callback function. If
674 * the callback function calls peel_ref(), then peel_ref() first
675 * checks whether the reference to be peeled is the current reference
676 * (it usually is) and if so, returns that reference's peeled version
677 * if it is available. This avoids a refname lookup in a common case.
679 static struct ref_entry
*current_ref
;
681 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
683 struct ref_entry_cb
{
692 * Handle one reference in a do_for_each_ref*()-style iteration,
693 * calling an each_ref_fn for each entry.
695 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
697 struct ref_entry_cb
*data
= cb_data
;
698 struct ref_entry
*old_current_ref
;
701 if (!starts_with(entry
->name
, data
->base
))
704 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
705 !ref_resolves_to_object(entry
))
708 /* Store the old value, in case this is a recursive call: */
709 old_current_ref
= current_ref
;
711 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
712 entry
->flag
, data
->cb_data
);
713 current_ref
= old_current_ref
;
718 * Call fn for each reference in dir that has index in the range
719 * offset <= index < dir->nr. Recurse into subdirectories that are in
720 * that index range, sorting them before iterating. This function
721 * does not sort dir itself; it should be sorted beforehand. fn is
722 * called for all references, including broken ones.
724 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
725 each_ref_entry_fn fn
, void *cb_data
)
728 assert(dir
->sorted
== dir
->nr
);
729 for (i
= offset
; i
< dir
->nr
; i
++) {
730 struct ref_entry
*entry
= dir
->entries
[i
];
732 if (entry
->flag
& REF_DIR
) {
733 struct ref_dir
*subdir
= get_ref_dir(entry
);
734 sort_ref_dir(subdir
);
735 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
737 retval
= fn(entry
, cb_data
);
746 * Call fn for each reference in the union of dir1 and dir2, in order
747 * by refname. Recurse into subdirectories. If a value entry appears
748 * in both dir1 and dir2, then only process the version that is in
749 * dir2. The input dirs must already be sorted, but subdirs will be
750 * sorted as needed. fn is called for all references, including
753 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
754 struct ref_dir
*dir2
,
755 each_ref_entry_fn fn
, void *cb_data
)
760 assert(dir1
->sorted
== dir1
->nr
);
761 assert(dir2
->sorted
== dir2
->nr
);
763 struct ref_entry
*e1
, *e2
;
765 if (i1
== dir1
->nr
) {
766 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
768 if (i2
== dir2
->nr
) {
769 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
771 e1
= dir1
->entries
[i1
];
772 e2
= dir2
->entries
[i2
];
773 cmp
= strcmp(e1
->name
, e2
->name
);
775 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
776 /* Both are directories; descend them in parallel. */
777 struct ref_dir
*subdir1
= get_ref_dir(e1
);
778 struct ref_dir
*subdir2
= get_ref_dir(e2
);
779 sort_ref_dir(subdir1
);
780 sort_ref_dir(subdir2
);
781 retval
= do_for_each_entry_in_dirs(
782 subdir1
, subdir2
, fn
, cb_data
);
785 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
786 /* Both are references; ignore the one from dir1. */
787 retval
= fn(e2
, cb_data
);
791 die("conflict between reference and directory: %s",
803 if (e
->flag
& REF_DIR
) {
804 struct ref_dir
*subdir
= get_ref_dir(e
);
805 sort_ref_dir(subdir
);
806 retval
= do_for_each_entry_in_dir(
807 subdir
, 0, fn
, cb_data
);
809 retval
= fn(e
, cb_data
);
818 * Load all of the refs from the dir into our in-memory cache. The hard work
819 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
820 * through all of the sub-directories. We do not even need to care about
821 * sorting, as traversal order does not matter to us.
823 static void prime_ref_dir(struct ref_dir
*dir
)
826 for (i
= 0; i
< dir
->nr
; i
++) {
827 struct ref_entry
*entry
= dir
->entries
[i
];
828 if (entry
->flag
& REF_DIR
)
829 prime_ref_dir(get_ref_dir(entry
));
833 static int entry_matches(struct ref_entry
*entry
, const struct string_list
*list
)
835 return list
&& string_list_has_string(list
, entry
->name
);
838 struct nonmatching_ref_data
{
839 const struct string_list
*skip
;
840 struct ref_entry
*found
;
843 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
845 struct nonmatching_ref_data
*data
= vdata
;
847 if (entry_matches(entry
, data
->skip
))
854 static void report_refname_conflict(struct ref_entry
*entry
,
857 error("'%s' exists; cannot create '%s'", entry
->name
, refname
);
861 * Return true iff a reference named refname could be created without
862 * conflicting with the name of an existing reference in dir. If
863 * skip is non-NULL, ignore potential conflicts with refs in skip
864 * (e.g., because they are scheduled for deletion in the same
867 * Two reference names conflict if one of them exactly matches the
868 * leading components of the other; e.g., "foo/bar" conflicts with
869 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
872 * skip must be sorted.
874 static int is_refname_available(const char *refname
,
875 const struct string_list
*skip
,
883 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
885 * We are still at a leading dir of the refname; we are
886 * looking for a conflict with a leaf entry.
888 * If we find one, we still must make sure it is
891 pos
= search_ref_dir(dir
, refname
, slash
- refname
);
893 struct ref_entry
*entry
= dir
->entries
[pos
];
894 if (entry_matches(entry
, skip
))
896 report_refname_conflict(entry
, refname
);
902 * Otherwise, we can try to continue our search with
903 * the next component; if we come up empty, we know
904 * there is nothing under this whole prefix.
906 pos
= search_ref_dir(dir
, refname
, slash
+ 1 - refname
);
910 dir
= get_ref_dir(dir
->entries
[pos
]);
914 * We are at the leaf of our refname; we want to
915 * make sure there are no directories which match it.
917 len
= strlen(refname
);
918 dirname
= xmallocz(len
+ 1);
919 sprintf(dirname
, "%s/", refname
);
920 pos
= search_ref_dir(dir
, dirname
, len
+ 1);
925 * We found a directory named "refname". It is a
926 * problem iff it contains any ref that is not
929 struct ref_entry
*entry
= dir
->entries
[pos
];
930 struct ref_dir
*dir
= get_ref_dir(entry
);
931 struct nonmatching_ref_data data
;
935 if (!do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
))
938 report_refname_conflict(data
.found
, refname
);
943 * There is no point in searching for another leaf
944 * node which matches it; such an entry would be the
945 * ref we are looking for, not a conflict.
950 struct packed_ref_cache
{
951 struct ref_entry
*root
;
954 * Count of references to the data structure in this instance,
955 * including the pointer from ref_cache::packed if any. The
956 * data will not be freed as long as the reference count is
959 unsigned int referrers
;
962 * Iff the packed-refs file associated with this instance is
963 * currently locked for writing, this points at the associated
964 * lock (which is owned by somebody else). The referrer count
965 * is also incremented when the file is locked and decremented
966 * when it is unlocked.
968 struct lock_file
*lock
;
970 /* The metadata from when this packed-refs cache was read */
971 struct stat_validity validity
;
975 * Future: need to be in "struct repository"
976 * when doing a full libification.
978 static struct ref_cache
{
979 struct ref_cache
*next
;
980 struct ref_entry
*loose
;
981 struct packed_ref_cache
*packed
;
983 * The submodule name, or "" for the main repo. We allocate
984 * length 1 rather than FLEX_ARRAY so that the main ref_cache
985 * is initialized correctly.
988 } ref_cache
, *submodule_ref_caches
;
990 /* Lock used for the main packed-refs file: */
991 static struct lock_file packlock
;
994 * Increment the reference count of *packed_refs.
996 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
998 packed_refs
->referrers
++;
1002 * Decrease the reference count of *packed_refs. If it goes to zero,
1003 * free *packed_refs and return true; otherwise return false.
1005 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1007 if (!--packed_refs
->referrers
) {
1008 free_ref_entry(packed_refs
->root
);
1009 stat_validity_clear(&packed_refs
->validity
);
1017 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1020 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1022 if (packed_refs
->lock
)
1023 die("internal error: packed-ref cache cleared while locked");
1024 refs
->packed
= NULL
;
1025 release_packed_ref_cache(packed_refs
);
1029 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1032 free_ref_entry(refs
->loose
);
1037 static struct ref_cache
*create_ref_cache(const char *submodule
)
1040 struct ref_cache
*refs
;
1043 len
= strlen(submodule
) + 1;
1044 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1045 memcpy(refs
->name
, submodule
, len
);
1050 * Return a pointer to a ref_cache for the specified submodule. For
1051 * the main repository, use submodule==NULL. The returned structure
1052 * will be allocated and initialized but not necessarily populated; it
1053 * should not be freed.
1055 static struct ref_cache
*get_ref_cache(const char *submodule
)
1057 struct ref_cache
*refs
;
1059 if (!submodule
|| !*submodule
)
1062 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1063 if (!strcmp(submodule
, refs
->name
))
1066 refs
= create_ref_cache(submodule
);
1067 refs
->next
= submodule_ref_caches
;
1068 submodule_ref_caches
= refs
;
1072 /* The length of a peeled reference line in packed-refs, including EOL: */
1073 #define PEELED_LINE_LENGTH 42
1076 * The packed-refs header line that we write out. Perhaps other
1077 * traits will be added later. The trailing space is required.
1079 static const char PACKED_REFS_HEADER
[] =
1080 "# pack-refs with: peeled fully-peeled \n";
1083 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1084 * Return a pointer to the refname within the line (null-terminated),
1085 * or NULL if there was a problem.
1087 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1092 * 42: the answer to everything.
1094 * In this case, it happens to be the answer to
1095 * 40 (length of sha1 hex representation)
1096 * +1 (space in between hex and name)
1097 * +1 (newline at the end of the line)
1099 if (line
->len
<= 42)
1102 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1104 if (!isspace(line
->buf
[40]))
1107 ref
= line
->buf
+ 41;
1111 if (line
->buf
[line
->len
- 1] != '\n')
1113 line
->buf
[--line
->len
] = 0;
1119 * Read f, which is a packed-refs file, into dir.
1121 * A comment line of the form "# pack-refs with: " may contain zero or
1122 * more traits. We interpret the traits as follows:
1126 * Probably no references are peeled. But if the file contains a
1127 * peeled value for a reference, we will use it.
1131 * References under "refs/tags/", if they *can* be peeled, *are*
1132 * peeled in this file. References outside of "refs/tags/" are
1133 * probably not peeled even if they could have been, but if we find
1134 * a peeled value for such a reference we will use it.
1138 * All references in the file that can be peeled are peeled.
1139 * Inversely (and this is more important), any references in the
1140 * file for which no peeled value is recorded is not peelable. This
1141 * trait should typically be written alongside "peeled" for
1142 * compatibility with older clients, but we do not require it
1143 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1145 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1147 struct ref_entry
*last
= NULL
;
1148 struct strbuf line
= STRBUF_INIT
;
1149 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1151 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1152 unsigned char sha1
[20];
1153 const char *refname
;
1156 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1157 if (strstr(traits
, " fully-peeled "))
1158 peeled
= PEELED_FULLY
;
1159 else if (strstr(traits
, " peeled "))
1160 peeled
= PEELED_TAGS
;
1161 /* perhaps other traits later as well */
1165 refname
= parse_ref_line(&line
, sha1
);
1167 int flag
= REF_ISPACKED
;
1169 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1171 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1173 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1174 if (peeled
== PEELED_FULLY
||
1175 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1176 last
->flag
|= REF_KNOWS_PEELED
;
1181 line
.buf
[0] == '^' &&
1182 line
.len
== PEELED_LINE_LENGTH
&&
1183 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1184 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1185 hashcpy(last
->u
.value
.peeled
, sha1
);
1187 * Regardless of what the file header said,
1188 * we definitely know the value of *this*
1191 last
->flag
|= REF_KNOWS_PEELED
;
1195 strbuf_release(&line
);
1199 * Get the packed_ref_cache for the specified ref_cache, creating it
1202 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1204 const char *packed_refs_file
;
1207 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1209 packed_refs_file
= git_path("packed-refs");
1212 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1213 clear_packed_ref_cache(refs
);
1215 if (!refs
->packed
) {
1218 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1219 acquire_packed_ref_cache(refs
->packed
);
1220 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1221 f
= fopen(packed_refs_file
, "r");
1223 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1224 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1228 return refs
->packed
;
1231 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1233 return get_ref_dir(packed_ref_cache
->root
);
1236 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1238 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1241 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1243 struct packed_ref_cache
*packed_ref_cache
=
1244 get_packed_ref_cache(&ref_cache
);
1246 if (!packed_ref_cache
->lock
)
1247 die("internal error: packed refs not locked");
1248 add_ref(get_packed_ref_dir(packed_ref_cache
),
1249 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1253 * Read the loose references from the namespace dirname into dir
1254 * (without recursing). dirname must end with '/'. dir must be the
1255 * directory entry corresponding to dirname.
1257 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1259 struct ref_cache
*refs
= dir
->ref_cache
;
1263 int dirnamelen
= strlen(dirname
);
1264 struct strbuf refname
;
1267 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1269 path
= git_path("%s", dirname
);
1275 strbuf_init(&refname
, dirnamelen
+ 257);
1276 strbuf_add(&refname
, dirname
, dirnamelen
);
1278 while ((de
= readdir(d
)) != NULL
) {
1279 unsigned char sha1
[20];
1284 if (de
->d_name
[0] == '.')
1286 if (ends_with(de
->d_name
, ".lock"))
1288 strbuf_addstr(&refname
, de
->d_name
);
1289 refdir
= *refs
->name
1290 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1291 : git_path("%s", refname
.buf
);
1292 if (stat(refdir
, &st
) < 0) {
1293 ; /* silently ignore */
1294 } else if (S_ISDIR(st
.st_mode
)) {
1295 strbuf_addch(&refname
, '/');
1296 add_entry_to_dir(dir
,
1297 create_dir_entry(refs
, refname
.buf
,
1303 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1305 flag
|= REF_ISBROKEN
;
1307 } else if (read_ref_full(refname
.buf
,
1308 RESOLVE_REF_READING
,
1311 flag
|= REF_ISBROKEN
;
1313 if (check_refname_format(refname
.buf
,
1314 REFNAME_ALLOW_ONELEVEL
)) {
1316 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1318 add_entry_to_dir(dir
,
1319 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1321 strbuf_setlen(&refname
, dirnamelen
);
1323 strbuf_release(&refname
);
1327 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1331 * Mark the top-level directory complete because we
1332 * are about to read the only subdirectory that can
1335 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1337 * Create an incomplete entry for "refs/":
1339 add_entry_to_dir(get_ref_dir(refs
->loose
),
1340 create_dir_entry(refs
, "refs/", 5, 1));
1342 return get_ref_dir(refs
->loose
);
1345 /* We allow "recursive" symbolic refs. Only within reason, though */
1347 #define MAXREFLEN (1024)
1350 * Called by resolve_gitlink_ref_recursive() after it failed to read
1351 * from the loose refs in ref_cache refs. Find <refname> in the
1352 * packed-refs file for the submodule.
1354 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1355 const char *refname
, unsigned char *sha1
)
1357 struct ref_entry
*ref
;
1358 struct ref_dir
*dir
= get_packed_refs(refs
);
1360 ref
= find_ref(dir
, refname
);
1364 hashcpy(sha1
, ref
->u
.value
.sha1
);
1368 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1369 const char *refname
, unsigned char *sha1
,
1373 char buffer
[128], *p
;
1376 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1379 ? git_path_submodule(refs
->name
, "%s", refname
)
1380 : git_path("%s", refname
);
1381 fd
= open(path
, O_RDONLY
);
1383 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1385 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1389 while (len
&& isspace(buffer
[len
-1]))
1393 /* Was it a detached head or an old-fashioned symlink? */
1394 if (!get_sha1_hex(buffer
, sha1
))
1398 if (strncmp(buffer
, "ref:", 4))
1404 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1407 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1409 int len
= strlen(path
), retval
;
1411 struct ref_cache
*refs
;
1413 while (len
&& path
[len
-1] == '/')
1417 submodule
= xstrndup(path
, len
);
1418 refs
= get_ref_cache(submodule
);
1421 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1426 * Return the ref_entry for the given refname from the packed
1427 * references. If it does not exist, return NULL.
1429 static struct ref_entry
*get_packed_ref(const char *refname
)
1431 return find_ref(get_packed_refs(&ref_cache
), refname
);
1435 * A loose ref file doesn't exist; check for a packed ref. The
1436 * options are forwarded from resolve_safe_unsafe().
1438 static int resolve_missing_loose_ref(const char *refname
,
1440 unsigned char *sha1
,
1443 struct ref_entry
*entry
;
1446 * The loose reference file does not exist; check for a packed
1449 entry
= get_packed_ref(refname
);
1451 hashcpy(sha1
, entry
->u
.value
.sha1
);
1453 *flags
|= REF_ISPACKED
;
1456 /* The reference is not a packed reference, either. */
1457 if (resolve_flags
& RESOLVE_REF_READING
) {
1466 /* This function needs to return a meaningful errno on failure */
1467 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1469 int depth
= MAXDEPTH
;
1472 static char refname_buffer
[256];
1478 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1480 *flags
|= REF_BAD_NAME
;
1482 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1483 !refname_is_safe(refname
)) {
1488 * dwim_ref() uses REF_ISBROKEN to distinguish between
1489 * missing refs and refs that were present but invalid,
1490 * to complain about the latter to stderr.
1492 * We don't know whether the ref exists, so don't set
1498 char path
[PATH_MAX
];
1508 git_snpath(path
, sizeof(path
), "%s", refname
);
1511 * We might have to loop back here to avoid a race
1512 * condition: first we lstat() the file, then we try
1513 * to read it as a link or as a file. But if somebody
1514 * changes the type of the file (file <-> directory
1515 * <-> symlink) between the lstat() and reading, then
1516 * we don't want to report that as an error but rather
1517 * try again starting with the lstat().
1520 if (lstat(path
, &st
) < 0) {
1521 if (errno
!= ENOENT
)
1523 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1529 *flags
|= REF_ISBROKEN
;
1534 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1535 if (S_ISLNK(st
.st_mode
)) {
1536 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1538 if (errno
== ENOENT
|| errno
== EINVAL
)
1539 /* inconsistent with lstat; retry */
1545 if (starts_with(buffer
, "refs/") &&
1546 !check_refname_format(buffer
, 0)) {
1547 strcpy(refname_buffer
, buffer
);
1548 refname
= refname_buffer
;
1550 *flags
|= REF_ISSYMREF
;
1551 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1559 /* Is it a directory? */
1560 if (S_ISDIR(st
.st_mode
)) {
1566 * Anything else, just open it and try to use it as
1569 fd
= open(path
, O_RDONLY
);
1571 if (errno
== ENOENT
)
1572 /* inconsistent with lstat; retry */
1577 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1579 int save_errno
= errno
;
1585 while (len
&& isspace(buffer
[len
-1]))
1590 * Is it a symbolic ref?
1592 if (!starts_with(buffer
, "ref:")) {
1594 * Please note that FETCH_HEAD has a second
1595 * line containing other data.
1597 if (get_sha1_hex(buffer
, sha1
) ||
1598 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1600 *flags
|= REF_ISBROKEN
;
1607 *flags
|= REF_ISBROKEN
;
1612 *flags
|= REF_ISSYMREF
;
1614 while (isspace(*buf
))
1616 refname
= strcpy(refname_buffer
, buf
);
1617 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1621 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1623 *flags
|= REF_ISBROKEN
;
1625 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1626 !refname_is_safe(buf
)) {
1635 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1637 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1640 /* The argument to filter_refs */
1642 const char *pattern
;
1647 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1649 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1654 int read_ref(const char *refname
, unsigned char *sha1
)
1656 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1659 int ref_exists(const char *refname
)
1661 unsigned char sha1
[20];
1662 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1665 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1668 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1669 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1671 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1675 /* object was peeled successfully: */
1679 * object cannot be peeled because the named object (or an
1680 * object referred to by a tag in the peel chain), does not
1685 /* object cannot be peeled because it is not a tag: */
1688 /* ref_entry contains no peeled value because it is a symref: */
1689 PEEL_IS_SYMREF
= -3,
1692 * ref_entry cannot be peeled because it is broken (i.e., the
1693 * symbolic reference cannot even be resolved to an object
1700 * Peel the named object; i.e., if the object is a tag, resolve the
1701 * tag recursively until a non-tag is found. If successful, store the
1702 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1703 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1704 * and leave sha1 unchanged.
1706 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1708 struct object
*o
= lookup_unknown_object(name
);
1710 if (o
->type
== OBJ_NONE
) {
1711 int type
= sha1_object_info(name
, NULL
);
1712 if (type
< 0 || !object_as_type(o
, type
, 0))
1713 return PEEL_INVALID
;
1716 if (o
->type
!= OBJ_TAG
)
1717 return PEEL_NON_TAG
;
1719 o
= deref_tag_noverify(o
);
1721 return PEEL_INVALID
;
1723 hashcpy(sha1
, o
->sha1
);
1728 * Peel the entry (if possible) and return its new peel_status. If
1729 * repeel is true, re-peel the entry even if there is an old peeled
1730 * value that is already stored in it.
1732 * It is OK to call this function with a packed reference entry that
1733 * might be stale and might even refer to an object that has since
1734 * been garbage-collected. In such a case, if the entry has
1735 * REF_KNOWS_PEELED then leave the status unchanged and return
1736 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1738 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1740 enum peel_status status
;
1742 if (entry
->flag
& REF_KNOWS_PEELED
) {
1744 entry
->flag
&= ~REF_KNOWS_PEELED
;
1745 hashclr(entry
->u
.value
.peeled
);
1747 return is_null_sha1(entry
->u
.value
.peeled
) ?
1748 PEEL_NON_TAG
: PEEL_PEELED
;
1751 if (entry
->flag
& REF_ISBROKEN
)
1753 if (entry
->flag
& REF_ISSYMREF
)
1754 return PEEL_IS_SYMREF
;
1756 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1757 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1758 entry
->flag
|= REF_KNOWS_PEELED
;
1762 int peel_ref(const char *refname
, unsigned char *sha1
)
1765 unsigned char base
[20];
1767 if (current_ref
&& (current_ref
->name
== refname
1768 || !strcmp(current_ref
->name
, refname
))) {
1769 if (peel_entry(current_ref
, 0))
1771 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1775 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1779 * If the reference is packed, read its ref_entry from the
1780 * cache in the hope that we already know its peeled value.
1781 * We only try this optimization on packed references because
1782 * (a) forcing the filling of the loose reference cache could
1783 * be expensive and (b) loose references anyway usually do not
1784 * have REF_KNOWS_PEELED.
1786 if (flag
& REF_ISPACKED
) {
1787 struct ref_entry
*r
= get_packed_ref(refname
);
1789 if (peel_entry(r
, 0))
1791 hashcpy(sha1
, r
->u
.value
.peeled
);
1796 return peel_object(base
, sha1
);
1799 struct warn_if_dangling_data
{
1801 const char *refname
;
1802 const struct string_list
*refnames
;
1803 const char *msg_fmt
;
1806 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1807 int flags
, void *cb_data
)
1809 struct warn_if_dangling_data
*d
= cb_data
;
1810 const char *resolves_to
;
1811 unsigned char junk
[20];
1813 if (!(flags
& REF_ISSYMREF
))
1816 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1819 ? strcmp(resolves_to
, d
->refname
)
1820 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1824 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1829 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1831 struct warn_if_dangling_data data
;
1834 data
.refname
= refname
;
1835 data
.refnames
= NULL
;
1836 data
.msg_fmt
= msg_fmt
;
1837 for_each_rawref(warn_if_dangling_symref
, &data
);
1840 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1842 struct warn_if_dangling_data data
;
1845 data
.refname
= NULL
;
1846 data
.refnames
= refnames
;
1847 data
.msg_fmt
= msg_fmt
;
1848 for_each_rawref(warn_if_dangling_symref
, &data
);
1852 * Call fn for each reference in the specified ref_cache, omitting
1853 * references not in the containing_dir of base. fn is called for all
1854 * references, including broken ones. If fn ever returns a non-zero
1855 * value, stop the iteration and return that value; otherwise, return
1858 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1859 each_ref_entry_fn fn
, void *cb_data
)
1861 struct packed_ref_cache
*packed_ref_cache
;
1862 struct ref_dir
*loose_dir
;
1863 struct ref_dir
*packed_dir
;
1867 * We must make sure that all loose refs are read before accessing the
1868 * packed-refs file; this avoids a race condition in which loose refs
1869 * are migrated to the packed-refs file by a simultaneous process, but
1870 * our in-memory view is from before the migration. get_packed_ref_cache()
1871 * takes care of making sure our view is up to date with what is on
1874 loose_dir
= get_loose_refs(refs
);
1875 if (base
&& *base
) {
1876 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1879 prime_ref_dir(loose_dir
);
1881 packed_ref_cache
= get_packed_ref_cache(refs
);
1882 acquire_packed_ref_cache(packed_ref_cache
);
1883 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1884 if (base
&& *base
) {
1885 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1888 if (packed_dir
&& loose_dir
) {
1889 sort_ref_dir(packed_dir
);
1890 sort_ref_dir(loose_dir
);
1891 retval
= do_for_each_entry_in_dirs(
1892 packed_dir
, loose_dir
, fn
, cb_data
);
1893 } else if (packed_dir
) {
1894 sort_ref_dir(packed_dir
);
1895 retval
= do_for_each_entry_in_dir(
1896 packed_dir
, 0, fn
, cb_data
);
1897 } else if (loose_dir
) {
1898 sort_ref_dir(loose_dir
);
1899 retval
= do_for_each_entry_in_dir(
1900 loose_dir
, 0, fn
, cb_data
);
1903 release_packed_ref_cache(packed_ref_cache
);
1908 * Call fn for each reference in the specified ref_cache for which the
1909 * refname begins with base. If trim is non-zero, then trim that many
1910 * characters off the beginning of each refname before passing the
1911 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1912 * broken references in the iteration. If fn ever returns a non-zero
1913 * value, stop the iteration and return that value; otherwise, return
1916 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
1917 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1919 struct ref_entry_cb data
;
1924 data
.cb_data
= cb_data
;
1926 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
1929 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1931 unsigned char sha1
[20];
1935 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
1936 return fn("HEAD", sha1
, 0, cb_data
);
1941 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
1942 return fn("HEAD", sha1
, flag
, cb_data
);
1947 int head_ref(each_ref_fn fn
, void *cb_data
)
1949 return do_head_ref(NULL
, fn
, cb_data
);
1952 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1954 return do_head_ref(submodule
, fn
, cb_data
);
1957 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1959 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
1962 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1964 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
1967 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1969 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
1972 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
1973 each_ref_fn fn
, void *cb_data
)
1975 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
1978 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
1980 return for_each_ref_in("refs/tags/", fn
, cb_data
);
1983 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1985 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
1988 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
1990 return for_each_ref_in("refs/heads/", fn
, cb_data
);
1993 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1995 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
1998 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2000 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2003 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2005 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2008 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2010 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2013 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2015 struct strbuf buf
= STRBUF_INIT
;
2017 unsigned char sha1
[20];
2020 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2021 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2022 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2023 strbuf_release(&buf
);
2028 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2030 struct strbuf buf
= STRBUF_INIT
;
2032 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2033 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2034 strbuf_release(&buf
);
2038 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2039 const char *prefix
, void *cb_data
)
2041 struct strbuf real_pattern
= STRBUF_INIT
;
2042 struct ref_filter filter
;
2045 if (!prefix
&& !starts_with(pattern
, "refs/"))
2046 strbuf_addstr(&real_pattern
, "refs/");
2048 strbuf_addstr(&real_pattern
, prefix
);
2049 strbuf_addstr(&real_pattern
, pattern
);
2051 if (!has_glob_specials(pattern
)) {
2052 /* Append implied '/' '*' if not present. */
2053 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2054 strbuf_addch(&real_pattern
, '/');
2055 /* No need to check for '*', there is none. */
2056 strbuf_addch(&real_pattern
, '*');
2059 filter
.pattern
= real_pattern
.buf
;
2061 filter
.cb_data
= cb_data
;
2062 ret
= for_each_ref(filter_refs
, &filter
);
2064 strbuf_release(&real_pattern
);
2068 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2070 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2073 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2075 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2076 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2079 const char *prettify_refname(const char *name
)
2082 starts_with(name
, "refs/heads/") ? 11 :
2083 starts_with(name
, "refs/tags/") ? 10 :
2084 starts_with(name
, "refs/remotes/") ? 13 :
2088 static const char *ref_rev_parse_rules
[] = {
2093 "refs/remotes/%.*s",
2094 "refs/remotes/%.*s/HEAD",
2098 int refname_match(const char *abbrev_name
, const char *full_name
)
2101 const int abbrev_name_len
= strlen(abbrev_name
);
2103 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2104 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2112 static void unlock_ref(struct ref_lock
*lock
)
2114 /* Do not free lock->lk -- atexit() still looks at them */
2116 rollback_lock_file(lock
->lk
);
2117 free(lock
->ref_name
);
2118 free(lock
->orig_ref_name
);
2122 /* This function should make sure errno is meaningful on error */
2123 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2124 const unsigned char *old_sha1
, int mustexist
)
2126 if (read_ref_full(lock
->ref_name
,
2127 mustexist
? RESOLVE_REF_READING
: 0,
2128 lock
->old_sha1
, NULL
)) {
2129 int save_errno
= errno
;
2130 error("Can't verify ref %s", lock
->ref_name
);
2135 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2136 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2137 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2145 static int remove_empty_directories(const char *file
)
2147 /* we want to create a file but there is a directory there;
2148 * if that is an empty directory (or a directory that contains
2149 * only empty directories), remove them.
2152 int result
, save_errno
;
2154 strbuf_init(&path
, 20);
2155 strbuf_addstr(&path
, file
);
2157 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2160 strbuf_release(&path
);
2167 * *string and *len will only be substituted, and *string returned (for
2168 * later free()ing) if the string passed in is a magic short-hand form
2171 static char *substitute_branch_name(const char **string
, int *len
)
2173 struct strbuf buf
= STRBUF_INIT
;
2174 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2178 *string
= strbuf_detach(&buf
, &size
);
2180 return (char *)*string
;
2186 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2188 char *last_branch
= substitute_branch_name(&str
, &len
);
2193 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2194 char fullref
[PATH_MAX
];
2195 unsigned char sha1_from_ref
[20];
2196 unsigned char *this_result
;
2199 this_result
= refs_found
? sha1_from_ref
: sha1
;
2200 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2201 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2202 this_result
, &flag
);
2206 if (!warn_ambiguous_refs
)
2208 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2209 warning("ignoring dangling symref %s.", fullref
);
2210 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2211 warning("ignoring broken ref %s.", fullref
);
2218 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2220 char *last_branch
= substitute_branch_name(&str
, &len
);
2225 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2226 unsigned char hash
[20];
2227 char path
[PATH_MAX
];
2228 const char *ref
, *it
;
2230 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2231 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2235 if (reflog_exists(path
))
2237 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2241 if (!logs_found
++) {
2243 hashcpy(sha1
, hash
);
2245 if (!warn_ambiguous_refs
)
2253 * Locks a ref returning the lock on success and NULL on failure.
2254 * On failure errno is set to something meaningful.
2256 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2257 const unsigned char *old_sha1
,
2258 const struct string_list
*skip
,
2259 int flags
, int *type_p
)
2262 const char *orig_refname
= refname
;
2263 struct ref_lock
*lock
;
2266 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2267 int resolve_flags
= 0;
2269 int attempts_remaining
= 3;
2271 lock
= xcalloc(1, sizeof(struct ref_lock
));
2275 resolve_flags
|= RESOLVE_REF_READING
;
2276 if (flags
& REF_DELETING
) {
2277 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2278 if (flags
& REF_NODEREF
)
2279 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2282 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2283 lock
->old_sha1
, &type
);
2284 if (!refname
&& errno
== EISDIR
) {
2285 /* we are trying to lock foo but we used to
2286 * have foo/bar which now does not exist;
2287 * it is normal for the empty directory 'foo'
2290 ref_file
= git_path("%s", orig_refname
);
2291 if (remove_empty_directories(ref_file
)) {
2293 error("there are still refs under '%s'", orig_refname
);
2296 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2297 lock
->old_sha1
, &type
);
2303 error("unable to resolve reference %s: %s",
2304 orig_refname
, strerror(errno
));
2307 missing
= is_null_sha1(lock
->old_sha1
);
2308 /* When the ref did not exist and we are creating it,
2309 * make sure there is no existing ref that is packed
2310 * whose name begins with our refname, nor a ref whose
2311 * name is a proper prefix of our refname.
2314 !is_refname_available(refname
, skip
, get_packed_refs(&ref_cache
))) {
2315 last_errno
= ENOTDIR
;
2319 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2322 if (flags
& REF_NODEREF
) {
2323 refname
= orig_refname
;
2324 lflags
|= LOCK_NO_DEREF
;
2326 lock
->ref_name
= xstrdup(refname
);
2327 lock
->orig_ref_name
= xstrdup(orig_refname
);
2328 ref_file
= git_path("%s", refname
);
2330 lock
->force_write
= 1;
2331 if ((flags
& REF_NODEREF
) && (type
& REF_ISSYMREF
))
2332 lock
->force_write
= 1;
2335 switch (safe_create_leading_directories(ref_file
)) {
2337 break; /* success */
2339 if (--attempts_remaining
> 0)
2344 error("unable to create directory for %s", ref_file
);
2348 lock
->lock_fd
= hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
);
2349 if (lock
->lock_fd
< 0) {
2351 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2353 * Maybe somebody just deleted one of the
2354 * directories leading to ref_file. Try
2359 struct strbuf err
= STRBUF_INIT
;
2360 unable_to_lock_message(ref_file
, errno
, &err
);
2361 error("%s", err
.buf
);
2362 strbuf_release(&err
);
2366 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2375 * Write an entry to the packed-refs file for the specified refname.
2376 * If peeled is non-NULL, write it as the entry's peeled value.
2378 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2379 unsigned char *peeled
)
2381 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2383 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2387 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2389 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2391 enum peel_status peel_status
= peel_entry(entry
, 0);
2393 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2394 error("internal error: %s is not a valid packed reference!",
2396 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2397 peel_status
== PEEL_PEELED
?
2398 entry
->u
.value
.peeled
: NULL
);
2402 /* This should return a meaningful errno on failure */
2403 int lock_packed_refs(int flags
)
2405 struct packed_ref_cache
*packed_ref_cache
;
2407 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2410 * Get the current packed-refs while holding the lock. If the
2411 * packed-refs file has been modified since we last read it,
2412 * this will automatically invalidate the cache and re-read
2413 * the packed-refs file.
2415 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2416 packed_ref_cache
->lock
= &packlock
;
2417 /* Increment the reference count to prevent it from being freed: */
2418 acquire_packed_ref_cache(packed_ref_cache
);
2423 * Commit the packed refs changes.
2424 * On error we must make sure that errno contains a meaningful value.
2426 int commit_packed_refs(void)
2428 struct packed_ref_cache
*packed_ref_cache
=
2429 get_packed_ref_cache(&ref_cache
);
2434 if (!packed_ref_cache
->lock
)
2435 die("internal error: packed-refs not locked");
2437 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2439 die_errno("unable to fdopen packed-refs descriptor");
2441 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2442 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2443 0, write_packed_entry_fn
, out
);
2445 if (commit_lock_file(packed_ref_cache
->lock
)) {
2449 packed_ref_cache
->lock
= NULL
;
2450 release_packed_ref_cache(packed_ref_cache
);
2455 void rollback_packed_refs(void)
2457 struct packed_ref_cache
*packed_ref_cache
=
2458 get_packed_ref_cache(&ref_cache
);
2460 if (!packed_ref_cache
->lock
)
2461 die("internal error: packed-refs not locked");
2462 rollback_lock_file(packed_ref_cache
->lock
);
2463 packed_ref_cache
->lock
= NULL
;
2464 release_packed_ref_cache(packed_ref_cache
);
2465 clear_packed_ref_cache(&ref_cache
);
2468 struct ref_to_prune
{
2469 struct ref_to_prune
*next
;
2470 unsigned char sha1
[20];
2471 char name
[FLEX_ARRAY
];
2474 struct pack_refs_cb_data
{
2476 struct ref_dir
*packed_refs
;
2477 struct ref_to_prune
*ref_to_prune
;
2481 * An each_ref_entry_fn that is run over loose references only. If
2482 * the loose reference can be packed, add an entry in the packed ref
2483 * cache. If the reference should be pruned, also add it to
2484 * ref_to_prune in the pack_refs_cb_data.
2486 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2488 struct pack_refs_cb_data
*cb
= cb_data
;
2489 enum peel_status peel_status
;
2490 struct ref_entry
*packed_entry
;
2491 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2493 /* ALWAYS pack tags */
2494 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2497 /* Do not pack symbolic or broken refs: */
2498 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2501 /* Add a packed ref cache entry equivalent to the loose entry. */
2502 peel_status
= peel_entry(entry
, 1);
2503 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2504 die("internal error peeling reference %s (%s)",
2505 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2506 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2508 /* Overwrite existing packed entry with info from loose entry */
2509 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2510 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2512 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2513 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2514 add_ref(cb
->packed_refs
, packed_entry
);
2516 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2518 /* Schedule the loose reference for pruning if requested. */
2519 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2520 int namelen
= strlen(entry
->name
) + 1;
2521 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2522 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2523 strcpy(n
->name
, entry
->name
);
2524 n
->next
= cb
->ref_to_prune
;
2525 cb
->ref_to_prune
= n
;
2531 * Remove empty parents, but spare refs/ and immediate subdirs.
2532 * Note: munges *name.
2534 static void try_remove_empty_parents(char *name
)
2539 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2540 while (*p
&& *p
!= '/')
2542 /* tolerate duplicate slashes; see check_refname_format() */
2546 for (q
= p
; *q
; q
++)
2549 while (q
> p
&& *q
!= '/')
2551 while (q
> p
&& *(q
-1) == '/')
2556 if (rmdir(git_path("%s", name
)))
2561 /* make sure nobody touched the ref, and unlink */
2562 static void prune_ref(struct ref_to_prune
*r
)
2564 struct ref_transaction
*transaction
;
2565 struct strbuf err
= STRBUF_INIT
;
2567 if (check_refname_format(r
->name
, 0))
2570 transaction
= ref_transaction_begin(&err
);
2572 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2573 REF_ISPRUNING
, 1, NULL
, &err
) ||
2574 ref_transaction_commit(transaction
, &err
)) {
2575 ref_transaction_free(transaction
);
2576 error("%s", err
.buf
);
2577 strbuf_release(&err
);
2580 ref_transaction_free(transaction
);
2581 strbuf_release(&err
);
2582 try_remove_empty_parents(r
->name
);
2585 static void prune_refs(struct ref_to_prune
*r
)
2593 int pack_refs(unsigned int flags
)
2595 struct pack_refs_cb_data cbdata
;
2597 memset(&cbdata
, 0, sizeof(cbdata
));
2598 cbdata
.flags
= flags
;
2600 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2601 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2603 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2604 pack_if_possible_fn
, &cbdata
);
2606 if (commit_packed_refs())
2607 die_errno("unable to overwrite old ref-pack file");
2609 prune_refs(cbdata
.ref_to_prune
);
2614 * If entry is no longer needed in packed-refs, add it to the string
2615 * list pointed to by cb_data. Reasons for deleting entries:
2617 * - Entry is broken.
2618 * - Entry is overridden by a loose ref.
2619 * - Entry does not point at a valid object.
2621 * In the first and third cases, also emit an error message because these
2622 * are indications of repository corruption.
2624 static int curate_packed_ref_fn(struct ref_entry
*entry
, void *cb_data
)
2626 struct string_list
*refs_to_delete
= cb_data
;
2628 if (entry
->flag
& REF_ISBROKEN
) {
2629 /* This shouldn't happen to packed refs. */
2630 error("%s is broken!", entry
->name
);
2631 string_list_append(refs_to_delete
, entry
->name
);
2634 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
2635 unsigned char sha1
[20];
2638 if (read_ref_full(entry
->name
, 0, sha1
, &flags
))
2639 /* We should at least have found the packed ref. */
2640 die("Internal error");
2641 if ((flags
& REF_ISSYMREF
) || !(flags
& REF_ISPACKED
)) {
2643 * This packed reference is overridden by a
2644 * loose reference, so it is OK that its value
2645 * is no longer valid; for example, it might
2646 * refer to an object that has been garbage
2647 * collected. For this purpose we don't even
2648 * care whether the loose reference itself is
2649 * invalid, broken, symbolic, etc. Silently
2650 * remove the packed reference.
2652 string_list_append(refs_to_delete
, entry
->name
);
2656 * There is no overriding loose reference, so the fact
2657 * that this reference doesn't refer to a valid object
2658 * indicates some kind of repository corruption.
2659 * Report the problem, then omit the reference from
2662 error("%s does not point to a valid object!", entry
->name
);
2663 string_list_append(refs_to_delete
, entry
->name
);
2670 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2672 struct ref_dir
*packed
;
2673 struct string_list refs_to_delete
= STRING_LIST_INIT_DUP
;
2674 struct string_list_item
*refname
, *ref_to_delete
;
2675 int ret
, needs_repacking
= 0, removed
= 0;
2679 /* Look for a packed ref */
2680 for_each_string_list_item(refname
, refnames
) {
2681 if (get_packed_ref(refname
->string
)) {
2682 needs_repacking
= 1;
2687 /* Avoid locking if we have nothing to do */
2688 if (!needs_repacking
)
2689 return 0; /* no refname exists in packed refs */
2691 if (lock_packed_refs(0)) {
2692 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2695 packed
= get_packed_refs(&ref_cache
);
2697 /* Remove refnames from the cache */
2698 for_each_string_list_item(refname
, refnames
)
2699 if (remove_entry(packed
, refname
->string
) != -1)
2703 * All packed entries disappeared while we were
2704 * acquiring the lock.
2706 rollback_packed_refs();
2710 /* Remove any other accumulated cruft */
2711 do_for_each_entry_in_dir(packed
, 0, curate_packed_ref_fn
, &refs_to_delete
);
2712 for_each_string_list_item(ref_to_delete
, &refs_to_delete
) {
2713 if (remove_entry(packed
, ref_to_delete
->string
) == -1)
2714 die("internal error");
2717 /* Write what remains */
2718 ret
= commit_packed_refs();
2720 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2725 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2729 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2731 * loose. The loose file name is the same as the
2732 * lockfile name, minus ".lock":
2734 char *loose_filename
= get_locked_file_path(lock
->lk
);
2735 int res
= unlink_or_msg(loose_filename
, err
);
2736 free(loose_filename
);
2743 int delete_ref(const char *refname
, const unsigned char *sha1
, int delopt
)
2745 struct ref_transaction
*transaction
;
2746 struct strbuf err
= STRBUF_INIT
;
2748 transaction
= ref_transaction_begin(&err
);
2750 ref_transaction_delete(transaction
, refname
, sha1
, delopt
,
2751 sha1
&& !is_null_sha1(sha1
), NULL
, &err
) ||
2752 ref_transaction_commit(transaction
, &err
)) {
2753 error("%s", err
.buf
);
2754 ref_transaction_free(transaction
);
2755 strbuf_release(&err
);
2758 ref_transaction_free(transaction
);
2759 strbuf_release(&err
);
2764 * People using contrib's git-new-workdir have .git/logs/refs ->
2765 * /some/other/path/.git/logs/refs, and that may live on another device.
2767 * IOW, to avoid cross device rename errors, the temporary renamed log must
2768 * live into logs/refs.
2770 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2772 static int rename_tmp_log(const char *newrefname
)
2774 int attempts_remaining
= 4;
2777 switch (safe_create_leading_directories(git_path("logs/%s", newrefname
))) {
2779 break; /* success */
2781 if (--attempts_remaining
> 0)
2785 error("unable to create directory for %s", newrefname
);
2789 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2790 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2792 * rename(a, b) when b is an existing
2793 * directory ought to result in ISDIR, but
2794 * Solaris 5.8 gives ENOTDIR. Sheesh.
2796 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2797 error("Directory not empty: logs/%s", newrefname
);
2801 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2803 * Maybe another process just deleted one of
2804 * the directories in the path to newrefname.
2805 * Try again from the beginning.
2809 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2810 newrefname
, strerror(errno
));
2817 static int rename_ref_available(const char *oldname
, const char *newname
)
2819 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2822 string_list_insert(&skip
, oldname
);
2823 ret
= is_refname_available(newname
, &skip
, get_packed_refs(&ref_cache
))
2824 && is_refname_available(newname
, &skip
, get_loose_refs(&ref_cache
));
2825 string_list_clear(&skip
, 0);
2829 static int write_ref_sha1(struct ref_lock
*lock
, const unsigned char *sha1
,
2830 const char *logmsg
);
2832 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2834 unsigned char sha1
[20], orig_sha1
[20];
2835 int flag
= 0, logmoved
= 0;
2836 struct ref_lock
*lock
;
2837 struct stat loginfo
;
2838 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2839 const char *symref
= NULL
;
2841 if (log
&& S_ISLNK(loginfo
.st_mode
))
2842 return error("reflog for %s is a symlink", oldrefname
);
2844 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2846 if (flag
& REF_ISSYMREF
)
2847 return error("refname %s is a symbolic ref, renaming it is not supported",
2850 return error("refname %s not found", oldrefname
);
2852 if (!rename_ref_available(oldrefname
, newrefname
))
2855 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2856 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2857 oldrefname
, strerror(errno
));
2859 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2860 error("unable to delete old %s", oldrefname
);
2864 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2865 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2866 if (errno
==EISDIR
) {
2867 if (remove_empty_directories(git_path("%s", newrefname
))) {
2868 error("Directory not empty: %s", newrefname
);
2872 error("unable to delete existing %s", newrefname
);
2877 if (log
&& rename_tmp_log(newrefname
))
2882 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, 0, NULL
);
2884 error("unable to lock %s for update", newrefname
);
2887 lock
->force_write
= 1;
2888 hashcpy(lock
->old_sha1
, orig_sha1
);
2889 if (write_ref_sha1(lock
, orig_sha1
, logmsg
)) {
2890 error("unable to write current sha1 into %s", newrefname
);
2897 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, 0, NULL
);
2899 error("unable to lock %s for rollback", oldrefname
);
2903 lock
->force_write
= 1;
2904 flag
= log_all_ref_updates
;
2905 log_all_ref_updates
= 0;
2906 if (write_ref_sha1(lock
, orig_sha1
, NULL
))
2907 error("unable to write current sha1 into %s", oldrefname
);
2908 log_all_ref_updates
= flag
;
2911 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2912 error("unable to restore logfile %s from %s: %s",
2913 oldrefname
, newrefname
, strerror(errno
));
2914 if (!logmoved
&& log
&&
2915 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2916 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2917 oldrefname
, strerror(errno
));
2922 static int close_ref(struct ref_lock
*lock
)
2924 if (close_lock_file(lock
->lk
))
2930 static int commit_ref(struct ref_lock
*lock
)
2932 if (commit_lock_file(lock
->lk
))
2939 * copy the reflog message msg to buf, which has been allocated sufficiently
2940 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2941 * because reflog file is one line per entry.
2943 static int copy_msg(char *buf
, const char *msg
)
2950 while ((c
= *msg
++)) {
2951 if (wasspace
&& isspace(c
))
2953 wasspace
= isspace(c
);
2958 while (buf
< cp
&& isspace(cp
[-1]))
2964 /* This function must set a meaningful errno on failure */
2965 int log_ref_setup(const char *refname
, char *logfile
, int bufsize
)
2967 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2969 git_snpath(logfile
, bufsize
, "logs/%s", refname
);
2970 if (log_all_ref_updates
&&
2971 (starts_with(refname
, "refs/heads/") ||
2972 starts_with(refname
, "refs/remotes/") ||
2973 starts_with(refname
, "refs/notes/") ||
2974 !strcmp(refname
, "HEAD"))) {
2975 if (safe_create_leading_directories(logfile
) < 0) {
2976 int save_errno
= errno
;
2977 error("unable to create directory for %s", logfile
);
2984 logfd
= open(logfile
, oflags
, 0666);
2986 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
2989 if (errno
== EISDIR
) {
2990 if (remove_empty_directories(logfile
)) {
2991 int save_errno
= errno
;
2992 error("There are still logs under '%s'",
2997 logfd
= open(logfile
, oflags
, 0666);
3001 int save_errno
= errno
;
3002 error("Unable to append to %s: %s", logfile
,
3009 adjust_shared_perm(logfile
);
3014 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3015 const unsigned char *new_sha1
,
3016 const char *committer
, const char *msg
)
3018 int msglen
, written
;
3019 unsigned maxlen
, len
;
3022 msglen
= msg
? strlen(msg
) : 0;
3023 maxlen
= strlen(committer
) + msglen
+ 100;
3024 logrec
= xmalloc(maxlen
);
3025 len
= sprintf(logrec
, "%s %s %s\n",
3026 sha1_to_hex(old_sha1
),
3027 sha1_to_hex(new_sha1
),
3030 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3032 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3040 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3041 const unsigned char *new_sha1
, const char *msg
)
3043 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3044 char log_file
[PATH_MAX
];
3046 if (log_all_ref_updates
< 0)
3047 log_all_ref_updates
= !is_bare_repository();
3049 result
= log_ref_setup(refname
, log_file
, sizeof(log_file
));
3053 logfd
= open(log_file
, oflags
);
3056 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3057 git_committer_info(0), msg
);
3059 int save_errno
= errno
;
3061 error("Unable to append to %s", log_file
);
3066 int save_errno
= errno
;
3067 error("Unable to append to %s", log_file
);
3074 int is_branch(const char *refname
)
3076 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3080 * Write sha1 into the ref specified by the lock. Make sure that errno
3083 static int write_ref_sha1(struct ref_lock
*lock
,
3084 const unsigned char *sha1
, const char *logmsg
)
3086 static char term
= '\n';
3093 if (!lock
->force_write
&& !hashcmp(lock
->old_sha1
, sha1
)) {
3097 o
= parse_object(sha1
);
3099 error("Trying to write ref %s with nonexistent object %s",
3100 lock
->ref_name
, sha1_to_hex(sha1
));
3105 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3106 error("Trying to write non-commit object %s to branch %s",
3107 sha1_to_hex(sha1
), lock
->ref_name
);
3112 if (write_in_full(lock
->lock_fd
, sha1_to_hex(sha1
), 40) != 40 ||
3113 write_in_full(lock
->lock_fd
, &term
, 1) != 1 ||
3114 close_ref(lock
) < 0) {
3115 int save_errno
= errno
;
3116 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3121 clear_loose_ref_cache(&ref_cache
);
3122 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3123 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3124 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3128 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3130 * Special hack: If a branch is updated directly and HEAD
3131 * points to it (may happen on the remote side of a push
3132 * for example) then logically the HEAD reflog should be
3134 * A generic solution implies reverse symref information,
3135 * but finding all symrefs pointing to the given branch
3136 * would be rather costly for this rare event (the direct
3137 * update of a branch) to be worth it. So let's cheat and
3138 * check with HEAD only which should cover 99% of all usage
3139 * scenarios (even 100% of the default ones).
3141 unsigned char head_sha1
[20];
3143 const char *head_ref
;
3144 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3145 head_sha1
, &head_flag
);
3146 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3147 !strcmp(head_ref
, lock
->ref_name
))
3148 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3150 if (commit_ref(lock
)) {
3151 error("Couldn't set %s", lock
->ref_name
);
3159 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3162 const char *lockpath
;
3164 int fd
, len
, written
;
3165 char *git_HEAD
= git_pathdup("%s", ref_target
);
3166 unsigned char old_sha1
[20], new_sha1
[20];
3168 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3171 if (safe_create_leading_directories(git_HEAD
) < 0)
3172 return error("unable to create directory for %s", git_HEAD
);
3174 #ifndef NO_SYMLINK_HEAD
3175 if (prefer_symlink_refs
) {
3177 if (!symlink(refs_heads_master
, git_HEAD
))
3179 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3183 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3184 if (sizeof(ref
) <= len
) {
3185 error("refname too long: %s", refs_heads_master
);
3186 goto error_free_return
;
3188 lockpath
= mkpath("%s.lock", git_HEAD
);
3189 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3191 error("Unable to open %s for writing", lockpath
);
3192 goto error_free_return
;
3194 written
= write_in_full(fd
, ref
, len
);
3195 if (close(fd
) != 0 || written
!= len
) {
3196 error("Unable to write to %s", lockpath
);
3197 goto error_unlink_return
;
3199 if (rename(lockpath
, git_HEAD
) < 0) {
3200 error("Unable to create %s", git_HEAD
);
3201 goto error_unlink_return
;
3203 if (adjust_shared_perm(git_HEAD
)) {
3204 error("Unable to fix permissions on %s", lockpath
);
3205 error_unlink_return
:
3206 unlink_or_warn(lockpath
);
3212 #ifndef NO_SYMLINK_HEAD
3215 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3216 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3222 struct read_ref_at_cb
{
3223 const char *refname
;
3224 unsigned long at_time
;
3227 unsigned char *sha1
;
3230 unsigned char osha1
[20];
3231 unsigned char nsha1
[20];
3235 unsigned long *cutoff_time
;
3240 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3241 const char *email
, unsigned long timestamp
, int tz
,
3242 const char *message
, void *cb_data
)
3244 struct read_ref_at_cb
*cb
= cb_data
;
3248 cb
->date
= timestamp
;
3250 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3252 *cb
->msg
= xstrdup(message
);
3253 if (cb
->cutoff_time
)
3254 *cb
->cutoff_time
= timestamp
;
3256 *cb
->cutoff_tz
= tz
;
3258 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3260 * we have not yet updated cb->[n|o]sha1 so they still
3261 * hold the values for the previous record.
3263 if (!is_null_sha1(cb
->osha1
)) {
3264 hashcpy(cb
->sha1
, nsha1
);
3265 if (hashcmp(cb
->osha1
, nsha1
))
3266 warning("Log for ref %s has gap after %s.",
3267 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3269 else if (cb
->date
== cb
->at_time
)
3270 hashcpy(cb
->sha1
, nsha1
);
3271 else if (hashcmp(nsha1
, cb
->sha1
))
3272 warning("Log for ref %s unexpectedly ended on %s.",
3273 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3275 hashcpy(cb
->osha1
, osha1
);
3276 hashcpy(cb
->nsha1
, nsha1
);
3280 hashcpy(cb
->osha1
, osha1
);
3281 hashcpy(cb
->nsha1
, nsha1
);
3287 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3288 const char *email
, unsigned long timestamp
,
3289 int tz
, const char *message
, void *cb_data
)
3291 struct read_ref_at_cb
*cb
= cb_data
;
3294 *cb
->msg
= xstrdup(message
);
3295 if (cb
->cutoff_time
)
3296 *cb
->cutoff_time
= timestamp
;
3298 *cb
->cutoff_tz
= tz
;
3300 *cb
->cutoff_cnt
= cb
->reccnt
;
3301 hashcpy(cb
->sha1
, osha1
);
3302 if (is_null_sha1(cb
->sha1
))
3303 hashcpy(cb
->sha1
, nsha1
);
3304 /* We just want the first entry */
3308 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3309 unsigned char *sha1
, char **msg
,
3310 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3312 struct read_ref_at_cb cb
;
3314 memset(&cb
, 0, sizeof(cb
));
3315 cb
.refname
= refname
;
3316 cb
.at_time
= at_time
;
3319 cb
.cutoff_time
= cutoff_time
;
3320 cb
.cutoff_tz
= cutoff_tz
;
3321 cb
.cutoff_cnt
= cutoff_cnt
;
3324 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3327 if (flags
& GET_SHA1_QUIETLY
)
3330 die("Log for %s is empty.", refname
);
3335 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3340 int reflog_exists(const char *refname
)
3344 return !lstat(git_path("logs/%s", refname
), &st
) &&
3345 S_ISREG(st
.st_mode
);
3348 int delete_reflog(const char *refname
)
3350 return remove_path(git_path("logs/%s", refname
));
3353 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3355 unsigned char osha1
[20], nsha1
[20];
3356 char *email_end
, *message
;
3357 unsigned long timestamp
;
3360 /* old SP new SP name <email> SP time TAB msg LF */
3361 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3362 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3363 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3364 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3365 email_end
[1] != ' ' ||
3366 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3367 !message
|| message
[0] != ' ' ||
3368 (message
[1] != '+' && message
[1] != '-') ||
3369 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3370 !isdigit(message
[4]) || !isdigit(message
[5]))
3371 return 0; /* corrupt? */
3372 email_end
[1] = '\0';
3373 tz
= strtol(message
+ 1, NULL
, 10);
3374 if (message
[6] != '\t')
3378 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3381 static char *find_beginning_of_line(char *bob
, char *scan
)
3383 while (bob
< scan
&& *(--scan
) != '\n')
3384 ; /* keep scanning backwards */
3386 * Return either beginning of the buffer, or LF at the end of
3387 * the previous line.
3392 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3394 struct strbuf sb
= STRBUF_INIT
;
3397 int ret
= 0, at_tail
= 1;
3399 logfp
= fopen(git_path("logs/%s", refname
), "r");
3403 /* Jump to the end */
3404 if (fseek(logfp
, 0, SEEK_END
) < 0)
3405 return error("cannot seek back reflog for %s: %s",
3406 refname
, strerror(errno
));
3408 while (!ret
&& 0 < pos
) {
3414 /* Fill next block from the end */
3415 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3416 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3417 return error("cannot seek back reflog for %s: %s",
3418 refname
, strerror(errno
));
3419 nread
= fread(buf
, cnt
, 1, logfp
);
3421 return error("cannot read %d bytes from reflog for %s: %s",
3422 cnt
, refname
, strerror(errno
));
3425 scanp
= endp
= buf
+ cnt
;
3426 if (at_tail
&& scanp
[-1] == '\n')
3427 /* Looking at the final LF at the end of the file */
3431 while (buf
< scanp
) {
3433 * terminating LF of the previous line, or the beginning
3438 bp
= find_beginning_of_line(buf
, scanp
);
3442 * The newline is the end of the previous line,
3443 * so we know we have complete line starting
3444 * at (bp + 1). Prefix it onto any prior data
3445 * we collected for the line and process it.
3447 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3450 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3456 * We are at the start of the buffer, and the
3457 * start of the file; there is no previous
3458 * line, and we have everything for this one.
3459 * Process it, and we can end the loop.
3461 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3462 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3469 * We are at the start of the buffer, and there
3470 * is more file to read backwards. Which means
3471 * we are in the middle of a line. Note that we
3472 * may get here even if *bp was a newline; that
3473 * just means we are at the exact end of the
3474 * previous line, rather than some spot in the
3477 * Save away what we have to be combined with
3478 * the data from the next read.
3480 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3487 die("BUG: reverse reflog parser had leftover data");
3490 strbuf_release(&sb
);
3494 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3497 struct strbuf sb
= STRBUF_INIT
;
3500 logfp
= fopen(git_path("logs/%s", refname
), "r");
3504 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3505 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3507 strbuf_release(&sb
);
3511 * Call fn for each reflog in the namespace indicated by name. name
3512 * must be empty or end with '/'. Name will be used as a scratch
3513 * space, but its contents will be restored before return.
3515 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3517 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3520 int oldlen
= name
->len
;
3523 return name
->len
? errno
: 0;
3525 while ((de
= readdir(d
)) != NULL
) {
3528 if (de
->d_name
[0] == '.')
3530 if (ends_with(de
->d_name
, ".lock"))
3532 strbuf_addstr(name
, de
->d_name
);
3533 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3534 ; /* silently ignore */
3536 if (S_ISDIR(st
.st_mode
)) {
3537 strbuf_addch(name
, '/');
3538 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3540 unsigned char sha1
[20];
3541 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3542 retval
= error("bad ref for %s", name
->buf
);
3544 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3549 strbuf_setlen(name
, oldlen
);
3555 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3559 strbuf_init(&name
, PATH_MAX
);
3560 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3561 strbuf_release(&name
);
3566 * Information needed for a single ref update. Set new_sha1 to the
3567 * new value or to zero to delete the ref. To check the old value
3568 * while locking the ref, set have_old to 1 and set old_sha1 to the
3569 * value or to zero to ensure the ref does not exist before update.
3572 unsigned char new_sha1
[20];
3573 unsigned char old_sha1
[20];
3574 int flags
; /* REF_NODEREF? */
3575 int have_old
; /* 1 if old_sha1 is valid, 0 otherwise */
3576 struct ref_lock
*lock
;
3579 const char refname
[FLEX_ARRAY
];
3583 * Transaction states.
3584 * OPEN: The transaction is in a valid state and can accept new updates.
3585 * An OPEN transaction can be committed.
3586 * CLOSED: A closed transaction is no longer active and no other operations
3587 * than free can be used on it in this state.
3588 * A transaction can either become closed by successfully committing
3589 * an active transaction or if there is a failure while building
3590 * the transaction thus rendering it failed/inactive.
3592 enum ref_transaction_state
{
3593 REF_TRANSACTION_OPEN
= 0,
3594 REF_TRANSACTION_CLOSED
= 1
3598 * Data structure for holding a reference transaction, which can
3599 * consist of checks and updates to multiple references, carried out
3600 * as atomically as possible. This structure is opaque to callers.
3602 struct ref_transaction
{
3603 struct ref_update
**updates
;
3606 enum ref_transaction_state state
;
3609 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3613 return xcalloc(1, sizeof(struct ref_transaction
));
3616 void ref_transaction_free(struct ref_transaction
*transaction
)
3623 for (i
= 0; i
< transaction
->nr
; i
++) {
3624 free(transaction
->updates
[i
]->msg
);
3625 free(transaction
->updates
[i
]);
3627 free(transaction
->updates
);
3631 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3632 const char *refname
)
3634 size_t len
= strlen(refname
);
3635 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3637 strcpy((char *)update
->refname
, refname
);
3638 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3639 transaction
->updates
[transaction
->nr
++] = update
;
3643 int ref_transaction_update(struct ref_transaction
*transaction
,
3644 const char *refname
,
3645 const unsigned char *new_sha1
,
3646 const unsigned char *old_sha1
,
3647 int flags
, int have_old
, const char *msg
,
3650 struct ref_update
*update
;
3654 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3655 die("BUG: update called for transaction that is not open");
3657 if (have_old
&& !old_sha1
)
3658 die("BUG: have_old is true but old_sha1 is NULL");
3660 if (!is_null_sha1(new_sha1
) &&
3661 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3662 strbuf_addf(err
, "refusing to update ref with bad name %s",
3667 update
= add_update(transaction
, refname
);
3668 hashcpy(update
->new_sha1
, new_sha1
);
3669 update
->flags
= flags
;
3670 update
->have_old
= have_old
;
3672 hashcpy(update
->old_sha1
, old_sha1
);
3674 update
->msg
= xstrdup(msg
);
3678 int ref_transaction_create(struct ref_transaction
*transaction
,
3679 const char *refname
,
3680 const unsigned char *new_sha1
,
3681 int flags
, const char *msg
,
3684 return ref_transaction_update(transaction
, refname
, new_sha1
,
3685 null_sha1
, flags
, 1, msg
, err
);
3688 int ref_transaction_delete(struct ref_transaction
*transaction
,
3689 const char *refname
,
3690 const unsigned char *old_sha1
,
3691 int flags
, int have_old
, const char *msg
,
3694 return ref_transaction_update(transaction
, refname
, null_sha1
,
3695 old_sha1
, flags
, have_old
, msg
, err
);
3698 int update_ref(const char *action
, const char *refname
,
3699 const unsigned char *sha1
, const unsigned char *oldval
,
3700 int flags
, enum action_on_err onerr
)
3702 struct ref_transaction
*t
;
3703 struct strbuf err
= STRBUF_INIT
;
3705 t
= ref_transaction_begin(&err
);
3707 ref_transaction_update(t
, refname
, sha1
, oldval
, flags
,
3708 !!oldval
, action
, &err
) ||
3709 ref_transaction_commit(t
, &err
)) {
3710 const char *str
= "update_ref failed for ref '%s': %s";
3712 ref_transaction_free(t
);
3714 case UPDATE_REFS_MSG_ON_ERR
:
3715 error(str
, refname
, err
.buf
);
3717 case UPDATE_REFS_DIE_ON_ERR
:
3718 die(str
, refname
, err
.buf
);
3720 case UPDATE_REFS_QUIET_ON_ERR
:
3723 strbuf_release(&err
);
3726 strbuf_release(&err
);
3727 ref_transaction_free(t
);
3731 static int ref_update_compare(const void *r1
, const void *r2
)
3733 const struct ref_update
* const *u1
= r1
;
3734 const struct ref_update
* const *u2
= r2
;
3735 return strcmp((*u1
)->refname
, (*u2
)->refname
);
3738 static int ref_update_reject_duplicates(struct ref_update
**updates
, int n
,
3745 for (i
= 1; i
< n
; i
++)
3746 if (!strcmp(updates
[i
- 1]->refname
, updates
[i
]->refname
)) {
3748 "Multiple updates for ref '%s' not allowed.",
3749 updates
[i
]->refname
);
3755 int ref_transaction_commit(struct ref_transaction
*transaction
,
3759 int n
= transaction
->nr
;
3760 struct ref_update
**updates
= transaction
->updates
;
3761 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3762 struct string_list_item
*ref_to_delete
;
3766 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3767 die("BUG: commit called for transaction that is not open");
3770 transaction
->state
= REF_TRANSACTION_CLOSED
;
3774 /* Copy, sort, and reject duplicate refs */
3775 qsort(updates
, n
, sizeof(*updates
), ref_update_compare
);
3776 if (ref_update_reject_duplicates(updates
, n
, err
)) {
3777 ret
= TRANSACTION_GENERIC_ERROR
;
3781 /* Acquire all locks while verifying old values */
3782 for (i
= 0; i
< n
; i
++) {
3783 struct ref_update
*update
= updates
[i
];
3784 int flags
= update
->flags
;
3786 if (is_null_sha1(update
->new_sha1
))
3787 flags
|= REF_DELETING
;
3788 update
->lock
= lock_ref_sha1_basic(update
->refname
,
3795 if (!update
->lock
) {
3796 ret
= (errno
== ENOTDIR
)
3797 ? TRANSACTION_NAME_CONFLICT
3798 : TRANSACTION_GENERIC_ERROR
;
3799 strbuf_addf(err
, "Cannot lock the ref '%s'.",
3805 /* Perform updates first so live commits remain referenced */
3806 for (i
= 0; i
< n
; i
++) {
3807 struct ref_update
*update
= updates
[i
];
3809 if (!is_null_sha1(update
->new_sha1
)) {
3810 if (write_ref_sha1(update
->lock
, update
->new_sha1
,
3812 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3813 strbuf_addf(err
, "Cannot update the ref '%s'.",
3815 ret
= TRANSACTION_GENERIC_ERROR
;
3818 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3822 /* Perform deletes now that updates are safely completed */
3823 for (i
= 0; i
< n
; i
++) {
3824 struct ref_update
*update
= updates
[i
];
3827 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3828 ret
= TRANSACTION_GENERIC_ERROR
;
3832 if (!(update
->flags
& REF_ISPRUNING
))
3833 string_list_append(&refs_to_delete
,
3834 update
->lock
->ref_name
);
3838 if (repack_without_refs(&refs_to_delete
, err
)) {
3839 ret
= TRANSACTION_GENERIC_ERROR
;
3842 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3843 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3844 clear_loose_ref_cache(&ref_cache
);
3847 transaction
->state
= REF_TRANSACTION_CLOSED
;
3849 for (i
= 0; i
< n
; i
++)
3850 if (updates
[i
]->lock
)
3851 unlock_ref(updates
[i
]->lock
);
3852 string_list_clear(&refs_to_delete
, 0);
3856 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3859 static char **scanf_fmts
;
3860 static int nr_rules
;
3865 * Pre-generate scanf formats from ref_rev_parse_rules[].
3866 * Generate a format suitable for scanf from a
3867 * ref_rev_parse_rules rule by interpolating "%s" at the
3868 * location of the "%.*s".
3870 size_t total_len
= 0;
3873 /* the rule list is NULL terminated, count them first */
3874 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3875 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3876 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3878 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3881 for (i
= 0; i
< nr_rules
; i
++) {
3882 assert(offset
< total_len
);
3883 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
3884 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
3885 ref_rev_parse_rules
[i
], 2, "%s") + 1;
3889 /* bail out if there are no rules */
3891 return xstrdup(refname
);
3893 /* buffer for scanf result, at most refname must fit */
3894 short_name
= xstrdup(refname
);
3896 /* skip first rule, it will always match */
3897 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
3899 int rules_to_fail
= i
;
3902 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
3905 short_name_len
= strlen(short_name
);
3908 * in strict mode, all (except the matched one) rules
3909 * must fail to resolve to a valid non-ambiguous ref
3912 rules_to_fail
= nr_rules
;
3915 * check if the short name resolves to a valid ref,
3916 * but use only rules prior to the matched one
3918 for (j
= 0; j
< rules_to_fail
; j
++) {
3919 const char *rule
= ref_rev_parse_rules
[j
];
3920 char refname
[PATH_MAX
];
3922 /* skip matched rule */
3927 * the short name is ambiguous, if it resolves
3928 * (with this previous rule) to a valid ref
3929 * read_ref() returns 0 on success
3931 mksnpath(refname
, sizeof(refname
),
3932 rule
, short_name_len
, short_name
);
3933 if (ref_exists(refname
))
3938 * short name is non-ambiguous if all previous rules
3939 * haven't resolved to a valid ref
3941 if (j
== rules_to_fail
)
3946 return xstrdup(refname
);
3949 static struct string_list
*hide_refs
;
3951 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
3953 if (!strcmp("transfer.hiderefs", var
) ||
3954 /* NEEDSWORK: use parse_config_key() once both are merged */
3955 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
3956 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
3961 return config_error_nonbool(var
);
3962 ref
= xstrdup(value
);
3964 while (len
&& ref
[len
- 1] == '/')
3967 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
3968 hide_refs
->strdup_strings
= 1;
3970 string_list_append(hide_refs
, ref
);
3975 int ref_is_hidden(const char *refname
)
3977 struct string_list_item
*item
;
3981 for_each_string_list_item(item
, hide_refs
) {
3983 if (!starts_with(refname
, item
->string
))
3985 len
= strlen(item
->string
);
3986 if (!refname
[len
] || refname
[len
] == '/')
3992 struct expire_reflog_cb
{
3994 reflog_expiry_should_prune_fn
*should_prune_fn
;
3997 unsigned char last_kept_sha1
[20];
4000 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4001 const char *email
, unsigned long timestamp
, int tz
,
4002 const char *message
, void *cb_data
)
4004 struct expire_reflog_cb
*cb
= cb_data
;
4005 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4007 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4008 osha1
= cb
->last_kept_sha1
;
4010 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4011 message
, policy_cb
)) {
4013 printf("would prune %s", message
);
4014 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4015 printf("prune %s", message
);
4018 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4019 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4020 email
, timestamp
, tz
, message
);
4021 hashcpy(cb
->last_kept_sha1
, nsha1
);
4023 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4024 printf("keep %s", message
);
4029 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4031 reflog_expiry_prepare_fn prepare_fn
,
4032 reflog_expiry_should_prune_fn should_prune_fn
,
4033 reflog_expiry_cleanup_fn cleanup_fn
,
4034 void *policy_cb_data
)
4036 static struct lock_file reflog_lock
;
4037 struct expire_reflog_cb cb
;
4038 struct ref_lock
*lock
;
4042 memset(&cb
, 0, sizeof(cb
));
4044 cb
.policy_cb
= policy_cb_data
;
4045 cb
.should_prune_fn
= should_prune_fn
;
4048 * The reflog file is locked by holding the lock on the
4049 * reference itself, plus we might need to update the
4050 * reference if --updateref was specified:
4052 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, 0, NULL
);
4054 return error("cannot lock ref '%s'", refname
);
4055 if (!reflog_exists(refname
)) {
4060 log_file
= git_pathdup("logs/%s", refname
);
4061 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4063 * Even though holding $GIT_DIR/logs/$reflog.lock has
4064 * no locking implications, we use the lock_file
4065 * machinery here anyway because it does a lot of the
4066 * work we need, including cleaning up if the program
4067 * exits unexpectedly.
4069 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4070 struct strbuf err
= STRBUF_INIT
;
4071 unable_to_lock_message(log_file
, errno
, &err
);
4072 error("%s", err
.buf
);
4073 strbuf_release(&err
);
4076 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4078 error("cannot fdopen %s (%s)",
4079 reflog_lock
.filename
.buf
, strerror(errno
));
4084 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4085 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4086 (*cleanup_fn
)(cb
.policy_cb
);
4088 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4089 if (close_lock_file(&reflog_lock
)) {
4090 status
|= error("couldn't write %s: %s", log_file
,
4092 } else if ((flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4093 (write_in_full(lock
->lock_fd
,
4094 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4095 write_str_in_full(lock
->lock_fd
, "\n") != 1 ||
4096 close_ref(lock
) < 0)) {
4097 status
|= error("couldn't write %s",
4098 lock
->lk
->filename
.buf
);
4099 rollback_lock_file(&reflog_lock
);
4100 } else if (commit_lock_file(&reflog_lock
)) {
4101 status
|= error("unable to commit reflog '%s' (%s)",
4102 log_file
, strerror(errno
));
4103 } else if ((flags
& EXPIRE_REFLOGS_UPDATE_REF
) && commit_ref(lock
)) {
4104 status
|= error("couldn't set %s", lock
->ref_name
);
4112 rollback_lock_file(&reflog_lock
);