7 #include "string-list.h"
13 unsigned char old_sha1
[20];
17 * How to handle various characters in refnames:
18 * 0: An acceptable character for refs
20 * 2: ., look for a preceding . to reject .. in refs
21 * 3: {, look for a preceding @ to reject @{ in refs
22 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
24 static unsigned char refname_disposition
[256] = {
25 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
26 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
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, 3, 0, 0, 4, 4
36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
37 * refs (i.e., because the reference is about to be deleted anyway).
39 #define REF_DELETING 0x02
42 * Used as a flag in ref_update::flags when a loose ref is being
45 #define REF_ISPRUNING 0x04
48 * Used as a flag in ref_update::flags when the reference should be
49 * updated to new_sha1.
51 #define REF_HAVE_NEW 0x08
54 * Used as a flag in ref_update::flags when old_sha1 should be
57 #define REF_HAVE_OLD 0x10
60 * Try to read one refname component from the front of refname.
61 * Return the length of the component found, or -1 if the component is
62 * not legal. It is legal if it is something reasonable to have under
63 * ".git/refs/"; We do not like it if:
65 * - any path component of it begins with ".", or
66 * - it has double dots "..", or
67 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
68 * - it ends with a "/".
69 * - it ends with ".lock"
70 * - it contains a "\" (backslash)
72 static int check_refname_component(const char *refname
, int flags
)
77 for (cp
= refname
; ; cp
++) {
79 unsigned char disp
= refname_disposition
[ch
];
85 return -1; /* Refname contains "..". */
89 return -1; /* Refname contains "@{". */
98 return 0; /* Component has zero length. */
99 if (refname
[0] == '.')
100 return -1; /* Component starts with '.'. */
101 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
102 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
103 return -1; /* Refname ends with ".lock". */
107 int check_refname_format(const char *refname
, int flags
)
109 int component_len
, component_count
= 0;
111 if (!strcmp(refname
, "@"))
112 /* Refname is a single character '@'. */
116 /* We are at the start of a path component. */
117 component_len
= check_refname_component(refname
, flags
);
118 if (component_len
<= 0) {
119 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
121 (refname
[1] == '\0' || refname
[1] == '/')) {
122 /* Accept one wildcard as a full refname component. */
123 flags
&= ~REFNAME_REFSPEC_PATTERN
;
130 if (refname
[component_len
] == '\0')
132 /* Skip to next component. */
133 refname
+= component_len
+ 1;
136 if (refname
[component_len
- 1] == '.')
137 return -1; /* Refname ends with '.'. */
138 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
139 return -1; /* Refname has only one component. */
146 * Information used (along with the information in ref_entry) to
147 * describe a single cached reference. This data structure only
148 * occurs embedded in a union in struct ref_entry, and only when
149 * (ref_entry->flag & REF_DIR) is zero.
153 * The name of the object to which this reference resolves
154 * (which may be a tag object). If REF_ISBROKEN, this is
155 * null. If REF_ISSYMREF, then this is the name of the object
156 * referred to by the last reference in the symlink chain.
158 unsigned char sha1
[20];
161 * If REF_KNOWS_PEELED, then this field holds the peeled value
162 * of this reference, or null if the reference is known not to
163 * be peelable. See the documentation for peel_ref() for an
164 * exact definition of "peelable".
166 unsigned char peeled
[20];
172 * Information used (along with the information in ref_entry) to
173 * describe a level in the hierarchy of references. This data
174 * structure only occurs embedded in a union in struct ref_entry, and
175 * only when (ref_entry.flag & REF_DIR) is set. In that case,
176 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
177 * in the directory have already been read:
179 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
180 * or packed references, already read.
182 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
183 * references that hasn't been read yet (nor has any of its
186 * Entries within a directory are stored within a growable array of
187 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
188 * sorted are sorted by their component name in strcmp() order and the
189 * remaining entries are unsorted.
191 * Loose references are read lazily, one directory at a time. When a
192 * directory of loose references is read, then all of the references
193 * in that directory are stored, and REF_INCOMPLETE stubs are created
194 * for any subdirectories, but the subdirectories themselves are not
195 * read. The reading is triggered by get_ref_dir().
201 * Entries with index 0 <= i < sorted are sorted by name. New
202 * entries are appended to the list unsorted, and are sorted
203 * only when required; thus we avoid the need to sort the list
204 * after the addition of every reference.
208 /* A pointer to the ref_cache that contains this ref_dir. */
209 struct ref_cache
*ref_cache
;
211 struct ref_entry
**entries
;
215 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
216 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
217 * public values; see refs.h.
221 * The field ref_entry->u.value.peeled of this value entry contains
222 * the correct peeled value for the reference, which might be
223 * null_sha1 if the reference is not a tag or if it is broken.
225 #define REF_KNOWS_PEELED 0x10
227 /* ref_entry represents a directory of references */
231 * Entry has not yet been read from disk (used only for REF_DIR
232 * entries representing loose references)
234 #define REF_INCOMPLETE 0x40
237 * A ref_entry represents either a reference or a "subdirectory" of
240 * Each directory in the reference namespace is represented by a
241 * ref_entry with (flags & REF_DIR) set and containing a subdir member
242 * that holds the entries in that directory that have been read so
243 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
244 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
245 * used for loose reference directories.
247 * References are represented by a ref_entry with (flags & REF_DIR)
248 * unset and a value member that describes the reference's value. The
249 * flag member is at the ref_entry level, but it is also needed to
250 * interpret the contents of the value field (in other words, a
251 * ref_value object is not very much use without the enclosing
254 * Reference names cannot end with slash and directories' names are
255 * always stored with a trailing slash (except for the top-level
256 * directory, which is always denoted by ""). This has two nice
257 * consequences: (1) when the entries in each subdir are sorted
258 * lexicographically by name (as they usually are), the references in
259 * a whole tree can be generated in lexicographic order by traversing
260 * the tree in left-to-right, depth-first order; (2) the names of
261 * references and subdirectories cannot conflict, and therefore the
262 * presence of an empty subdirectory does not block the creation of a
263 * similarly-named reference. (The fact that reference names with the
264 * same leading components can conflict *with each other* is a
265 * separate issue that is regulated by is_refname_available().)
267 * Please note that the name field contains the fully-qualified
268 * reference (or subdirectory) name. Space could be saved by only
269 * storing the relative names. But that would require the full names
270 * to be generated on the fly when iterating in do_for_each_ref(), and
271 * would break callback functions, who have always been able to assume
272 * that the name strings that they are passed will not be freed during
276 unsigned char flag
; /* ISSYMREF? ISPACKED? */
278 struct ref_value value
; /* if not (flags&REF_DIR) */
279 struct ref_dir subdir
; /* if (flags&REF_DIR) */
282 * The full name of the reference (e.g., "refs/heads/master")
283 * or the full name of the directory with a trailing slash
284 * (e.g., "refs/heads/"):
286 char name
[FLEX_ARRAY
];
289 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
291 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
294 assert(entry
->flag
& REF_DIR
);
295 dir
= &entry
->u
.subdir
;
296 if (entry
->flag
& REF_INCOMPLETE
) {
297 read_loose_refs(entry
->name
, dir
);
298 entry
->flag
&= ~REF_INCOMPLETE
;
304 * Check if a refname is safe.
305 * For refs that start with "refs/" we consider it safe as long they do
306 * not try to resolve to outside of refs/.
308 * For all other refs we only consider them safe iff they only contain
309 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
312 static int refname_is_safe(const char *refname
)
314 if (starts_with(refname
, "refs/")) {
318 buf
= xmalloc(strlen(refname
) + 1);
320 * Does the refname try to escape refs/?
321 * For example: refs/foo/../bar is safe but refs/foo/../../bar
324 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
329 if (!isupper(*refname
) && *refname
!= '_')
336 static struct ref_entry
*create_ref_entry(const char *refname
,
337 const unsigned char *sha1
, int flag
,
341 struct ref_entry
*ref
;
344 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
345 die("Reference has invalid format: '%s'", refname
);
346 len
= strlen(refname
) + 1;
347 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
348 hashcpy(ref
->u
.value
.sha1
, sha1
);
349 hashclr(ref
->u
.value
.peeled
);
350 memcpy(ref
->name
, refname
, len
);
355 static void clear_ref_dir(struct ref_dir
*dir
);
357 static void free_ref_entry(struct ref_entry
*entry
)
359 if (entry
->flag
& REF_DIR
) {
361 * Do not use get_ref_dir() here, as that might
362 * trigger the reading of loose refs.
364 clear_ref_dir(&entry
->u
.subdir
);
370 * Add a ref_entry to the end of dir (unsorted). Entry is always
371 * stored directly in dir; no recursion into subdirectories is
374 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
376 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
377 dir
->entries
[dir
->nr
++] = entry
;
378 /* optimize for the case that entries are added in order */
380 (dir
->nr
== dir
->sorted
+ 1 &&
381 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
382 dir
->entries
[dir
->nr
- 1]->name
) < 0))
383 dir
->sorted
= dir
->nr
;
387 * Clear and free all entries in dir, recursively.
389 static void clear_ref_dir(struct ref_dir
*dir
)
392 for (i
= 0; i
< dir
->nr
; i
++)
393 free_ref_entry(dir
->entries
[i
]);
395 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
400 * Create a struct ref_entry object for the specified dirname.
401 * dirname is the name of the directory with a trailing slash (e.g.,
402 * "refs/heads/") or "" for the top-level directory.
404 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
405 const char *dirname
, size_t len
,
408 struct ref_entry
*direntry
;
409 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
410 memcpy(direntry
->name
, dirname
, len
);
411 direntry
->name
[len
] = '\0';
412 direntry
->u
.subdir
.ref_cache
= ref_cache
;
413 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
417 static int ref_entry_cmp(const void *a
, const void *b
)
419 struct ref_entry
*one
= *(struct ref_entry
**)a
;
420 struct ref_entry
*two
= *(struct ref_entry
**)b
;
421 return strcmp(one
->name
, two
->name
);
424 static void sort_ref_dir(struct ref_dir
*dir
);
426 struct string_slice
{
431 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
433 const struct string_slice
*key
= key_
;
434 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
435 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
438 return '\0' - (unsigned char)ent
->name
[key
->len
];
442 * Return the index of the entry with the given refname from the
443 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
444 * no such entry is found. dir must already be complete.
446 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
448 struct ref_entry
**r
;
449 struct string_slice key
;
451 if (refname
== NULL
|| !dir
->nr
)
457 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
458 ref_entry_cmp_sslice
);
463 return r
- dir
->entries
;
467 * Search for a directory entry directly within dir (without
468 * recursing). Sort dir if necessary. subdirname must be a directory
469 * name (i.e., end in '/'). If mkdir is set, then create the
470 * directory if it is missing; otherwise, return NULL if the desired
471 * directory cannot be found. dir must already be complete.
473 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
474 const char *subdirname
, size_t len
,
477 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
478 struct ref_entry
*entry
;
479 if (entry_index
== -1) {
483 * Since dir is complete, the absence of a subdir
484 * means that the subdir really doesn't exist;
485 * therefore, create an empty record for it but mark
486 * the record complete.
488 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
489 add_entry_to_dir(dir
, entry
);
491 entry
= dir
->entries
[entry_index
];
493 return get_ref_dir(entry
);
497 * If refname is a reference name, find the ref_dir within the dir
498 * tree that should hold refname. If refname is a directory name
499 * (i.e., ends in '/'), then return that ref_dir itself. dir must
500 * represent the top-level directory and must already be complete.
501 * Sort ref_dirs and recurse into subdirectories as necessary. If
502 * mkdir is set, then create any missing directories; otherwise,
503 * return NULL if the desired directory cannot be found.
505 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
506 const char *refname
, int mkdir
)
509 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
510 size_t dirnamelen
= slash
- refname
+ 1;
511 struct ref_dir
*subdir
;
512 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
524 * Find the value entry with the given name in dir, sorting ref_dirs
525 * and recursing into subdirectories as necessary. If the name is not
526 * found or it corresponds to a directory entry, return NULL.
528 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
531 struct ref_entry
*entry
;
532 dir
= find_containing_dir(dir
, refname
, 0);
535 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
536 if (entry_index
== -1)
538 entry
= dir
->entries
[entry_index
];
539 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
543 * Remove the entry with the given name from dir, recursing into
544 * subdirectories as necessary. If refname is the name of a directory
545 * (i.e., ends with '/'), then remove the directory and its contents.
546 * If the removal was successful, return the number of entries
547 * remaining in the directory entry that contained the deleted entry.
548 * If the name was not found, return -1. Please note that this
549 * function only deletes the entry from the cache; it does not delete
550 * it from the filesystem or ensure that other cache entries (which
551 * might be symbolic references to the removed entry) are updated.
552 * Nor does it remove any containing dir entries that might be made
553 * empty by the removal. dir must represent the top-level directory
554 * and must already be complete.
556 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
558 int refname_len
= strlen(refname
);
560 struct ref_entry
*entry
;
561 int is_dir
= refname
[refname_len
- 1] == '/';
564 * refname represents a reference directory. Remove
565 * the trailing slash; otherwise we will get the
566 * directory *representing* refname rather than the
567 * one *containing* it.
569 char *dirname
= xmemdupz(refname
, refname_len
- 1);
570 dir
= find_containing_dir(dir
, dirname
, 0);
573 dir
= find_containing_dir(dir
, refname
, 0);
577 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
578 if (entry_index
== -1)
580 entry
= dir
->entries
[entry_index
];
582 memmove(&dir
->entries
[entry_index
],
583 &dir
->entries
[entry_index
+ 1],
584 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
587 if (dir
->sorted
> entry_index
)
589 free_ref_entry(entry
);
594 * Add a ref_entry to the ref_dir (unsorted), recursing into
595 * subdirectories as necessary. dir must represent the top-level
596 * directory. Return 0 on success.
598 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
600 dir
= find_containing_dir(dir
, ref
->name
, 1);
603 add_entry_to_dir(dir
, ref
);
608 * Emit a warning and return true iff ref1 and ref2 have the same name
609 * and the same sha1. Die if they have the same name but different
612 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
614 if (strcmp(ref1
->name
, ref2
->name
))
617 /* Duplicate name; make sure that they don't conflict: */
619 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
620 /* This is impossible by construction */
621 die("Reference directory conflict: %s", ref1
->name
);
623 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
624 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
626 warning("Duplicated ref: %s", ref1
->name
);
631 * Sort the entries in dir non-recursively (if they are not already
632 * sorted) and remove any duplicate entries.
634 static void sort_ref_dir(struct ref_dir
*dir
)
637 struct ref_entry
*last
= NULL
;
640 * This check also prevents passing a zero-length array to qsort(),
641 * which is a problem on some platforms.
643 if (dir
->sorted
== dir
->nr
)
646 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
648 /* Remove any duplicates: */
649 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
650 struct ref_entry
*entry
= dir
->entries
[j
];
651 if (last
&& is_dup_ref(last
, entry
))
652 free_ref_entry(entry
);
654 last
= dir
->entries
[i
++] = entry
;
656 dir
->sorted
= dir
->nr
= i
;
659 /* Include broken references in a do_for_each_ref*() iteration: */
660 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
663 * Return true iff the reference described by entry can be resolved to
664 * an object in the database. Emit a warning if the referred-to
665 * object does not exist.
667 static int ref_resolves_to_object(struct ref_entry
*entry
)
669 if (entry
->flag
& REF_ISBROKEN
)
671 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
672 error("%s does not point to a valid object!", entry
->name
);
679 * current_ref is a performance hack: when iterating over references
680 * using the for_each_ref*() functions, current_ref is set to the
681 * current reference's entry before calling the callback function. If
682 * the callback function calls peel_ref(), then peel_ref() first
683 * checks whether the reference to be peeled is the current reference
684 * (it usually is) and if so, returns that reference's peeled version
685 * if it is available. This avoids a refname lookup in a common case.
687 static struct ref_entry
*current_ref
;
689 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
691 struct ref_entry_cb
{
700 * Handle one reference in a do_for_each_ref*()-style iteration,
701 * calling an each_ref_fn for each entry.
703 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
705 struct ref_entry_cb
*data
= cb_data
;
706 struct ref_entry
*old_current_ref
;
709 if (!starts_with(entry
->name
, data
->base
))
712 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
713 !ref_resolves_to_object(entry
))
716 /* Store the old value, in case this is a recursive call: */
717 old_current_ref
= current_ref
;
719 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
720 entry
->flag
, data
->cb_data
);
721 current_ref
= old_current_ref
;
726 * Call fn for each reference in dir that has index in the range
727 * offset <= index < dir->nr. Recurse into subdirectories that are in
728 * that index range, sorting them before iterating. This function
729 * does not sort dir itself; it should be sorted beforehand. fn is
730 * called for all references, including broken ones.
732 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
733 each_ref_entry_fn fn
, void *cb_data
)
736 assert(dir
->sorted
== dir
->nr
);
737 for (i
= offset
; i
< dir
->nr
; i
++) {
738 struct ref_entry
*entry
= dir
->entries
[i
];
740 if (entry
->flag
& REF_DIR
) {
741 struct ref_dir
*subdir
= get_ref_dir(entry
);
742 sort_ref_dir(subdir
);
743 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
745 retval
= fn(entry
, cb_data
);
754 * Call fn for each reference in the union of dir1 and dir2, in order
755 * by refname. Recurse into subdirectories. If a value entry appears
756 * in both dir1 and dir2, then only process the version that is in
757 * dir2. The input dirs must already be sorted, but subdirs will be
758 * sorted as needed. fn is called for all references, including
761 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
762 struct ref_dir
*dir2
,
763 each_ref_entry_fn fn
, void *cb_data
)
768 assert(dir1
->sorted
== dir1
->nr
);
769 assert(dir2
->sorted
== dir2
->nr
);
771 struct ref_entry
*e1
, *e2
;
773 if (i1
== dir1
->nr
) {
774 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
776 if (i2
== dir2
->nr
) {
777 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
779 e1
= dir1
->entries
[i1
];
780 e2
= dir2
->entries
[i2
];
781 cmp
= strcmp(e1
->name
, e2
->name
);
783 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
784 /* Both are directories; descend them in parallel. */
785 struct ref_dir
*subdir1
= get_ref_dir(e1
);
786 struct ref_dir
*subdir2
= get_ref_dir(e2
);
787 sort_ref_dir(subdir1
);
788 sort_ref_dir(subdir2
);
789 retval
= do_for_each_entry_in_dirs(
790 subdir1
, subdir2
, fn
, cb_data
);
793 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
794 /* Both are references; ignore the one from dir1. */
795 retval
= fn(e2
, cb_data
);
799 die("conflict between reference and directory: %s",
811 if (e
->flag
& REF_DIR
) {
812 struct ref_dir
*subdir
= get_ref_dir(e
);
813 sort_ref_dir(subdir
);
814 retval
= do_for_each_entry_in_dir(
815 subdir
, 0, fn
, cb_data
);
817 retval
= fn(e
, cb_data
);
826 * Load all of the refs from the dir into our in-memory cache. The hard work
827 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
828 * through all of the sub-directories. We do not even need to care about
829 * sorting, as traversal order does not matter to us.
831 static void prime_ref_dir(struct ref_dir
*dir
)
834 for (i
= 0; i
< dir
->nr
; i
++) {
835 struct ref_entry
*entry
= dir
->entries
[i
];
836 if (entry
->flag
& REF_DIR
)
837 prime_ref_dir(get_ref_dir(entry
));
841 static int entry_matches(struct ref_entry
*entry
, const struct string_list
*list
)
843 return list
&& string_list_has_string(list
, entry
->name
);
846 struct nonmatching_ref_data
{
847 const struct string_list
*skip
;
848 struct ref_entry
*found
;
851 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
853 struct nonmatching_ref_data
*data
= vdata
;
855 if (entry_matches(entry
, data
->skip
))
862 static void report_refname_conflict(struct ref_entry
*entry
,
865 error("'%s' exists; cannot create '%s'", entry
->name
, refname
);
869 * Return true iff a reference named refname could be created without
870 * conflicting with the name of an existing reference in dir. If
871 * skip is non-NULL, ignore potential conflicts with refs in skip
872 * (e.g., because they are scheduled for deletion in the same
875 * Two reference names conflict if one of them exactly matches the
876 * leading components of the other; e.g., "foo/bar" conflicts with
877 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
880 * skip must be sorted.
882 static int is_refname_available(const char *refname
,
883 const struct string_list
*skip
,
891 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
893 * We are still at a leading dir of the refname; we are
894 * looking for a conflict with a leaf entry.
896 * If we find one, we still must make sure it is
899 pos
= search_ref_dir(dir
, refname
, slash
- refname
);
901 struct ref_entry
*entry
= dir
->entries
[pos
];
902 if (entry_matches(entry
, skip
))
904 report_refname_conflict(entry
, refname
);
910 * Otherwise, we can try to continue our search with
911 * the next component; if we come up empty, we know
912 * there is nothing under this whole prefix.
914 pos
= search_ref_dir(dir
, refname
, slash
+ 1 - refname
);
918 dir
= get_ref_dir(dir
->entries
[pos
]);
922 * We are at the leaf of our refname; we want to
923 * make sure there are no directories which match it.
925 len
= strlen(refname
);
926 dirname
= xmallocz(len
+ 1);
927 sprintf(dirname
, "%s/", refname
);
928 pos
= search_ref_dir(dir
, dirname
, len
+ 1);
933 * We found a directory named "refname". It is a
934 * problem iff it contains any ref that is not
937 struct ref_entry
*entry
= dir
->entries
[pos
];
938 struct ref_dir
*dir
= get_ref_dir(entry
);
939 struct nonmatching_ref_data data
;
943 if (!do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
))
946 report_refname_conflict(data
.found
, refname
);
951 * There is no point in searching for another leaf
952 * node which matches it; such an entry would be the
953 * ref we are looking for, not a conflict.
958 struct packed_ref_cache
{
959 struct ref_entry
*root
;
962 * Count of references to the data structure in this instance,
963 * including the pointer from ref_cache::packed if any. The
964 * data will not be freed as long as the reference count is
967 unsigned int referrers
;
970 * Iff the packed-refs file associated with this instance is
971 * currently locked for writing, this points at the associated
972 * lock (which is owned by somebody else). The referrer count
973 * is also incremented when the file is locked and decremented
974 * when it is unlocked.
976 struct lock_file
*lock
;
978 /* The metadata from when this packed-refs cache was read */
979 struct stat_validity validity
;
983 * Future: need to be in "struct repository"
984 * when doing a full libification.
986 static struct ref_cache
{
987 struct ref_cache
*next
;
988 struct ref_entry
*loose
;
989 struct packed_ref_cache
*packed
;
991 * The submodule name, or "" for the main repo. We allocate
992 * length 1 rather than FLEX_ARRAY so that the main ref_cache
993 * is initialized correctly.
996 } ref_cache
, *submodule_ref_caches
;
998 /* Lock used for the main packed-refs file: */
999 static struct lock_file packlock
;
1002 * Increment the reference count of *packed_refs.
1004 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1006 packed_refs
->referrers
++;
1010 * Decrease the reference count of *packed_refs. If it goes to zero,
1011 * free *packed_refs and return true; otherwise return false.
1013 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1015 if (!--packed_refs
->referrers
) {
1016 free_ref_entry(packed_refs
->root
);
1017 stat_validity_clear(&packed_refs
->validity
);
1025 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1028 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1030 if (packed_refs
->lock
)
1031 die("internal error: packed-ref cache cleared while locked");
1032 refs
->packed
= NULL
;
1033 release_packed_ref_cache(packed_refs
);
1037 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1040 free_ref_entry(refs
->loose
);
1045 static struct ref_cache
*create_ref_cache(const char *submodule
)
1048 struct ref_cache
*refs
;
1051 len
= strlen(submodule
) + 1;
1052 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1053 memcpy(refs
->name
, submodule
, len
);
1058 * Return a pointer to a ref_cache for the specified submodule. For
1059 * the main repository, use submodule==NULL. The returned structure
1060 * will be allocated and initialized but not necessarily populated; it
1061 * should not be freed.
1063 static struct ref_cache
*get_ref_cache(const char *submodule
)
1065 struct ref_cache
*refs
;
1067 if (!submodule
|| !*submodule
)
1070 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1071 if (!strcmp(submodule
, refs
->name
))
1074 refs
= create_ref_cache(submodule
);
1075 refs
->next
= submodule_ref_caches
;
1076 submodule_ref_caches
= refs
;
1080 /* The length of a peeled reference line in packed-refs, including EOL: */
1081 #define PEELED_LINE_LENGTH 42
1084 * The packed-refs header line that we write out. Perhaps other
1085 * traits will be added later. The trailing space is required.
1087 static const char PACKED_REFS_HEADER
[] =
1088 "# pack-refs with: peeled fully-peeled \n";
1091 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1092 * Return a pointer to the refname within the line (null-terminated),
1093 * or NULL if there was a problem.
1095 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1100 * 42: the answer to everything.
1102 * In this case, it happens to be the answer to
1103 * 40 (length of sha1 hex representation)
1104 * +1 (space in between hex and name)
1105 * +1 (newline at the end of the line)
1107 if (line
->len
<= 42)
1110 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1112 if (!isspace(line
->buf
[40]))
1115 ref
= line
->buf
+ 41;
1119 if (line
->buf
[line
->len
- 1] != '\n')
1121 line
->buf
[--line
->len
] = 0;
1127 * Read f, which is a packed-refs file, into dir.
1129 * A comment line of the form "# pack-refs with: " may contain zero or
1130 * more traits. We interpret the traits as follows:
1134 * Probably no references are peeled. But if the file contains a
1135 * peeled value for a reference, we will use it.
1139 * References under "refs/tags/", if they *can* be peeled, *are*
1140 * peeled in this file. References outside of "refs/tags/" are
1141 * probably not peeled even if they could have been, but if we find
1142 * a peeled value for such a reference we will use it.
1146 * All references in the file that can be peeled are peeled.
1147 * Inversely (and this is more important), any references in the
1148 * file for which no peeled value is recorded is not peelable. This
1149 * trait should typically be written alongside "peeled" for
1150 * compatibility with older clients, but we do not require it
1151 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1153 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1155 struct ref_entry
*last
= NULL
;
1156 struct strbuf line
= STRBUF_INIT
;
1157 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1159 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1160 unsigned char sha1
[20];
1161 const char *refname
;
1164 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1165 if (strstr(traits
, " fully-peeled "))
1166 peeled
= PEELED_FULLY
;
1167 else if (strstr(traits
, " peeled "))
1168 peeled
= PEELED_TAGS
;
1169 /* perhaps other traits later as well */
1173 refname
= parse_ref_line(&line
, sha1
);
1175 int flag
= REF_ISPACKED
;
1177 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1178 if (!refname_is_safe(refname
))
1179 die("packed refname is dangerous: %s", refname
);
1181 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1183 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1184 if (peeled
== PEELED_FULLY
||
1185 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1186 last
->flag
|= REF_KNOWS_PEELED
;
1191 line
.buf
[0] == '^' &&
1192 line
.len
== PEELED_LINE_LENGTH
&&
1193 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1194 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1195 hashcpy(last
->u
.value
.peeled
, sha1
);
1197 * Regardless of what the file header said,
1198 * we definitely know the value of *this*
1201 last
->flag
|= REF_KNOWS_PEELED
;
1205 strbuf_release(&line
);
1209 * Get the packed_ref_cache for the specified ref_cache, creating it
1212 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1214 const char *packed_refs_file
;
1217 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1219 packed_refs_file
= git_path("packed-refs");
1222 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1223 clear_packed_ref_cache(refs
);
1225 if (!refs
->packed
) {
1228 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1229 acquire_packed_ref_cache(refs
->packed
);
1230 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1231 f
= fopen(packed_refs_file
, "r");
1233 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1234 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1238 return refs
->packed
;
1241 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1243 return get_ref_dir(packed_ref_cache
->root
);
1246 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1248 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1251 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1253 struct packed_ref_cache
*packed_ref_cache
=
1254 get_packed_ref_cache(&ref_cache
);
1256 if (!packed_ref_cache
->lock
)
1257 die("internal error: packed refs not locked");
1258 add_ref(get_packed_ref_dir(packed_ref_cache
),
1259 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1263 * Read the loose references from the namespace dirname into dir
1264 * (without recursing). dirname must end with '/'. dir must be the
1265 * directory entry corresponding to dirname.
1267 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1269 struct ref_cache
*refs
= dir
->ref_cache
;
1273 int dirnamelen
= strlen(dirname
);
1274 struct strbuf refname
;
1277 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1279 path
= git_path("%s", dirname
);
1285 strbuf_init(&refname
, dirnamelen
+ 257);
1286 strbuf_add(&refname
, dirname
, dirnamelen
);
1288 while ((de
= readdir(d
)) != NULL
) {
1289 unsigned char sha1
[20];
1294 if (de
->d_name
[0] == '.')
1296 if (ends_with(de
->d_name
, ".lock"))
1298 strbuf_addstr(&refname
, de
->d_name
);
1299 refdir
= *refs
->name
1300 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1301 : git_path("%s", refname
.buf
);
1302 if (stat(refdir
, &st
) < 0) {
1303 ; /* silently ignore */
1304 } else if (S_ISDIR(st
.st_mode
)) {
1305 strbuf_addch(&refname
, '/');
1306 add_entry_to_dir(dir
,
1307 create_dir_entry(refs
, refname
.buf
,
1313 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1315 flag
|= REF_ISBROKEN
;
1317 } else if (read_ref_full(refname
.buf
,
1318 RESOLVE_REF_READING
,
1321 flag
|= REF_ISBROKEN
;
1323 if (check_refname_format(refname
.buf
,
1324 REFNAME_ALLOW_ONELEVEL
)) {
1325 if (!refname_is_safe(refname
.buf
))
1326 die("loose refname is dangerous: %s", refname
.buf
);
1328 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1330 add_entry_to_dir(dir
,
1331 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1333 strbuf_setlen(&refname
, dirnamelen
);
1335 strbuf_release(&refname
);
1339 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1343 * Mark the top-level directory complete because we
1344 * are about to read the only subdirectory that can
1347 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1349 * Create an incomplete entry for "refs/":
1351 add_entry_to_dir(get_ref_dir(refs
->loose
),
1352 create_dir_entry(refs
, "refs/", 5, 1));
1354 return get_ref_dir(refs
->loose
);
1357 /* We allow "recursive" symbolic refs. Only within reason, though */
1359 #define MAXREFLEN (1024)
1362 * Called by resolve_gitlink_ref_recursive() after it failed to read
1363 * from the loose refs in ref_cache refs. Find <refname> in the
1364 * packed-refs file for the submodule.
1366 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1367 const char *refname
, unsigned char *sha1
)
1369 struct ref_entry
*ref
;
1370 struct ref_dir
*dir
= get_packed_refs(refs
);
1372 ref
= find_ref(dir
, refname
);
1376 hashcpy(sha1
, ref
->u
.value
.sha1
);
1380 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1381 const char *refname
, unsigned char *sha1
,
1385 char buffer
[128], *p
;
1388 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1391 ? git_path_submodule(refs
->name
, "%s", refname
)
1392 : git_path("%s", refname
);
1393 fd
= open(path
, O_RDONLY
);
1395 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1397 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1401 while (len
&& isspace(buffer
[len
-1]))
1405 /* Was it a detached head or an old-fashioned symlink? */
1406 if (!get_sha1_hex(buffer
, sha1
))
1410 if (strncmp(buffer
, "ref:", 4))
1416 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1419 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1421 int len
= strlen(path
), retval
;
1423 struct ref_cache
*refs
;
1425 while (len
&& path
[len
-1] == '/')
1429 submodule
= xstrndup(path
, len
);
1430 refs
= get_ref_cache(submodule
);
1433 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1438 * Return the ref_entry for the given refname from the packed
1439 * references. If it does not exist, return NULL.
1441 static struct ref_entry
*get_packed_ref(const char *refname
)
1443 return find_ref(get_packed_refs(&ref_cache
), refname
);
1447 * A loose ref file doesn't exist; check for a packed ref. The
1448 * options are forwarded from resolve_safe_unsafe().
1450 static int resolve_missing_loose_ref(const char *refname
,
1452 unsigned char *sha1
,
1455 struct ref_entry
*entry
;
1458 * The loose reference file does not exist; check for a packed
1461 entry
= get_packed_ref(refname
);
1463 hashcpy(sha1
, entry
->u
.value
.sha1
);
1465 *flags
|= REF_ISPACKED
;
1468 /* The reference is not a packed reference, either. */
1469 if (resolve_flags
& RESOLVE_REF_READING
) {
1478 /* This function needs to return a meaningful errno on failure */
1479 static const char *resolve_ref_unsafe_1(const char *refname
,
1481 unsigned char *sha1
,
1483 struct strbuf
*sb_path
)
1485 int depth
= MAXDEPTH
;
1488 static char refname_buffer
[256];
1494 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1496 *flags
|= REF_BAD_NAME
;
1498 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1499 !refname_is_safe(refname
)) {
1504 * dwim_ref() uses REF_ISBROKEN to distinguish between
1505 * missing refs and refs that were present but invalid,
1506 * to complain about the latter to stderr.
1508 * We don't know whether the ref exists, so don't set
1524 strbuf_reset(sb_path
);
1525 strbuf_git_path(sb_path
, "%s", refname
);
1526 path
= sb_path
->buf
;
1529 * We might have to loop back here to avoid a race
1530 * condition: first we lstat() the file, then we try
1531 * to read it as a link or as a file. But if somebody
1532 * changes the type of the file (file <-> directory
1533 * <-> symlink) between the lstat() and reading, then
1534 * we don't want to report that as an error but rather
1535 * try again starting with the lstat().
1538 if (lstat(path
, &st
) < 0) {
1539 if (errno
!= ENOENT
)
1541 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1547 *flags
|= REF_ISBROKEN
;
1552 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1553 if (S_ISLNK(st
.st_mode
)) {
1554 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1556 if (errno
== ENOENT
|| errno
== EINVAL
)
1557 /* inconsistent with lstat; retry */
1563 if (starts_with(buffer
, "refs/") &&
1564 !check_refname_format(buffer
, 0)) {
1565 strcpy(refname_buffer
, buffer
);
1566 refname
= refname_buffer
;
1568 *flags
|= REF_ISSYMREF
;
1569 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1577 /* Is it a directory? */
1578 if (S_ISDIR(st
.st_mode
)) {
1584 * Anything else, just open it and try to use it as
1587 fd
= open(path
, O_RDONLY
);
1589 if (errno
== ENOENT
)
1590 /* inconsistent with lstat; retry */
1595 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1597 int save_errno
= errno
;
1603 while (len
&& isspace(buffer
[len
-1]))
1608 * Is it a symbolic ref?
1610 if (!starts_with(buffer
, "ref:")) {
1612 * Please note that FETCH_HEAD has a second
1613 * line containing other data.
1615 if (get_sha1_hex(buffer
, sha1
) ||
1616 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1618 *flags
|= REF_ISBROKEN
;
1625 *flags
|= REF_ISBROKEN
;
1630 *flags
|= REF_ISSYMREF
;
1632 while (isspace(*buf
))
1634 refname
= strcpy(refname_buffer
, buf
);
1635 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1639 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1641 *flags
|= REF_ISBROKEN
;
1643 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1644 !refname_is_safe(buf
)) {
1653 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1654 unsigned char *sha1
, int *flags
)
1656 struct strbuf sb_path
= STRBUF_INIT
;
1657 const char *ret
= resolve_ref_unsafe_1(refname
, resolve_flags
,
1658 sha1
, flags
, &sb_path
);
1659 strbuf_release(&sb_path
);
1663 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1665 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1668 /* The argument to filter_refs */
1670 const char *pattern
;
1675 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1677 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1682 int read_ref(const char *refname
, unsigned char *sha1
)
1684 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1687 int ref_exists(const char *refname
)
1689 unsigned char sha1
[20];
1690 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1693 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1696 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1697 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1699 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1703 /* object was peeled successfully: */
1707 * object cannot be peeled because the named object (or an
1708 * object referred to by a tag in the peel chain), does not
1713 /* object cannot be peeled because it is not a tag: */
1716 /* ref_entry contains no peeled value because it is a symref: */
1717 PEEL_IS_SYMREF
= -3,
1720 * ref_entry cannot be peeled because it is broken (i.e., the
1721 * symbolic reference cannot even be resolved to an object
1728 * Peel the named object; i.e., if the object is a tag, resolve the
1729 * tag recursively until a non-tag is found. If successful, store the
1730 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1731 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1732 * and leave sha1 unchanged.
1734 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1736 struct object
*o
= lookup_unknown_object(name
);
1738 if (o
->type
== OBJ_NONE
) {
1739 int type
= sha1_object_info(name
, NULL
);
1740 if (type
< 0 || !object_as_type(o
, type
, 0))
1741 return PEEL_INVALID
;
1744 if (o
->type
!= OBJ_TAG
)
1745 return PEEL_NON_TAG
;
1747 o
= deref_tag_noverify(o
);
1749 return PEEL_INVALID
;
1751 hashcpy(sha1
, o
->sha1
);
1756 * Peel the entry (if possible) and return its new peel_status. If
1757 * repeel is true, re-peel the entry even if there is an old peeled
1758 * value that is already stored in it.
1760 * It is OK to call this function with a packed reference entry that
1761 * might be stale and might even refer to an object that has since
1762 * been garbage-collected. In such a case, if the entry has
1763 * REF_KNOWS_PEELED then leave the status unchanged and return
1764 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1766 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1768 enum peel_status status
;
1770 if (entry
->flag
& REF_KNOWS_PEELED
) {
1772 entry
->flag
&= ~REF_KNOWS_PEELED
;
1773 hashclr(entry
->u
.value
.peeled
);
1775 return is_null_sha1(entry
->u
.value
.peeled
) ?
1776 PEEL_NON_TAG
: PEEL_PEELED
;
1779 if (entry
->flag
& REF_ISBROKEN
)
1781 if (entry
->flag
& REF_ISSYMREF
)
1782 return PEEL_IS_SYMREF
;
1784 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1785 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1786 entry
->flag
|= REF_KNOWS_PEELED
;
1790 int peel_ref(const char *refname
, unsigned char *sha1
)
1793 unsigned char base
[20];
1795 if (current_ref
&& (current_ref
->name
== refname
1796 || !strcmp(current_ref
->name
, refname
))) {
1797 if (peel_entry(current_ref
, 0))
1799 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1803 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1807 * If the reference is packed, read its ref_entry from the
1808 * cache in the hope that we already know its peeled value.
1809 * We only try this optimization on packed references because
1810 * (a) forcing the filling of the loose reference cache could
1811 * be expensive and (b) loose references anyway usually do not
1812 * have REF_KNOWS_PEELED.
1814 if (flag
& REF_ISPACKED
) {
1815 struct ref_entry
*r
= get_packed_ref(refname
);
1817 if (peel_entry(r
, 0))
1819 hashcpy(sha1
, r
->u
.value
.peeled
);
1824 return peel_object(base
, sha1
);
1827 struct warn_if_dangling_data
{
1829 const char *refname
;
1830 const struct string_list
*refnames
;
1831 const char *msg_fmt
;
1834 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1835 int flags
, void *cb_data
)
1837 struct warn_if_dangling_data
*d
= cb_data
;
1838 const char *resolves_to
;
1839 unsigned char junk
[20];
1841 if (!(flags
& REF_ISSYMREF
))
1844 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1847 ? strcmp(resolves_to
, d
->refname
)
1848 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1852 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1857 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1859 struct warn_if_dangling_data data
;
1862 data
.refname
= refname
;
1863 data
.refnames
= NULL
;
1864 data
.msg_fmt
= msg_fmt
;
1865 for_each_rawref(warn_if_dangling_symref
, &data
);
1868 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1870 struct warn_if_dangling_data data
;
1873 data
.refname
= NULL
;
1874 data
.refnames
= refnames
;
1875 data
.msg_fmt
= msg_fmt
;
1876 for_each_rawref(warn_if_dangling_symref
, &data
);
1880 * Call fn for each reference in the specified ref_cache, omitting
1881 * references not in the containing_dir of base. fn is called for all
1882 * references, including broken ones. If fn ever returns a non-zero
1883 * value, stop the iteration and return that value; otherwise, return
1886 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1887 each_ref_entry_fn fn
, void *cb_data
)
1889 struct packed_ref_cache
*packed_ref_cache
;
1890 struct ref_dir
*loose_dir
;
1891 struct ref_dir
*packed_dir
;
1895 * We must make sure that all loose refs are read before accessing the
1896 * packed-refs file; this avoids a race condition in which loose refs
1897 * are migrated to the packed-refs file by a simultaneous process, but
1898 * our in-memory view is from before the migration. get_packed_ref_cache()
1899 * takes care of making sure our view is up to date with what is on
1902 loose_dir
= get_loose_refs(refs
);
1903 if (base
&& *base
) {
1904 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1907 prime_ref_dir(loose_dir
);
1909 packed_ref_cache
= get_packed_ref_cache(refs
);
1910 acquire_packed_ref_cache(packed_ref_cache
);
1911 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1912 if (base
&& *base
) {
1913 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1916 if (packed_dir
&& loose_dir
) {
1917 sort_ref_dir(packed_dir
);
1918 sort_ref_dir(loose_dir
);
1919 retval
= do_for_each_entry_in_dirs(
1920 packed_dir
, loose_dir
, fn
, cb_data
);
1921 } else if (packed_dir
) {
1922 sort_ref_dir(packed_dir
);
1923 retval
= do_for_each_entry_in_dir(
1924 packed_dir
, 0, fn
, cb_data
);
1925 } else if (loose_dir
) {
1926 sort_ref_dir(loose_dir
);
1927 retval
= do_for_each_entry_in_dir(
1928 loose_dir
, 0, fn
, cb_data
);
1931 release_packed_ref_cache(packed_ref_cache
);
1936 * Call fn for each reference in the specified ref_cache for which the
1937 * refname begins with base. If trim is non-zero, then trim that many
1938 * characters off the beginning of each refname before passing the
1939 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1940 * broken references in the iteration. If fn ever returns a non-zero
1941 * value, stop the iteration and return that value; otherwise, return
1944 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
1945 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1947 struct ref_entry_cb data
;
1952 data
.cb_data
= cb_data
;
1954 if (ref_paranoia
< 0)
1955 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
1957 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1959 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
1962 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1964 unsigned char sha1
[20];
1968 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
1969 return fn("HEAD", sha1
, 0, cb_data
);
1974 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
1975 return fn("HEAD", sha1
, flag
, cb_data
);
1980 int head_ref(each_ref_fn fn
, void *cb_data
)
1982 return do_head_ref(NULL
, fn
, cb_data
);
1985 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1987 return do_head_ref(submodule
, fn
, cb_data
);
1990 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1992 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
1995 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
1997 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2000 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2002 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2005 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2006 each_ref_fn fn
, void *cb_data
)
2008 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2011 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2013 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2016 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2018 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2021 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2023 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2026 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2028 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2031 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2033 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2036 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2038 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2041 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2043 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2046 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2048 struct strbuf buf
= STRBUF_INIT
;
2050 unsigned char sha1
[20];
2053 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2054 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2055 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2056 strbuf_release(&buf
);
2061 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2063 struct strbuf buf
= STRBUF_INIT
;
2065 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2066 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2067 strbuf_release(&buf
);
2071 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2072 const char *prefix
, void *cb_data
)
2074 struct strbuf real_pattern
= STRBUF_INIT
;
2075 struct ref_filter filter
;
2078 if (!prefix
&& !starts_with(pattern
, "refs/"))
2079 strbuf_addstr(&real_pattern
, "refs/");
2081 strbuf_addstr(&real_pattern
, prefix
);
2082 strbuf_addstr(&real_pattern
, pattern
);
2084 if (!has_glob_specials(pattern
)) {
2085 /* Append implied '/' '*' if not present. */
2086 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2087 strbuf_addch(&real_pattern
, '/');
2088 /* No need to check for '*', there is none. */
2089 strbuf_addch(&real_pattern
, '*');
2092 filter
.pattern
= real_pattern
.buf
;
2094 filter
.cb_data
= cb_data
;
2095 ret
= for_each_ref(filter_refs
, &filter
);
2097 strbuf_release(&real_pattern
);
2101 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2103 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2106 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2108 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2109 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2112 const char *prettify_refname(const char *name
)
2115 starts_with(name
, "refs/heads/") ? 11 :
2116 starts_with(name
, "refs/tags/") ? 10 :
2117 starts_with(name
, "refs/remotes/") ? 13 :
2121 static const char *ref_rev_parse_rules
[] = {
2126 "refs/remotes/%.*s",
2127 "refs/remotes/%.*s/HEAD",
2131 int refname_match(const char *abbrev_name
, const char *full_name
)
2134 const int abbrev_name_len
= strlen(abbrev_name
);
2136 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2137 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2145 static void unlock_ref(struct ref_lock
*lock
)
2147 /* Do not free lock->lk -- atexit() still looks at them */
2149 rollback_lock_file(lock
->lk
);
2150 free(lock
->ref_name
);
2151 free(lock
->orig_ref_name
);
2155 /* This function should make sure errno is meaningful on error */
2156 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2157 const unsigned char *old_sha1
, int mustexist
)
2159 if (read_ref_full(lock
->ref_name
,
2160 mustexist
? RESOLVE_REF_READING
: 0,
2161 lock
->old_sha1
, NULL
)) {
2162 int save_errno
= errno
;
2163 error("Can't verify ref %s", lock
->ref_name
);
2168 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2169 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2170 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2178 static int remove_empty_directories(const char *file
)
2180 /* we want to create a file but there is a directory there;
2181 * if that is an empty directory (or a directory that contains
2182 * only empty directories), remove them.
2185 int result
, save_errno
;
2187 strbuf_init(&path
, 20);
2188 strbuf_addstr(&path
, file
);
2190 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2193 strbuf_release(&path
);
2200 * *string and *len will only be substituted, and *string returned (for
2201 * later free()ing) if the string passed in is a magic short-hand form
2204 static char *substitute_branch_name(const char **string
, int *len
)
2206 struct strbuf buf
= STRBUF_INIT
;
2207 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2211 *string
= strbuf_detach(&buf
, &size
);
2213 return (char *)*string
;
2219 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2221 char *last_branch
= substitute_branch_name(&str
, &len
);
2226 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2227 char fullref
[PATH_MAX
];
2228 unsigned char sha1_from_ref
[20];
2229 unsigned char *this_result
;
2232 this_result
= refs_found
? sha1_from_ref
: sha1
;
2233 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2234 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2235 this_result
, &flag
);
2239 if (!warn_ambiguous_refs
)
2241 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2242 warning("ignoring dangling symref %s.", fullref
);
2243 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2244 warning("ignoring broken ref %s.", fullref
);
2251 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2253 char *last_branch
= substitute_branch_name(&str
, &len
);
2258 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2259 unsigned char hash
[20];
2260 char path
[PATH_MAX
];
2261 const char *ref
, *it
;
2263 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2264 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2268 if (reflog_exists(path
))
2270 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2274 if (!logs_found
++) {
2276 hashcpy(sha1
, hash
);
2278 if (!warn_ambiguous_refs
)
2286 * Locks a ref returning the lock on success and NULL on failure.
2287 * On failure errno is set to something meaningful.
2289 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2290 const unsigned char *old_sha1
,
2291 const struct string_list
*skip
,
2292 unsigned int flags
, int *type_p
)
2294 const char *ref_file
;
2295 const char *orig_refname
= refname
;
2296 struct ref_lock
*lock
;
2299 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2300 int resolve_flags
= 0;
2301 int attempts_remaining
= 3;
2303 lock
= xcalloc(1, sizeof(struct ref_lock
));
2306 resolve_flags
|= RESOLVE_REF_READING
;
2307 if (flags
& REF_DELETING
) {
2308 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2309 if (flags
& REF_NODEREF
)
2310 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2313 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2314 lock
->old_sha1
, &type
);
2315 if (!refname
&& errno
== EISDIR
) {
2316 /* we are trying to lock foo but we used to
2317 * have foo/bar which now does not exist;
2318 * it is normal for the empty directory 'foo'
2321 ref_file
= git_path("%s", orig_refname
);
2322 if (remove_empty_directories(ref_file
)) {
2324 error("there are still refs under '%s'", orig_refname
);
2327 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2328 lock
->old_sha1
, &type
);
2334 error("unable to resolve reference %s: %s",
2335 orig_refname
, strerror(errno
));
2339 * If the ref did not exist and we are creating it, make sure
2340 * there is no existing packed ref whose name begins with our
2341 * refname, nor a packed ref whose name is a proper prefix of
2344 if (is_null_sha1(lock
->old_sha1
) &&
2345 !is_refname_available(refname
, skip
, get_packed_refs(&ref_cache
))) {
2346 last_errno
= ENOTDIR
;
2350 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2353 if (flags
& REF_NODEREF
) {
2354 refname
= orig_refname
;
2355 lflags
|= LOCK_NO_DEREF
;
2357 lock
->ref_name
= xstrdup(refname
);
2358 lock
->orig_ref_name
= xstrdup(orig_refname
);
2359 ref_file
= git_path("%s", refname
);
2362 switch (safe_create_leading_directories_const(ref_file
)) {
2364 break; /* success */
2366 if (--attempts_remaining
> 0)
2371 error("unable to create directory for %s", ref_file
);
2375 if (hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
) < 0) {
2377 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2379 * Maybe somebody just deleted one of the
2380 * directories leading to ref_file. Try
2385 struct strbuf err
= STRBUF_INIT
;
2386 unable_to_lock_message(ref_file
, errno
, &err
);
2387 error("%s", err
.buf
);
2388 strbuf_release(&err
);
2392 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2401 * Write an entry to the packed-refs file for the specified refname.
2402 * If peeled is non-NULL, write it as the entry's peeled value.
2404 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2405 unsigned char *peeled
)
2407 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2409 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2413 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2415 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2417 enum peel_status peel_status
= peel_entry(entry
, 0);
2419 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2420 error("internal error: %s is not a valid packed reference!",
2422 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2423 peel_status
== PEEL_PEELED
?
2424 entry
->u
.value
.peeled
: NULL
);
2428 /* This should return a meaningful errno on failure */
2429 int lock_packed_refs(int flags
)
2431 struct packed_ref_cache
*packed_ref_cache
;
2433 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2436 * Get the current packed-refs while holding the lock. If the
2437 * packed-refs file has been modified since we last read it,
2438 * this will automatically invalidate the cache and re-read
2439 * the packed-refs file.
2441 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2442 packed_ref_cache
->lock
= &packlock
;
2443 /* Increment the reference count to prevent it from being freed: */
2444 acquire_packed_ref_cache(packed_ref_cache
);
2449 * Commit the packed refs changes.
2450 * On error we must make sure that errno contains a meaningful value.
2452 int commit_packed_refs(void)
2454 struct packed_ref_cache
*packed_ref_cache
=
2455 get_packed_ref_cache(&ref_cache
);
2460 if (!packed_ref_cache
->lock
)
2461 die("internal error: packed-refs not locked");
2463 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2465 die_errno("unable to fdopen packed-refs descriptor");
2467 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2468 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2469 0, write_packed_entry_fn
, out
);
2471 if (commit_lock_file(packed_ref_cache
->lock
)) {
2475 packed_ref_cache
->lock
= NULL
;
2476 release_packed_ref_cache(packed_ref_cache
);
2481 void rollback_packed_refs(void)
2483 struct packed_ref_cache
*packed_ref_cache
=
2484 get_packed_ref_cache(&ref_cache
);
2486 if (!packed_ref_cache
->lock
)
2487 die("internal error: packed-refs not locked");
2488 rollback_lock_file(packed_ref_cache
->lock
);
2489 packed_ref_cache
->lock
= NULL
;
2490 release_packed_ref_cache(packed_ref_cache
);
2491 clear_packed_ref_cache(&ref_cache
);
2494 struct ref_to_prune
{
2495 struct ref_to_prune
*next
;
2496 unsigned char sha1
[20];
2497 char name
[FLEX_ARRAY
];
2500 struct pack_refs_cb_data
{
2502 struct ref_dir
*packed_refs
;
2503 struct ref_to_prune
*ref_to_prune
;
2507 * An each_ref_entry_fn that is run over loose references only. If
2508 * the loose reference can be packed, add an entry in the packed ref
2509 * cache. If the reference should be pruned, also add it to
2510 * ref_to_prune in the pack_refs_cb_data.
2512 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2514 struct pack_refs_cb_data
*cb
= cb_data
;
2515 enum peel_status peel_status
;
2516 struct ref_entry
*packed_entry
;
2517 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2519 /* ALWAYS pack tags */
2520 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2523 /* Do not pack symbolic or broken refs: */
2524 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2527 /* Add a packed ref cache entry equivalent to the loose entry. */
2528 peel_status
= peel_entry(entry
, 1);
2529 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2530 die("internal error peeling reference %s (%s)",
2531 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2532 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2534 /* Overwrite existing packed entry with info from loose entry */
2535 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2536 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2538 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2539 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2540 add_ref(cb
->packed_refs
, packed_entry
);
2542 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2544 /* Schedule the loose reference for pruning if requested. */
2545 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2546 int namelen
= strlen(entry
->name
) + 1;
2547 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2548 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2549 strcpy(n
->name
, entry
->name
);
2550 n
->next
= cb
->ref_to_prune
;
2551 cb
->ref_to_prune
= n
;
2557 * Remove empty parents, but spare refs/ and immediate subdirs.
2558 * Note: munges *name.
2560 static void try_remove_empty_parents(char *name
)
2565 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2566 while (*p
&& *p
!= '/')
2568 /* tolerate duplicate slashes; see check_refname_format() */
2572 for (q
= p
; *q
; q
++)
2575 while (q
> p
&& *q
!= '/')
2577 while (q
> p
&& *(q
-1) == '/')
2582 if (rmdir(git_path("%s", name
)))
2587 /* make sure nobody touched the ref, and unlink */
2588 static void prune_ref(struct ref_to_prune
*r
)
2590 struct ref_transaction
*transaction
;
2591 struct strbuf err
= STRBUF_INIT
;
2593 if (check_refname_format(r
->name
, 0))
2596 transaction
= ref_transaction_begin(&err
);
2598 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2599 REF_ISPRUNING
, NULL
, &err
) ||
2600 ref_transaction_commit(transaction
, &err
)) {
2601 ref_transaction_free(transaction
);
2602 error("%s", err
.buf
);
2603 strbuf_release(&err
);
2606 ref_transaction_free(transaction
);
2607 strbuf_release(&err
);
2608 try_remove_empty_parents(r
->name
);
2611 static void prune_refs(struct ref_to_prune
*r
)
2619 int pack_refs(unsigned int flags
)
2621 struct pack_refs_cb_data cbdata
;
2623 memset(&cbdata
, 0, sizeof(cbdata
));
2624 cbdata
.flags
= flags
;
2626 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2627 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2629 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2630 pack_if_possible_fn
, &cbdata
);
2632 if (commit_packed_refs())
2633 die_errno("unable to overwrite old ref-pack file");
2635 prune_refs(cbdata
.ref_to_prune
);
2639 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2641 struct ref_dir
*packed
;
2642 struct string_list_item
*refname
;
2643 int ret
, needs_repacking
= 0, removed
= 0;
2647 /* Look for a packed ref */
2648 for_each_string_list_item(refname
, refnames
) {
2649 if (get_packed_ref(refname
->string
)) {
2650 needs_repacking
= 1;
2655 /* Avoid locking if we have nothing to do */
2656 if (!needs_repacking
)
2657 return 0; /* no refname exists in packed refs */
2659 if (lock_packed_refs(0)) {
2660 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2663 packed
= get_packed_refs(&ref_cache
);
2665 /* Remove refnames from the cache */
2666 for_each_string_list_item(refname
, refnames
)
2667 if (remove_entry(packed
, refname
->string
) != -1)
2671 * All packed entries disappeared while we were
2672 * acquiring the lock.
2674 rollback_packed_refs();
2678 /* Write what remains */
2679 ret
= commit_packed_refs();
2681 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2686 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2690 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2692 * loose. The loose file name is the same as the
2693 * lockfile name, minus ".lock":
2695 char *loose_filename
= get_locked_file_path(lock
->lk
);
2696 int res
= unlink_or_msg(loose_filename
, err
);
2697 free(loose_filename
);
2704 int delete_ref(const char *refname
, const unsigned char *sha1
, unsigned int flags
)
2706 struct ref_transaction
*transaction
;
2707 struct strbuf err
= STRBUF_INIT
;
2709 transaction
= ref_transaction_begin(&err
);
2711 ref_transaction_delete(transaction
, refname
,
2712 (sha1
&& !is_null_sha1(sha1
)) ? sha1
: NULL
,
2713 flags
, NULL
, &err
) ||
2714 ref_transaction_commit(transaction
, &err
)) {
2715 error("%s", err
.buf
);
2716 ref_transaction_free(transaction
);
2717 strbuf_release(&err
);
2720 ref_transaction_free(transaction
);
2721 strbuf_release(&err
);
2726 * People using contrib's git-new-workdir have .git/logs/refs ->
2727 * /some/other/path/.git/logs/refs, and that may live on another device.
2729 * IOW, to avoid cross device rename errors, the temporary renamed log must
2730 * live into logs/refs.
2732 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2734 static int rename_tmp_log(const char *newrefname
)
2736 int attempts_remaining
= 4;
2739 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname
))) {
2741 break; /* success */
2743 if (--attempts_remaining
> 0)
2747 error("unable to create directory for %s", newrefname
);
2751 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2752 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2754 * rename(a, b) when b is an existing
2755 * directory ought to result in ISDIR, but
2756 * Solaris 5.8 gives ENOTDIR. Sheesh.
2758 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2759 error("Directory not empty: logs/%s", newrefname
);
2763 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2765 * Maybe another process just deleted one of
2766 * the directories in the path to newrefname.
2767 * Try again from the beginning.
2771 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2772 newrefname
, strerror(errno
));
2779 static int rename_ref_available(const char *oldname
, const char *newname
)
2781 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2784 string_list_insert(&skip
, oldname
);
2785 ret
= is_refname_available(newname
, &skip
, get_packed_refs(&ref_cache
))
2786 && is_refname_available(newname
, &skip
, get_loose_refs(&ref_cache
));
2787 string_list_clear(&skip
, 0);
2791 static int write_ref_sha1(struct ref_lock
*lock
, const unsigned char *sha1
,
2792 const char *logmsg
);
2794 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2796 unsigned char sha1
[20], orig_sha1
[20];
2797 int flag
= 0, logmoved
= 0;
2798 struct ref_lock
*lock
;
2799 struct stat loginfo
;
2800 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2801 const char *symref
= NULL
;
2803 if (log
&& S_ISLNK(loginfo
.st_mode
))
2804 return error("reflog for %s is a symlink", oldrefname
);
2806 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2808 if (flag
& REF_ISSYMREF
)
2809 return error("refname %s is a symbolic ref, renaming it is not supported",
2812 return error("refname %s not found", oldrefname
);
2814 if (!rename_ref_available(oldrefname
, newrefname
))
2817 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2818 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2819 oldrefname
, strerror(errno
));
2821 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2822 error("unable to delete old %s", oldrefname
);
2826 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2827 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2828 if (errno
==EISDIR
) {
2829 if (remove_empty_directories(git_path("%s", newrefname
))) {
2830 error("Directory not empty: %s", newrefname
);
2834 error("unable to delete existing %s", newrefname
);
2839 if (log
&& rename_tmp_log(newrefname
))
2844 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, 0, NULL
);
2846 error("unable to lock %s for update", newrefname
);
2849 hashcpy(lock
->old_sha1
, orig_sha1
);
2850 if (write_ref_sha1(lock
, orig_sha1
, logmsg
)) {
2851 error("unable to write current sha1 into %s", newrefname
);
2858 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, 0, NULL
);
2860 error("unable to lock %s for rollback", oldrefname
);
2864 flag
= log_all_ref_updates
;
2865 log_all_ref_updates
= 0;
2866 if (write_ref_sha1(lock
, orig_sha1
, NULL
))
2867 error("unable to write current sha1 into %s", oldrefname
);
2868 log_all_ref_updates
= flag
;
2871 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2872 error("unable to restore logfile %s from %s: %s",
2873 oldrefname
, newrefname
, strerror(errno
));
2874 if (!logmoved
&& log
&&
2875 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2876 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2877 oldrefname
, strerror(errno
));
2882 static int close_ref(struct ref_lock
*lock
)
2884 if (close_lock_file(lock
->lk
))
2889 static int commit_ref(struct ref_lock
*lock
)
2891 if (commit_lock_file(lock
->lk
))
2897 * copy the reflog message msg to buf, which has been allocated sufficiently
2898 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2899 * because reflog file is one line per entry.
2901 static int copy_msg(char *buf
, const char *msg
)
2908 while ((c
= *msg
++)) {
2909 if (wasspace
&& isspace(c
))
2911 wasspace
= isspace(c
);
2916 while (buf
< cp
&& isspace(cp
[-1]))
2922 /* This function must set a meaningful errno on failure */
2923 int log_ref_setup(const char *refname
, struct strbuf
*sb_logfile
)
2925 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
2928 strbuf_git_path(sb_logfile
, "logs/%s", refname
);
2929 logfile
= sb_logfile
->buf
;
2930 /* make sure the rest of the function can't change "logfile" */
2932 if (log_all_ref_updates
&&
2933 (starts_with(refname
, "refs/heads/") ||
2934 starts_with(refname
, "refs/remotes/") ||
2935 starts_with(refname
, "refs/notes/") ||
2936 !strcmp(refname
, "HEAD"))) {
2937 if (safe_create_leading_directories(logfile
) < 0) {
2938 int save_errno
= errno
;
2939 error("unable to create directory for %s", logfile
);
2946 logfd
= open(logfile
, oflags
, 0666);
2948 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
2951 if (errno
== EISDIR
) {
2952 if (remove_empty_directories(logfile
)) {
2953 int save_errno
= errno
;
2954 error("There are still logs under '%s'",
2959 logfd
= open(logfile
, oflags
, 0666);
2963 int save_errno
= errno
;
2964 error("Unable to append to %s: %s", logfile
,
2971 adjust_shared_perm(logfile
);
2976 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
2977 const unsigned char *new_sha1
,
2978 const char *committer
, const char *msg
)
2980 int msglen
, written
;
2981 unsigned maxlen
, len
;
2984 msglen
= msg
? strlen(msg
) : 0;
2985 maxlen
= strlen(committer
) + msglen
+ 100;
2986 logrec
= xmalloc(maxlen
);
2987 len
= sprintf(logrec
, "%s %s %s\n",
2988 sha1_to_hex(old_sha1
),
2989 sha1_to_hex(new_sha1
),
2992 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
2994 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3002 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
3003 const unsigned char *new_sha1
, const char *msg
,
3004 struct strbuf
*sb_log_file
)
3006 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3009 if (log_all_ref_updates
< 0)
3010 log_all_ref_updates
= !is_bare_repository();
3012 result
= log_ref_setup(refname
, sb_log_file
);
3015 log_file
= sb_log_file
->buf
;
3016 /* make sure the rest of the function can't change "log_file" */
3019 logfd
= open(log_file
, oflags
);
3022 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3023 git_committer_info(0), msg
);
3025 int save_errno
= errno
;
3027 error("Unable to append to %s", log_file
);
3032 int save_errno
= errno
;
3033 error("Unable to append to %s", log_file
);
3040 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3041 const unsigned char *new_sha1
, const char *msg
)
3043 struct strbuf sb
= STRBUF_INIT
;
3044 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
);
3045 strbuf_release(&sb
);
3049 int is_branch(const char *refname
)
3051 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3055 * Write sha1 into the ref specified by the lock. Make sure that errno
3058 static int write_ref_sha1(struct ref_lock
*lock
,
3059 const unsigned char *sha1
, const char *logmsg
)
3061 static char term
= '\n';
3064 o
= parse_object(sha1
);
3066 error("Trying to write ref %s with nonexistent object %s",
3067 lock
->ref_name
, sha1_to_hex(sha1
));
3072 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3073 error("Trying to write non-commit object %s to branch %s",
3074 sha1_to_hex(sha1
), lock
->ref_name
);
3079 if (write_in_full(lock
->lk
->fd
, sha1_to_hex(sha1
), 40) != 40 ||
3080 write_in_full(lock
->lk
->fd
, &term
, 1) != 1 ||
3081 close_ref(lock
) < 0) {
3082 int save_errno
= errno
;
3083 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3088 clear_loose_ref_cache(&ref_cache
);
3089 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3090 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3091 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3095 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3097 * Special hack: If a branch is updated directly and HEAD
3098 * points to it (may happen on the remote side of a push
3099 * for example) then logically the HEAD reflog should be
3101 * A generic solution implies reverse symref information,
3102 * but finding all symrefs pointing to the given branch
3103 * would be rather costly for this rare event (the direct
3104 * update of a branch) to be worth it. So let's cheat and
3105 * check with HEAD only which should cover 99% of all usage
3106 * scenarios (even 100% of the default ones).
3108 unsigned char head_sha1
[20];
3110 const char *head_ref
;
3111 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3112 head_sha1
, &head_flag
);
3113 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3114 !strcmp(head_ref
, lock
->ref_name
))
3115 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3117 if (commit_ref(lock
)) {
3118 error("Couldn't set %s", lock
->ref_name
);
3126 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3129 const char *lockpath
;
3131 int fd
, len
, written
;
3132 char *git_HEAD
= git_pathdup("%s", ref_target
);
3133 unsigned char old_sha1
[20], new_sha1
[20];
3135 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3138 if (safe_create_leading_directories(git_HEAD
) < 0)
3139 return error("unable to create directory for %s", git_HEAD
);
3141 #ifndef NO_SYMLINK_HEAD
3142 if (prefer_symlink_refs
) {
3144 if (!symlink(refs_heads_master
, git_HEAD
))
3146 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3150 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3151 if (sizeof(ref
) <= len
) {
3152 error("refname too long: %s", refs_heads_master
);
3153 goto error_free_return
;
3155 lockpath
= mkpath("%s.lock", git_HEAD
);
3156 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3158 error("Unable to open %s for writing", lockpath
);
3159 goto error_free_return
;
3161 written
= write_in_full(fd
, ref
, len
);
3162 if (close(fd
) != 0 || written
!= len
) {
3163 error("Unable to write to %s", lockpath
);
3164 goto error_unlink_return
;
3166 if (rename(lockpath
, git_HEAD
) < 0) {
3167 error("Unable to create %s", git_HEAD
);
3168 goto error_unlink_return
;
3170 if (adjust_shared_perm(git_HEAD
)) {
3171 error("Unable to fix permissions on %s", lockpath
);
3172 error_unlink_return
:
3173 unlink_or_warn(lockpath
);
3179 #ifndef NO_SYMLINK_HEAD
3182 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3183 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3189 struct read_ref_at_cb
{
3190 const char *refname
;
3191 unsigned long at_time
;
3194 unsigned char *sha1
;
3197 unsigned char osha1
[20];
3198 unsigned char nsha1
[20];
3202 unsigned long *cutoff_time
;
3207 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3208 const char *email
, unsigned long timestamp
, int tz
,
3209 const char *message
, void *cb_data
)
3211 struct read_ref_at_cb
*cb
= cb_data
;
3215 cb
->date
= timestamp
;
3217 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3219 *cb
->msg
= xstrdup(message
);
3220 if (cb
->cutoff_time
)
3221 *cb
->cutoff_time
= timestamp
;
3223 *cb
->cutoff_tz
= tz
;
3225 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3227 * we have not yet updated cb->[n|o]sha1 so they still
3228 * hold the values for the previous record.
3230 if (!is_null_sha1(cb
->osha1
)) {
3231 hashcpy(cb
->sha1
, nsha1
);
3232 if (hashcmp(cb
->osha1
, nsha1
))
3233 warning("Log for ref %s has gap after %s.",
3234 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3236 else if (cb
->date
== cb
->at_time
)
3237 hashcpy(cb
->sha1
, nsha1
);
3238 else if (hashcmp(nsha1
, cb
->sha1
))
3239 warning("Log for ref %s unexpectedly ended on %s.",
3240 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3242 hashcpy(cb
->osha1
, osha1
);
3243 hashcpy(cb
->nsha1
, nsha1
);
3247 hashcpy(cb
->osha1
, osha1
);
3248 hashcpy(cb
->nsha1
, nsha1
);
3254 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3255 const char *email
, unsigned long timestamp
,
3256 int tz
, const char *message
, void *cb_data
)
3258 struct read_ref_at_cb
*cb
= cb_data
;
3261 *cb
->msg
= xstrdup(message
);
3262 if (cb
->cutoff_time
)
3263 *cb
->cutoff_time
= timestamp
;
3265 *cb
->cutoff_tz
= tz
;
3267 *cb
->cutoff_cnt
= cb
->reccnt
;
3268 hashcpy(cb
->sha1
, osha1
);
3269 if (is_null_sha1(cb
->sha1
))
3270 hashcpy(cb
->sha1
, nsha1
);
3271 /* We just want the first entry */
3275 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3276 unsigned char *sha1
, char **msg
,
3277 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3279 struct read_ref_at_cb cb
;
3281 memset(&cb
, 0, sizeof(cb
));
3282 cb
.refname
= refname
;
3283 cb
.at_time
= at_time
;
3286 cb
.cutoff_time
= cutoff_time
;
3287 cb
.cutoff_tz
= cutoff_tz
;
3288 cb
.cutoff_cnt
= cutoff_cnt
;
3291 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3294 if (flags
& GET_SHA1_QUIETLY
)
3297 die("Log for %s is empty.", refname
);
3302 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3307 int reflog_exists(const char *refname
)
3311 return !lstat(git_path("logs/%s", refname
), &st
) &&
3312 S_ISREG(st
.st_mode
);
3315 int delete_reflog(const char *refname
)
3317 return remove_path(git_path("logs/%s", refname
));
3320 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3322 unsigned char osha1
[20], nsha1
[20];
3323 char *email_end
, *message
;
3324 unsigned long timestamp
;
3327 /* old SP new SP name <email> SP time TAB msg LF */
3328 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3329 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3330 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3331 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3332 email_end
[1] != ' ' ||
3333 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3334 !message
|| message
[0] != ' ' ||
3335 (message
[1] != '+' && message
[1] != '-') ||
3336 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3337 !isdigit(message
[4]) || !isdigit(message
[5]))
3338 return 0; /* corrupt? */
3339 email_end
[1] = '\0';
3340 tz
= strtol(message
+ 1, NULL
, 10);
3341 if (message
[6] != '\t')
3345 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3348 static char *find_beginning_of_line(char *bob
, char *scan
)
3350 while (bob
< scan
&& *(--scan
) != '\n')
3351 ; /* keep scanning backwards */
3353 * Return either beginning of the buffer, or LF at the end of
3354 * the previous line.
3359 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3361 struct strbuf sb
= STRBUF_INIT
;
3364 int ret
= 0, at_tail
= 1;
3366 logfp
= fopen(git_path("logs/%s", refname
), "r");
3370 /* Jump to the end */
3371 if (fseek(logfp
, 0, SEEK_END
) < 0)
3372 return error("cannot seek back reflog for %s: %s",
3373 refname
, strerror(errno
));
3375 while (!ret
&& 0 < pos
) {
3381 /* Fill next block from the end */
3382 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3383 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3384 return error("cannot seek back reflog for %s: %s",
3385 refname
, strerror(errno
));
3386 nread
= fread(buf
, cnt
, 1, logfp
);
3388 return error("cannot read %d bytes from reflog for %s: %s",
3389 cnt
, refname
, strerror(errno
));
3392 scanp
= endp
= buf
+ cnt
;
3393 if (at_tail
&& scanp
[-1] == '\n')
3394 /* Looking at the final LF at the end of the file */
3398 while (buf
< scanp
) {
3400 * terminating LF of the previous line, or the beginning
3405 bp
= find_beginning_of_line(buf
, scanp
);
3409 * The newline is the end of the previous line,
3410 * so we know we have complete line starting
3411 * at (bp + 1). Prefix it onto any prior data
3412 * we collected for the line and process it.
3414 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3417 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3423 * We are at the start of the buffer, and the
3424 * start of the file; there is no previous
3425 * line, and we have everything for this one.
3426 * Process it, and we can end the loop.
3428 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3429 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3436 * We are at the start of the buffer, and there
3437 * is more file to read backwards. Which means
3438 * we are in the middle of a line. Note that we
3439 * may get here even if *bp was a newline; that
3440 * just means we are at the exact end of the
3441 * previous line, rather than some spot in the
3444 * Save away what we have to be combined with
3445 * the data from the next read.
3447 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3454 die("BUG: reverse reflog parser had leftover data");
3457 strbuf_release(&sb
);
3461 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3464 struct strbuf sb
= STRBUF_INIT
;
3467 logfp
= fopen(git_path("logs/%s", refname
), "r");
3471 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3472 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3474 strbuf_release(&sb
);
3478 * Call fn for each reflog in the namespace indicated by name. name
3479 * must be empty or end with '/'. Name will be used as a scratch
3480 * space, but its contents will be restored before return.
3482 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3484 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3487 int oldlen
= name
->len
;
3490 return name
->len
? errno
: 0;
3492 while ((de
= readdir(d
)) != NULL
) {
3495 if (de
->d_name
[0] == '.')
3497 if (ends_with(de
->d_name
, ".lock"))
3499 strbuf_addstr(name
, de
->d_name
);
3500 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3501 ; /* silently ignore */
3503 if (S_ISDIR(st
.st_mode
)) {
3504 strbuf_addch(name
, '/');
3505 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3507 unsigned char sha1
[20];
3508 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3509 retval
= error("bad ref for %s", name
->buf
);
3511 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3516 strbuf_setlen(name
, oldlen
);
3522 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3526 strbuf_init(&name
, PATH_MAX
);
3527 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3528 strbuf_release(&name
);
3533 * Information needed for a single ref update. Set new_sha1 to the new
3534 * value or to null_sha1 to delete the ref. To check the old value
3535 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3536 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3537 * not exist before update.
3541 * If (flags & REF_HAVE_NEW), set the reference to this value:
3543 unsigned char new_sha1
[20];
3545 * If (flags & REF_HAVE_OLD), check that the reference
3546 * previously had this value:
3548 unsigned char old_sha1
[20];
3550 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3551 * REF_DELETING, and REF_ISPRUNING:
3554 struct ref_lock
*lock
;
3557 const char refname
[FLEX_ARRAY
];
3561 * Transaction states.
3562 * OPEN: The transaction is in a valid state and can accept new updates.
3563 * An OPEN transaction can be committed.
3564 * CLOSED: A closed transaction is no longer active and no other operations
3565 * than free can be used on it in this state.
3566 * A transaction can either become closed by successfully committing
3567 * an active transaction or if there is a failure while building
3568 * the transaction thus rendering it failed/inactive.
3570 enum ref_transaction_state
{
3571 REF_TRANSACTION_OPEN
= 0,
3572 REF_TRANSACTION_CLOSED
= 1
3576 * Data structure for holding a reference transaction, which can
3577 * consist of checks and updates to multiple references, carried out
3578 * as atomically as possible. This structure is opaque to callers.
3580 struct ref_transaction
{
3581 struct ref_update
**updates
;
3584 enum ref_transaction_state state
;
3587 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3591 return xcalloc(1, sizeof(struct ref_transaction
));
3594 void ref_transaction_free(struct ref_transaction
*transaction
)
3601 for (i
= 0; i
< transaction
->nr
; i
++) {
3602 free(transaction
->updates
[i
]->msg
);
3603 free(transaction
->updates
[i
]);
3605 free(transaction
->updates
);
3609 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3610 const char *refname
)
3612 size_t len
= strlen(refname
);
3613 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3615 strcpy((char *)update
->refname
, refname
);
3616 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3617 transaction
->updates
[transaction
->nr
++] = update
;
3621 int ref_transaction_update(struct ref_transaction
*transaction
,
3622 const char *refname
,
3623 const unsigned char *new_sha1
,
3624 const unsigned char *old_sha1
,
3625 unsigned int flags
, const char *msg
,
3628 struct ref_update
*update
;
3632 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3633 die("BUG: update called for transaction that is not open");
3635 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
3636 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3637 strbuf_addf(err
, "refusing to update ref with bad name %s",
3642 update
= add_update(transaction
, refname
);
3644 hashcpy(update
->new_sha1
, new_sha1
);
3645 flags
|= REF_HAVE_NEW
;
3648 hashcpy(update
->old_sha1
, old_sha1
);
3649 flags
|= REF_HAVE_OLD
;
3651 update
->flags
= flags
;
3653 update
->msg
= xstrdup(msg
);
3657 int ref_transaction_create(struct ref_transaction
*transaction
,
3658 const char *refname
,
3659 const unsigned char *new_sha1
,
3660 unsigned int flags
, const char *msg
,
3663 if (!new_sha1
|| is_null_sha1(new_sha1
))
3664 die("BUG: create called without valid new_sha1");
3665 return ref_transaction_update(transaction
, refname
, new_sha1
,
3666 null_sha1
, flags
, msg
, err
);
3669 int ref_transaction_delete(struct ref_transaction
*transaction
,
3670 const char *refname
,
3671 const unsigned char *old_sha1
,
3672 unsigned int flags
, const char *msg
,
3675 if (old_sha1
&& is_null_sha1(old_sha1
))
3676 die("BUG: delete called with old_sha1 set to zeros");
3677 return ref_transaction_update(transaction
, refname
,
3678 null_sha1
, old_sha1
,
3682 int ref_transaction_verify(struct ref_transaction
*transaction
,
3683 const char *refname
,
3684 const unsigned char *old_sha1
,
3689 die("BUG: verify called with old_sha1 set to NULL");
3690 return ref_transaction_update(transaction
, refname
,
3695 int update_ref(const char *msg
, const char *refname
,
3696 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
3697 unsigned int flags
, enum action_on_err onerr
)
3699 struct ref_transaction
*t
;
3700 struct strbuf err
= STRBUF_INIT
;
3702 t
= ref_transaction_begin(&err
);
3704 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
3705 flags
, msg
, &err
) ||
3706 ref_transaction_commit(t
, &err
)) {
3707 const char *str
= "update_ref failed for ref '%s': %s";
3709 ref_transaction_free(t
);
3711 case UPDATE_REFS_MSG_ON_ERR
:
3712 error(str
, refname
, err
.buf
);
3714 case UPDATE_REFS_DIE_ON_ERR
:
3715 die(str
, refname
, err
.buf
);
3717 case UPDATE_REFS_QUIET_ON_ERR
:
3720 strbuf_release(&err
);
3723 strbuf_release(&err
);
3724 ref_transaction_free(t
);
3728 static int ref_update_compare(const void *r1
, const void *r2
)
3730 const struct ref_update
* const *u1
= r1
;
3731 const struct ref_update
* const *u2
= r2
;
3732 return strcmp((*u1
)->refname
, (*u2
)->refname
);
3735 static int ref_update_reject_duplicates(struct ref_update
**updates
, int n
,
3742 for (i
= 1; i
< n
; i
++)
3743 if (!strcmp(updates
[i
- 1]->refname
, updates
[i
]->refname
)) {
3745 "Multiple updates for ref '%s' not allowed.",
3746 updates
[i
]->refname
);
3752 int ref_transaction_commit(struct ref_transaction
*transaction
,
3756 int n
= transaction
->nr
;
3757 struct ref_update
**updates
= transaction
->updates
;
3758 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3759 struct string_list_item
*ref_to_delete
;
3763 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3764 die("BUG: commit called for transaction that is not open");
3767 transaction
->state
= REF_TRANSACTION_CLOSED
;
3771 /* Copy, sort, and reject duplicate refs */
3772 qsort(updates
, n
, sizeof(*updates
), ref_update_compare
);
3773 if (ref_update_reject_duplicates(updates
, n
, err
)) {
3774 ret
= TRANSACTION_GENERIC_ERROR
;
3778 /* Acquire all locks while verifying old values */
3779 for (i
= 0; i
< n
; i
++) {
3780 struct ref_update
*update
= updates
[i
];
3781 unsigned int flags
= update
->flags
;
3783 if ((flags
& REF_HAVE_NEW
) && is_null_sha1(update
->new_sha1
))
3784 flags
|= REF_DELETING
;
3785 update
->lock
= lock_ref_sha1_basic(
3787 ((update
->flags
& REF_HAVE_OLD
) ?
3788 update
->old_sha1
: NULL
),
3792 if (!update
->lock
) {
3793 ret
= (errno
== ENOTDIR
)
3794 ? TRANSACTION_NAME_CONFLICT
3795 : TRANSACTION_GENERIC_ERROR
;
3796 strbuf_addf(err
, "Cannot lock the ref '%s'.",
3802 /* Perform updates first so live commits remain referenced */
3803 for (i
= 0; i
< n
; i
++) {
3804 struct ref_update
*update
= updates
[i
];
3805 int flags
= update
->flags
;
3807 if ((flags
& REF_HAVE_NEW
) && !is_null_sha1(update
->new_sha1
)) {
3808 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
3809 (update
->flags
& REF_NODEREF
));
3811 if (!overwriting_symref
3812 && !hashcmp(update
->lock
->old_sha1
, update
->new_sha1
)) {
3814 * The reference already has the desired
3815 * value, so we don't need to write it.
3817 unlock_ref(update
->lock
);
3818 update
->lock
= NULL
;
3819 } else if (write_ref_sha1(update
->lock
, update
->new_sha1
,
3821 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3822 strbuf_addf(err
, "Cannot update the ref '%s'.",
3824 ret
= TRANSACTION_GENERIC_ERROR
;
3827 /* freed by write_ref_sha1(): */
3828 update
->lock
= NULL
;
3833 /* Perform deletes now that updates are safely completed */
3834 for (i
= 0; i
< n
; i
++) {
3835 struct ref_update
*update
= updates
[i
];
3836 int flags
= update
->flags
;
3838 if ((flags
& REF_HAVE_NEW
) && is_null_sha1(update
->new_sha1
)) {
3839 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3840 ret
= TRANSACTION_GENERIC_ERROR
;
3844 if (!(flags
& REF_ISPRUNING
))
3845 string_list_append(&refs_to_delete
,
3846 update
->lock
->ref_name
);
3850 if (repack_without_refs(&refs_to_delete
, err
)) {
3851 ret
= TRANSACTION_GENERIC_ERROR
;
3854 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3855 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3856 clear_loose_ref_cache(&ref_cache
);
3859 transaction
->state
= REF_TRANSACTION_CLOSED
;
3861 for (i
= 0; i
< n
; i
++)
3862 if (updates
[i
]->lock
)
3863 unlock_ref(updates
[i
]->lock
);
3864 string_list_clear(&refs_to_delete
, 0);
3868 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3871 static char **scanf_fmts
;
3872 static int nr_rules
;
3877 * Pre-generate scanf formats from ref_rev_parse_rules[].
3878 * Generate a format suitable for scanf from a
3879 * ref_rev_parse_rules rule by interpolating "%s" at the
3880 * location of the "%.*s".
3882 size_t total_len
= 0;
3885 /* the rule list is NULL terminated, count them first */
3886 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3887 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3888 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3890 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3893 for (i
= 0; i
< nr_rules
; i
++) {
3894 assert(offset
< total_len
);
3895 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
3896 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
3897 ref_rev_parse_rules
[i
], 2, "%s") + 1;
3901 /* bail out if there are no rules */
3903 return xstrdup(refname
);
3905 /* buffer for scanf result, at most refname must fit */
3906 short_name
= xstrdup(refname
);
3908 /* skip first rule, it will always match */
3909 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
3911 int rules_to_fail
= i
;
3914 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
3917 short_name_len
= strlen(short_name
);
3920 * in strict mode, all (except the matched one) rules
3921 * must fail to resolve to a valid non-ambiguous ref
3924 rules_to_fail
= nr_rules
;
3927 * check if the short name resolves to a valid ref,
3928 * but use only rules prior to the matched one
3930 for (j
= 0; j
< rules_to_fail
; j
++) {
3931 const char *rule
= ref_rev_parse_rules
[j
];
3932 char refname
[PATH_MAX
];
3934 /* skip matched rule */
3939 * the short name is ambiguous, if it resolves
3940 * (with this previous rule) to a valid ref
3941 * read_ref() returns 0 on success
3943 mksnpath(refname
, sizeof(refname
),
3944 rule
, short_name_len
, short_name
);
3945 if (ref_exists(refname
))
3950 * short name is non-ambiguous if all previous rules
3951 * haven't resolved to a valid ref
3953 if (j
== rules_to_fail
)
3958 return xstrdup(refname
);
3961 static struct string_list
*hide_refs
;
3963 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
3965 if (!strcmp("transfer.hiderefs", var
) ||
3966 /* NEEDSWORK: use parse_config_key() once both are merged */
3967 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
3968 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
3973 return config_error_nonbool(var
);
3974 ref
= xstrdup(value
);
3976 while (len
&& ref
[len
- 1] == '/')
3979 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
3980 hide_refs
->strdup_strings
= 1;
3982 string_list_append(hide_refs
, ref
);
3987 int ref_is_hidden(const char *refname
)
3989 struct string_list_item
*item
;
3993 for_each_string_list_item(item
, hide_refs
) {
3995 if (!starts_with(refname
, item
->string
))
3997 len
= strlen(item
->string
);
3998 if (!refname
[len
] || refname
[len
] == '/')
4004 struct expire_reflog_cb
{
4006 reflog_expiry_should_prune_fn
*should_prune_fn
;
4009 unsigned char last_kept_sha1
[20];
4012 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4013 const char *email
, unsigned long timestamp
, int tz
,
4014 const char *message
, void *cb_data
)
4016 struct expire_reflog_cb
*cb
= cb_data
;
4017 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4019 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4020 osha1
= cb
->last_kept_sha1
;
4022 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4023 message
, policy_cb
)) {
4025 printf("would prune %s", message
);
4026 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4027 printf("prune %s", message
);
4030 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4031 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4032 email
, timestamp
, tz
, message
);
4033 hashcpy(cb
->last_kept_sha1
, nsha1
);
4035 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4036 printf("keep %s", message
);
4041 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4043 reflog_expiry_prepare_fn prepare_fn
,
4044 reflog_expiry_should_prune_fn should_prune_fn
,
4045 reflog_expiry_cleanup_fn cleanup_fn
,
4046 void *policy_cb_data
)
4048 static struct lock_file reflog_lock
;
4049 struct expire_reflog_cb cb
;
4050 struct ref_lock
*lock
;
4055 memset(&cb
, 0, sizeof(cb
));
4057 cb
.policy_cb
= policy_cb_data
;
4058 cb
.should_prune_fn
= should_prune_fn
;
4061 * The reflog file is locked by holding the lock on the
4062 * reference itself, plus we might need to update the
4063 * reference if --updateref was specified:
4065 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, 0, &type
);
4067 return error("cannot lock ref '%s'", refname
);
4068 if (!reflog_exists(refname
)) {
4073 log_file
= git_pathdup("logs/%s", refname
);
4074 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4076 * Even though holding $GIT_DIR/logs/$reflog.lock has
4077 * no locking implications, we use the lock_file
4078 * machinery here anyway because it does a lot of the
4079 * work we need, including cleaning up if the program
4080 * exits unexpectedly.
4082 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4083 struct strbuf err
= STRBUF_INIT
;
4084 unable_to_lock_message(log_file
, errno
, &err
);
4085 error("%s", err
.buf
);
4086 strbuf_release(&err
);
4089 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4091 error("cannot fdopen %s (%s)",
4092 reflog_lock
.filename
.buf
, strerror(errno
));
4097 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4098 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4099 (*cleanup_fn
)(cb
.policy_cb
);
4101 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4103 * It doesn't make sense to adjust a reference pointed
4104 * to by a symbolic ref based on expiring entries in
4105 * the symbolic reference's reflog. Nor can we update
4106 * a reference if there are no remaining reflog
4109 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4110 !(type
& REF_ISSYMREF
) &&
4111 !is_null_sha1(cb
.last_kept_sha1
);
4113 if (close_lock_file(&reflog_lock
)) {
4114 status
|= error("couldn't write %s: %s", log_file
,
4116 } else if (update
&&
4117 (write_in_full(lock
->lk
->fd
,
4118 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4119 write_str_in_full(lock
->lk
->fd
, "\n") != 1 ||
4120 close_ref(lock
) < 0)) {
4121 status
|= error("couldn't write %s",
4122 lock
->lk
->filename
.buf
);
4123 rollback_lock_file(&reflog_lock
);
4124 } else if (commit_lock_file(&reflog_lock
)) {
4125 status
|= error("unable to commit reflog '%s' (%s)",
4126 log_file
, strerror(errno
));
4127 } else if (update
&& commit_ref(lock
)) {
4128 status
|= error("couldn't set %s", lock
->ref_name
);
4136 rollback_lock_file(&reflog_lock
);