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 * Used as a flag to ref_transaction_delete when a loose ref is being
41 #define REF_ISPRUNING 0x0100
43 * Try to read one refname component from the front of refname.
44 * Return the length of the component found, or -1 if the component is
45 * not legal. It is legal if it is something reasonable to have under
46 * ".git/refs/"; We do not like it if:
48 * - any path component of it begins with ".", or
49 * - it has double dots "..", or
50 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
51 * - it ends with a "/".
52 * - it ends with ".lock"
53 * - it contains a "\" (backslash)
55 static int check_refname_component(const char *refname
, int flags
)
60 for (cp
= refname
; ; cp
++) {
62 unsigned char disp
= refname_disposition
[ch
];
68 return -1; /* Refname contains "..". */
72 return -1; /* Refname contains "@{". */
81 return 0; /* Component has zero length. */
82 if (refname
[0] == '.')
83 return -1; /* Component starts with '.'. */
84 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
85 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
86 return -1; /* Refname ends with ".lock". */
90 int check_refname_format(const char *refname
, int flags
)
92 int component_len
, component_count
= 0;
94 if (!strcmp(refname
, "@"))
95 /* Refname is a single character '@'. */
99 /* We are at the start of a path component. */
100 component_len
= check_refname_component(refname
, flags
);
101 if (component_len
<= 0) {
102 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
104 (refname
[1] == '\0' || refname
[1] == '/')) {
105 /* Accept one wildcard as a full refname component. */
106 flags
&= ~REFNAME_REFSPEC_PATTERN
;
113 if (refname
[component_len
] == '\0')
115 /* Skip to next component. */
116 refname
+= component_len
+ 1;
119 if (refname
[component_len
- 1] == '.')
120 return -1; /* Refname ends with '.'. */
121 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
122 return -1; /* Refname has only one component. */
129 * Information used (along with the information in ref_entry) to
130 * describe a single cached reference. This data structure only
131 * occurs embedded in a union in struct ref_entry, and only when
132 * (ref_entry->flag & REF_DIR) is zero.
136 * The name of the object to which this reference resolves
137 * (which may be a tag object). If REF_ISBROKEN, this is
138 * null. If REF_ISSYMREF, then this is the name of the object
139 * referred to by the last reference in the symlink chain.
141 unsigned char sha1
[20];
144 * If REF_KNOWS_PEELED, then this field holds the peeled value
145 * of this reference, or null if the reference is known not to
146 * be peelable. See the documentation for peel_ref() for an
147 * exact definition of "peelable".
149 unsigned char peeled
[20];
155 * Information used (along with the information in ref_entry) to
156 * describe a level in the hierarchy of references. This data
157 * structure only occurs embedded in a union in struct ref_entry, and
158 * only when (ref_entry.flag & REF_DIR) is set. In that case,
159 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
160 * in the directory have already been read:
162 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
163 * or packed references, already read.
165 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
166 * references that hasn't been read yet (nor has any of its
169 * Entries within a directory are stored within a growable array of
170 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
171 * sorted are sorted by their component name in strcmp() order and the
172 * remaining entries are unsorted.
174 * Loose references are read lazily, one directory at a time. When a
175 * directory of loose references is read, then all of the references
176 * in that directory are stored, and REF_INCOMPLETE stubs are created
177 * for any subdirectories, but the subdirectories themselves are not
178 * read. The reading is triggered by get_ref_dir().
184 * Entries with index 0 <= i < sorted are sorted by name. New
185 * entries are appended to the list unsorted, and are sorted
186 * only when required; thus we avoid the need to sort the list
187 * after the addition of every reference.
191 /* A pointer to the ref_cache that contains this ref_dir. */
192 struct ref_cache
*ref_cache
;
194 struct ref_entry
**entries
;
198 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
199 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
200 * public values; see refs.h.
204 * The field ref_entry->u.value.peeled of this value entry contains
205 * the correct peeled value for the reference, which might be
206 * null_sha1 if the reference is not a tag or if it is broken.
208 #define REF_KNOWS_PEELED 0x10
210 /* ref_entry represents a directory of references */
214 * Entry has not yet been read from disk (used only for REF_DIR
215 * entries representing loose references)
217 #define REF_INCOMPLETE 0x40
220 * A ref_entry represents either a reference or a "subdirectory" of
223 * Each directory in the reference namespace is represented by a
224 * ref_entry with (flags & REF_DIR) set and containing a subdir member
225 * that holds the entries in that directory that have been read so
226 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
227 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
228 * used for loose reference directories.
230 * References are represented by a ref_entry with (flags & REF_DIR)
231 * unset and a value member that describes the reference's value. The
232 * flag member is at the ref_entry level, but it is also needed to
233 * interpret the contents of the value field (in other words, a
234 * ref_value object is not very much use without the enclosing
237 * Reference names cannot end with slash and directories' names are
238 * always stored with a trailing slash (except for the top-level
239 * directory, which is always denoted by ""). This has two nice
240 * consequences: (1) when the entries in each subdir are sorted
241 * lexicographically by name (as they usually are), the references in
242 * a whole tree can be generated in lexicographic order by traversing
243 * the tree in left-to-right, depth-first order; (2) the names of
244 * references and subdirectories cannot conflict, and therefore the
245 * presence of an empty subdirectory does not block the creation of a
246 * similarly-named reference. (The fact that reference names with the
247 * same leading components can conflict *with each other* is a
248 * separate issue that is regulated by is_refname_available().)
250 * Please note that the name field contains the fully-qualified
251 * reference (or subdirectory) name. Space could be saved by only
252 * storing the relative names. But that would require the full names
253 * to be generated on the fly when iterating in do_for_each_ref(), and
254 * would break callback functions, who have always been able to assume
255 * that the name strings that they are passed will not be freed during
259 unsigned char flag
; /* ISSYMREF? ISPACKED? */
261 struct ref_value value
; /* if not (flags&REF_DIR) */
262 struct ref_dir subdir
; /* if (flags&REF_DIR) */
265 * The full name of the reference (e.g., "refs/heads/master")
266 * or the full name of the directory with a trailing slash
267 * (e.g., "refs/heads/"):
269 char name
[FLEX_ARRAY
];
272 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
274 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
277 assert(entry
->flag
& REF_DIR
);
278 dir
= &entry
->u
.subdir
;
279 if (entry
->flag
& REF_INCOMPLETE
) {
280 read_loose_refs(entry
->name
, dir
);
281 entry
->flag
&= ~REF_INCOMPLETE
;
287 * Check if a refname is safe.
288 * For refs that start with "refs/" we consider it safe as long they do
289 * not try to resolve to outside of refs/.
291 * For all other refs we only consider them safe iff they only contain
292 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
295 static int refname_is_safe(const char *refname
)
297 if (starts_with(refname
, "refs/")) {
301 buf
= xmalloc(strlen(refname
) + 1);
303 * Does the refname try to escape refs/?
304 * For example: refs/foo/../bar is safe but refs/foo/../../bar
307 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
312 if (!isupper(*refname
) && *refname
!= '_')
319 static struct ref_entry
*create_ref_entry(const char *refname
,
320 const unsigned char *sha1
, int flag
,
324 struct ref_entry
*ref
;
327 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
328 die("Reference has invalid format: '%s'", refname
);
329 if (!check_name
&& !refname_is_safe(refname
))
330 die("Reference has invalid name: '%s'", refname
);
331 len
= strlen(refname
) + 1;
332 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
333 hashcpy(ref
->u
.value
.sha1
, sha1
);
334 hashclr(ref
->u
.value
.peeled
);
335 memcpy(ref
->name
, refname
, len
);
340 static void clear_ref_dir(struct ref_dir
*dir
);
342 static void free_ref_entry(struct ref_entry
*entry
)
344 if (entry
->flag
& REF_DIR
) {
346 * Do not use get_ref_dir() here, as that might
347 * trigger the reading of loose refs.
349 clear_ref_dir(&entry
->u
.subdir
);
355 * Add a ref_entry to the end of dir (unsorted). Entry is always
356 * stored directly in dir; no recursion into subdirectories is
359 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
361 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
362 dir
->entries
[dir
->nr
++] = entry
;
363 /* optimize for the case that entries are added in order */
365 (dir
->nr
== dir
->sorted
+ 1 &&
366 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
367 dir
->entries
[dir
->nr
- 1]->name
) < 0))
368 dir
->sorted
= dir
->nr
;
372 * Clear and free all entries in dir, recursively.
374 static void clear_ref_dir(struct ref_dir
*dir
)
377 for (i
= 0; i
< dir
->nr
; i
++)
378 free_ref_entry(dir
->entries
[i
]);
380 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
385 * Create a struct ref_entry object for the specified dirname.
386 * dirname is the name of the directory with a trailing slash (e.g.,
387 * "refs/heads/") or "" for the top-level directory.
389 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
390 const char *dirname
, size_t len
,
393 struct ref_entry
*direntry
;
394 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
395 memcpy(direntry
->name
, dirname
, len
);
396 direntry
->name
[len
] = '\0';
397 direntry
->u
.subdir
.ref_cache
= ref_cache
;
398 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
402 static int ref_entry_cmp(const void *a
, const void *b
)
404 struct ref_entry
*one
= *(struct ref_entry
**)a
;
405 struct ref_entry
*two
= *(struct ref_entry
**)b
;
406 return strcmp(one
->name
, two
->name
);
409 static void sort_ref_dir(struct ref_dir
*dir
);
411 struct string_slice
{
416 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
418 const struct string_slice
*key
= key_
;
419 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
420 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
423 return '\0' - (unsigned char)ent
->name
[key
->len
];
427 * Return the index of the entry with the given refname from the
428 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
429 * no such entry is found. dir must already be complete.
431 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
433 struct ref_entry
**r
;
434 struct string_slice key
;
436 if (refname
== NULL
|| !dir
->nr
)
442 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
443 ref_entry_cmp_sslice
);
448 return r
- dir
->entries
;
452 * Search for a directory entry directly within dir (without
453 * recursing). Sort dir if necessary. subdirname must be a directory
454 * name (i.e., end in '/'). If mkdir is set, then create the
455 * directory if it is missing; otherwise, return NULL if the desired
456 * directory cannot be found. dir must already be complete.
458 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
459 const char *subdirname
, size_t len
,
462 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
463 struct ref_entry
*entry
;
464 if (entry_index
== -1) {
468 * Since dir is complete, the absence of a subdir
469 * means that the subdir really doesn't exist;
470 * therefore, create an empty record for it but mark
471 * the record complete.
473 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
474 add_entry_to_dir(dir
, entry
);
476 entry
= dir
->entries
[entry_index
];
478 return get_ref_dir(entry
);
482 * If refname is a reference name, find the ref_dir within the dir
483 * tree that should hold refname. If refname is a directory name
484 * (i.e., ends in '/'), then return that ref_dir itself. dir must
485 * represent the top-level directory and must already be complete.
486 * Sort ref_dirs and recurse into subdirectories as necessary. If
487 * mkdir is set, then create any missing directories; otherwise,
488 * return NULL if the desired directory cannot be found.
490 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
491 const char *refname
, int mkdir
)
494 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
495 size_t dirnamelen
= slash
- refname
+ 1;
496 struct ref_dir
*subdir
;
497 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
509 * Find the value entry with the given name in dir, sorting ref_dirs
510 * and recursing into subdirectories as necessary. If the name is not
511 * found or it corresponds to a directory entry, return NULL.
513 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
516 struct ref_entry
*entry
;
517 dir
= find_containing_dir(dir
, refname
, 0);
520 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
521 if (entry_index
== -1)
523 entry
= dir
->entries
[entry_index
];
524 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
528 * Remove the entry with the given name from dir, recursing into
529 * subdirectories as necessary. If refname is the name of a directory
530 * (i.e., ends with '/'), then remove the directory and its contents.
531 * If the removal was successful, return the number of entries
532 * remaining in the directory entry that contained the deleted entry.
533 * If the name was not found, return -1. Please note that this
534 * function only deletes the entry from the cache; it does not delete
535 * it from the filesystem or ensure that other cache entries (which
536 * might be symbolic references to the removed entry) are updated.
537 * Nor does it remove any containing dir entries that might be made
538 * empty by the removal. dir must represent the top-level directory
539 * and must already be complete.
541 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
543 int refname_len
= strlen(refname
);
545 struct ref_entry
*entry
;
546 int is_dir
= refname
[refname_len
- 1] == '/';
549 * refname represents a reference directory. Remove
550 * the trailing slash; otherwise we will get the
551 * directory *representing* refname rather than the
552 * one *containing* it.
554 char *dirname
= xmemdupz(refname
, refname_len
- 1);
555 dir
= find_containing_dir(dir
, dirname
, 0);
558 dir
= find_containing_dir(dir
, refname
, 0);
562 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
563 if (entry_index
== -1)
565 entry
= dir
->entries
[entry_index
];
567 memmove(&dir
->entries
[entry_index
],
568 &dir
->entries
[entry_index
+ 1],
569 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
572 if (dir
->sorted
> entry_index
)
574 free_ref_entry(entry
);
579 * Add a ref_entry to the ref_dir (unsorted), recursing into
580 * subdirectories as necessary. dir must represent the top-level
581 * directory. Return 0 on success.
583 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
585 dir
= find_containing_dir(dir
, ref
->name
, 1);
588 add_entry_to_dir(dir
, ref
);
593 * Emit a warning and return true iff ref1 and ref2 have the same name
594 * and the same sha1. Die if they have the same name but different
597 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
599 if (strcmp(ref1
->name
, ref2
->name
))
602 /* Duplicate name; make sure that they don't conflict: */
604 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
605 /* This is impossible by construction */
606 die("Reference directory conflict: %s", ref1
->name
);
608 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
609 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
611 warning("Duplicated ref: %s", ref1
->name
);
616 * Sort the entries in dir non-recursively (if they are not already
617 * sorted) and remove any duplicate entries.
619 static void sort_ref_dir(struct ref_dir
*dir
)
622 struct ref_entry
*last
= NULL
;
625 * This check also prevents passing a zero-length array to qsort(),
626 * which is a problem on some platforms.
628 if (dir
->sorted
== dir
->nr
)
631 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
633 /* Remove any duplicates: */
634 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
635 struct ref_entry
*entry
= dir
->entries
[j
];
636 if (last
&& is_dup_ref(last
, entry
))
637 free_ref_entry(entry
);
639 last
= dir
->entries
[i
++] = entry
;
641 dir
->sorted
= dir
->nr
= i
;
644 /* Include broken references in a do_for_each_ref*() iteration: */
645 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
648 * Return true iff the reference described by entry can be resolved to
649 * an object in the database. Emit a warning if the referred-to
650 * object does not exist.
652 static int ref_resolves_to_object(struct ref_entry
*entry
)
654 if (entry
->flag
& REF_ISBROKEN
)
656 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
657 error("%s does not point to a valid object!", entry
->name
);
664 * current_ref is a performance hack: when iterating over references
665 * using the for_each_ref*() functions, current_ref is set to the
666 * current reference's entry before calling the callback function. If
667 * the callback function calls peel_ref(), then peel_ref() first
668 * checks whether the reference to be peeled is the current reference
669 * (it usually is) and if so, returns that reference's peeled version
670 * if it is available. This avoids a refname lookup in a common case.
672 static struct ref_entry
*current_ref
;
674 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
676 struct ref_entry_cb
{
685 * Handle one reference in a do_for_each_ref*()-style iteration,
686 * calling an each_ref_fn for each entry.
688 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
690 struct ref_entry_cb
*data
= cb_data
;
691 struct ref_entry
*old_current_ref
;
694 if (!starts_with(entry
->name
, data
->base
))
697 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
698 !ref_resolves_to_object(entry
))
701 /* Store the old value, in case this is a recursive call: */
702 old_current_ref
= current_ref
;
704 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
705 entry
->flag
, data
->cb_data
);
706 current_ref
= old_current_ref
;
711 * Call fn for each reference in dir that has index in the range
712 * offset <= index < dir->nr. Recurse into subdirectories that are in
713 * that index range, sorting them before iterating. This function
714 * does not sort dir itself; it should be sorted beforehand. fn is
715 * called for all references, including broken ones.
717 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
718 each_ref_entry_fn fn
, void *cb_data
)
721 assert(dir
->sorted
== dir
->nr
);
722 for (i
= offset
; i
< dir
->nr
; i
++) {
723 struct ref_entry
*entry
= dir
->entries
[i
];
725 if (entry
->flag
& REF_DIR
) {
726 struct ref_dir
*subdir
= get_ref_dir(entry
);
727 sort_ref_dir(subdir
);
728 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
730 retval
= fn(entry
, cb_data
);
739 * Call fn for each reference in the union of dir1 and dir2, in order
740 * by refname. Recurse into subdirectories. If a value entry appears
741 * in both dir1 and dir2, then only process the version that is in
742 * dir2. The input dirs must already be sorted, but subdirs will be
743 * sorted as needed. fn is called for all references, including
746 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
747 struct ref_dir
*dir2
,
748 each_ref_entry_fn fn
, void *cb_data
)
753 assert(dir1
->sorted
== dir1
->nr
);
754 assert(dir2
->sorted
== dir2
->nr
);
756 struct ref_entry
*e1
, *e2
;
758 if (i1
== dir1
->nr
) {
759 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
761 if (i2
== dir2
->nr
) {
762 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
764 e1
= dir1
->entries
[i1
];
765 e2
= dir2
->entries
[i2
];
766 cmp
= strcmp(e1
->name
, e2
->name
);
768 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
769 /* Both are directories; descend them in parallel. */
770 struct ref_dir
*subdir1
= get_ref_dir(e1
);
771 struct ref_dir
*subdir2
= get_ref_dir(e2
);
772 sort_ref_dir(subdir1
);
773 sort_ref_dir(subdir2
);
774 retval
= do_for_each_entry_in_dirs(
775 subdir1
, subdir2
, fn
, cb_data
);
778 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
779 /* Both are references; ignore the one from dir1. */
780 retval
= fn(e2
, cb_data
);
784 die("conflict between reference and directory: %s",
796 if (e
->flag
& REF_DIR
) {
797 struct ref_dir
*subdir
= get_ref_dir(e
);
798 sort_ref_dir(subdir
);
799 retval
= do_for_each_entry_in_dir(
800 subdir
, 0, fn
, cb_data
);
802 retval
= fn(e
, cb_data
);
811 * Load all of the refs from the dir into our in-memory cache. The hard work
812 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
813 * through all of the sub-directories. We do not even need to care about
814 * sorting, as traversal order does not matter to us.
816 static void prime_ref_dir(struct ref_dir
*dir
)
819 for (i
= 0; i
< dir
->nr
; i
++) {
820 struct ref_entry
*entry
= dir
->entries
[i
];
821 if (entry
->flag
& REF_DIR
)
822 prime_ref_dir(get_ref_dir(entry
));
826 static int entry_matches(struct ref_entry
*entry
, const struct string_list
*list
)
828 return list
&& string_list_has_string(list
, entry
->name
);
831 struct nonmatching_ref_data
{
832 const struct string_list
*skip
;
833 struct ref_entry
*found
;
836 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
838 struct nonmatching_ref_data
*data
= vdata
;
840 if (entry_matches(entry
, data
->skip
))
847 static void report_refname_conflict(struct ref_entry
*entry
,
850 error("'%s' exists; cannot create '%s'", entry
->name
, refname
);
854 * Return true iff a reference named refname could be created without
855 * conflicting with the name of an existing reference in dir. If
856 * skip is non-NULL, ignore potential conflicts with refs in skip
857 * (e.g., because they are scheduled for deletion in the same
860 * Two reference names conflict if one of them exactly matches the
861 * leading components of the other; e.g., "foo/bar" conflicts with
862 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
865 * skip must be sorted.
867 static int is_refname_available(const char *refname
,
868 const struct string_list
*skip
,
876 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
878 * We are still at a leading dir of the refname; we are
879 * looking for a conflict with a leaf entry.
881 * If we find one, we still must make sure it is
884 pos
= search_ref_dir(dir
, refname
, slash
- refname
);
886 struct ref_entry
*entry
= dir
->entries
[pos
];
887 if (entry_matches(entry
, skip
))
889 report_refname_conflict(entry
, refname
);
895 * Otherwise, we can try to continue our search with
896 * the next component; if we come up empty, we know
897 * there is nothing under this whole prefix.
899 pos
= search_ref_dir(dir
, refname
, slash
+ 1 - refname
);
903 dir
= get_ref_dir(dir
->entries
[pos
]);
907 * We are at the leaf of our refname; we want to
908 * make sure there are no directories which match it.
910 len
= strlen(refname
);
911 dirname
= xmallocz(len
+ 1);
912 sprintf(dirname
, "%s/", refname
);
913 pos
= search_ref_dir(dir
, dirname
, len
+ 1);
918 * We found a directory named "refname". It is a
919 * problem iff it contains any ref that is not
922 struct ref_entry
*entry
= dir
->entries
[pos
];
923 struct ref_dir
*dir
= get_ref_dir(entry
);
924 struct nonmatching_ref_data data
;
928 if (!do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
))
931 report_refname_conflict(data
.found
, refname
);
936 * There is no point in searching for another leaf
937 * node which matches it; such an entry would be the
938 * ref we are looking for, not a conflict.
943 struct packed_ref_cache
{
944 struct ref_entry
*root
;
947 * Count of references to the data structure in this instance,
948 * including the pointer from ref_cache::packed if any. The
949 * data will not be freed as long as the reference count is
952 unsigned int referrers
;
955 * Iff the packed-refs file associated with this instance is
956 * currently locked for writing, this points at the associated
957 * lock (which is owned by somebody else). The referrer count
958 * is also incremented when the file is locked and decremented
959 * when it is unlocked.
961 struct lock_file
*lock
;
963 /* The metadata from when this packed-refs cache was read */
964 struct stat_validity validity
;
968 * Future: need to be in "struct repository"
969 * when doing a full libification.
971 static struct ref_cache
{
972 struct ref_cache
*next
;
973 struct ref_entry
*loose
;
974 struct packed_ref_cache
*packed
;
976 * The submodule name, or "" for the main repo. We allocate
977 * length 1 rather than FLEX_ARRAY so that the main ref_cache
978 * is initialized correctly.
981 } ref_cache
, *submodule_ref_caches
;
983 /* Lock used for the main packed-refs file: */
984 static struct lock_file packlock
;
987 * Increment the reference count of *packed_refs.
989 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
991 packed_refs
->referrers
++;
995 * Decrease the reference count of *packed_refs. If it goes to zero,
996 * free *packed_refs and return true; otherwise return false.
998 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1000 if (!--packed_refs
->referrers
) {
1001 free_ref_entry(packed_refs
->root
);
1002 stat_validity_clear(&packed_refs
->validity
);
1010 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1013 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1015 if (packed_refs
->lock
)
1016 die("internal error: packed-ref cache cleared while locked");
1017 refs
->packed
= NULL
;
1018 release_packed_ref_cache(packed_refs
);
1022 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1025 free_ref_entry(refs
->loose
);
1030 static struct ref_cache
*create_ref_cache(const char *submodule
)
1033 struct ref_cache
*refs
;
1036 len
= strlen(submodule
) + 1;
1037 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1038 memcpy(refs
->name
, submodule
, len
);
1043 * Return a pointer to a ref_cache for the specified submodule. For
1044 * the main repository, use submodule==NULL. The returned structure
1045 * will be allocated and initialized but not necessarily populated; it
1046 * should not be freed.
1048 static struct ref_cache
*get_ref_cache(const char *submodule
)
1050 struct ref_cache
*refs
;
1052 if (!submodule
|| !*submodule
)
1055 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1056 if (!strcmp(submodule
, refs
->name
))
1059 refs
= create_ref_cache(submodule
);
1060 refs
->next
= submodule_ref_caches
;
1061 submodule_ref_caches
= refs
;
1065 /* The length of a peeled reference line in packed-refs, including EOL: */
1066 #define PEELED_LINE_LENGTH 42
1069 * The packed-refs header line that we write out. Perhaps other
1070 * traits will be added later. The trailing space is required.
1072 static const char PACKED_REFS_HEADER
[] =
1073 "# pack-refs with: peeled fully-peeled \n";
1076 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1077 * Return a pointer to the refname within the line (null-terminated),
1078 * or NULL if there was a problem.
1080 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1085 * 42: the answer to everything.
1087 * In this case, it happens to be the answer to
1088 * 40 (length of sha1 hex representation)
1089 * +1 (space in between hex and name)
1090 * +1 (newline at the end of the line)
1092 if (line
->len
<= 42)
1095 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1097 if (!isspace(line
->buf
[40]))
1100 ref
= line
->buf
+ 41;
1104 if (line
->buf
[line
->len
- 1] != '\n')
1106 line
->buf
[--line
->len
] = 0;
1112 * Read f, which is a packed-refs file, into dir.
1114 * A comment line of the form "# pack-refs with: " may contain zero or
1115 * more traits. We interpret the traits as follows:
1119 * Probably no references are peeled. But if the file contains a
1120 * peeled value for a reference, we will use it.
1124 * References under "refs/tags/", if they *can* be peeled, *are*
1125 * peeled in this file. References outside of "refs/tags/" are
1126 * probably not peeled even if they could have been, but if we find
1127 * a peeled value for such a reference we will use it.
1131 * All references in the file that can be peeled are peeled.
1132 * Inversely (and this is more important), any references in the
1133 * file for which no peeled value is recorded is not peelable. This
1134 * trait should typically be written alongside "peeled" for
1135 * compatibility with older clients, but we do not require it
1136 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1138 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1140 struct ref_entry
*last
= NULL
;
1141 struct strbuf line
= STRBUF_INIT
;
1142 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1144 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1145 unsigned char sha1
[20];
1146 const char *refname
;
1149 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1150 if (strstr(traits
, " fully-peeled "))
1151 peeled
= PEELED_FULLY
;
1152 else if (strstr(traits
, " peeled "))
1153 peeled
= PEELED_TAGS
;
1154 /* perhaps other traits later as well */
1158 refname
= parse_ref_line(&line
, sha1
);
1160 int flag
= REF_ISPACKED
;
1162 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1164 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1166 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1167 if (peeled
== PEELED_FULLY
||
1168 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1169 last
->flag
|= REF_KNOWS_PEELED
;
1174 line
.buf
[0] == '^' &&
1175 line
.len
== PEELED_LINE_LENGTH
&&
1176 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1177 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1178 hashcpy(last
->u
.value
.peeled
, sha1
);
1180 * Regardless of what the file header said,
1181 * we definitely know the value of *this*
1184 last
->flag
|= REF_KNOWS_PEELED
;
1188 strbuf_release(&line
);
1192 * Get the packed_ref_cache for the specified ref_cache, creating it
1195 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1197 const char *packed_refs_file
;
1200 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1202 packed_refs_file
= git_path("packed-refs");
1205 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1206 clear_packed_ref_cache(refs
);
1208 if (!refs
->packed
) {
1211 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1212 acquire_packed_ref_cache(refs
->packed
);
1213 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1214 f
= fopen(packed_refs_file
, "r");
1216 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1217 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1221 return refs
->packed
;
1224 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1226 return get_ref_dir(packed_ref_cache
->root
);
1229 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1231 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1234 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1236 struct packed_ref_cache
*packed_ref_cache
=
1237 get_packed_ref_cache(&ref_cache
);
1239 if (!packed_ref_cache
->lock
)
1240 die("internal error: packed refs not locked");
1241 add_ref(get_packed_ref_dir(packed_ref_cache
),
1242 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1246 * Read the loose references from the namespace dirname into dir
1247 * (without recursing). dirname must end with '/'. dir must be the
1248 * directory entry corresponding to dirname.
1250 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1252 struct ref_cache
*refs
= dir
->ref_cache
;
1256 int dirnamelen
= strlen(dirname
);
1257 struct strbuf refname
;
1260 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1262 path
= git_path("%s", dirname
);
1268 strbuf_init(&refname
, dirnamelen
+ 257);
1269 strbuf_add(&refname
, dirname
, dirnamelen
);
1271 while ((de
= readdir(d
)) != NULL
) {
1272 unsigned char sha1
[20];
1277 if (de
->d_name
[0] == '.')
1279 if (ends_with(de
->d_name
, ".lock"))
1281 strbuf_addstr(&refname
, de
->d_name
);
1282 refdir
= *refs
->name
1283 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1284 : git_path("%s", refname
.buf
);
1285 if (stat(refdir
, &st
) < 0) {
1286 ; /* silently ignore */
1287 } else if (S_ISDIR(st
.st_mode
)) {
1288 strbuf_addch(&refname
, '/');
1289 add_entry_to_dir(dir
,
1290 create_dir_entry(refs
, refname
.buf
,
1296 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1298 flag
|= REF_ISBROKEN
;
1300 } else if (read_ref_full(refname
.buf
,
1301 RESOLVE_REF_READING
,
1304 flag
|= REF_ISBROKEN
;
1306 if (check_refname_format(refname
.buf
,
1307 REFNAME_ALLOW_ONELEVEL
)) {
1309 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1311 add_entry_to_dir(dir
,
1312 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1314 strbuf_setlen(&refname
, dirnamelen
);
1316 strbuf_release(&refname
);
1320 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1324 * Mark the top-level directory complete because we
1325 * are about to read the only subdirectory that can
1328 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1330 * Create an incomplete entry for "refs/":
1332 add_entry_to_dir(get_ref_dir(refs
->loose
),
1333 create_dir_entry(refs
, "refs/", 5, 1));
1335 return get_ref_dir(refs
->loose
);
1338 /* We allow "recursive" symbolic refs. Only within reason, though */
1340 #define MAXREFLEN (1024)
1343 * Called by resolve_gitlink_ref_recursive() after it failed to read
1344 * from the loose refs in ref_cache refs. Find <refname> in the
1345 * packed-refs file for the submodule.
1347 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1348 const char *refname
, unsigned char *sha1
)
1350 struct ref_entry
*ref
;
1351 struct ref_dir
*dir
= get_packed_refs(refs
);
1353 ref
= find_ref(dir
, refname
);
1357 hashcpy(sha1
, ref
->u
.value
.sha1
);
1361 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1362 const char *refname
, unsigned char *sha1
,
1366 char buffer
[128], *p
;
1369 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1372 ? git_path_submodule(refs
->name
, "%s", refname
)
1373 : git_path("%s", refname
);
1374 fd
= open(path
, O_RDONLY
);
1376 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1378 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1382 while (len
&& isspace(buffer
[len
-1]))
1386 /* Was it a detached head or an old-fashioned symlink? */
1387 if (!get_sha1_hex(buffer
, sha1
))
1391 if (strncmp(buffer
, "ref:", 4))
1397 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1400 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1402 int len
= strlen(path
), retval
;
1404 struct ref_cache
*refs
;
1406 while (len
&& path
[len
-1] == '/')
1410 submodule
= xstrndup(path
, len
);
1411 refs
= get_ref_cache(submodule
);
1414 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1419 * Return the ref_entry for the given refname from the packed
1420 * references. If it does not exist, return NULL.
1422 static struct ref_entry
*get_packed_ref(const char *refname
)
1424 return find_ref(get_packed_refs(&ref_cache
), refname
);
1428 * A loose ref file doesn't exist; check for a packed ref. The
1429 * options are forwarded from resolve_safe_unsafe().
1431 static int resolve_missing_loose_ref(const char *refname
,
1433 unsigned char *sha1
,
1436 struct ref_entry
*entry
;
1439 * The loose reference file does not exist; check for a packed
1442 entry
= get_packed_ref(refname
);
1444 hashcpy(sha1
, entry
->u
.value
.sha1
);
1446 *flags
|= REF_ISPACKED
;
1449 /* The reference is not a packed reference, either. */
1450 if (resolve_flags
& RESOLVE_REF_READING
) {
1459 /* This function needs to return a meaningful errno on failure */
1460 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1462 int depth
= MAXDEPTH
;
1465 static char refname_buffer
[256];
1471 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1473 *flags
|= REF_BAD_NAME
;
1475 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1476 !refname_is_safe(refname
)) {
1481 * dwim_ref() uses REF_ISBROKEN to distinguish between
1482 * missing refs and refs that were present but invalid,
1483 * to complain about the latter to stderr.
1485 * We don't know whether the ref exists, so don't set
1491 char path
[PATH_MAX
];
1501 git_snpath(path
, sizeof(path
), "%s", refname
);
1504 * We might have to loop back here to avoid a race
1505 * condition: first we lstat() the file, then we try
1506 * to read it as a link or as a file. But if somebody
1507 * changes the type of the file (file <-> directory
1508 * <-> symlink) between the lstat() and reading, then
1509 * we don't want to report that as an error but rather
1510 * try again starting with the lstat().
1513 if (lstat(path
, &st
) < 0) {
1514 if (errno
!= ENOENT
)
1516 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1522 *flags
|= REF_ISBROKEN
;
1527 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1528 if (S_ISLNK(st
.st_mode
)) {
1529 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1531 if (errno
== ENOENT
|| errno
== EINVAL
)
1532 /* inconsistent with lstat; retry */
1538 if (starts_with(buffer
, "refs/") &&
1539 !check_refname_format(buffer
, 0)) {
1540 strcpy(refname_buffer
, buffer
);
1541 refname
= refname_buffer
;
1543 *flags
|= REF_ISSYMREF
;
1544 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1552 /* Is it a directory? */
1553 if (S_ISDIR(st
.st_mode
)) {
1559 * Anything else, just open it and try to use it as
1562 fd
= open(path
, O_RDONLY
);
1564 if (errno
== ENOENT
)
1565 /* inconsistent with lstat; retry */
1570 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1572 int save_errno
= errno
;
1578 while (len
&& isspace(buffer
[len
-1]))
1583 * Is it a symbolic ref?
1585 if (!starts_with(buffer
, "ref:")) {
1587 * Please note that FETCH_HEAD has a second
1588 * line containing other data.
1590 if (get_sha1_hex(buffer
, sha1
) ||
1591 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1593 *flags
|= REF_ISBROKEN
;
1600 *flags
|= REF_ISBROKEN
;
1605 *flags
|= REF_ISSYMREF
;
1607 while (isspace(*buf
))
1609 refname
= strcpy(refname_buffer
, buf
);
1610 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1614 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1616 *flags
|= REF_ISBROKEN
;
1618 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1619 !refname_is_safe(buf
)) {
1628 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1630 const char *ret
= resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
);
1631 return ret
? xstrdup(ret
) : NULL
;
1634 /* The argument to filter_refs */
1636 const char *pattern
;
1641 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1643 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1648 int read_ref(const char *refname
, unsigned char *sha1
)
1650 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1653 int ref_exists(const char *refname
)
1655 unsigned char sha1
[20];
1656 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1659 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1662 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1663 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1665 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1669 /* object was peeled successfully: */
1673 * object cannot be peeled because the named object (or an
1674 * object referred to by a tag in the peel chain), does not
1679 /* object cannot be peeled because it is not a tag: */
1682 /* ref_entry contains no peeled value because it is a symref: */
1683 PEEL_IS_SYMREF
= -3,
1686 * ref_entry cannot be peeled because it is broken (i.e., the
1687 * symbolic reference cannot even be resolved to an object
1694 * Peel the named object; i.e., if the object is a tag, resolve the
1695 * tag recursively until a non-tag is found. If successful, store the
1696 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1697 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1698 * and leave sha1 unchanged.
1700 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1702 struct object
*o
= lookup_unknown_object(name
);
1704 if (o
->type
== OBJ_NONE
) {
1705 int type
= sha1_object_info(name
, NULL
);
1706 if (type
< 0 || !object_as_type(o
, type
, 0))
1707 return PEEL_INVALID
;
1710 if (o
->type
!= OBJ_TAG
)
1711 return PEEL_NON_TAG
;
1713 o
= deref_tag_noverify(o
);
1715 return PEEL_INVALID
;
1717 hashcpy(sha1
, o
->sha1
);
1722 * Peel the entry (if possible) and return its new peel_status. If
1723 * repeel is true, re-peel the entry even if there is an old peeled
1724 * value that is already stored in it.
1726 * It is OK to call this function with a packed reference entry that
1727 * might be stale and might even refer to an object that has since
1728 * been garbage-collected. In such a case, if the entry has
1729 * REF_KNOWS_PEELED then leave the status unchanged and return
1730 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1732 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1734 enum peel_status status
;
1736 if (entry
->flag
& REF_KNOWS_PEELED
) {
1738 entry
->flag
&= ~REF_KNOWS_PEELED
;
1739 hashclr(entry
->u
.value
.peeled
);
1741 return is_null_sha1(entry
->u
.value
.peeled
) ?
1742 PEEL_NON_TAG
: PEEL_PEELED
;
1745 if (entry
->flag
& REF_ISBROKEN
)
1747 if (entry
->flag
& REF_ISSYMREF
)
1748 return PEEL_IS_SYMREF
;
1750 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1751 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1752 entry
->flag
|= REF_KNOWS_PEELED
;
1756 int peel_ref(const char *refname
, unsigned char *sha1
)
1759 unsigned char base
[20];
1761 if (current_ref
&& (current_ref
->name
== refname
1762 || !strcmp(current_ref
->name
, refname
))) {
1763 if (peel_entry(current_ref
, 0))
1765 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1769 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1773 * If the reference is packed, read its ref_entry from the
1774 * cache in the hope that we already know its peeled value.
1775 * We only try this optimization on packed references because
1776 * (a) forcing the filling of the loose reference cache could
1777 * be expensive and (b) loose references anyway usually do not
1778 * have REF_KNOWS_PEELED.
1780 if (flag
& REF_ISPACKED
) {
1781 struct ref_entry
*r
= get_packed_ref(refname
);
1783 if (peel_entry(r
, 0))
1785 hashcpy(sha1
, r
->u
.value
.peeled
);
1790 return peel_object(base
, sha1
);
1793 struct warn_if_dangling_data
{
1795 const char *refname
;
1796 const struct string_list
*refnames
;
1797 const char *msg_fmt
;
1800 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1801 int flags
, void *cb_data
)
1803 struct warn_if_dangling_data
*d
= cb_data
;
1804 const char *resolves_to
;
1805 unsigned char junk
[20];
1807 if (!(flags
& REF_ISSYMREF
))
1810 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1813 ? strcmp(resolves_to
, d
->refname
)
1814 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1818 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1823 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1825 struct warn_if_dangling_data data
;
1828 data
.refname
= refname
;
1829 data
.refnames
= NULL
;
1830 data
.msg_fmt
= msg_fmt
;
1831 for_each_rawref(warn_if_dangling_symref
, &data
);
1834 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1836 struct warn_if_dangling_data data
;
1839 data
.refname
= NULL
;
1840 data
.refnames
= refnames
;
1841 data
.msg_fmt
= msg_fmt
;
1842 for_each_rawref(warn_if_dangling_symref
, &data
);
1846 * Call fn for each reference in the specified ref_cache, omitting
1847 * references not in the containing_dir of base. fn is called for all
1848 * references, including broken ones. If fn ever returns a non-zero
1849 * value, stop the iteration and return that value; otherwise, return
1852 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1853 each_ref_entry_fn fn
, void *cb_data
)
1855 struct packed_ref_cache
*packed_ref_cache
;
1856 struct ref_dir
*loose_dir
;
1857 struct ref_dir
*packed_dir
;
1861 * We must make sure that all loose refs are read before accessing the
1862 * packed-refs file; this avoids a race condition in which loose refs
1863 * are migrated to the packed-refs file by a simultaneous process, but
1864 * our in-memory view is from before the migration. get_packed_ref_cache()
1865 * takes care of making sure our view is up to date with what is on
1868 loose_dir
= get_loose_refs(refs
);
1869 if (base
&& *base
) {
1870 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1873 prime_ref_dir(loose_dir
);
1875 packed_ref_cache
= get_packed_ref_cache(refs
);
1876 acquire_packed_ref_cache(packed_ref_cache
);
1877 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1878 if (base
&& *base
) {
1879 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1882 if (packed_dir
&& loose_dir
) {
1883 sort_ref_dir(packed_dir
);
1884 sort_ref_dir(loose_dir
);
1885 retval
= do_for_each_entry_in_dirs(
1886 packed_dir
, loose_dir
, fn
, cb_data
);
1887 } else if (packed_dir
) {
1888 sort_ref_dir(packed_dir
);
1889 retval
= do_for_each_entry_in_dir(
1890 packed_dir
, 0, fn
, cb_data
);
1891 } else if (loose_dir
) {
1892 sort_ref_dir(loose_dir
);
1893 retval
= do_for_each_entry_in_dir(
1894 loose_dir
, 0, fn
, cb_data
);
1897 release_packed_ref_cache(packed_ref_cache
);
1902 * Call fn for each reference in the specified ref_cache for which the
1903 * refname begins with base. If trim is non-zero, then trim that many
1904 * characters off the beginning of each refname before passing the
1905 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1906 * broken references in the iteration. If fn ever returns a non-zero
1907 * value, stop the iteration and return that value; otherwise, return
1910 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
1911 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1913 struct ref_entry_cb data
;
1918 data
.cb_data
= cb_data
;
1920 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
1923 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1925 unsigned char sha1
[20];
1929 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
1930 return fn("HEAD", sha1
, 0, cb_data
);
1935 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
1936 return fn("HEAD", sha1
, flag
, cb_data
);
1941 int head_ref(each_ref_fn fn
, void *cb_data
)
1943 return do_head_ref(NULL
, fn
, cb_data
);
1946 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1948 return do_head_ref(submodule
, fn
, cb_data
);
1951 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1953 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
1956 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1958 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
1961 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1963 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
1966 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
1967 each_ref_fn fn
, void *cb_data
)
1969 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
1972 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
1974 return for_each_ref_in("refs/tags/", fn
, cb_data
);
1977 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1979 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
1982 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
1984 return for_each_ref_in("refs/heads/", fn
, cb_data
);
1987 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1989 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
1992 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
1994 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
1997 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1999 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2002 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2004 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2007 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2009 struct strbuf buf
= STRBUF_INIT
;
2011 unsigned char sha1
[20];
2014 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2015 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2016 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2017 strbuf_release(&buf
);
2022 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2024 struct strbuf buf
= STRBUF_INIT
;
2026 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2027 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2028 strbuf_release(&buf
);
2032 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2033 const char *prefix
, void *cb_data
)
2035 struct strbuf real_pattern
= STRBUF_INIT
;
2036 struct ref_filter filter
;
2039 if (!prefix
&& !starts_with(pattern
, "refs/"))
2040 strbuf_addstr(&real_pattern
, "refs/");
2042 strbuf_addstr(&real_pattern
, prefix
);
2043 strbuf_addstr(&real_pattern
, pattern
);
2045 if (!has_glob_specials(pattern
)) {
2046 /* Append implied '/' '*' if not present. */
2047 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2048 strbuf_addch(&real_pattern
, '/');
2049 /* No need to check for '*', there is none. */
2050 strbuf_addch(&real_pattern
, '*');
2053 filter
.pattern
= real_pattern
.buf
;
2055 filter
.cb_data
= cb_data
;
2056 ret
= for_each_ref(filter_refs
, &filter
);
2058 strbuf_release(&real_pattern
);
2062 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2064 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2067 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2069 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2070 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2073 const char *prettify_refname(const char *name
)
2076 starts_with(name
, "refs/heads/") ? 11 :
2077 starts_with(name
, "refs/tags/") ? 10 :
2078 starts_with(name
, "refs/remotes/") ? 13 :
2082 static const char *ref_rev_parse_rules
[] = {
2087 "refs/remotes/%.*s",
2088 "refs/remotes/%.*s/HEAD",
2092 int refname_match(const char *abbrev_name
, const char *full_name
)
2095 const int abbrev_name_len
= strlen(abbrev_name
);
2097 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2098 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2106 static void unlock_ref(struct ref_lock
*lock
)
2108 /* Do not free lock->lk -- atexit() still looks at them */
2110 rollback_lock_file(lock
->lk
);
2111 free(lock
->ref_name
);
2112 free(lock
->orig_ref_name
);
2116 /* This function should make sure errno is meaningful on error */
2117 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2118 const unsigned char *old_sha1
, int mustexist
)
2120 if (read_ref_full(lock
->ref_name
,
2121 mustexist
? RESOLVE_REF_READING
: 0,
2122 lock
->old_sha1
, NULL
)) {
2123 int save_errno
= errno
;
2124 error("Can't verify ref %s", lock
->ref_name
);
2129 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2130 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2131 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2139 static int remove_empty_directories(const char *file
)
2141 /* we want to create a file but there is a directory there;
2142 * if that is an empty directory (or a directory that contains
2143 * only empty directories), remove them.
2146 int result
, save_errno
;
2148 strbuf_init(&path
, 20);
2149 strbuf_addstr(&path
, file
);
2151 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2154 strbuf_release(&path
);
2161 * *string and *len will only be substituted, and *string returned (for
2162 * later free()ing) if the string passed in is a magic short-hand form
2165 static char *substitute_branch_name(const char **string
, int *len
)
2167 struct strbuf buf
= STRBUF_INIT
;
2168 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2172 *string
= strbuf_detach(&buf
, &size
);
2174 return (char *)*string
;
2180 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2182 char *last_branch
= substitute_branch_name(&str
, &len
);
2187 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2188 char fullref
[PATH_MAX
];
2189 unsigned char sha1_from_ref
[20];
2190 unsigned char *this_result
;
2193 this_result
= refs_found
? sha1_from_ref
: sha1
;
2194 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2195 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2196 this_result
, &flag
);
2200 if (!warn_ambiguous_refs
)
2202 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2203 warning("ignoring dangling symref %s.", fullref
);
2204 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2205 warning("ignoring broken ref %s.", fullref
);
2212 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2214 char *last_branch
= substitute_branch_name(&str
, &len
);
2219 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2220 unsigned char hash
[20];
2221 char path
[PATH_MAX
];
2222 const char *ref
, *it
;
2224 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2225 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2229 if (reflog_exists(path
))
2231 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2235 if (!logs_found
++) {
2237 hashcpy(sha1
, hash
);
2239 if (!warn_ambiguous_refs
)
2247 * Locks a ref returning the lock on success and NULL on failure.
2248 * On failure errno is set to something meaningful.
2250 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2251 const unsigned char *old_sha1
,
2252 const struct string_list
*skip
,
2253 int flags
, int *type_p
)
2256 const char *orig_refname
= refname
;
2257 struct ref_lock
*lock
;
2260 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2261 int resolve_flags
= 0;
2263 int attempts_remaining
= 3;
2265 lock
= xcalloc(1, sizeof(struct ref_lock
));
2269 resolve_flags
|= RESOLVE_REF_READING
;
2270 if (flags
& REF_DELETING
) {
2271 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2272 if (flags
& REF_NODEREF
)
2273 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2276 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2277 lock
->old_sha1
, &type
);
2278 if (!refname
&& errno
== EISDIR
) {
2279 /* we are trying to lock foo but we used to
2280 * have foo/bar which now does not exist;
2281 * it is normal for the empty directory 'foo'
2284 ref_file
= git_path("%s", orig_refname
);
2285 if (remove_empty_directories(ref_file
)) {
2287 error("there are still refs under '%s'", orig_refname
);
2290 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2291 lock
->old_sha1
, &type
);
2297 error("unable to resolve reference %s: %s",
2298 orig_refname
, strerror(errno
));
2301 missing
= is_null_sha1(lock
->old_sha1
);
2302 /* When the ref did not exist and we are creating it,
2303 * make sure there is no existing ref that is packed
2304 * whose name begins with our refname, nor a ref whose
2305 * name is a proper prefix of our refname.
2308 !is_refname_available(refname
, skip
, get_packed_refs(&ref_cache
))) {
2309 last_errno
= ENOTDIR
;
2313 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2316 if (flags
& REF_NODEREF
) {
2317 refname
= orig_refname
;
2318 lflags
|= LOCK_NO_DEREF
;
2320 lock
->ref_name
= xstrdup(refname
);
2321 lock
->orig_ref_name
= xstrdup(orig_refname
);
2322 ref_file
= git_path("%s", refname
);
2324 lock
->force_write
= 1;
2325 if ((flags
& REF_NODEREF
) && (type
& REF_ISSYMREF
))
2326 lock
->force_write
= 1;
2329 switch (safe_create_leading_directories(ref_file
)) {
2331 break; /* success */
2333 if (--attempts_remaining
> 0)
2338 error("unable to create directory for %s", ref_file
);
2342 lock
->lock_fd
= hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
);
2343 if (lock
->lock_fd
< 0) {
2345 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2347 * Maybe somebody just deleted one of the
2348 * directories leading to ref_file. Try
2353 struct strbuf err
= STRBUF_INIT
;
2354 unable_to_lock_message(ref_file
, errno
, &err
);
2355 error("%s", err
.buf
);
2356 strbuf_release(&err
);
2360 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2369 * Write an entry to the packed-refs file for the specified refname.
2370 * If peeled is non-NULL, write it as the entry's peeled value.
2372 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2373 unsigned char *peeled
)
2375 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2377 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2381 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2383 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2385 enum peel_status peel_status
= peel_entry(entry
, 0);
2387 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2388 error("internal error: %s is not a valid packed reference!",
2390 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2391 peel_status
== PEEL_PEELED
?
2392 entry
->u
.value
.peeled
: NULL
);
2396 /* This should return a meaningful errno on failure */
2397 int lock_packed_refs(int flags
)
2399 struct packed_ref_cache
*packed_ref_cache
;
2401 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2404 * Get the current packed-refs while holding the lock. If the
2405 * packed-refs file has been modified since we last read it,
2406 * this will automatically invalidate the cache and re-read
2407 * the packed-refs file.
2409 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2410 packed_ref_cache
->lock
= &packlock
;
2411 /* Increment the reference count to prevent it from being freed: */
2412 acquire_packed_ref_cache(packed_ref_cache
);
2417 * Commit the packed refs changes.
2418 * On error we must make sure that errno contains a meaningful value.
2420 int commit_packed_refs(void)
2422 struct packed_ref_cache
*packed_ref_cache
=
2423 get_packed_ref_cache(&ref_cache
);
2428 if (!packed_ref_cache
->lock
)
2429 die("internal error: packed-refs not locked");
2431 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2433 die_errno("unable to fdopen packed-refs descriptor");
2435 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2436 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2437 0, write_packed_entry_fn
, out
);
2439 if (commit_lock_file(packed_ref_cache
->lock
)) {
2443 packed_ref_cache
->lock
= NULL
;
2444 release_packed_ref_cache(packed_ref_cache
);
2449 void rollback_packed_refs(void)
2451 struct packed_ref_cache
*packed_ref_cache
=
2452 get_packed_ref_cache(&ref_cache
);
2454 if (!packed_ref_cache
->lock
)
2455 die("internal error: packed-refs not locked");
2456 rollback_lock_file(packed_ref_cache
->lock
);
2457 packed_ref_cache
->lock
= NULL
;
2458 release_packed_ref_cache(packed_ref_cache
);
2459 clear_packed_ref_cache(&ref_cache
);
2462 struct ref_to_prune
{
2463 struct ref_to_prune
*next
;
2464 unsigned char sha1
[20];
2465 char name
[FLEX_ARRAY
];
2468 struct pack_refs_cb_data
{
2470 struct ref_dir
*packed_refs
;
2471 struct ref_to_prune
*ref_to_prune
;
2475 * An each_ref_entry_fn that is run over loose references only. If
2476 * the loose reference can be packed, add an entry in the packed ref
2477 * cache. If the reference should be pruned, also add it to
2478 * ref_to_prune in the pack_refs_cb_data.
2480 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2482 struct pack_refs_cb_data
*cb
= cb_data
;
2483 enum peel_status peel_status
;
2484 struct ref_entry
*packed_entry
;
2485 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2487 /* ALWAYS pack tags */
2488 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2491 /* Do not pack symbolic or broken refs: */
2492 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2495 /* Add a packed ref cache entry equivalent to the loose entry. */
2496 peel_status
= peel_entry(entry
, 1);
2497 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2498 die("internal error peeling reference %s (%s)",
2499 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2500 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2502 /* Overwrite existing packed entry with info from loose entry */
2503 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2504 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2506 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2507 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2508 add_ref(cb
->packed_refs
, packed_entry
);
2510 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2512 /* Schedule the loose reference for pruning if requested. */
2513 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2514 int namelen
= strlen(entry
->name
) + 1;
2515 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2516 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2517 strcpy(n
->name
, entry
->name
);
2518 n
->next
= cb
->ref_to_prune
;
2519 cb
->ref_to_prune
= n
;
2525 * Remove empty parents, but spare refs/ and immediate subdirs.
2526 * Note: munges *name.
2528 static void try_remove_empty_parents(char *name
)
2533 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2534 while (*p
&& *p
!= '/')
2536 /* tolerate duplicate slashes; see check_refname_format() */
2540 for (q
= p
; *q
; q
++)
2543 while (q
> p
&& *q
!= '/')
2545 while (q
> p
&& *(q
-1) == '/')
2550 if (rmdir(git_path("%s", name
)))
2555 /* make sure nobody touched the ref, and unlink */
2556 static void prune_ref(struct ref_to_prune
*r
)
2558 struct ref_transaction
*transaction
;
2559 struct strbuf err
= STRBUF_INIT
;
2561 if (check_refname_format(r
->name
, 0))
2564 transaction
= ref_transaction_begin(&err
);
2566 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2567 REF_ISPRUNING
, 1, NULL
, &err
) ||
2568 ref_transaction_commit(transaction
, &err
)) {
2569 ref_transaction_free(transaction
);
2570 error("%s", err
.buf
);
2571 strbuf_release(&err
);
2574 ref_transaction_free(transaction
);
2575 strbuf_release(&err
);
2576 try_remove_empty_parents(r
->name
);
2579 static void prune_refs(struct ref_to_prune
*r
)
2587 int pack_refs(unsigned int flags
)
2589 struct pack_refs_cb_data cbdata
;
2591 memset(&cbdata
, 0, sizeof(cbdata
));
2592 cbdata
.flags
= flags
;
2594 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2595 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2597 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2598 pack_if_possible_fn
, &cbdata
);
2600 if (commit_packed_refs())
2601 die_errno("unable to overwrite old ref-pack file");
2603 prune_refs(cbdata
.ref_to_prune
);
2608 * If entry is no longer needed in packed-refs, add it to the string
2609 * list pointed to by cb_data. Reasons for deleting entries:
2611 * - Entry is broken.
2612 * - Entry is overridden by a loose ref.
2613 * - Entry does not point at a valid object.
2615 * In the first and third cases, also emit an error message because these
2616 * are indications of repository corruption.
2618 static int curate_packed_ref_fn(struct ref_entry
*entry
, void *cb_data
)
2620 struct string_list
*refs_to_delete
= cb_data
;
2622 if (entry
->flag
& REF_ISBROKEN
) {
2623 /* This shouldn't happen to packed refs. */
2624 error("%s is broken!", entry
->name
);
2625 string_list_append(refs_to_delete
, entry
->name
);
2628 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
2629 unsigned char sha1
[20];
2632 if (read_ref_full(entry
->name
, 0, sha1
, &flags
))
2633 /* We should at least have found the packed ref. */
2634 die("Internal error");
2635 if ((flags
& REF_ISSYMREF
) || !(flags
& REF_ISPACKED
)) {
2637 * This packed reference is overridden by a
2638 * loose reference, so it is OK that its value
2639 * is no longer valid; for example, it might
2640 * refer to an object that has been garbage
2641 * collected. For this purpose we don't even
2642 * care whether the loose reference itself is
2643 * invalid, broken, symbolic, etc. Silently
2644 * remove the packed reference.
2646 string_list_append(refs_to_delete
, entry
->name
);
2650 * There is no overriding loose reference, so the fact
2651 * that this reference doesn't refer to a valid object
2652 * indicates some kind of repository corruption.
2653 * Report the problem, then omit the reference from
2656 error("%s does not point to a valid object!", entry
->name
);
2657 string_list_append(refs_to_delete
, entry
->name
);
2664 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2666 struct ref_dir
*packed
;
2667 struct string_list refs_to_delete
= STRING_LIST_INIT_DUP
;
2668 struct string_list_item
*refname
, *ref_to_delete
;
2669 int ret
, needs_repacking
= 0, removed
= 0;
2673 /* Look for a packed ref */
2674 for_each_string_list_item(refname
, refnames
) {
2675 if (get_packed_ref(refname
->string
)) {
2676 needs_repacking
= 1;
2681 /* Avoid locking if we have nothing to do */
2682 if (!needs_repacking
)
2683 return 0; /* no refname exists in packed refs */
2685 if (lock_packed_refs(0)) {
2686 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2689 packed
= get_packed_refs(&ref_cache
);
2691 /* Remove refnames from the cache */
2692 for_each_string_list_item(refname
, refnames
)
2693 if (remove_entry(packed
, refname
->string
) != -1)
2697 * All packed entries disappeared while we were
2698 * acquiring the lock.
2700 rollback_packed_refs();
2704 /* Remove any other accumulated cruft */
2705 do_for_each_entry_in_dir(packed
, 0, curate_packed_ref_fn
, &refs_to_delete
);
2706 for_each_string_list_item(ref_to_delete
, &refs_to_delete
) {
2707 if (remove_entry(packed
, ref_to_delete
->string
) == -1)
2708 die("internal error");
2711 /* Write what remains */
2712 ret
= commit_packed_refs();
2714 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2719 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2723 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2725 * loose. The loose file name is the same as the
2726 * lockfile name, minus ".lock":
2728 char *loose_filename
= get_locked_file_path(lock
->lk
);
2729 int res
= unlink_or_msg(loose_filename
, err
);
2730 free(loose_filename
);
2737 int delete_ref(const char *refname
, const unsigned char *sha1
, int delopt
)
2739 struct ref_transaction
*transaction
;
2740 struct strbuf err
= STRBUF_INIT
;
2742 transaction
= ref_transaction_begin(&err
);
2744 ref_transaction_delete(transaction
, refname
, sha1
, delopt
,
2745 sha1
&& !is_null_sha1(sha1
), NULL
, &err
) ||
2746 ref_transaction_commit(transaction
, &err
)) {
2747 error("%s", err
.buf
);
2748 ref_transaction_free(transaction
);
2749 strbuf_release(&err
);
2752 ref_transaction_free(transaction
);
2753 strbuf_release(&err
);
2758 * People using contrib's git-new-workdir have .git/logs/refs ->
2759 * /some/other/path/.git/logs/refs, and that may live on another device.
2761 * IOW, to avoid cross device rename errors, the temporary renamed log must
2762 * live into logs/refs.
2764 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2766 static int rename_tmp_log(const char *newrefname
)
2768 int attempts_remaining
= 4;
2771 switch (safe_create_leading_directories(git_path("logs/%s", newrefname
))) {
2773 break; /* success */
2775 if (--attempts_remaining
> 0)
2779 error("unable to create directory for %s", newrefname
);
2783 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2784 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2786 * rename(a, b) when b is an existing
2787 * directory ought to result in ISDIR, but
2788 * Solaris 5.8 gives ENOTDIR. Sheesh.
2790 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2791 error("Directory not empty: logs/%s", newrefname
);
2795 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2797 * Maybe another process just deleted one of
2798 * the directories in the path to newrefname.
2799 * Try again from the beginning.
2803 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2804 newrefname
, strerror(errno
));
2811 static int rename_ref_available(const char *oldname
, const char *newname
)
2813 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2816 string_list_insert(&skip
, oldname
);
2817 ret
= is_refname_available(newname
, &skip
, get_packed_refs(&ref_cache
))
2818 && is_refname_available(newname
, &skip
, get_loose_refs(&ref_cache
));
2819 string_list_clear(&skip
, 0);
2823 static int write_ref_sha1(struct ref_lock
*lock
, const unsigned char *sha1
,
2824 const char *logmsg
);
2826 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2828 unsigned char sha1
[20], orig_sha1
[20];
2829 int flag
= 0, logmoved
= 0;
2830 struct ref_lock
*lock
;
2831 struct stat loginfo
;
2832 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2833 const char *symref
= NULL
;
2835 if (log
&& S_ISLNK(loginfo
.st_mode
))
2836 return error("reflog for %s is a symlink", oldrefname
);
2838 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2840 if (flag
& REF_ISSYMREF
)
2841 return error("refname %s is a symbolic ref, renaming it is not supported",
2844 return error("refname %s not found", oldrefname
);
2846 if (!rename_ref_available(oldrefname
, newrefname
))
2849 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2850 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2851 oldrefname
, strerror(errno
));
2853 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2854 error("unable to delete old %s", oldrefname
);
2858 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2859 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2860 if (errno
==EISDIR
) {
2861 if (remove_empty_directories(git_path("%s", newrefname
))) {
2862 error("Directory not empty: %s", newrefname
);
2866 error("unable to delete existing %s", newrefname
);
2871 if (log
&& rename_tmp_log(newrefname
))
2876 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, 0, NULL
);
2878 error("unable to lock %s for update", newrefname
);
2881 lock
->force_write
= 1;
2882 hashcpy(lock
->old_sha1
, orig_sha1
);
2883 if (write_ref_sha1(lock
, orig_sha1
, logmsg
)) {
2884 error("unable to write current sha1 into %s", newrefname
);
2891 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, 0, NULL
);
2893 error("unable to lock %s for rollback", oldrefname
);
2897 lock
->force_write
= 1;
2898 flag
= log_all_ref_updates
;
2899 log_all_ref_updates
= 0;
2900 if (write_ref_sha1(lock
, orig_sha1
, NULL
))
2901 error("unable to write current sha1 into %s", oldrefname
);
2902 log_all_ref_updates
= flag
;
2905 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2906 error("unable to restore logfile %s from %s: %s",
2907 oldrefname
, newrefname
, strerror(errno
));
2908 if (!logmoved
&& log
&&
2909 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2910 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2911 oldrefname
, strerror(errno
));
2916 static int close_ref(struct ref_lock
*lock
)
2918 if (close_lock_file(lock
->lk
))
2924 static int commit_ref(struct ref_lock
*lock
)
2926 if (commit_lock_file(lock
->lk
))
2933 * copy the reflog message msg to buf, which has been allocated sufficiently
2934 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2935 * because reflog file is one line per entry.
2937 static int copy_msg(char *buf
, const char *msg
)
2944 while ((c
= *msg
++)) {
2945 if (wasspace
&& isspace(c
))
2947 wasspace
= isspace(c
);
2952 while (buf
< cp
&& isspace(cp
[-1]))
2958 /* This function must set a meaningful errno on failure */
2959 int log_ref_setup(const char *refname
, char *logfile
, int bufsize
)
2961 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2963 git_snpath(logfile
, bufsize
, "logs/%s", refname
);
2964 if (log_all_ref_updates
&&
2965 (starts_with(refname
, "refs/heads/") ||
2966 starts_with(refname
, "refs/remotes/") ||
2967 starts_with(refname
, "refs/notes/") ||
2968 !strcmp(refname
, "HEAD"))) {
2969 if (safe_create_leading_directories(logfile
) < 0) {
2970 int save_errno
= errno
;
2971 error("unable to create directory for %s", logfile
);
2978 logfd
= open(logfile
, oflags
, 0666);
2980 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
2983 if (errno
== EISDIR
) {
2984 if (remove_empty_directories(logfile
)) {
2985 int save_errno
= errno
;
2986 error("There are still logs under '%s'",
2991 logfd
= open(logfile
, oflags
, 0666);
2995 int save_errno
= errno
;
2996 error("Unable to append to %s: %s", logfile
,
3003 adjust_shared_perm(logfile
);
3008 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3009 const unsigned char *new_sha1
,
3010 const char *committer
, const char *msg
)
3012 int msglen
, written
;
3013 unsigned maxlen
, len
;
3016 msglen
= msg
? strlen(msg
) : 0;
3017 maxlen
= strlen(committer
) + msglen
+ 100;
3018 logrec
= xmalloc(maxlen
);
3019 len
= sprintf(logrec
, "%s %s %s\n",
3020 sha1_to_hex(old_sha1
),
3021 sha1_to_hex(new_sha1
),
3024 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3026 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3034 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3035 const unsigned char *new_sha1
, const char *msg
)
3037 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3038 char log_file
[PATH_MAX
];
3040 if (log_all_ref_updates
< 0)
3041 log_all_ref_updates
= !is_bare_repository();
3043 result
= log_ref_setup(refname
, log_file
, sizeof(log_file
));
3047 logfd
= open(log_file
, oflags
);
3050 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3051 git_committer_info(0), msg
);
3053 int save_errno
= errno
;
3055 error("Unable to append to %s", log_file
);
3060 int save_errno
= errno
;
3061 error("Unable to append to %s", log_file
);
3068 int is_branch(const char *refname
)
3070 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3074 * Write sha1 into the ref specified by the lock. Make sure that errno
3077 static int write_ref_sha1(struct ref_lock
*lock
,
3078 const unsigned char *sha1
, const char *logmsg
)
3080 static char term
= '\n';
3083 if (!lock
->force_write
&& !hashcmp(lock
->old_sha1
, sha1
)) {
3087 o
= parse_object(sha1
);
3089 error("Trying to write ref %s with nonexistent object %s",
3090 lock
->ref_name
, sha1_to_hex(sha1
));
3095 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3096 error("Trying to write non-commit object %s to branch %s",
3097 sha1_to_hex(sha1
), lock
->ref_name
);
3102 if (write_in_full(lock
->lock_fd
, sha1_to_hex(sha1
), 40) != 40 ||
3103 write_in_full(lock
->lock_fd
, &term
, 1) != 1 ||
3104 close_ref(lock
) < 0) {
3105 int save_errno
= errno
;
3106 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3111 clear_loose_ref_cache(&ref_cache
);
3112 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3113 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3114 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3118 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3120 * Special hack: If a branch is updated directly and HEAD
3121 * points to it (may happen on the remote side of a push
3122 * for example) then logically the HEAD reflog should be
3124 * A generic solution implies reverse symref information,
3125 * but finding all symrefs pointing to the given branch
3126 * would be rather costly for this rare event (the direct
3127 * update of a branch) to be worth it. So let's cheat and
3128 * check with HEAD only which should cover 99% of all usage
3129 * scenarios (even 100% of the default ones).
3131 unsigned char head_sha1
[20];
3133 const char *head_ref
;
3134 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3135 head_sha1
, &head_flag
);
3136 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3137 !strcmp(head_ref
, lock
->ref_name
))
3138 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3140 if (commit_ref(lock
)) {
3141 error("Couldn't set %s", lock
->ref_name
);
3149 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3152 const char *lockpath
;
3154 int fd
, len
, written
;
3155 char *git_HEAD
= git_pathdup("%s", ref_target
);
3156 unsigned char old_sha1
[20], new_sha1
[20];
3158 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3161 if (safe_create_leading_directories(git_HEAD
) < 0)
3162 return error("unable to create directory for %s", git_HEAD
);
3164 #ifndef NO_SYMLINK_HEAD
3165 if (prefer_symlink_refs
) {
3167 if (!symlink(refs_heads_master
, git_HEAD
))
3169 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3173 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3174 if (sizeof(ref
) <= len
) {
3175 error("refname too long: %s", refs_heads_master
);
3176 goto error_free_return
;
3178 lockpath
= mkpath("%s.lock", git_HEAD
);
3179 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3181 error("Unable to open %s for writing", lockpath
);
3182 goto error_free_return
;
3184 written
= write_in_full(fd
, ref
, len
);
3185 if (close(fd
) != 0 || written
!= len
) {
3186 error("Unable to write to %s", lockpath
);
3187 goto error_unlink_return
;
3189 if (rename(lockpath
, git_HEAD
) < 0) {
3190 error("Unable to create %s", git_HEAD
);
3191 goto error_unlink_return
;
3193 if (adjust_shared_perm(git_HEAD
)) {
3194 error("Unable to fix permissions on %s", lockpath
);
3195 error_unlink_return
:
3196 unlink_or_warn(lockpath
);
3202 #ifndef NO_SYMLINK_HEAD
3205 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3206 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3212 struct read_ref_at_cb
{
3213 const char *refname
;
3214 unsigned long at_time
;
3217 unsigned char *sha1
;
3220 unsigned char osha1
[20];
3221 unsigned char nsha1
[20];
3225 unsigned long *cutoff_time
;
3230 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3231 const char *email
, unsigned long timestamp
, int tz
,
3232 const char *message
, void *cb_data
)
3234 struct read_ref_at_cb
*cb
= cb_data
;
3238 cb
->date
= timestamp
;
3240 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3242 *cb
->msg
= xstrdup(message
);
3243 if (cb
->cutoff_time
)
3244 *cb
->cutoff_time
= timestamp
;
3246 *cb
->cutoff_tz
= tz
;
3248 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3250 * we have not yet updated cb->[n|o]sha1 so they still
3251 * hold the values for the previous record.
3253 if (!is_null_sha1(cb
->osha1
)) {
3254 hashcpy(cb
->sha1
, nsha1
);
3255 if (hashcmp(cb
->osha1
, nsha1
))
3256 warning("Log for ref %s has gap after %s.",
3257 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3259 else if (cb
->date
== cb
->at_time
)
3260 hashcpy(cb
->sha1
, nsha1
);
3261 else if (hashcmp(nsha1
, cb
->sha1
))
3262 warning("Log for ref %s unexpectedly ended on %s.",
3263 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3265 hashcpy(cb
->osha1
, osha1
);
3266 hashcpy(cb
->nsha1
, nsha1
);
3270 hashcpy(cb
->osha1
, osha1
);
3271 hashcpy(cb
->nsha1
, nsha1
);
3277 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3278 const char *email
, unsigned long timestamp
,
3279 int tz
, const char *message
, void *cb_data
)
3281 struct read_ref_at_cb
*cb
= cb_data
;
3284 *cb
->msg
= xstrdup(message
);
3285 if (cb
->cutoff_time
)
3286 *cb
->cutoff_time
= timestamp
;
3288 *cb
->cutoff_tz
= tz
;
3290 *cb
->cutoff_cnt
= cb
->reccnt
;
3291 hashcpy(cb
->sha1
, osha1
);
3292 if (is_null_sha1(cb
->sha1
))
3293 hashcpy(cb
->sha1
, nsha1
);
3294 /* We just want the first entry */
3298 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3299 unsigned char *sha1
, char **msg
,
3300 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3302 struct read_ref_at_cb cb
;
3304 memset(&cb
, 0, sizeof(cb
));
3305 cb
.refname
= refname
;
3306 cb
.at_time
= at_time
;
3309 cb
.cutoff_time
= cutoff_time
;
3310 cb
.cutoff_tz
= cutoff_tz
;
3311 cb
.cutoff_cnt
= cutoff_cnt
;
3314 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3317 if (flags
& GET_SHA1_QUIETLY
)
3320 die("Log for %s is empty.", refname
);
3325 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3330 int reflog_exists(const char *refname
)
3334 return !lstat(git_path("logs/%s", refname
), &st
) &&
3335 S_ISREG(st
.st_mode
);
3338 int delete_reflog(const char *refname
)
3340 return remove_path(git_path("logs/%s", refname
));
3343 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3345 unsigned char osha1
[20], nsha1
[20];
3346 char *email_end
, *message
;
3347 unsigned long timestamp
;
3350 /* old SP new SP name <email> SP time TAB msg LF */
3351 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3352 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3353 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3354 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3355 email_end
[1] != ' ' ||
3356 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3357 !message
|| message
[0] != ' ' ||
3358 (message
[1] != '+' && message
[1] != '-') ||
3359 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3360 !isdigit(message
[4]) || !isdigit(message
[5]))
3361 return 0; /* corrupt? */
3362 email_end
[1] = '\0';
3363 tz
= strtol(message
+ 1, NULL
, 10);
3364 if (message
[6] != '\t')
3368 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3371 static char *find_beginning_of_line(char *bob
, char *scan
)
3373 while (bob
< scan
&& *(--scan
) != '\n')
3374 ; /* keep scanning backwards */
3376 * Return either beginning of the buffer, or LF at the end of
3377 * the previous line.
3382 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3384 struct strbuf sb
= STRBUF_INIT
;
3387 int ret
= 0, at_tail
= 1;
3389 logfp
= fopen(git_path("logs/%s", refname
), "r");
3393 /* Jump to the end */
3394 if (fseek(logfp
, 0, SEEK_END
) < 0)
3395 return error("cannot seek back reflog for %s: %s",
3396 refname
, strerror(errno
));
3398 while (!ret
&& 0 < pos
) {
3404 /* Fill next block from the end */
3405 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3406 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3407 return error("cannot seek back reflog for %s: %s",
3408 refname
, strerror(errno
));
3409 nread
= fread(buf
, cnt
, 1, logfp
);
3411 return error("cannot read %d bytes from reflog for %s: %s",
3412 cnt
, refname
, strerror(errno
));
3415 scanp
= endp
= buf
+ cnt
;
3416 if (at_tail
&& scanp
[-1] == '\n')
3417 /* Looking at the final LF at the end of the file */
3421 while (buf
< scanp
) {
3423 * terminating LF of the previous line, or the beginning
3428 bp
= find_beginning_of_line(buf
, scanp
);
3432 * The newline is the end of the previous line,
3433 * so we know we have complete line starting
3434 * at (bp + 1). Prefix it onto any prior data
3435 * we collected for the line and process it.
3437 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3440 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3446 * We are at the start of the buffer, and the
3447 * start of the file; there is no previous
3448 * line, and we have everything for this one.
3449 * Process it, and we can end the loop.
3451 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3452 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3459 * We are at the start of the buffer, and there
3460 * is more file to read backwards. Which means
3461 * we are in the middle of a line. Note that we
3462 * may get here even if *bp was a newline; that
3463 * just means we are at the exact end of the
3464 * previous line, rather than some spot in the
3467 * Save away what we have to be combined with
3468 * the data from the next read.
3470 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3477 die("BUG: reverse reflog parser had leftover data");
3480 strbuf_release(&sb
);
3484 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3487 struct strbuf sb
= STRBUF_INIT
;
3490 logfp
= fopen(git_path("logs/%s", refname
), "r");
3494 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3495 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3497 strbuf_release(&sb
);
3501 * Call fn for each reflog in the namespace indicated by name. name
3502 * must be empty or end with '/'. Name will be used as a scratch
3503 * space, but its contents will be restored before return.
3505 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3507 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3510 int oldlen
= name
->len
;
3513 return name
->len
? errno
: 0;
3515 while ((de
= readdir(d
)) != NULL
) {
3518 if (de
->d_name
[0] == '.')
3520 if (ends_with(de
->d_name
, ".lock"))
3522 strbuf_addstr(name
, de
->d_name
);
3523 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3524 ; /* silently ignore */
3526 if (S_ISDIR(st
.st_mode
)) {
3527 strbuf_addch(name
, '/');
3528 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3530 unsigned char sha1
[20];
3531 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3532 retval
= error("bad ref for %s", name
->buf
);
3534 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3539 strbuf_setlen(name
, oldlen
);
3545 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3549 strbuf_init(&name
, PATH_MAX
);
3550 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3551 strbuf_release(&name
);
3556 * Information needed for a single ref update. Set new_sha1 to the
3557 * new value or to zero to delete the ref. To check the old value
3558 * while locking the ref, set have_old to 1 and set old_sha1 to the
3559 * value or to zero to ensure the ref does not exist before update.
3562 unsigned char new_sha1
[20];
3563 unsigned char old_sha1
[20];
3564 int flags
; /* REF_NODEREF? */
3565 int have_old
; /* 1 if old_sha1 is valid, 0 otherwise */
3566 struct ref_lock
*lock
;
3569 const char refname
[FLEX_ARRAY
];
3573 * Transaction states.
3574 * OPEN: The transaction is in a valid state and can accept new updates.
3575 * An OPEN transaction can be committed.
3576 * CLOSED: A closed transaction is no longer active and no other operations
3577 * than free can be used on it in this state.
3578 * A transaction can either become closed by successfully committing
3579 * an active transaction or if there is a failure while building
3580 * the transaction thus rendering it failed/inactive.
3582 enum ref_transaction_state
{
3583 REF_TRANSACTION_OPEN
= 0,
3584 REF_TRANSACTION_CLOSED
= 1
3588 * Data structure for holding a reference transaction, which can
3589 * consist of checks and updates to multiple references, carried out
3590 * as atomically as possible. This structure is opaque to callers.
3592 struct ref_transaction
{
3593 struct ref_update
**updates
;
3596 enum ref_transaction_state state
;
3599 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3603 return xcalloc(1, sizeof(struct ref_transaction
));
3606 void ref_transaction_free(struct ref_transaction
*transaction
)
3613 for (i
= 0; i
< transaction
->nr
; i
++) {
3614 free(transaction
->updates
[i
]->msg
);
3615 free(transaction
->updates
[i
]);
3617 free(transaction
->updates
);
3621 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3622 const char *refname
)
3624 size_t len
= strlen(refname
);
3625 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3627 strcpy((char *)update
->refname
, refname
);
3628 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3629 transaction
->updates
[transaction
->nr
++] = update
;
3633 int ref_transaction_update(struct ref_transaction
*transaction
,
3634 const char *refname
,
3635 const unsigned char *new_sha1
,
3636 const unsigned char *old_sha1
,
3637 int flags
, int have_old
, const char *msg
,
3640 struct ref_update
*update
;
3644 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3645 die("BUG: update called for transaction that is not open");
3647 if (have_old
&& !old_sha1
)
3648 die("BUG: have_old is true but old_sha1 is NULL");
3650 if (!is_null_sha1(new_sha1
) &&
3651 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3652 strbuf_addf(err
, "refusing to update ref with bad name %s",
3657 update
= add_update(transaction
, refname
);
3658 hashcpy(update
->new_sha1
, new_sha1
);
3659 update
->flags
= flags
;
3660 update
->have_old
= have_old
;
3662 hashcpy(update
->old_sha1
, old_sha1
);
3664 update
->msg
= xstrdup(msg
);
3668 int ref_transaction_create(struct ref_transaction
*transaction
,
3669 const char *refname
,
3670 const unsigned char *new_sha1
,
3671 int flags
, const char *msg
,
3674 return ref_transaction_update(transaction
, refname
, new_sha1
,
3675 null_sha1
, flags
, 1, msg
, err
);
3678 int ref_transaction_delete(struct ref_transaction
*transaction
,
3679 const char *refname
,
3680 const unsigned char *old_sha1
,
3681 int flags
, int have_old
, const char *msg
,
3684 return ref_transaction_update(transaction
, refname
, null_sha1
,
3685 old_sha1
, flags
, have_old
, msg
, err
);
3688 int update_ref(const char *action
, const char *refname
,
3689 const unsigned char *sha1
, const unsigned char *oldval
,
3690 int flags
, enum action_on_err onerr
)
3692 struct ref_transaction
*t
;
3693 struct strbuf err
= STRBUF_INIT
;
3695 t
= ref_transaction_begin(&err
);
3697 ref_transaction_update(t
, refname
, sha1
, oldval
, flags
,
3698 !!oldval
, action
, &err
) ||
3699 ref_transaction_commit(t
, &err
)) {
3700 const char *str
= "update_ref failed for ref '%s': %s";
3702 ref_transaction_free(t
);
3704 case UPDATE_REFS_MSG_ON_ERR
:
3705 error(str
, refname
, err
.buf
);
3707 case UPDATE_REFS_DIE_ON_ERR
:
3708 die(str
, refname
, err
.buf
);
3710 case UPDATE_REFS_QUIET_ON_ERR
:
3713 strbuf_release(&err
);
3716 strbuf_release(&err
);
3717 ref_transaction_free(t
);
3721 static int ref_update_compare(const void *r1
, const void *r2
)
3723 const struct ref_update
* const *u1
= r1
;
3724 const struct ref_update
* const *u2
= r2
;
3725 return strcmp((*u1
)->refname
, (*u2
)->refname
);
3728 static int ref_update_reject_duplicates(struct ref_update
**updates
, int n
,
3735 for (i
= 1; i
< n
; i
++)
3736 if (!strcmp(updates
[i
- 1]->refname
, updates
[i
]->refname
)) {
3738 "Multiple updates for ref '%s' not allowed.",
3739 updates
[i
]->refname
);
3745 int ref_transaction_commit(struct ref_transaction
*transaction
,
3749 int n
= transaction
->nr
;
3750 struct ref_update
**updates
= transaction
->updates
;
3751 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3752 struct string_list_item
*ref_to_delete
;
3756 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3757 die("BUG: commit called for transaction that is not open");
3760 transaction
->state
= REF_TRANSACTION_CLOSED
;
3764 /* Copy, sort, and reject duplicate refs */
3765 qsort(updates
, n
, sizeof(*updates
), ref_update_compare
);
3766 if (ref_update_reject_duplicates(updates
, n
, err
)) {
3767 ret
= TRANSACTION_GENERIC_ERROR
;
3771 /* Acquire all locks while verifying old values */
3772 for (i
= 0; i
< n
; i
++) {
3773 struct ref_update
*update
= updates
[i
];
3774 int flags
= update
->flags
;
3776 if (is_null_sha1(update
->new_sha1
))
3777 flags
|= REF_DELETING
;
3778 update
->lock
= lock_ref_sha1_basic(update
->refname
,
3785 if (!update
->lock
) {
3786 ret
= (errno
== ENOTDIR
)
3787 ? TRANSACTION_NAME_CONFLICT
3788 : TRANSACTION_GENERIC_ERROR
;
3789 strbuf_addf(err
, "Cannot lock the ref '%s'.",
3795 /* Perform updates first so live commits remain referenced */
3796 for (i
= 0; i
< n
; i
++) {
3797 struct ref_update
*update
= updates
[i
];
3799 if (!is_null_sha1(update
->new_sha1
)) {
3800 if (write_ref_sha1(update
->lock
, update
->new_sha1
,
3802 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3803 strbuf_addf(err
, "Cannot update the ref '%s'.",
3805 ret
= TRANSACTION_GENERIC_ERROR
;
3808 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3812 /* Perform deletes now that updates are safely completed */
3813 for (i
= 0; i
< n
; i
++) {
3814 struct ref_update
*update
= updates
[i
];
3817 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3818 ret
= TRANSACTION_GENERIC_ERROR
;
3822 if (!(update
->flags
& REF_ISPRUNING
))
3823 string_list_append(&refs_to_delete
,
3824 update
->lock
->ref_name
);
3828 if (repack_without_refs(&refs_to_delete
, err
)) {
3829 ret
= TRANSACTION_GENERIC_ERROR
;
3832 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3833 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3834 clear_loose_ref_cache(&ref_cache
);
3837 transaction
->state
= REF_TRANSACTION_CLOSED
;
3839 for (i
= 0; i
< n
; i
++)
3840 if (updates
[i
]->lock
)
3841 unlock_ref(updates
[i
]->lock
);
3842 string_list_clear(&refs_to_delete
, 0);
3846 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3849 static char **scanf_fmts
;
3850 static int nr_rules
;
3855 * Pre-generate scanf formats from ref_rev_parse_rules[].
3856 * Generate a format suitable for scanf from a
3857 * ref_rev_parse_rules rule by interpolating "%s" at the
3858 * location of the "%.*s".
3860 size_t total_len
= 0;
3863 /* the rule list is NULL terminated, count them first */
3864 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3865 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3866 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3868 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3871 for (i
= 0; i
< nr_rules
; i
++) {
3872 assert(offset
< total_len
);
3873 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
3874 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
3875 ref_rev_parse_rules
[i
], 2, "%s") + 1;
3879 /* bail out if there are no rules */
3881 return xstrdup(refname
);
3883 /* buffer for scanf result, at most refname must fit */
3884 short_name
= xstrdup(refname
);
3886 /* skip first rule, it will always match */
3887 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
3889 int rules_to_fail
= i
;
3892 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
3895 short_name_len
= strlen(short_name
);
3898 * in strict mode, all (except the matched one) rules
3899 * must fail to resolve to a valid non-ambiguous ref
3902 rules_to_fail
= nr_rules
;
3905 * check if the short name resolves to a valid ref,
3906 * but use only rules prior to the matched one
3908 for (j
= 0; j
< rules_to_fail
; j
++) {
3909 const char *rule
= ref_rev_parse_rules
[j
];
3910 char refname
[PATH_MAX
];
3912 /* skip matched rule */
3917 * the short name is ambiguous, if it resolves
3918 * (with this previous rule) to a valid ref
3919 * read_ref() returns 0 on success
3921 mksnpath(refname
, sizeof(refname
),
3922 rule
, short_name_len
, short_name
);
3923 if (ref_exists(refname
))
3928 * short name is non-ambiguous if all previous rules
3929 * haven't resolved to a valid ref
3931 if (j
== rules_to_fail
)
3936 return xstrdup(refname
);
3939 static struct string_list
*hide_refs
;
3941 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
3943 if (!strcmp("transfer.hiderefs", var
) ||
3944 /* NEEDSWORK: use parse_config_key() once both are merged */
3945 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
3946 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
3951 return config_error_nonbool(var
);
3952 ref
= xstrdup(value
);
3954 while (len
&& ref
[len
- 1] == '/')
3957 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
3958 hide_refs
->strdup_strings
= 1;
3960 string_list_append(hide_refs
, ref
);
3965 int ref_is_hidden(const char *refname
)
3967 struct string_list_item
*item
;
3971 for_each_string_list_item(item
, hide_refs
) {
3973 if (!starts_with(refname
, item
->string
))
3975 len
= strlen(item
->string
);
3976 if (!refname
[len
] || refname
[len
] == '/')
3982 struct expire_reflog_cb
{
3984 reflog_expiry_should_prune_fn
*should_prune_fn
;
3987 unsigned char last_kept_sha1
[20];
3990 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
3991 const char *email
, unsigned long timestamp
, int tz
,
3992 const char *message
, void *cb_data
)
3994 struct expire_reflog_cb
*cb
= cb_data
;
3995 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
3997 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
3998 osha1
= cb
->last_kept_sha1
;
4000 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4001 message
, policy_cb
)) {
4003 printf("would prune %s", message
);
4004 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4005 printf("prune %s", message
);
4008 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4009 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4010 email
, timestamp
, tz
, message
);
4011 hashcpy(cb
->last_kept_sha1
, nsha1
);
4013 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4014 printf("keep %s", message
);
4019 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4021 reflog_expiry_prepare_fn prepare_fn
,
4022 reflog_expiry_should_prune_fn should_prune_fn
,
4023 reflog_expiry_cleanup_fn cleanup_fn
,
4024 void *policy_cb_data
)
4026 static struct lock_file reflog_lock
;
4027 struct expire_reflog_cb cb
;
4028 struct ref_lock
*lock
;
4032 memset(&cb
, 0, sizeof(cb
));
4034 cb
.policy_cb
= policy_cb_data
;
4035 cb
.should_prune_fn
= should_prune_fn
;
4038 * The reflog file is locked by holding the lock on the
4039 * reference itself, plus we might need to update the
4040 * reference if --updateref was specified:
4042 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, 0, NULL
);
4044 return error("cannot lock ref '%s'", refname
);
4045 if (!reflog_exists(refname
)) {
4050 log_file
= git_pathdup("logs/%s", refname
);
4051 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4053 * Even though holding $GIT_DIR/logs/$reflog.lock has
4054 * no locking implications, we use the lock_file
4055 * machinery here anyway because it does a lot of the
4056 * work we need, including cleaning up if the program
4057 * exits unexpectedly.
4059 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4060 struct strbuf err
= STRBUF_INIT
;
4061 unable_to_lock_message(log_file
, errno
, &err
);
4062 error("%s", err
.buf
);
4063 strbuf_release(&err
);
4066 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4068 error("cannot fdopen %s (%s)",
4069 reflog_lock
.filename
.buf
, strerror(errno
));
4074 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4075 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4076 (*cleanup_fn
)(cb
.policy_cb
);
4078 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4079 if (close_lock_file(&reflog_lock
)) {
4080 status
|= error("couldn't write %s: %s", log_file
,
4082 } else if ((flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4083 (write_in_full(lock
->lock_fd
,
4084 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4085 write_str_in_full(lock
->lock_fd
, "\n") != 1 ||
4086 close_ref(lock
) < 0)) {
4087 status
|= error("couldn't write %s",
4088 lock
->lk
->filename
.buf
);
4089 rollback_lock_file(&reflog_lock
);
4090 } else if (commit_lock_file(&reflog_lock
)) {
4091 status
|= error("unable to commit reflog '%s' (%s)",
4092 log_file
, strerror(errno
));
4093 } else if ((flags
& EXPIRE_REFLOGS_UPDATE_REF
) && commit_ref(lock
)) {
4094 status
|= error("couldn't set %s", lock
->ref_name
);
4102 rollback_lock_file(&reflog_lock
);