7 #include "string-list.h"
13 unsigned char old_sha1
[20];
19 * How to handle various characters in refnames:
20 * 0: An acceptable character for refs
22 * 2: ., look for a preceding . to reject .. in refs
23 * 3: {, look for a preceding @ to reject @{ in refs
24 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
26 static unsigned char refname_disposition
[256] = {
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
41 #define REF_DELETING 0x02
44 * Used as a flag to ref_transaction_delete when a loose ref is being
47 #define REF_ISPRUNING 0x0100
49 * Try to read one refname component from the front of refname.
50 * Return the length of the component found, or -1 if the component is
51 * not legal. It is legal if it is something reasonable to have under
52 * ".git/refs/"; We do not like it if:
54 * - any path component of it begins with ".", or
55 * - it has double dots "..", or
56 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
57 * - it ends with a "/".
58 * - it ends with ".lock"
59 * - it contains a "\" (backslash)
61 static int check_refname_component(const char *refname
, int flags
)
66 for (cp
= refname
; ; cp
++) {
68 unsigned char disp
= refname_disposition
[ch
];
74 return -1; /* Refname contains "..". */
78 return -1; /* Refname contains "@{". */
87 return 0; /* Component has zero length. */
88 if (refname
[0] == '.')
89 return -1; /* Component starts with '.'. */
90 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
91 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
92 return -1; /* Refname ends with ".lock". */
96 int check_refname_format(const char *refname
, int flags
)
98 int component_len
, component_count
= 0;
100 if (!strcmp(refname
, "@"))
101 /* Refname is a single character '@'. */
105 /* We are at the start of a path component. */
106 component_len
= check_refname_component(refname
, flags
);
107 if (component_len
<= 0) {
108 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
110 (refname
[1] == '\0' || refname
[1] == '/')) {
111 /* Accept one wildcard as a full refname component. */
112 flags
&= ~REFNAME_REFSPEC_PATTERN
;
119 if (refname
[component_len
] == '\0')
121 /* Skip to next component. */
122 refname
+= component_len
+ 1;
125 if (refname
[component_len
- 1] == '.')
126 return -1; /* Refname ends with '.'. */
127 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
128 return -1; /* Refname has only one component. */
135 * Information used (along with the information in ref_entry) to
136 * describe a single cached reference. This data structure only
137 * occurs embedded in a union in struct ref_entry, and only when
138 * (ref_entry->flag & REF_DIR) is zero.
142 * The name of the object to which this reference resolves
143 * (which may be a tag object). If REF_ISBROKEN, this is
144 * null. If REF_ISSYMREF, then this is the name of the object
145 * referred to by the last reference in the symlink chain.
147 unsigned char sha1
[20];
150 * If REF_KNOWS_PEELED, then this field holds the peeled value
151 * of this reference, or null if the reference is known not to
152 * be peelable. See the documentation for peel_ref() for an
153 * exact definition of "peelable".
155 unsigned char peeled
[20];
161 * Information used (along with the information in ref_entry) to
162 * describe a level in the hierarchy of references. This data
163 * structure only occurs embedded in a union in struct ref_entry, and
164 * only when (ref_entry.flag & REF_DIR) is set. In that case,
165 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
166 * in the directory have already been read:
168 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
169 * or packed references, already read.
171 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
172 * references that hasn't been read yet (nor has any of its
175 * Entries within a directory are stored within a growable array of
176 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
177 * sorted are sorted by their component name in strcmp() order and the
178 * remaining entries are unsorted.
180 * Loose references are read lazily, one directory at a time. When a
181 * directory of loose references is read, then all of the references
182 * in that directory are stored, and REF_INCOMPLETE stubs are created
183 * for any subdirectories, but the subdirectories themselves are not
184 * read. The reading is triggered by get_ref_dir().
190 * Entries with index 0 <= i < sorted are sorted by name. New
191 * entries are appended to the list unsorted, and are sorted
192 * only when required; thus we avoid the need to sort the list
193 * after the addition of every reference.
197 /* A pointer to the ref_cache that contains this ref_dir. */
198 struct ref_cache
*ref_cache
;
200 struct ref_entry
**entries
;
204 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
205 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
206 * public values; see refs.h.
210 * The field ref_entry->u.value.peeled of this value entry contains
211 * the correct peeled value for the reference, which might be
212 * null_sha1 if the reference is not a tag or if it is broken.
214 #define REF_KNOWS_PEELED 0x10
216 /* ref_entry represents a directory of references */
220 * Entry has not yet been read from disk (used only for REF_DIR
221 * entries representing loose references)
223 #define REF_INCOMPLETE 0x40
226 * A ref_entry represents either a reference or a "subdirectory" of
229 * Each directory in the reference namespace is represented by a
230 * ref_entry with (flags & REF_DIR) set and containing a subdir member
231 * that holds the entries in that directory that have been read so
232 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
233 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
234 * used for loose reference directories.
236 * References are represented by a ref_entry with (flags & REF_DIR)
237 * unset and a value member that describes the reference's value. The
238 * flag member is at the ref_entry level, but it is also needed to
239 * interpret the contents of the value field (in other words, a
240 * ref_value object is not very much use without the enclosing
243 * Reference names cannot end with slash and directories' names are
244 * always stored with a trailing slash (except for the top-level
245 * directory, which is always denoted by ""). This has two nice
246 * consequences: (1) when the entries in each subdir are sorted
247 * lexicographically by name (as they usually are), the references in
248 * a whole tree can be generated in lexicographic order by traversing
249 * the tree in left-to-right, depth-first order; (2) the names of
250 * references and subdirectories cannot conflict, and therefore the
251 * presence of an empty subdirectory does not block the creation of a
252 * similarly-named reference. (The fact that reference names with the
253 * same leading components can conflict *with each other* is a
254 * separate issue that is regulated by is_refname_available().)
256 * Please note that the name field contains the fully-qualified
257 * reference (or subdirectory) name. Space could be saved by only
258 * storing the relative names. But that would require the full names
259 * to be generated on the fly when iterating in do_for_each_ref(), and
260 * would break callback functions, who have always been able to assume
261 * that the name strings that they are passed will not be freed during
265 unsigned char flag
; /* ISSYMREF? ISPACKED? */
267 struct ref_value value
; /* if not (flags&REF_DIR) */
268 struct ref_dir subdir
; /* if (flags&REF_DIR) */
271 * The full name of the reference (e.g., "refs/heads/master")
272 * or the full name of the directory with a trailing slash
273 * (e.g., "refs/heads/"):
275 char name
[FLEX_ARRAY
];
278 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
280 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
283 assert(entry
->flag
& REF_DIR
);
284 dir
= &entry
->u
.subdir
;
285 if (entry
->flag
& REF_INCOMPLETE
) {
286 read_loose_refs(entry
->name
, dir
);
287 entry
->flag
&= ~REF_INCOMPLETE
;
293 * Check if a refname is safe.
294 * For refs that start with "refs/" we consider it safe as long they do
295 * not try to resolve to outside of refs/.
297 * For all other refs we only consider them safe iff they only contain
298 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
301 static int refname_is_safe(const char *refname
)
303 if (starts_with(refname
, "refs/")) {
307 buf
= xmalloc(strlen(refname
) + 1);
309 * Does the refname try to escape refs/?
310 * For example: refs/foo/../bar is safe but refs/foo/../../bar
313 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
318 if (!isupper(*refname
) && *refname
!= '_')
325 static struct ref_entry
*create_ref_entry(const char *refname
,
326 const unsigned char *sha1
, int flag
,
330 struct ref_entry
*ref
;
333 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
334 die("Reference has invalid format: '%s'", refname
);
335 if (!check_name
&& !refname_is_safe(refname
))
336 die("Reference has invalid name: '%s'", refname
);
337 len
= strlen(refname
) + 1;
338 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
339 hashcpy(ref
->u
.value
.sha1
, sha1
);
340 hashclr(ref
->u
.value
.peeled
);
341 memcpy(ref
->name
, refname
, len
);
346 static void clear_ref_dir(struct ref_dir
*dir
);
348 static void free_ref_entry(struct ref_entry
*entry
)
350 if (entry
->flag
& REF_DIR
) {
352 * Do not use get_ref_dir() here, as that might
353 * trigger the reading of loose refs.
355 clear_ref_dir(&entry
->u
.subdir
);
361 * Add a ref_entry to the end of dir (unsorted). Entry is always
362 * stored directly in dir; no recursion into subdirectories is
365 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
367 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
368 dir
->entries
[dir
->nr
++] = entry
;
369 /* optimize for the case that entries are added in order */
371 (dir
->nr
== dir
->sorted
+ 1 &&
372 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
373 dir
->entries
[dir
->nr
- 1]->name
) < 0))
374 dir
->sorted
= dir
->nr
;
378 * Clear and free all entries in dir, recursively.
380 static void clear_ref_dir(struct ref_dir
*dir
)
383 for (i
= 0; i
< dir
->nr
; i
++)
384 free_ref_entry(dir
->entries
[i
]);
386 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
391 * Create a struct ref_entry object for the specified dirname.
392 * dirname is the name of the directory with a trailing slash (e.g.,
393 * "refs/heads/") or "" for the top-level directory.
395 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
396 const char *dirname
, size_t len
,
399 struct ref_entry
*direntry
;
400 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
401 memcpy(direntry
->name
, dirname
, len
);
402 direntry
->name
[len
] = '\0';
403 direntry
->u
.subdir
.ref_cache
= ref_cache
;
404 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
408 static int ref_entry_cmp(const void *a
, const void *b
)
410 struct ref_entry
*one
= *(struct ref_entry
**)a
;
411 struct ref_entry
*two
= *(struct ref_entry
**)b
;
412 return strcmp(one
->name
, two
->name
);
415 static void sort_ref_dir(struct ref_dir
*dir
);
417 struct string_slice
{
422 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
424 const struct string_slice
*key
= key_
;
425 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
426 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
429 return '\0' - (unsigned char)ent
->name
[key
->len
];
433 * Return the index of the entry with the given refname from the
434 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
435 * no such entry is found. dir must already be complete.
437 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
439 struct ref_entry
**r
;
440 struct string_slice key
;
442 if (refname
== NULL
|| !dir
->nr
)
448 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
449 ref_entry_cmp_sslice
);
454 return r
- dir
->entries
;
458 * Search for a directory entry directly within dir (without
459 * recursing). Sort dir if necessary. subdirname must be a directory
460 * name (i.e., end in '/'). If mkdir is set, then create the
461 * directory if it is missing; otherwise, return NULL if the desired
462 * directory cannot be found. dir must already be complete.
464 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
465 const char *subdirname
, size_t len
,
468 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
469 struct ref_entry
*entry
;
470 if (entry_index
== -1) {
474 * Since dir is complete, the absence of a subdir
475 * means that the subdir really doesn't exist;
476 * therefore, create an empty record for it but mark
477 * the record complete.
479 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
480 add_entry_to_dir(dir
, entry
);
482 entry
= dir
->entries
[entry_index
];
484 return get_ref_dir(entry
);
488 * If refname is a reference name, find the ref_dir within the dir
489 * tree that should hold refname. If refname is a directory name
490 * (i.e., ends in '/'), then return that ref_dir itself. dir must
491 * represent the top-level directory and must already be complete.
492 * Sort ref_dirs and recurse into subdirectories as necessary. If
493 * mkdir is set, then create any missing directories; otherwise,
494 * return NULL if the desired directory cannot be found.
496 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
497 const char *refname
, int mkdir
)
500 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
501 size_t dirnamelen
= slash
- refname
+ 1;
502 struct ref_dir
*subdir
;
503 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
515 * Find the value entry with the given name in dir, sorting ref_dirs
516 * and recursing into subdirectories as necessary. If the name is not
517 * found or it corresponds to a directory entry, return NULL.
519 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
522 struct ref_entry
*entry
;
523 dir
= find_containing_dir(dir
, refname
, 0);
526 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
527 if (entry_index
== -1)
529 entry
= dir
->entries
[entry_index
];
530 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
534 * Remove the entry with the given name from dir, recursing into
535 * subdirectories as necessary. If refname is the name of a directory
536 * (i.e., ends with '/'), then remove the directory and its contents.
537 * If the removal was successful, return the number of entries
538 * remaining in the directory entry that contained the deleted entry.
539 * If the name was not found, return -1. Please note that this
540 * function only deletes the entry from the cache; it does not delete
541 * it from the filesystem or ensure that other cache entries (which
542 * might be symbolic references to the removed entry) are updated.
543 * Nor does it remove any containing dir entries that might be made
544 * empty by the removal. dir must represent the top-level directory
545 * and must already be complete.
547 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
549 int refname_len
= strlen(refname
);
551 struct ref_entry
*entry
;
552 int is_dir
= refname
[refname_len
- 1] == '/';
555 * refname represents a reference directory. Remove
556 * the trailing slash; otherwise we will get the
557 * directory *representing* refname rather than the
558 * one *containing* it.
560 char *dirname
= xmemdupz(refname
, refname_len
- 1);
561 dir
= find_containing_dir(dir
, dirname
, 0);
564 dir
= find_containing_dir(dir
, refname
, 0);
568 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
569 if (entry_index
== -1)
571 entry
= dir
->entries
[entry_index
];
573 memmove(&dir
->entries
[entry_index
],
574 &dir
->entries
[entry_index
+ 1],
575 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
578 if (dir
->sorted
> entry_index
)
580 free_ref_entry(entry
);
585 * Add a ref_entry to the ref_dir (unsorted), recursing into
586 * subdirectories as necessary. dir must represent the top-level
587 * directory. Return 0 on success.
589 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
591 dir
= find_containing_dir(dir
, ref
->name
, 1);
594 add_entry_to_dir(dir
, ref
);
599 * Emit a warning and return true iff ref1 and ref2 have the same name
600 * and the same sha1. Die if they have the same name but different
603 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
605 if (strcmp(ref1
->name
, ref2
->name
))
608 /* Duplicate name; make sure that they don't conflict: */
610 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
611 /* This is impossible by construction */
612 die("Reference directory conflict: %s", ref1
->name
);
614 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
615 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
617 warning("Duplicated ref: %s", ref1
->name
);
622 * Sort the entries in dir non-recursively (if they are not already
623 * sorted) and remove any duplicate entries.
625 static void sort_ref_dir(struct ref_dir
*dir
)
628 struct ref_entry
*last
= NULL
;
631 * This check also prevents passing a zero-length array to qsort(),
632 * which is a problem on some platforms.
634 if (dir
->sorted
== dir
->nr
)
637 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
639 /* Remove any duplicates: */
640 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
641 struct ref_entry
*entry
= dir
->entries
[j
];
642 if (last
&& is_dup_ref(last
, entry
))
643 free_ref_entry(entry
);
645 last
= dir
->entries
[i
++] = entry
;
647 dir
->sorted
= dir
->nr
= i
;
650 /* Include broken references in a do_for_each_ref*() iteration: */
651 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
654 * Return true iff the reference described by entry can be resolved to
655 * an object in the database. Emit a warning if the referred-to
656 * object does not exist.
658 static int ref_resolves_to_object(struct ref_entry
*entry
)
660 if (entry
->flag
& REF_ISBROKEN
)
662 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
663 error("%s does not point to a valid object!", entry
->name
);
670 * current_ref is a performance hack: when iterating over references
671 * using the for_each_ref*() functions, current_ref is set to the
672 * current reference's entry before calling the callback function. If
673 * the callback function calls peel_ref(), then peel_ref() first
674 * checks whether the reference to be peeled is the current reference
675 * (it usually is) and if so, returns that reference's peeled version
676 * if it is available. This avoids a refname lookup in a common case.
678 static struct ref_entry
*current_ref
;
680 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
682 struct ref_entry_cb
{
691 * Handle one reference in a do_for_each_ref*()-style iteration,
692 * calling an each_ref_fn for each entry.
694 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
696 struct ref_entry_cb
*data
= cb_data
;
697 struct ref_entry
*old_current_ref
;
700 if (!starts_with(entry
->name
, data
->base
))
703 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
704 !ref_resolves_to_object(entry
))
707 /* Store the old value, in case this is a recursive call: */
708 old_current_ref
= current_ref
;
710 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
711 entry
->flag
, data
->cb_data
);
712 current_ref
= old_current_ref
;
717 * Call fn for each reference in dir that has index in the range
718 * offset <= index < dir->nr. Recurse into subdirectories that are in
719 * that index range, sorting them before iterating. This function
720 * does not sort dir itself; it should be sorted beforehand. fn is
721 * called for all references, including broken ones.
723 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
724 each_ref_entry_fn fn
, void *cb_data
)
727 assert(dir
->sorted
== dir
->nr
);
728 for (i
= offset
; i
< dir
->nr
; i
++) {
729 struct ref_entry
*entry
= dir
->entries
[i
];
731 if (entry
->flag
& REF_DIR
) {
732 struct ref_dir
*subdir
= get_ref_dir(entry
);
733 sort_ref_dir(subdir
);
734 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
736 retval
= fn(entry
, cb_data
);
745 * Call fn for each reference in the union of dir1 and dir2, in order
746 * by refname. Recurse into subdirectories. If a value entry appears
747 * in both dir1 and dir2, then only process the version that is in
748 * dir2. The input dirs must already be sorted, but subdirs will be
749 * sorted as needed. fn is called for all references, including
752 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
753 struct ref_dir
*dir2
,
754 each_ref_entry_fn fn
, void *cb_data
)
759 assert(dir1
->sorted
== dir1
->nr
);
760 assert(dir2
->sorted
== dir2
->nr
);
762 struct ref_entry
*e1
, *e2
;
764 if (i1
== dir1
->nr
) {
765 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
767 if (i2
== dir2
->nr
) {
768 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
770 e1
= dir1
->entries
[i1
];
771 e2
= dir2
->entries
[i2
];
772 cmp
= strcmp(e1
->name
, e2
->name
);
774 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
775 /* Both are directories; descend them in parallel. */
776 struct ref_dir
*subdir1
= get_ref_dir(e1
);
777 struct ref_dir
*subdir2
= get_ref_dir(e2
);
778 sort_ref_dir(subdir1
);
779 sort_ref_dir(subdir2
);
780 retval
= do_for_each_entry_in_dirs(
781 subdir1
, subdir2
, fn
, cb_data
);
784 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
785 /* Both are references; ignore the one from dir1. */
786 retval
= fn(e2
, cb_data
);
790 die("conflict between reference and directory: %s",
802 if (e
->flag
& REF_DIR
) {
803 struct ref_dir
*subdir
= get_ref_dir(e
);
804 sort_ref_dir(subdir
);
805 retval
= do_for_each_entry_in_dir(
806 subdir
, 0, fn
, cb_data
);
808 retval
= fn(e
, cb_data
);
817 * Load all of the refs from the dir into our in-memory cache. The hard work
818 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
819 * through all of the sub-directories. We do not even need to care about
820 * sorting, as traversal order does not matter to us.
822 static void prime_ref_dir(struct ref_dir
*dir
)
825 for (i
= 0; i
< dir
->nr
; i
++) {
826 struct ref_entry
*entry
= dir
->entries
[i
];
827 if (entry
->flag
& REF_DIR
)
828 prime_ref_dir(get_ref_dir(entry
));
832 static int entry_matches(struct ref_entry
*entry
, const struct string_list
*list
)
834 return list
&& string_list_has_string(list
, entry
->name
);
837 struct nonmatching_ref_data
{
838 const struct string_list
*skip
;
839 struct ref_entry
*found
;
842 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
844 struct nonmatching_ref_data
*data
= vdata
;
846 if (entry_matches(entry
, data
->skip
))
853 static void report_refname_conflict(struct ref_entry
*entry
,
856 error("'%s' exists; cannot create '%s'", entry
->name
, refname
);
860 * Return true iff a reference named refname could be created without
861 * conflicting with the name of an existing reference in dir. If
862 * skip is non-NULL, ignore potential conflicts with refs in skip
863 * (e.g., because they are scheduled for deletion in the same
866 * Two reference names conflict if one of them exactly matches the
867 * leading components of the other; e.g., "foo/bar" conflicts with
868 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
871 * skip must be sorted.
873 static int is_refname_available(const char *refname
,
874 const struct string_list
*skip
,
882 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
884 * We are still at a leading dir of the refname; we are
885 * looking for a conflict with a leaf entry.
887 * If we find one, we still must make sure it is
890 pos
= search_ref_dir(dir
, refname
, slash
- refname
);
892 struct ref_entry
*entry
= dir
->entries
[pos
];
893 if (entry_matches(entry
, skip
))
895 report_refname_conflict(entry
, refname
);
901 * Otherwise, we can try to continue our search with
902 * the next component; if we come up empty, we know
903 * there is nothing under this whole prefix.
905 pos
= search_ref_dir(dir
, refname
, slash
+ 1 - refname
);
909 dir
= get_ref_dir(dir
->entries
[pos
]);
913 * We are at the leaf of our refname; we want to
914 * make sure there are no directories which match it.
916 len
= strlen(refname
);
917 dirname
= xmallocz(len
+ 1);
918 sprintf(dirname
, "%s/", refname
);
919 pos
= search_ref_dir(dir
, dirname
, len
+ 1);
924 * We found a directory named "refname". It is a
925 * problem iff it contains any ref that is not
928 struct ref_entry
*entry
= dir
->entries
[pos
];
929 struct ref_dir
*dir
= get_ref_dir(entry
);
930 struct nonmatching_ref_data data
;
934 if (!do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
))
937 report_refname_conflict(data
.found
, refname
);
942 * There is no point in searching for another leaf
943 * node which matches it; such an entry would be the
944 * ref we are looking for, not a conflict.
949 struct packed_ref_cache
{
950 struct ref_entry
*root
;
953 * Count of references to the data structure in this instance,
954 * including the pointer from ref_cache::packed if any. The
955 * data will not be freed as long as the reference count is
958 unsigned int referrers
;
961 * Iff the packed-refs file associated with this instance is
962 * currently locked for writing, this points at the associated
963 * lock (which is owned by somebody else). The referrer count
964 * is also incremented when the file is locked and decremented
965 * when it is unlocked.
967 struct lock_file
*lock
;
969 /* The metadata from when this packed-refs cache was read */
970 struct stat_validity validity
;
974 * Future: need to be in "struct repository"
975 * when doing a full libification.
977 static struct ref_cache
{
978 struct ref_cache
*next
;
979 struct ref_entry
*loose
;
980 struct packed_ref_cache
*packed
;
982 * The submodule name, or "" for the main repo. We allocate
983 * length 1 rather than FLEX_ARRAY so that the main ref_cache
984 * is initialized correctly.
987 } ref_cache
, *submodule_ref_caches
;
989 /* Lock used for the main packed-refs file: */
990 static struct lock_file packlock
;
993 * Increment the reference count of *packed_refs.
995 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
997 packed_refs
->referrers
++;
1001 * Decrease the reference count of *packed_refs. If it goes to zero,
1002 * free *packed_refs and return true; otherwise return false.
1004 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1006 if (!--packed_refs
->referrers
) {
1007 free_ref_entry(packed_refs
->root
);
1008 stat_validity_clear(&packed_refs
->validity
);
1016 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1019 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1021 if (packed_refs
->lock
)
1022 die("internal error: packed-ref cache cleared while locked");
1023 refs
->packed
= NULL
;
1024 release_packed_ref_cache(packed_refs
);
1028 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1031 free_ref_entry(refs
->loose
);
1036 static struct ref_cache
*create_ref_cache(const char *submodule
)
1039 struct ref_cache
*refs
;
1042 len
= strlen(submodule
) + 1;
1043 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1044 memcpy(refs
->name
, submodule
, len
);
1049 * Return a pointer to a ref_cache for the specified submodule. For
1050 * the main repository, use submodule==NULL. The returned structure
1051 * will be allocated and initialized but not necessarily populated; it
1052 * should not be freed.
1054 static struct ref_cache
*get_ref_cache(const char *submodule
)
1056 struct ref_cache
*refs
;
1058 if (!submodule
|| !*submodule
)
1061 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1062 if (!strcmp(submodule
, refs
->name
))
1065 refs
= create_ref_cache(submodule
);
1066 refs
->next
= submodule_ref_caches
;
1067 submodule_ref_caches
= refs
;
1071 /* The length of a peeled reference line in packed-refs, including EOL: */
1072 #define PEELED_LINE_LENGTH 42
1075 * The packed-refs header line that we write out. Perhaps other
1076 * traits will be added later. The trailing space is required.
1078 static const char PACKED_REFS_HEADER
[] =
1079 "# pack-refs with: peeled fully-peeled \n";
1082 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1083 * Return a pointer to the refname within the line (null-terminated),
1084 * or NULL if there was a problem.
1086 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1091 * 42: the answer to everything.
1093 * In this case, it happens to be the answer to
1094 * 40 (length of sha1 hex representation)
1095 * +1 (space in between hex and name)
1096 * +1 (newline at the end of the line)
1098 if (line
->len
<= 42)
1101 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1103 if (!isspace(line
->buf
[40]))
1106 ref
= line
->buf
+ 41;
1110 if (line
->buf
[line
->len
- 1] != '\n')
1112 line
->buf
[--line
->len
] = 0;
1118 * Read f, which is a packed-refs file, into dir.
1120 * A comment line of the form "# pack-refs with: " may contain zero or
1121 * more traits. We interpret the traits as follows:
1125 * Probably no references are peeled. But if the file contains a
1126 * peeled value for a reference, we will use it.
1130 * References under "refs/tags/", if they *can* be peeled, *are*
1131 * peeled in this file. References outside of "refs/tags/" are
1132 * probably not peeled even if they could have been, but if we find
1133 * a peeled value for such a reference we will use it.
1137 * All references in the file that can be peeled are peeled.
1138 * Inversely (and this is more important), any references in the
1139 * file for which no peeled value is recorded is not peelable. This
1140 * trait should typically be written alongside "peeled" for
1141 * compatibility with older clients, but we do not require it
1142 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1144 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1146 struct ref_entry
*last
= NULL
;
1147 struct strbuf line
= STRBUF_INIT
;
1148 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1150 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1151 unsigned char sha1
[20];
1152 const char *refname
;
1155 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1156 if (strstr(traits
, " fully-peeled "))
1157 peeled
= PEELED_FULLY
;
1158 else if (strstr(traits
, " peeled "))
1159 peeled
= PEELED_TAGS
;
1160 /* perhaps other traits later as well */
1164 refname
= parse_ref_line(&line
, sha1
);
1166 int flag
= REF_ISPACKED
;
1168 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1170 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1172 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1173 if (peeled
== PEELED_FULLY
||
1174 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1175 last
->flag
|= REF_KNOWS_PEELED
;
1180 line
.buf
[0] == '^' &&
1181 line
.len
== PEELED_LINE_LENGTH
&&
1182 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1183 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1184 hashcpy(last
->u
.value
.peeled
, sha1
);
1186 * Regardless of what the file header said,
1187 * we definitely know the value of *this*
1190 last
->flag
|= REF_KNOWS_PEELED
;
1194 strbuf_release(&line
);
1198 * Get the packed_ref_cache for the specified ref_cache, creating it
1201 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1203 const char *packed_refs_file
;
1206 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1208 packed_refs_file
= git_path("packed-refs");
1211 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1212 clear_packed_ref_cache(refs
);
1214 if (!refs
->packed
) {
1217 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1218 acquire_packed_ref_cache(refs
->packed
);
1219 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1220 f
= fopen(packed_refs_file
, "r");
1222 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1223 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1227 return refs
->packed
;
1230 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1232 return get_ref_dir(packed_ref_cache
->root
);
1235 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1237 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1240 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1242 struct packed_ref_cache
*packed_ref_cache
=
1243 get_packed_ref_cache(&ref_cache
);
1245 if (!packed_ref_cache
->lock
)
1246 die("internal error: packed refs not locked");
1247 add_ref(get_packed_ref_dir(packed_ref_cache
),
1248 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1252 * Read the loose references from the namespace dirname into dir
1253 * (without recursing). dirname must end with '/'. dir must be the
1254 * directory entry corresponding to dirname.
1256 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1258 struct ref_cache
*refs
= dir
->ref_cache
;
1262 int dirnamelen
= strlen(dirname
);
1263 struct strbuf refname
;
1266 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1268 path
= git_path("%s", dirname
);
1274 strbuf_init(&refname
, dirnamelen
+ 257);
1275 strbuf_add(&refname
, dirname
, dirnamelen
);
1277 while ((de
= readdir(d
)) != NULL
) {
1278 unsigned char sha1
[20];
1283 if (de
->d_name
[0] == '.')
1285 if (ends_with(de
->d_name
, ".lock"))
1287 strbuf_addstr(&refname
, de
->d_name
);
1288 refdir
= *refs
->name
1289 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1290 : git_path("%s", refname
.buf
);
1291 if (stat(refdir
, &st
) < 0) {
1292 ; /* silently ignore */
1293 } else if (S_ISDIR(st
.st_mode
)) {
1294 strbuf_addch(&refname
, '/');
1295 add_entry_to_dir(dir
,
1296 create_dir_entry(refs
, refname
.buf
,
1302 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1304 flag
|= REF_ISBROKEN
;
1306 } else if (read_ref_full(refname
.buf
,
1307 RESOLVE_REF_READING
,
1310 flag
|= REF_ISBROKEN
;
1312 if (check_refname_format(refname
.buf
,
1313 REFNAME_ALLOW_ONELEVEL
)) {
1315 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1317 add_entry_to_dir(dir
,
1318 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1320 strbuf_setlen(&refname
, dirnamelen
);
1322 strbuf_release(&refname
);
1326 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1330 * Mark the top-level directory complete because we
1331 * are about to read the only subdirectory that can
1334 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1336 * Create an incomplete entry for "refs/":
1338 add_entry_to_dir(get_ref_dir(refs
->loose
),
1339 create_dir_entry(refs
, "refs/", 5, 1));
1341 return get_ref_dir(refs
->loose
);
1344 /* We allow "recursive" symbolic refs. Only within reason, though */
1346 #define MAXREFLEN (1024)
1349 * Called by resolve_gitlink_ref_recursive() after it failed to read
1350 * from the loose refs in ref_cache refs. Find <refname> in the
1351 * packed-refs file for the submodule.
1353 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1354 const char *refname
, unsigned char *sha1
)
1356 struct ref_entry
*ref
;
1357 struct ref_dir
*dir
= get_packed_refs(refs
);
1359 ref
= find_ref(dir
, refname
);
1363 hashcpy(sha1
, ref
->u
.value
.sha1
);
1367 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1368 const char *refname
, unsigned char *sha1
,
1372 char buffer
[128], *p
;
1375 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1378 ? git_path_submodule(refs
->name
, "%s", refname
)
1379 : git_path("%s", refname
);
1380 fd
= open(path
, O_RDONLY
);
1382 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1384 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1388 while (len
&& isspace(buffer
[len
-1]))
1392 /* Was it a detached head or an old-fashioned symlink? */
1393 if (!get_sha1_hex(buffer
, sha1
))
1397 if (strncmp(buffer
, "ref:", 4))
1403 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1406 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1408 int len
= strlen(path
), retval
;
1410 struct ref_cache
*refs
;
1412 while (len
&& path
[len
-1] == '/')
1416 submodule
= xstrndup(path
, len
);
1417 refs
= get_ref_cache(submodule
);
1420 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1425 * Return the ref_entry for the given refname from the packed
1426 * references. If it does not exist, return NULL.
1428 static struct ref_entry
*get_packed_ref(const char *refname
)
1430 return find_ref(get_packed_refs(&ref_cache
), refname
);
1434 * A loose ref file doesn't exist; check for a packed ref. The
1435 * options are forwarded from resolve_safe_unsafe().
1437 static int resolve_missing_loose_ref(const char *refname
,
1439 unsigned char *sha1
,
1442 struct ref_entry
*entry
;
1445 * The loose reference file does not exist; check for a packed
1448 entry
= get_packed_ref(refname
);
1450 hashcpy(sha1
, entry
->u
.value
.sha1
);
1452 *flags
|= REF_ISPACKED
;
1455 /* The reference is not a packed reference, either. */
1456 if (resolve_flags
& RESOLVE_REF_READING
) {
1465 /* This function needs to return a meaningful errno on failure */
1466 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1468 int depth
= MAXDEPTH
;
1471 static char refname_buffer
[256];
1477 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1479 *flags
|= REF_BAD_NAME
;
1481 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1482 !refname_is_safe(refname
)) {
1487 * dwim_ref() uses REF_ISBROKEN to distinguish between
1488 * missing refs and refs that were present but invalid,
1489 * to complain about the latter to stderr.
1491 * We don't know whether the ref exists, so don't set
1497 char path
[PATH_MAX
];
1507 git_snpath(path
, sizeof(path
), "%s", refname
);
1510 * We might have to loop back here to avoid a race
1511 * condition: first we lstat() the file, then we try
1512 * to read it as a link or as a file. But if somebody
1513 * changes the type of the file (file <-> directory
1514 * <-> symlink) between the lstat() and reading, then
1515 * we don't want to report that as an error but rather
1516 * try again starting with the lstat().
1519 if (lstat(path
, &st
) < 0) {
1520 if (errno
!= ENOENT
)
1522 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1528 *flags
|= REF_ISBROKEN
;
1533 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1534 if (S_ISLNK(st
.st_mode
)) {
1535 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1537 if (errno
== ENOENT
|| errno
== EINVAL
)
1538 /* inconsistent with lstat; retry */
1544 if (starts_with(buffer
, "refs/") &&
1545 !check_refname_format(buffer
, 0)) {
1546 strcpy(refname_buffer
, buffer
);
1547 refname
= refname_buffer
;
1549 *flags
|= REF_ISSYMREF
;
1550 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1558 /* Is it a directory? */
1559 if (S_ISDIR(st
.st_mode
)) {
1565 * Anything else, just open it and try to use it as
1568 fd
= open(path
, O_RDONLY
);
1570 if (errno
== ENOENT
)
1571 /* inconsistent with lstat; retry */
1576 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1578 int save_errno
= errno
;
1584 while (len
&& isspace(buffer
[len
-1]))
1589 * Is it a symbolic ref?
1591 if (!starts_with(buffer
, "ref:")) {
1593 * Please note that FETCH_HEAD has a second
1594 * line containing other data.
1596 if (get_sha1_hex(buffer
, sha1
) ||
1597 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1599 *flags
|= REF_ISBROKEN
;
1606 *flags
|= REF_ISBROKEN
;
1611 *flags
|= REF_ISSYMREF
;
1613 while (isspace(*buf
))
1615 refname
= strcpy(refname_buffer
, buf
);
1616 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1620 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1622 *flags
|= REF_ISBROKEN
;
1624 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1625 !refname_is_safe(buf
)) {
1634 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1636 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1639 /* The argument to filter_refs */
1641 const char *pattern
;
1646 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1648 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1653 int read_ref(const char *refname
, unsigned char *sha1
)
1655 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1658 int ref_exists(const char *refname
)
1660 unsigned char sha1
[20];
1661 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1664 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1667 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1668 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1670 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1674 /* object was peeled successfully: */
1678 * object cannot be peeled because the named object (or an
1679 * object referred to by a tag in the peel chain), does not
1684 /* object cannot be peeled because it is not a tag: */
1687 /* ref_entry contains no peeled value because it is a symref: */
1688 PEEL_IS_SYMREF
= -3,
1691 * ref_entry cannot be peeled because it is broken (i.e., the
1692 * symbolic reference cannot even be resolved to an object
1699 * Peel the named object; i.e., if the object is a tag, resolve the
1700 * tag recursively until a non-tag is found. If successful, store the
1701 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1702 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1703 * and leave sha1 unchanged.
1705 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1707 struct object
*o
= lookup_unknown_object(name
);
1709 if (o
->type
== OBJ_NONE
) {
1710 int type
= sha1_object_info(name
, NULL
);
1711 if (type
< 0 || !object_as_type(o
, type
, 0))
1712 return PEEL_INVALID
;
1715 if (o
->type
!= OBJ_TAG
)
1716 return PEEL_NON_TAG
;
1718 o
= deref_tag_noverify(o
);
1720 return PEEL_INVALID
;
1722 hashcpy(sha1
, o
->sha1
);
1727 * Peel the entry (if possible) and return its new peel_status. If
1728 * repeel is true, re-peel the entry even if there is an old peeled
1729 * value that is already stored in it.
1731 * It is OK to call this function with a packed reference entry that
1732 * might be stale and might even refer to an object that has since
1733 * been garbage-collected. In such a case, if the entry has
1734 * REF_KNOWS_PEELED then leave the status unchanged and return
1735 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1737 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1739 enum peel_status status
;
1741 if (entry
->flag
& REF_KNOWS_PEELED
) {
1743 entry
->flag
&= ~REF_KNOWS_PEELED
;
1744 hashclr(entry
->u
.value
.peeled
);
1746 return is_null_sha1(entry
->u
.value
.peeled
) ?
1747 PEEL_NON_TAG
: PEEL_PEELED
;
1750 if (entry
->flag
& REF_ISBROKEN
)
1752 if (entry
->flag
& REF_ISSYMREF
)
1753 return PEEL_IS_SYMREF
;
1755 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1756 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1757 entry
->flag
|= REF_KNOWS_PEELED
;
1761 int peel_ref(const char *refname
, unsigned char *sha1
)
1764 unsigned char base
[20];
1766 if (current_ref
&& (current_ref
->name
== refname
1767 || !strcmp(current_ref
->name
, refname
))) {
1768 if (peel_entry(current_ref
, 0))
1770 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1774 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1778 * If the reference is packed, read its ref_entry from the
1779 * cache in the hope that we already know its peeled value.
1780 * We only try this optimization on packed references because
1781 * (a) forcing the filling of the loose reference cache could
1782 * be expensive and (b) loose references anyway usually do not
1783 * have REF_KNOWS_PEELED.
1785 if (flag
& REF_ISPACKED
) {
1786 struct ref_entry
*r
= get_packed_ref(refname
);
1788 if (peel_entry(r
, 0))
1790 hashcpy(sha1
, r
->u
.value
.peeled
);
1795 return peel_object(base
, sha1
);
1798 struct warn_if_dangling_data
{
1800 const char *refname
;
1801 const struct string_list
*refnames
;
1802 const char *msg_fmt
;
1805 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1806 int flags
, void *cb_data
)
1808 struct warn_if_dangling_data
*d
= cb_data
;
1809 const char *resolves_to
;
1810 unsigned char junk
[20];
1812 if (!(flags
& REF_ISSYMREF
))
1815 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1818 ? strcmp(resolves_to
, d
->refname
)
1819 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1823 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1828 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1830 struct warn_if_dangling_data data
;
1833 data
.refname
= refname
;
1834 data
.refnames
= NULL
;
1835 data
.msg_fmt
= msg_fmt
;
1836 for_each_rawref(warn_if_dangling_symref
, &data
);
1839 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1841 struct warn_if_dangling_data data
;
1844 data
.refname
= NULL
;
1845 data
.refnames
= refnames
;
1846 data
.msg_fmt
= msg_fmt
;
1847 for_each_rawref(warn_if_dangling_symref
, &data
);
1851 * Call fn for each reference in the specified ref_cache, omitting
1852 * references not in the containing_dir of base. fn is called for all
1853 * references, including broken ones. If fn ever returns a non-zero
1854 * value, stop the iteration and return that value; otherwise, return
1857 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1858 each_ref_entry_fn fn
, void *cb_data
)
1860 struct packed_ref_cache
*packed_ref_cache
;
1861 struct ref_dir
*loose_dir
;
1862 struct ref_dir
*packed_dir
;
1866 * We must make sure that all loose refs are read before accessing the
1867 * packed-refs file; this avoids a race condition in which loose refs
1868 * are migrated to the packed-refs file by a simultaneous process, but
1869 * our in-memory view is from before the migration. get_packed_ref_cache()
1870 * takes care of making sure our view is up to date with what is on
1873 loose_dir
= get_loose_refs(refs
);
1874 if (base
&& *base
) {
1875 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1878 prime_ref_dir(loose_dir
);
1880 packed_ref_cache
= get_packed_ref_cache(refs
);
1881 acquire_packed_ref_cache(packed_ref_cache
);
1882 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1883 if (base
&& *base
) {
1884 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1887 if (packed_dir
&& loose_dir
) {
1888 sort_ref_dir(packed_dir
);
1889 sort_ref_dir(loose_dir
);
1890 retval
= do_for_each_entry_in_dirs(
1891 packed_dir
, loose_dir
, fn
, cb_data
);
1892 } else if (packed_dir
) {
1893 sort_ref_dir(packed_dir
);
1894 retval
= do_for_each_entry_in_dir(
1895 packed_dir
, 0, fn
, cb_data
);
1896 } else if (loose_dir
) {
1897 sort_ref_dir(loose_dir
);
1898 retval
= do_for_each_entry_in_dir(
1899 loose_dir
, 0, fn
, cb_data
);
1902 release_packed_ref_cache(packed_ref_cache
);
1907 * Call fn for each reference in the specified ref_cache for which the
1908 * refname begins with base. If trim is non-zero, then trim that many
1909 * characters off the beginning of each refname before passing the
1910 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1911 * broken references in the iteration. If fn ever returns a non-zero
1912 * value, stop the iteration and return that value; otherwise, return
1915 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
1916 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1918 struct ref_entry_cb data
;
1923 data
.cb_data
= cb_data
;
1925 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
1928 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1930 unsigned char sha1
[20];
1934 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
1935 return fn("HEAD", sha1
, 0, cb_data
);
1940 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
1941 return fn("HEAD", sha1
, flag
, cb_data
);
1946 int head_ref(each_ref_fn fn
, void *cb_data
)
1948 return do_head_ref(NULL
, fn
, cb_data
);
1951 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1953 return do_head_ref(submodule
, fn
, cb_data
);
1956 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1958 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
1961 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1963 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
1966 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1968 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
1971 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
1972 each_ref_fn fn
, void *cb_data
)
1974 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
1977 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
1979 return for_each_ref_in("refs/tags/", fn
, cb_data
);
1982 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1984 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
1987 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
1989 return for_each_ref_in("refs/heads/", fn
, cb_data
);
1992 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1994 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
1997 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
1999 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2002 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2004 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2007 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2009 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2012 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2014 struct strbuf buf
= STRBUF_INIT
;
2016 unsigned char sha1
[20];
2019 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2020 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2021 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2022 strbuf_release(&buf
);
2027 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2029 struct strbuf buf
= STRBUF_INIT
;
2031 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2032 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2033 strbuf_release(&buf
);
2037 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2038 const char *prefix
, void *cb_data
)
2040 struct strbuf real_pattern
= STRBUF_INIT
;
2041 struct ref_filter filter
;
2044 if (!prefix
&& !starts_with(pattern
, "refs/"))
2045 strbuf_addstr(&real_pattern
, "refs/");
2047 strbuf_addstr(&real_pattern
, prefix
);
2048 strbuf_addstr(&real_pattern
, pattern
);
2050 if (!has_glob_specials(pattern
)) {
2051 /* Append implied '/' '*' if not present. */
2052 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2053 strbuf_addch(&real_pattern
, '/');
2054 /* No need to check for '*', there is none. */
2055 strbuf_addch(&real_pattern
, '*');
2058 filter
.pattern
= real_pattern
.buf
;
2060 filter
.cb_data
= cb_data
;
2061 ret
= for_each_ref(filter_refs
, &filter
);
2063 strbuf_release(&real_pattern
);
2067 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2069 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2072 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2074 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2075 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2078 const char *prettify_refname(const char *name
)
2081 starts_with(name
, "refs/heads/") ? 11 :
2082 starts_with(name
, "refs/tags/") ? 10 :
2083 starts_with(name
, "refs/remotes/") ? 13 :
2087 static const char *ref_rev_parse_rules
[] = {
2092 "refs/remotes/%.*s",
2093 "refs/remotes/%.*s/HEAD",
2097 int refname_match(const char *abbrev_name
, const char *full_name
)
2100 const int abbrev_name_len
= strlen(abbrev_name
);
2102 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2103 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2111 static void unlock_ref(struct ref_lock
*lock
)
2113 /* Do not free lock->lk -- atexit() still looks at them */
2115 rollback_lock_file(lock
->lk
);
2116 free(lock
->ref_name
);
2117 free(lock
->orig_ref_name
);
2121 /* This function should make sure errno is meaningful on error */
2122 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2123 const unsigned char *old_sha1
, int mustexist
)
2125 if (read_ref_full(lock
->ref_name
,
2126 mustexist
? RESOLVE_REF_READING
: 0,
2127 lock
->old_sha1
, NULL
)) {
2128 int save_errno
= errno
;
2129 error("Can't verify ref %s", lock
->ref_name
);
2134 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2135 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2136 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2144 static int remove_empty_directories(const char *file
)
2146 /* we want to create a file but there is a directory there;
2147 * if that is an empty directory (or a directory that contains
2148 * only empty directories), remove them.
2151 int result
, save_errno
;
2153 strbuf_init(&path
, 20);
2154 strbuf_addstr(&path
, file
);
2156 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2159 strbuf_release(&path
);
2166 * *string and *len will only be substituted, and *string returned (for
2167 * later free()ing) if the string passed in is a magic short-hand form
2170 static char *substitute_branch_name(const char **string
, int *len
)
2172 struct strbuf buf
= STRBUF_INIT
;
2173 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2177 *string
= strbuf_detach(&buf
, &size
);
2179 return (char *)*string
;
2185 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2187 char *last_branch
= substitute_branch_name(&str
, &len
);
2192 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2193 char fullref
[PATH_MAX
];
2194 unsigned char sha1_from_ref
[20];
2195 unsigned char *this_result
;
2198 this_result
= refs_found
? sha1_from_ref
: sha1
;
2199 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2200 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2201 this_result
, &flag
);
2205 if (!warn_ambiguous_refs
)
2207 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2208 warning("ignoring dangling symref %s.", fullref
);
2209 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2210 warning("ignoring broken ref %s.", fullref
);
2217 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2219 char *last_branch
= substitute_branch_name(&str
, &len
);
2224 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2225 unsigned char hash
[20];
2226 char path
[PATH_MAX
];
2227 const char *ref
, *it
;
2229 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2230 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2234 if (reflog_exists(path
))
2236 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2240 if (!logs_found
++) {
2242 hashcpy(sha1
, hash
);
2244 if (!warn_ambiguous_refs
)
2252 * Locks a ref returning the lock on success and NULL on failure.
2253 * On failure errno is set to something meaningful.
2255 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2256 const unsigned char *old_sha1
,
2257 const struct string_list
*skip
,
2258 int flags
, int *type_p
)
2261 const char *orig_refname
= refname
;
2262 struct ref_lock
*lock
;
2265 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2266 int resolve_flags
= 0;
2268 int attempts_remaining
= 3;
2270 lock
= xcalloc(1, sizeof(struct ref_lock
));
2274 resolve_flags
|= RESOLVE_REF_READING
;
2275 if (flags
& REF_DELETING
) {
2276 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2277 if (flags
& REF_NODEREF
)
2278 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2281 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2282 lock
->old_sha1
, &type
);
2283 if (!refname
&& errno
== EISDIR
) {
2284 /* we are trying to lock foo but we used to
2285 * have foo/bar which now does not exist;
2286 * it is normal for the empty directory 'foo'
2289 ref_file
= git_path("%s", orig_refname
);
2290 if (remove_empty_directories(ref_file
)) {
2292 error("there are still refs under '%s'", orig_refname
);
2295 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2296 lock
->old_sha1
, &type
);
2302 error("unable to resolve reference %s: %s",
2303 orig_refname
, strerror(errno
));
2306 missing
= is_null_sha1(lock
->old_sha1
);
2307 /* When the ref did not exist and we are creating it,
2308 * make sure there is no existing ref that is packed
2309 * whose name begins with our refname, nor a ref whose
2310 * name is a proper prefix of our refname.
2313 !is_refname_available(refname
, skip
, get_packed_refs(&ref_cache
))) {
2314 last_errno
= ENOTDIR
;
2318 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2321 if (flags
& REF_NODEREF
) {
2322 refname
= orig_refname
;
2323 lflags
|= LOCK_NO_DEREF
;
2325 lock
->ref_name
= xstrdup(refname
);
2326 lock
->orig_ref_name
= xstrdup(orig_refname
);
2327 ref_file
= git_path("%s", refname
);
2329 lock
->force_write
= 1;
2330 if ((flags
& REF_NODEREF
) && (type
& REF_ISSYMREF
))
2331 lock
->force_write
= 1;
2334 switch (safe_create_leading_directories(ref_file
)) {
2336 break; /* success */
2338 if (--attempts_remaining
> 0)
2343 error("unable to create directory for %s", ref_file
);
2347 lock
->lock_fd
= hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
);
2348 if (lock
->lock_fd
< 0) {
2350 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2352 * Maybe somebody just deleted one of the
2353 * directories leading to ref_file. Try
2358 struct strbuf err
= STRBUF_INIT
;
2359 unable_to_lock_message(ref_file
, errno
, &err
);
2360 error("%s", err
.buf
);
2361 strbuf_release(&err
);
2365 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2374 * Write an entry to the packed-refs file for the specified refname.
2375 * If peeled is non-NULL, write it as the entry's peeled value.
2377 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2378 unsigned char *peeled
)
2380 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2382 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2386 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2388 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2390 enum peel_status peel_status
= peel_entry(entry
, 0);
2392 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2393 error("internal error: %s is not a valid packed reference!",
2395 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2396 peel_status
== PEEL_PEELED
?
2397 entry
->u
.value
.peeled
: NULL
);
2401 /* This should return a meaningful errno on failure */
2402 int lock_packed_refs(int flags
)
2404 struct packed_ref_cache
*packed_ref_cache
;
2406 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2409 * Get the current packed-refs while holding the lock. If the
2410 * packed-refs file has been modified since we last read it,
2411 * this will automatically invalidate the cache and re-read
2412 * the packed-refs file.
2414 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2415 packed_ref_cache
->lock
= &packlock
;
2416 /* Increment the reference count to prevent it from being freed: */
2417 acquire_packed_ref_cache(packed_ref_cache
);
2422 * Commit the packed refs changes.
2423 * On error we must make sure that errno contains a meaningful value.
2425 int commit_packed_refs(void)
2427 struct packed_ref_cache
*packed_ref_cache
=
2428 get_packed_ref_cache(&ref_cache
);
2433 if (!packed_ref_cache
->lock
)
2434 die("internal error: packed-refs not locked");
2436 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2438 die_errno("unable to fdopen packed-refs descriptor");
2440 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2441 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2442 0, write_packed_entry_fn
, out
);
2444 if (commit_lock_file(packed_ref_cache
->lock
)) {
2448 packed_ref_cache
->lock
= NULL
;
2449 release_packed_ref_cache(packed_ref_cache
);
2454 void rollback_packed_refs(void)
2456 struct packed_ref_cache
*packed_ref_cache
=
2457 get_packed_ref_cache(&ref_cache
);
2459 if (!packed_ref_cache
->lock
)
2460 die("internal error: packed-refs not locked");
2461 rollback_lock_file(packed_ref_cache
->lock
);
2462 packed_ref_cache
->lock
= NULL
;
2463 release_packed_ref_cache(packed_ref_cache
);
2464 clear_packed_ref_cache(&ref_cache
);
2467 struct ref_to_prune
{
2468 struct ref_to_prune
*next
;
2469 unsigned char sha1
[20];
2470 char name
[FLEX_ARRAY
];
2473 struct pack_refs_cb_data
{
2475 struct ref_dir
*packed_refs
;
2476 struct ref_to_prune
*ref_to_prune
;
2480 * An each_ref_entry_fn that is run over loose references only. If
2481 * the loose reference can be packed, add an entry in the packed ref
2482 * cache. If the reference should be pruned, also add it to
2483 * ref_to_prune in the pack_refs_cb_data.
2485 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2487 struct pack_refs_cb_data
*cb
= cb_data
;
2488 enum peel_status peel_status
;
2489 struct ref_entry
*packed_entry
;
2490 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2492 /* ALWAYS pack tags */
2493 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2496 /* Do not pack symbolic or broken refs: */
2497 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2500 /* Add a packed ref cache entry equivalent to the loose entry. */
2501 peel_status
= peel_entry(entry
, 1);
2502 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2503 die("internal error peeling reference %s (%s)",
2504 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2505 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2507 /* Overwrite existing packed entry with info from loose entry */
2508 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2509 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2511 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2512 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2513 add_ref(cb
->packed_refs
, packed_entry
);
2515 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2517 /* Schedule the loose reference for pruning if requested. */
2518 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2519 int namelen
= strlen(entry
->name
) + 1;
2520 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2521 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2522 strcpy(n
->name
, entry
->name
);
2523 n
->next
= cb
->ref_to_prune
;
2524 cb
->ref_to_prune
= n
;
2530 * Remove empty parents, but spare refs/ and immediate subdirs.
2531 * Note: munges *name.
2533 static void try_remove_empty_parents(char *name
)
2538 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2539 while (*p
&& *p
!= '/')
2541 /* tolerate duplicate slashes; see check_refname_format() */
2545 for (q
= p
; *q
; q
++)
2548 while (q
> p
&& *q
!= '/')
2550 while (q
> p
&& *(q
-1) == '/')
2555 if (rmdir(git_path("%s", name
)))
2560 /* make sure nobody touched the ref, and unlink */
2561 static void prune_ref(struct ref_to_prune
*r
)
2563 struct ref_transaction
*transaction
;
2564 struct strbuf err
= STRBUF_INIT
;
2566 if (check_refname_format(r
->name
, 0))
2569 transaction
= ref_transaction_begin(&err
);
2571 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2572 REF_ISPRUNING
, 1, NULL
, &err
) ||
2573 ref_transaction_commit(transaction
, &err
)) {
2574 ref_transaction_free(transaction
);
2575 error("%s", err
.buf
);
2576 strbuf_release(&err
);
2579 ref_transaction_free(transaction
);
2580 strbuf_release(&err
);
2581 try_remove_empty_parents(r
->name
);
2584 static void prune_refs(struct ref_to_prune
*r
)
2592 int pack_refs(unsigned int flags
)
2594 struct pack_refs_cb_data cbdata
;
2596 memset(&cbdata
, 0, sizeof(cbdata
));
2597 cbdata
.flags
= flags
;
2599 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2600 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2602 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2603 pack_if_possible_fn
, &cbdata
);
2605 if (commit_packed_refs())
2606 die_errno("unable to overwrite old ref-pack file");
2608 prune_refs(cbdata
.ref_to_prune
);
2613 * If entry is no longer needed in packed-refs, add it to the string
2614 * list pointed to by cb_data. Reasons for deleting entries:
2616 * - Entry is broken.
2617 * - Entry is overridden by a loose ref.
2618 * - Entry does not point at a valid object.
2620 * In the first and third cases, also emit an error message because these
2621 * are indications of repository corruption.
2623 static int curate_packed_ref_fn(struct ref_entry
*entry
, void *cb_data
)
2625 struct string_list
*refs_to_delete
= cb_data
;
2627 if (entry
->flag
& REF_ISBROKEN
) {
2628 /* This shouldn't happen to packed refs. */
2629 error("%s is broken!", entry
->name
);
2630 string_list_append(refs_to_delete
, entry
->name
);
2633 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
2634 unsigned char sha1
[20];
2637 if (read_ref_full(entry
->name
, 0, sha1
, &flags
))
2638 /* We should at least have found the packed ref. */
2639 die("Internal error");
2640 if ((flags
& REF_ISSYMREF
) || !(flags
& REF_ISPACKED
)) {
2642 * This packed reference is overridden by a
2643 * loose reference, so it is OK that its value
2644 * is no longer valid; for example, it might
2645 * refer to an object that has been garbage
2646 * collected. For this purpose we don't even
2647 * care whether the loose reference itself is
2648 * invalid, broken, symbolic, etc. Silently
2649 * remove the packed reference.
2651 string_list_append(refs_to_delete
, entry
->name
);
2655 * There is no overriding loose reference, so the fact
2656 * that this reference doesn't refer to a valid object
2657 * indicates some kind of repository corruption.
2658 * Report the problem, then omit the reference from
2661 error("%s does not point to a valid object!", entry
->name
);
2662 string_list_append(refs_to_delete
, entry
->name
);
2669 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2671 struct ref_dir
*packed
;
2672 struct string_list refs_to_delete
= STRING_LIST_INIT_DUP
;
2673 struct string_list_item
*refname
, *ref_to_delete
;
2674 int ret
, needs_repacking
= 0, removed
= 0;
2678 /* Look for a packed ref */
2679 for_each_string_list_item(refname
, refnames
) {
2680 if (get_packed_ref(refname
->string
)) {
2681 needs_repacking
= 1;
2686 /* Avoid locking if we have nothing to do */
2687 if (!needs_repacking
)
2688 return 0; /* no refname exists in packed refs */
2690 if (lock_packed_refs(0)) {
2691 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2694 packed
= get_packed_refs(&ref_cache
);
2696 /* Remove refnames from the cache */
2697 for_each_string_list_item(refname
, refnames
)
2698 if (remove_entry(packed
, refname
->string
) != -1)
2702 * All packed entries disappeared while we were
2703 * acquiring the lock.
2705 rollback_packed_refs();
2709 /* Remove any other accumulated cruft */
2710 do_for_each_entry_in_dir(packed
, 0, curate_packed_ref_fn
, &refs_to_delete
);
2711 for_each_string_list_item(ref_to_delete
, &refs_to_delete
) {
2712 if (remove_entry(packed
, ref_to_delete
->string
) == -1)
2713 die("internal error");
2716 /* Write what remains */
2717 ret
= commit_packed_refs();
2719 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2724 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2728 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2730 * loose. The loose file name is the same as the
2731 * lockfile name, minus ".lock":
2733 char *loose_filename
= get_locked_file_path(lock
->lk
);
2734 int res
= unlink_or_msg(loose_filename
, err
);
2735 free(loose_filename
);
2742 int delete_ref(const char *refname
, const unsigned char *sha1
, int delopt
)
2744 struct ref_transaction
*transaction
;
2745 struct strbuf err
= STRBUF_INIT
;
2747 transaction
= ref_transaction_begin(&err
);
2749 ref_transaction_delete(transaction
, refname
, sha1
, delopt
,
2750 sha1
&& !is_null_sha1(sha1
), NULL
, &err
) ||
2751 ref_transaction_commit(transaction
, &err
)) {
2752 error("%s", err
.buf
);
2753 ref_transaction_free(transaction
);
2754 strbuf_release(&err
);
2757 ref_transaction_free(transaction
);
2758 strbuf_release(&err
);
2763 * People using contrib's git-new-workdir have .git/logs/refs ->
2764 * /some/other/path/.git/logs/refs, and that may live on another device.
2766 * IOW, to avoid cross device rename errors, the temporary renamed log must
2767 * live into logs/refs.
2769 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2771 static int rename_tmp_log(const char *newrefname
)
2773 int attempts_remaining
= 4;
2776 switch (safe_create_leading_directories(git_path("logs/%s", newrefname
))) {
2778 break; /* success */
2780 if (--attempts_remaining
> 0)
2784 error("unable to create directory for %s", newrefname
);
2788 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2789 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2791 * rename(a, b) when b is an existing
2792 * directory ought to result in ISDIR, but
2793 * Solaris 5.8 gives ENOTDIR. Sheesh.
2795 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2796 error("Directory not empty: logs/%s", newrefname
);
2800 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2802 * Maybe another process just deleted one of
2803 * the directories in the path to newrefname.
2804 * Try again from the beginning.
2808 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2809 newrefname
, strerror(errno
));
2816 static int rename_ref_available(const char *oldname
, const char *newname
)
2818 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2821 string_list_insert(&skip
, oldname
);
2822 ret
= is_refname_available(newname
, &skip
, get_packed_refs(&ref_cache
))
2823 && is_refname_available(newname
, &skip
, get_loose_refs(&ref_cache
));
2824 string_list_clear(&skip
, 0);
2828 static int write_ref_sha1(struct ref_lock
*lock
, const unsigned char *sha1
,
2829 const char *logmsg
);
2831 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2833 unsigned char sha1
[20], orig_sha1
[20];
2834 int flag
= 0, logmoved
= 0;
2835 struct ref_lock
*lock
;
2836 struct stat loginfo
;
2837 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2838 const char *symref
= NULL
;
2840 if (log
&& S_ISLNK(loginfo
.st_mode
))
2841 return error("reflog for %s is a symlink", oldrefname
);
2843 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2845 if (flag
& REF_ISSYMREF
)
2846 return error("refname %s is a symbolic ref, renaming it is not supported",
2849 return error("refname %s not found", oldrefname
);
2851 if (!rename_ref_available(oldrefname
, newrefname
))
2854 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2855 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2856 oldrefname
, strerror(errno
));
2858 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2859 error("unable to delete old %s", oldrefname
);
2863 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2864 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2865 if (errno
==EISDIR
) {
2866 if (remove_empty_directories(git_path("%s", newrefname
))) {
2867 error("Directory not empty: %s", newrefname
);
2871 error("unable to delete existing %s", newrefname
);
2876 if (log
&& rename_tmp_log(newrefname
))
2881 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, 0, NULL
);
2883 error("unable to lock %s for update", newrefname
);
2886 lock
->force_write
= 1;
2887 hashcpy(lock
->old_sha1
, orig_sha1
);
2888 if (write_ref_sha1(lock
, orig_sha1
, logmsg
)) {
2889 error("unable to write current sha1 into %s", newrefname
);
2896 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, 0, NULL
);
2898 error("unable to lock %s for rollback", oldrefname
);
2902 lock
->force_write
= 1;
2903 flag
= log_all_ref_updates
;
2904 log_all_ref_updates
= 0;
2905 if (write_ref_sha1(lock
, orig_sha1
, NULL
))
2906 error("unable to write current sha1 into %s", oldrefname
);
2907 log_all_ref_updates
= flag
;
2910 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2911 error("unable to restore logfile %s from %s: %s",
2912 oldrefname
, newrefname
, strerror(errno
));
2913 if (!logmoved
&& log
&&
2914 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2915 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2916 oldrefname
, strerror(errno
));
2921 static int close_ref(struct ref_lock
*lock
)
2923 if (close_lock_file(lock
->lk
))
2929 static int commit_ref(struct ref_lock
*lock
)
2931 if (commit_lock_file(lock
->lk
))
2938 * copy the reflog message msg to buf, which has been allocated sufficiently
2939 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2940 * because reflog file is one line per entry.
2942 static int copy_msg(char *buf
, const char *msg
)
2949 while ((c
= *msg
++)) {
2950 if (wasspace
&& isspace(c
))
2952 wasspace
= isspace(c
);
2957 while (buf
< cp
&& isspace(cp
[-1]))
2963 /* This function must set a meaningful errno on failure */
2964 int log_ref_setup(const char *refname
, char *logfile
, int bufsize
)
2966 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2968 git_snpath(logfile
, bufsize
, "logs/%s", refname
);
2969 if (log_all_ref_updates
&&
2970 (starts_with(refname
, "refs/heads/") ||
2971 starts_with(refname
, "refs/remotes/") ||
2972 starts_with(refname
, "refs/notes/") ||
2973 !strcmp(refname
, "HEAD"))) {
2974 if (safe_create_leading_directories(logfile
) < 0) {
2975 int save_errno
= errno
;
2976 error("unable to create directory for %s", logfile
);
2983 logfd
= open(logfile
, oflags
, 0666);
2985 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
2988 if (errno
== EISDIR
) {
2989 if (remove_empty_directories(logfile
)) {
2990 int save_errno
= errno
;
2991 error("There are still logs under '%s'",
2996 logfd
= open(logfile
, oflags
, 0666);
3000 int save_errno
= errno
;
3001 error("Unable to append to %s: %s", logfile
,
3008 adjust_shared_perm(logfile
);
3013 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3014 const unsigned char *new_sha1
,
3015 const char *committer
, const char *msg
)
3017 int msglen
, written
;
3018 unsigned maxlen
, len
;
3021 msglen
= msg
? strlen(msg
) : 0;
3022 maxlen
= strlen(committer
) + msglen
+ 100;
3023 logrec
= xmalloc(maxlen
);
3024 len
= sprintf(logrec
, "%s %s %s\n",
3025 sha1_to_hex(old_sha1
),
3026 sha1_to_hex(new_sha1
),
3029 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3031 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3039 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3040 const unsigned char *new_sha1
, const char *msg
)
3042 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3043 char log_file
[PATH_MAX
];
3045 if (log_all_ref_updates
< 0)
3046 log_all_ref_updates
= !is_bare_repository();
3048 result
= log_ref_setup(refname
, log_file
, sizeof(log_file
));
3052 logfd
= open(log_file
, oflags
);
3055 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3056 git_committer_info(0), msg
);
3058 int save_errno
= errno
;
3060 error("Unable to append to %s", log_file
);
3065 int save_errno
= errno
;
3066 error("Unable to append to %s", log_file
);
3073 int is_branch(const char *refname
)
3075 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3079 * Write sha1 into the ref specified by the lock. Make sure that errno
3082 static int write_ref_sha1(struct ref_lock
*lock
,
3083 const unsigned char *sha1
, const char *logmsg
)
3085 static char term
= '\n';
3092 if (!lock
->force_write
&& !hashcmp(lock
->old_sha1
, sha1
)) {
3096 o
= parse_object(sha1
);
3098 error("Trying to write ref %s with nonexistent object %s",
3099 lock
->ref_name
, sha1_to_hex(sha1
));
3104 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3105 error("Trying to write non-commit object %s to branch %s",
3106 sha1_to_hex(sha1
), lock
->ref_name
);
3111 if (write_in_full(lock
->lock_fd
, sha1_to_hex(sha1
), 40) != 40 ||
3112 write_in_full(lock
->lock_fd
, &term
, 1) != 1 ||
3113 close_ref(lock
) < 0) {
3114 int save_errno
= errno
;
3115 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3120 clear_loose_ref_cache(&ref_cache
);
3121 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3122 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3123 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3127 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3129 * Special hack: If a branch is updated directly and HEAD
3130 * points to it (may happen on the remote side of a push
3131 * for example) then logically the HEAD reflog should be
3133 * A generic solution implies reverse symref information,
3134 * but finding all symrefs pointing to the given branch
3135 * would be rather costly for this rare event (the direct
3136 * update of a branch) to be worth it. So let's cheat and
3137 * check with HEAD only which should cover 99% of all usage
3138 * scenarios (even 100% of the default ones).
3140 unsigned char head_sha1
[20];
3142 const char *head_ref
;
3143 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3144 head_sha1
, &head_flag
);
3145 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3146 !strcmp(head_ref
, lock
->ref_name
))
3147 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3149 if (commit_ref(lock
)) {
3150 error("Couldn't set %s", lock
->ref_name
);
3158 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3161 const char *lockpath
;
3163 int fd
, len
, written
;
3164 char *git_HEAD
= git_pathdup("%s", ref_target
);
3165 unsigned char old_sha1
[20], new_sha1
[20];
3167 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3170 if (safe_create_leading_directories(git_HEAD
) < 0)
3171 return error("unable to create directory for %s", git_HEAD
);
3173 #ifndef NO_SYMLINK_HEAD
3174 if (prefer_symlink_refs
) {
3176 if (!symlink(refs_heads_master
, git_HEAD
))
3178 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3182 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3183 if (sizeof(ref
) <= len
) {
3184 error("refname too long: %s", refs_heads_master
);
3185 goto error_free_return
;
3187 lockpath
= mkpath("%s.lock", git_HEAD
);
3188 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3190 error("Unable to open %s for writing", lockpath
);
3191 goto error_free_return
;
3193 written
= write_in_full(fd
, ref
, len
);
3194 if (close(fd
) != 0 || written
!= len
) {
3195 error("Unable to write to %s", lockpath
);
3196 goto error_unlink_return
;
3198 if (rename(lockpath
, git_HEAD
) < 0) {
3199 error("Unable to create %s", git_HEAD
);
3200 goto error_unlink_return
;
3202 if (adjust_shared_perm(git_HEAD
)) {
3203 error("Unable to fix permissions on %s", lockpath
);
3204 error_unlink_return
:
3205 unlink_or_warn(lockpath
);
3211 #ifndef NO_SYMLINK_HEAD
3214 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3215 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3221 struct read_ref_at_cb
{
3222 const char *refname
;
3223 unsigned long at_time
;
3226 unsigned char *sha1
;
3229 unsigned char osha1
[20];
3230 unsigned char nsha1
[20];
3234 unsigned long *cutoff_time
;
3239 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3240 const char *email
, unsigned long timestamp
, int tz
,
3241 const char *message
, void *cb_data
)
3243 struct read_ref_at_cb
*cb
= cb_data
;
3247 cb
->date
= timestamp
;
3249 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3251 *cb
->msg
= xstrdup(message
);
3252 if (cb
->cutoff_time
)
3253 *cb
->cutoff_time
= timestamp
;
3255 *cb
->cutoff_tz
= tz
;
3257 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3259 * we have not yet updated cb->[n|o]sha1 so they still
3260 * hold the values for the previous record.
3262 if (!is_null_sha1(cb
->osha1
)) {
3263 hashcpy(cb
->sha1
, nsha1
);
3264 if (hashcmp(cb
->osha1
, nsha1
))
3265 warning("Log for ref %s has gap after %s.",
3266 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3268 else if (cb
->date
== cb
->at_time
)
3269 hashcpy(cb
->sha1
, nsha1
);
3270 else if (hashcmp(nsha1
, cb
->sha1
))
3271 warning("Log for ref %s unexpectedly ended on %s.",
3272 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3274 hashcpy(cb
->osha1
, osha1
);
3275 hashcpy(cb
->nsha1
, nsha1
);
3279 hashcpy(cb
->osha1
, osha1
);
3280 hashcpy(cb
->nsha1
, nsha1
);
3286 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3287 const char *email
, unsigned long timestamp
,
3288 int tz
, const char *message
, void *cb_data
)
3290 struct read_ref_at_cb
*cb
= cb_data
;
3293 *cb
->msg
= xstrdup(message
);
3294 if (cb
->cutoff_time
)
3295 *cb
->cutoff_time
= timestamp
;
3297 *cb
->cutoff_tz
= tz
;
3299 *cb
->cutoff_cnt
= cb
->reccnt
;
3300 hashcpy(cb
->sha1
, osha1
);
3301 if (is_null_sha1(cb
->sha1
))
3302 hashcpy(cb
->sha1
, nsha1
);
3303 /* We just want the first entry */
3307 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3308 unsigned char *sha1
, char **msg
,
3309 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3311 struct read_ref_at_cb cb
;
3313 memset(&cb
, 0, sizeof(cb
));
3314 cb
.refname
= refname
;
3315 cb
.at_time
= at_time
;
3318 cb
.cutoff_time
= cutoff_time
;
3319 cb
.cutoff_tz
= cutoff_tz
;
3320 cb
.cutoff_cnt
= cutoff_cnt
;
3323 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3326 if (flags
& GET_SHA1_QUIETLY
)
3329 die("Log for %s is empty.", refname
);
3334 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3339 int reflog_exists(const char *refname
)
3343 return !lstat(git_path("logs/%s", refname
), &st
) &&
3344 S_ISREG(st
.st_mode
);
3347 int delete_reflog(const char *refname
)
3349 return remove_path(git_path("logs/%s", refname
));
3352 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3354 unsigned char osha1
[20], nsha1
[20];
3355 char *email_end
, *message
;
3356 unsigned long timestamp
;
3359 /* old SP new SP name <email> SP time TAB msg LF */
3360 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3361 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3362 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3363 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3364 email_end
[1] != ' ' ||
3365 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3366 !message
|| message
[0] != ' ' ||
3367 (message
[1] != '+' && message
[1] != '-') ||
3368 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3369 !isdigit(message
[4]) || !isdigit(message
[5]))
3370 return 0; /* corrupt? */
3371 email_end
[1] = '\0';
3372 tz
= strtol(message
+ 1, NULL
, 10);
3373 if (message
[6] != '\t')
3377 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3380 static char *find_beginning_of_line(char *bob
, char *scan
)
3382 while (bob
< scan
&& *(--scan
) != '\n')
3383 ; /* keep scanning backwards */
3385 * Return either beginning of the buffer, or LF at the end of
3386 * the previous line.
3391 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3393 struct strbuf sb
= STRBUF_INIT
;
3396 int ret
= 0, at_tail
= 1;
3398 logfp
= fopen(git_path("logs/%s", refname
), "r");
3402 /* Jump to the end */
3403 if (fseek(logfp
, 0, SEEK_END
) < 0)
3404 return error("cannot seek back reflog for %s: %s",
3405 refname
, strerror(errno
));
3407 while (!ret
&& 0 < pos
) {
3413 /* Fill next block from the end */
3414 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3415 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3416 return error("cannot seek back reflog for %s: %s",
3417 refname
, strerror(errno
));
3418 nread
= fread(buf
, cnt
, 1, logfp
);
3420 return error("cannot read %d bytes from reflog for %s: %s",
3421 cnt
, refname
, strerror(errno
));
3424 scanp
= endp
= buf
+ cnt
;
3425 if (at_tail
&& scanp
[-1] == '\n')
3426 /* Looking at the final LF at the end of the file */
3430 while (buf
< scanp
) {
3432 * terminating LF of the previous line, or the beginning
3437 bp
= find_beginning_of_line(buf
, scanp
);
3441 * The newline is the end of the previous line,
3442 * so we know we have complete line starting
3443 * at (bp + 1). Prefix it onto any prior data
3444 * we collected for the line and process it.
3446 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3449 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3455 * We are at the start of the buffer, and the
3456 * start of the file; there is no previous
3457 * line, and we have everything for this one.
3458 * Process it, and we can end the loop.
3460 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3461 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3468 * We are at the start of the buffer, and there
3469 * is more file to read backwards. Which means
3470 * we are in the middle of a line. Note that we
3471 * may get here even if *bp was a newline; that
3472 * just means we are at the exact end of the
3473 * previous line, rather than some spot in the
3476 * Save away what we have to be combined with
3477 * the data from the next read.
3479 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3486 die("BUG: reverse reflog parser had leftover data");
3489 strbuf_release(&sb
);
3493 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3496 struct strbuf sb
= STRBUF_INIT
;
3499 logfp
= fopen(git_path("logs/%s", refname
), "r");
3503 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3504 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3506 strbuf_release(&sb
);
3510 * Call fn for each reflog in the namespace indicated by name. name
3511 * must be empty or end with '/'. Name will be used as a scratch
3512 * space, but its contents will be restored before return.
3514 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3516 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3519 int oldlen
= name
->len
;
3522 return name
->len
? errno
: 0;
3524 while ((de
= readdir(d
)) != NULL
) {
3527 if (de
->d_name
[0] == '.')
3529 if (ends_with(de
->d_name
, ".lock"))
3531 strbuf_addstr(name
, de
->d_name
);
3532 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3533 ; /* silently ignore */
3535 if (S_ISDIR(st
.st_mode
)) {
3536 strbuf_addch(name
, '/');
3537 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3539 unsigned char sha1
[20];
3540 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3541 retval
= error("bad ref for %s", name
->buf
);
3543 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3548 strbuf_setlen(name
, oldlen
);
3554 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3558 strbuf_init(&name
, PATH_MAX
);
3559 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3560 strbuf_release(&name
);
3565 * Information needed for a single ref update. Set new_sha1 to the
3566 * new value or to zero to delete the ref. To check the old value
3567 * while locking the ref, set have_old to 1 and set old_sha1 to the
3568 * value or to zero to ensure the ref does not exist before update.
3571 unsigned char new_sha1
[20];
3572 unsigned char old_sha1
[20];
3573 int flags
; /* REF_NODEREF? */
3574 int have_old
; /* 1 if old_sha1 is valid, 0 otherwise */
3575 struct ref_lock
*lock
;
3578 const char refname
[FLEX_ARRAY
];
3582 * Transaction states.
3583 * OPEN: The transaction is in a valid state and can accept new updates.
3584 * An OPEN transaction can be committed.
3585 * CLOSED: A closed transaction is no longer active and no other operations
3586 * than free can be used on it in this state.
3587 * A transaction can either become closed by successfully committing
3588 * an active transaction or if there is a failure while building
3589 * the transaction thus rendering it failed/inactive.
3591 enum ref_transaction_state
{
3592 REF_TRANSACTION_OPEN
= 0,
3593 REF_TRANSACTION_CLOSED
= 1
3597 * Data structure for holding a reference transaction, which can
3598 * consist of checks and updates to multiple references, carried out
3599 * as atomically as possible. This structure is opaque to callers.
3601 struct ref_transaction
{
3602 struct ref_update
**updates
;
3605 enum ref_transaction_state state
;
3608 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3612 return xcalloc(1, sizeof(struct ref_transaction
));
3615 void ref_transaction_free(struct ref_transaction
*transaction
)
3622 for (i
= 0; i
< transaction
->nr
; i
++) {
3623 free(transaction
->updates
[i
]->msg
);
3624 free(transaction
->updates
[i
]);
3626 free(transaction
->updates
);
3630 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3631 const char *refname
)
3633 size_t len
= strlen(refname
);
3634 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3636 strcpy((char *)update
->refname
, refname
);
3637 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3638 transaction
->updates
[transaction
->nr
++] = update
;
3642 int ref_transaction_update(struct ref_transaction
*transaction
,
3643 const char *refname
,
3644 const unsigned char *new_sha1
,
3645 const unsigned char *old_sha1
,
3646 int flags
, int have_old
, const char *msg
,
3649 struct ref_update
*update
;
3653 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3654 die("BUG: update called for transaction that is not open");
3656 if (have_old
&& !old_sha1
)
3657 die("BUG: have_old is true but old_sha1 is NULL");
3659 if (!is_null_sha1(new_sha1
) &&
3660 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3661 strbuf_addf(err
, "refusing to update ref with bad name %s",
3666 update
= add_update(transaction
, refname
);
3667 hashcpy(update
->new_sha1
, new_sha1
);
3668 update
->flags
= flags
;
3669 update
->have_old
= have_old
;
3671 hashcpy(update
->old_sha1
, old_sha1
);
3673 update
->msg
= xstrdup(msg
);
3677 int ref_transaction_create(struct ref_transaction
*transaction
,
3678 const char *refname
,
3679 const unsigned char *new_sha1
,
3680 int flags
, const char *msg
,
3683 return ref_transaction_update(transaction
, refname
, new_sha1
,
3684 null_sha1
, flags
, 1, msg
, err
);
3687 int ref_transaction_delete(struct ref_transaction
*transaction
,
3688 const char *refname
,
3689 const unsigned char *old_sha1
,
3690 int flags
, int have_old
, const char *msg
,
3693 return ref_transaction_update(transaction
, refname
, null_sha1
,
3694 old_sha1
, flags
, have_old
, msg
, err
);
3697 int update_ref(const char *action
, const char *refname
,
3698 const unsigned char *sha1
, const unsigned char *oldval
,
3699 int flags
, enum action_on_err onerr
)
3701 struct ref_transaction
*t
;
3702 struct strbuf err
= STRBUF_INIT
;
3704 t
= ref_transaction_begin(&err
);
3706 ref_transaction_update(t
, refname
, sha1
, oldval
, flags
,
3707 !!oldval
, action
, &err
) ||
3708 ref_transaction_commit(t
, &err
)) {
3709 const char *str
= "update_ref failed for ref '%s': %s";
3711 ref_transaction_free(t
);
3713 case UPDATE_REFS_MSG_ON_ERR
:
3714 error(str
, refname
, err
.buf
);
3716 case UPDATE_REFS_DIE_ON_ERR
:
3717 die(str
, refname
, err
.buf
);
3719 case UPDATE_REFS_QUIET_ON_ERR
:
3722 strbuf_release(&err
);
3725 strbuf_release(&err
);
3726 ref_transaction_free(t
);
3730 static int ref_update_compare(const void *r1
, const void *r2
)
3732 const struct ref_update
* const *u1
= r1
;
3733 const struct ref_update
* const *u2
= r2
;
3734 return strcmp((*u1
)->refname
, (*u2
)->refname
);
3737 static int ref_update_reject_duplicates(struct ref_update
**updates
, int n
,
3744 for (i
= 1; i
< n
; i
++)
3745 if (!strcmp(updates
[i
- 1]->refname
, updates
[i
]->refname
)) {
3747 "Multiple updates for ref '%s' not allowed.",
3748 updates
[i
]->refname
);
3754 int ref_transaction_commit(struct ref_transaction
*transaction
,
3758 int n
= transaction
->nr
;
3759 struct ref_update
**updates
= transaction
->updates
;
3760 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3761 struct string_list_item
*ref_to_delete
;
3765 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3766 die("BUG: commit called for transaction that is not open");
3769 transaction
->state
= REF_TRANSACTION_CLOSED
;
3773 /* Copy, sort, and reject duplicate refs */
3774 qsort(updates
, n
, sizeof(*updates
), ref_update_compare
);
3775 if (ref_update_reject_duplicates(updates
, n
, err
)) {
3776 ret
= TRANSACTION_GENERIC_ERROR
;
3780 /* Acquire all locks while verifying old values */
3781 for (i
= 0; i
< n
; i
++) {
3782 struct ref_update
*update
= updates
[i
];
3783 int flags
= update
->flags
;
3785 if (is_null_sha1(update
->new_sha1
))
3786 flags
|= REF_DELETING
;
3787 update
->lock
= lock_ref_sha1_basic(update
->refname
,
3794 if (!update
->lock
) {
3795 ret
= (errno
== ENOTDIR
)
3796 ? TRANSACTION_NAME_CONFLICT
3797 : TRANSACTION_GENERIC_ERROR
;
3798 strbuf_addf(err
, "Cannot lock the ref '%s'.",
3804 /* Perform updates first so live commits remain referenced */
3805 for (i
= 0; i
< n
; i
++) {
3806 struct ref_update
*update
= updates
[i
];
3808 if (!is_null_sha1(update
->new_sha1
)) {
3809 if (write_ref_sha1(update
->lock
, update
->new_sha1
,
3811 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3812 strbuf_addf(err
, "Cannot update the ref '%s'.",
3814 ret
= TRANSACTION_GENERIC_ERROR
;
3817 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3821 /* Perform deletes now that updates are safely completed */
3822 for (i
= 0; i
< n
; i
++) {
3823 struct ref_update
*update
= updates
[i
];
3826 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3827 ret
= TRANSACTION_GENERIC_ERROR
;
3831 if (!(update
->flags
& REF_ISPRUNING
))
3832 string_list_append(&refs_to_delete
,
3833 update
->lock
->ref_name
);
3837 if (repack_without_refs(&refs_to_delete
, err
)) {
3838 ret
= TRANSACTION_GENERIC_ERROR
;
3841 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3842 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3843 clear_loose_ref_cache(&ref_cache
);
3846 transaction
->state
= REF_TRANSACTION_CLOSED
;
3848 for (i
= 0; i
< n
; i
++)
3849 if (updates
[i
]->lock
)
3850 unlock_ref(updates
[i
]->lock
);
3851 string_list_clear(&refs_to_delete
, 0);
3855 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3858 static char **scanf_fmts
;
3859 static int nr_rules
;
3864 * Pre-generate scanf formats from ref_rev_parse_rules[].
3865 * Generate a format suitable for scanf from a
3866 * ref_rev_parse_rules rule by interpolating "%s" at the
3867 * location of the "%.*s".
3869 size_t total_len
= 0;
3872 /* the rule list is NULL terminated, count them first */
3873 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3874 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3875 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3877 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3880 for (i
= 0; i
< nr_rules
; i
++) {
3881 assert(offset
< total_len
);
3882 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
3883 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
3884 ref_rev_parse_rules
[i
], 2, "%s") + 1;
3888 /* bail out if there are no rules */
3890 return xstrdup(refname
);
3892 /* buffer for scanf result, at most refname must fit */
3893 short_name
= xstrdup(refname
);
3895 /* skip first rule, it will always match */
3896 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
3898 int rules_to_fail
= i
;
3901 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
3904 short_name_len
= strlen(short_name
);
3907 * in strict mode, all (except the matched one) rules
3908 * must fail to resolve to a valid non-ambiguous ref
3911 rules_to_fail
= nr_rules
;
3914 * check if the short name resolves to a valid ref,
3915 * but use only rules prior to the matched one
3917 for (j
= 0; j
< rules_to_fail
; j
++) {
3918 const char *rule
= ref_rev_parse_rules
[j
];
3919 char refname
[PATH_MAX
];
3921 /* skip matched rule */
3926 * the short name is ambiguous, if it resolves
3927 * (with this previous rule) to a valid ref
3928 * read_ref() returns 0 on success
3930 mksnpath(refname
, sizeof(refname
),
3931 rule
, short_name_len
, short_name
);
3932 if (ref_exists(refname
))
3937 * short name is non-ambiguous if all previous rules
3938 * haven't resolved to a valid ref
3940 if (j
== rules_to_fail
)
3945 return xstrdup(refname
);
3948 static struct string_list
*hide_refs
;
3950 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
3952 if (!strcmp("transfer.hiderefs", var
) ||
3953 /* NEEDSWORK: use parse_config_key() once both are merged */
3954 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
3955 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
3960 return config_error_nonbool(var
);
3961 ref
= xstrdup(value
);
3963 while (len
&& ref
[len
- 1] == '/')
3966 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
3967 hide_refs
->strdup_strings
= 1;
3969 string_list_append(hide_refs
, ref
);
3974 int ref_is_hidden(const char *refname
)
3976 struct string_list_item
*item
;
3980 for_each_string_list_item(item
, hide_refs
) {
3982 if (!starts_with(refname
, item
->string
))
3984 len
= strlen(item
->string
);
3985 if (!refname
[len
] || refname
[len
] == '/')
3991 struct expire_reflog_cb
{
3993 reflog_expiry_should_prune_fn
*should_prune_fn
;
3996 unsigned char last_kept_sha1
[20];
3999 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4000 const char *email
, unsigned long timestamp
, int tz
,
4001 const char *message
, void *cb_data
)
4003 struct expire_reflog_cb
*cb
= cb_data
;
4004 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4006 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4007 osha1
= cb
->last_kept_sha1
;
4009 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4010 message
, policy_cb
)) {
4012 printf("would prune %s", message
);
4013 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4014 printf("prune %s", message
);
4017 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4018 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4019 email
, timestamp
, tz
, message
);
4020 hashcpy(cb
->last_kept_sha1
, nsha1
);
4022 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4023 printf("keep %s", message
);
4028 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4030 reflog_expiry_prepare_fn prepare_fn
,
4031 reflog_expiry_should_prune_fn should_prune_fn
,
4032 reflog_expiry_cleanup_fn cleanup_fn
,
4033 void *policy_cb_data
)
4035 static struct lock_file reflog_lock
;
4036 struct expire_reflog_cb cb
;
4037 struct ref_lock
*lock
;
4041 memset(&cb
, 0, sizeof(cb
));
4043 cb
.policy_cb
= policy_cb_data
;
4044 cb
.should_prune_fn
= should_prune_fn
;
4047 * The reflog file is locked by holding the lock on the
4048 * reference itself, plus we might need to update the
4049 * reference if --updateref was specified:
4051 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, 0, NULL
);
4053 return error("cannot lock ref '%s'", refname
);
4054 if (!reflog_exists(refname
)) {
4059 log_file
= git_pathdup("logs/%s", refname
);
4060 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4062 * Even though holding $GIT_DIR/logs/$reflog.lock has
4063 * no locking implications, we use the lock_file
4064 * machinery here anyway because it does a lot of the
4065 * work we need, including cleaning up if the program
4066 * exits unexpectedly.
4068 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4069 struct strbuf err
= STRBUF_INIT
;
4070 unable_to_lock_message(log_file
, errno
, &err
);
4071 error("%s", err
.buf
);
4072 strbuf_release(&err
);
4075 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4077 error("cannot fdopen %s (%s)",
4078 reflog_lock
.filename
.buf
, strerror(errno
));
4083 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4084 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4085 (*cleanup_fn
)(cb
.policy_cb
);
4087 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4088 if (close_lock_file(&reflog_lock
)) {
4089 status
|= error("couldn't write %s: %s", log_file
,
4091 } else if ((flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4092 (write_in_full(lock
->lock_fd
,
4093 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4094 write_str_in_full(lock
->lock_fd
, "\n") != 1 ||
4095 close_ref(lock
) < 0)) {
4096 status
|= error("couldn't write %s",
4097 lock
->lk
->filename
.buf
);
4098 rollback_lock_file(&reflog_lock
);
4099 } else if (commit_lock_file(&reflog_lock
)) {
4100 status
|= error("unable to commit reflog '%s' (%s)",
4101 log_file
, strerror(errno
));
4102 } else if ((flags
& EXPIRE_REFLOGS_UPDATE_REF
) && commit_ref(lock
)) {
4103 status
|= error("couldn't set %s", lock
->ref_name
);
4111 rollback_lock_file(&reflog_lock
);