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 * Used as a flag in ref_update::flags when the lockfile needs to be
63 #define REF_NEEDS_COMMIT 0x20
66 * Try to read one refname component from the front of refname.
67 * Return the length of the component found, or -1 if the component is
68 * not legal. It is legal if it is something reasonable to have under
69 * ".git/refs/"; We do not like it if:
71 * - any path component of it begins with ".", or
72 * - it has double dots "..", or
73 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
74 * - it ends with a "/".
75 * - it ends with ".lock"
76 * - it contains a "\" (backslash)
78 static int check_refname_component(const char *refname
, int flags
)
83 for (cp
= refname
; ; cp
++) {
85 unsigned char disp
= refname_disposition
[ch
];
91 return -1; /* Refname contains "..". */
95 return -1; /* Refname contains "@{". */
104 return 0; /* Component has zero length. */
105 if (refname
[0] == '.')
106 return -1; /* Component starts with '.'. */
107 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
108 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
109 return -1; /* Refname ends with ".lock". */
113 int check_refname_format(const char *refname
, int flags
)
115 int component_len
, component_count
= 0;
117 if (!strcmp(refname
, "@"))
118 /* Refname is a single character '@'. */
122 /* We are at the start of a path component. */
123 component_len
= check_refname_component(refname
, flags
);
124 if (component_len
<= 0) {
125 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
127 (refname
[1] == '\0' || refname
[1] == '/')) {
128 /* Accept one wildcard as a full refname component. */
129 flags
&= ~REFNAME_REFSPEC_PATTERN
;
136 if (refname
[component_len
] == '\0')
138 /* Skip to next component. */
139 refname
+= component_len
+ 1;
142 if (refname
[component_len
- 1] == '.')
143 return -1; /* Refname ends with '.'. */
144 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
145 return -1; /* Refname has only one component. */
152 * Information used (along with the information in ref_entry) to
153 * describe a single cached reference. This data structure only
154 * occurs embedded in a union in struct ref_entry, and only when
155 * (ref_entry->flag & REF_DIR) is zero.
159 * The name of the object to which this reference resolves
160 * (which may be a tag object). If REF_ISBROKEN, this is
161 * null. If REF_ISSYMREF, then this is the name of the object
162 * referred to by the last reference in the symlink chain.
164 unsigned char sha1
[20];
167 * If REF_KNOWS_PEELED, then this field holds the peeled value
168 * of this reference, or null if the reference is known not to
169 * be peelable. See the documentation for peel_ref() for an
170 * exact definition of "peelable".
172 unsigned char peeled
[20];
178 * Information used (along with the information in ref_entry) to
179 * describe a level in the hierarchy of references. This data
180 * structure only occurs embedded in a union in struct ref_entry, and
181 * only when (ref_entry.flag & REF_DIR) is set. In that case,
182 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
183 * in the directory have already been read:
185 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
186 * or packed references, already read.
188 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
189 * references that hasn't been read yet (nor has any of its
192 * Entries within a directory are stored within a growable array of
193 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
194 * sorted are sorted by their component name in strcmp() order and the
195 * remaining entries are unsorted.
197 * Loose references are read lazily, one directory at a time. When a
198 * directory of loose references is read, then all of the references
199 * in that directory are stored, and REF_INCOMPLETE stubs are created
200 * for any subdirectories, but the subdirectories themselves are not
201 * read. The reading is triggered by get_ref_dir().
207 * Entries with index 0 <= i < sorted are sorted by name. New
208 * entries are appended to the list unsorted, and are sorted
209 * only when required; thus we avoid the need to sort the list
210 * after the addition of every reference.
214 /* A pointer to the ref_cache that contains this ref_dir. */
215 struct ref_cache
*ref_cache
;
217 struct ref_entry
**entries
;
221 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
222 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
223 * public values; see refs.h.
227 * The field ref_entry->u.value.peeled of this value entry contains
228 * the correct peeled value for the reference, which might be
229 * null_sha1 if the reference is not a tag or if it is broken.
231 #define REF_KNOWS_PEELED 0x10
233 /* ref_entry represents a directory of references */
237 * Entry has not yet been read from disk (used only for REF_DIR
238 * entries representing loose references)
240 #define REF_INCOMPLETE 0x40
243 * A ref_entry represents either a reference or a "subdirectory" of
246 * Each directory in the reference namespace is represented by a
247 * ref_entry with (flags & REF_DIR) set and containing a subdir member
248 * that holds the entries in that directory that have been read so
249 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
250 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
251 * used for loose reference directories.
253 * References are represented by a ref_entry with (flags & REF_DIR)
254 * unset and a value member that describes the reference's value. The
255 * flag member is at the ref_entry level, but it is also needed to
256 * interpret the contents of the value field (in other words, a
257 * ref_value object is not very much use without the enclosing
260 * Reference names cannot end with slash and directories' names are
261 * always stored with a trailing slash (except for the top-level
262 * directory, which is always denoted by ""). This has two nice
263 * consequences: (1) when the entries in each subdir are sorted
264 * lexicographically by name (as they usually are), the references in
265 * a whole tree can be generated in lexicographic order by traversing
266 * the tree in left-to-right, depth-first order; (2) the names of
267 * references and subdirectories cannot conflict, and therefore the
268 * presence of an empty subdirectory does not block the creation of a
269 * similarly-named reference. (The fact that reference names with the
270 * same leading components can conflict *with each other* is a
271 * separate issue that is regulated by verify_refname_available().)
273 * Please note that the name field contains the fully-qualified
274 * reference (or subdirectory) name. Space could be saved by only
275 * storing the relative names. But that would require the full names
276 * to be generated on the fly when iterating in do_for_each_ref(), and
277 * would break callback functions, who have always been able to assume
278 * that the name strings that they are passed will not be freed during
282 unsigned char flag
; /* ISSYMREF? ISPACKED? */
284 struct ref_value value
; /* if not (flags&REF_DIR) */
285 struct ref_dir subdir
; /* if (flags&REF_DIR) */
288 * The full name of the reference (e.g., "refs/heads/master")
289 * or the full name of the directory with a trailing slash
290 * (e.g., "refs/heads/"):
292 char name
[FLEX_ARRAY
];
295 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
297 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
300 assert(entry
->flag
& REF_DIR
);
301 dir
= &entry
->u
.subdir
;
302 if (entry
->flag
& REF_INCOMPLETE
) {
303 read_loose_refs(entry
->name
, dir
);
304 entry
->flag
&= ~REF_INCOMPLETE
;
310 * Check if a refname is safe.
311 * For refs that start with "refs/" we consider it safe as long they do
312 * not try to resolve to outside of refs/.
314 * For all other refs we only consider them safe iff they only contain
315 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
318 static int refname_is_safe(const char *refname
)
320 if (starts_with(refname
, "refs/")) {
324 buf
= xmalloc(strlen(refname
) + 1);
326 * Does the refname try to escape refs/?
327 * For example: refs/foo/../bar is safe but refs/foo/../../bar
330 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
335 if (!isupper(*refname
) && *refname
!= '_')
342 static struct ref_entry
*create_ref_entry(const char *refname
,
343 const unsigned char *sha1
, int flag
,
347 struct ref_entry
*ref
;
350 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
351 die("Reference has invalid format: '%s'", refname
);
352 len
= strlen(refname
) + 1;
353 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
354 hashcpy(ref
->u
.value
.sha1
, sha1
);
355 hashclr(ref
->u
.value
.peeled
);
356 memcpy(ref
->name
, refname
, len
);
361 static void clear_ref_dir(struct ref_dir
*dir
);
363 static void free_ref_entry(struct ref_entry
*entry
)
365 if (entry
->flag
& REF_DIR
) {
367 * Do not use get_ref_dir() here, as that might
368 * trigger the reading of loose refs.
370 clear_ref_dir(&entry
->u
.subdir
);
376 * Add a ref_entry to the end of dir (unsorted). Entry is always
377 * stored directly in dir; no recursion into subdirectories is
380 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
382 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
383 dir
->entries
[dir
->nr
++] = entry
;
384 /* optimize for the case that entries are added in order */
386 (dir
->nr
== dir
->sorted
+ 1 &&
387 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
388 dir
->entries
[dir
->nr
- 1]->name
) < 0))
389 dir
->sorted
= dir
->nr
;
393 * Clear and free all entries in dir, recursively.
395 static void clear_ref_dir(struct ref_dir
*dir
)
398 for (i
= 0; i
< dir
->nr
; i
++)
399 free_ref_entry(dir
->entries
[i
]);
401 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
406 * Create a struct ref_entry object for the specified dirname.
407 * dirname is the name of the directory with a trailing slash (e.g.,
408 * "refs/heads/") or "" for the top-level directory.
410 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
411 const char *dirname
, size_t len
,
414 struct ref_entry
*direntry
;
415 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
416 memcpy(direntry
->name
, dirname
, len
);
417 direntry
->name
[len
] = '\0';
418 direntry
->u
.subdir
.ref_cache
= ref_cache
;
419 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
423 static int ref_entry_cmp(const void *a
, const void *b
)
425 struct ref_entry
*one
= *(struct ref_entry
**)a
;
426 struct ref_entry
*two
= *(struct ref_entry
**)b
;
427 return strcmp(one
->name
, two
->name
);
430 static void sort_ref_dir(struct ref_dir
*dir
);
432 struct string_slice
{
437 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
439 const struct string_slice
*key
= key_
;
440 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
441 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
444 return '\0' - (unsigned char)ent
->name
[key
->len
];
448 * Return the index of the entry with the given refname from the
449 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
450 * no such entry is found. dir must already be complete.
452 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
454 struct ref_entry
**r
;
455 struct string_slice key
;
457 if (refname
== NULL
|| !dir
->nr
)
463 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
464 ref_entry_cmp_sslice
);
469 return r
- dir
->entries
;
473 * Search for a directory entry directly within dir (without
474 * recursing). Sort dir if necessary. subdirname must be a directory
475 * name (i.e., end in '/'). If mkdir is set, then create the
476 * directory if it is missing; otherwise, return NULL if the desired
477 * directory cannot be found. dir must already be complete.
479 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
480 const char *subdirname
, size_t len
,
483 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
484 struct ref_entry
*entry
;
485 if (entry_index
== -1) {
489 * Since dir is complete, the absence of a subdir
490 * means that the subdir really doesn't exist;
491 * therefore, create an empty record for it but mark
492 * the record complete.
494 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
495 add_entry_to_dir(dir
, entry
);
497 entry
= dir
->entries
[entry_index
];
499 return get_ref_dir(entry
);
503 * If refname is a reference name, find the ref_dir within the dir
504 * tree that should hold refname. If refname is a directory name
505 * (i.e., ends in '/'), then return that ref_dir itself. dir must
506 * represent the top-level directory and must already be complete.
507 * Sort ref_dirs and recurse into subdirectories as necessary. If
508 * mkdir is set, then create any missing directories; otherwise,
509 * return NULL if the desired directory cannot be found.
511 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
512 const char *refname
, int mkdir
)
515 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
516 size_t dirnamelen
= slash
- refname
+ 1;
517 struct ref_dir
*subdir
;
518 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
530 * Find the value entry with the given name in dir, sorting ref_dirs
531 * and recursing into subdirectories as necessary. If the name is not
532 * found or it corresponds to a directory entry, return NULL.
534 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
537 struct ref_entry
*entry
;
538 dir
= find_containing_dir(dir
, refname
, 0);
541 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
542 if (entry_index
== -1)
544 entry
= dir
->entries
[entry_index
];
545 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
549 * Remove the entry with the given name from dir, recursing into
550 * subdirectories as necessary. If refname is the name of a directory
551 * (i.e., ends with '/'), then remove the directory and its contents.
552 * If the removal was successful, return the number of entries
553 * remaining in the directory entry that contained the deleted entry.
554 * If the name was not found, return -1. Please note that this
555 * function only deletes the entry from the cache; it does not delete
556 * it from the filesystem or ensure that other cache entries (which
557 * might be symbolic references to the removed entry) are updated.
558 * Nor does it remove any containing dir entries that might be made
559 * empty by the removal. dir must represent the top-level directory
560 * and must already be complete.
562 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
564 int refname_len
= strlen(refname
);
566 struct ref_entry
*entry
;
567 int is_dir
= refname
[refname_len
- 1] == '/';
570 * refname represents a reference directory. Remove
571 * the trailing slash; otherwise we will get the
572 * directory *representing* refname rather than the
573 * one *containing* it.
575 char *dirname
= xmemdupz(refname
, refname_len
- 1);
576 dir
= find_containing_dir(dir
, dirname
, 0);
579 dir
= find_containing_dir(dir
, refname
, 0);
583 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
584 if (entry_index
== -1)
586 entry
= dir
->entries
[entry_index
];
588 memmove(&dir
->entries
[entry_index
],
589 &dir
->entries
[entry_index
+ 1],
590 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
593 if (dir
->sorted
> entry_index
)
595 free_ref_entry(entry
);
600 * Add a ref_entry to the ref_dir (unsorted), recursing into
601 * subdirectories as necessary. dir must represent the top-level
602 * directory. Return 0 on success.
604 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
606 dir
= find_containing_dir(dir
, ref
->name
, 1);
609 add_entry_to_dir(dir
, ref
);
614 * Emit a warning and return true iff ref1 and ref2 have the same name
615 * and the same sha1. Die if they have the same name but different
618 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
620 if (strcmp(ref1
->name
, ref2
->name
))
623 /* Duplicate name; make sure that they don't conflict: */
625 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
626 /* This is impossible by construction */
627 die("Reference directory conflict: %s", ref1
->name
);
629 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
630 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
632 warning("Duplicated ref: %s", ref1
->name
);
637 * Sort the entries in dir non-recursively (if they are not already
638 * sorted) and remove any duplicate entries.
640 static void sort_ref_dir(struct ref_dir
*dir
)
643 struct ref_entry
*last
= NULL
;
646 * This check also prevents passing a zero-length array to qsort(),
647 * which is a problem on some platforms.
649 if (dir
->sorted
== dir
->nr
)
652 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
654 /* Remove any duplicates: */
655 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
656 struct ref_entry
*entry
= dir
->entries
[j
];
657 if (last
&& is_dup_ref(last
, entry
))
658 free_ref_entry(entry
);
660 last
= dir
->entries
[i
++] = entry
;
662 dir
->sorted
= dir
->nr
= i
;
665 /* Include broken references in a do_for_each_ref*() iteration: */
666 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
669 * Return true iff the reference described by entry can be resolved to
670 * an object in the database. Emit a warning if the referred-to
671 * object does not exist.
673 static int ref_resolves_to_object(struct ref_entry
*entry
)
675 if (entry
->flag
& REF_ISBROKEN
)
677 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
678 error("%s does not point to a valid object!", entry
->name
);
685 * current_ref is a performance hack: when iterating over references
686 * using the for_each_ref*() functions, current_ref is set to the
687 * current reference's entry before calling the callback function. If
688 * the callback function calls peel_ref(), then peel_ref() first
689 * checks whether the reference to be peeled is the current reference
690 * (it usually is) and if so, returns that reference's peeled version
691 * if it is available. This avoids a refname lookup in a common case.
693 static struct ref_entry
*current_ref
;
695 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
697 struct ref_entry_cb
{
706 * Handle one reference in a do_for_each_ref*()-style iteration,
707 * calling an each_ref_fn for each entry.
709 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
711 struct ref_entry_cb
*data
= cb_data
;
712 struct ref_entry
*old_current_ref
;
715 if (!starts_with(entry
->name
, data
->base
))
718 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
719 !ref_resolves_to_object(entry
))
722 /* Store the old value, in case this is a recursive call: */
723 old_current_ref
= current_ref
;
725 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
726 entry
->flag
, data
->cb_data
);
727 current_ref
= old_current_ref
;
732 * Call fn for each reference in dir that has index in the range
733 * offset <= index < dir->nr. Recurse into subdirectories that are in
734 * that index range, sorting them before iterating. This function
735 * does not sort dir itself; it should be sorted beforehand. fn is
736 * called for all references, including broken ones.
738 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
739 each_ref_entry_fn fn
, void *cb_data
)
742 assert(dir
->sorted
== dir
->nr
);
743 for (i
= offset
; i
< dir
->nr
; i
++) {
744 struct ref_entry
*entry
= dir
->entries
[i
];
746 if (entry
->flag
& REF_DIR
) {
747 struct ref_dir
*subdir
= get_ref_dir(entry
);
748 sort_ref_dir(subdir
);
749 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
751 retval
= fn(entry
, cb_data
);
760 * Call fn for each reference in the union of dir1 and dir2, in order
761 * by refname. Recurse into subdirectories. If a value entry appears
762 * in both dir1 and dir2, then only process the version that is in
763 * dir2. The input dirs must already be sorted, but subdirs will be
764 * sorted as needed. fn is called for all references, including
767 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
768 struct ref_dir
*dir2
,
769 each_ref_entry_fn fn
, void *cb_data
)
774 assert(dir1
->sorted
== dir1
->nr
);
775 assert(dir2
->sorted
== dir2
->nr
);
777 struct ref_entry
*e1
, *e2
;
779 if (i1
== dir1
->nr
) {
780 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
782 if (i2
== dir2
->nr
) {
783 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
785 e1
= dir1
->entries
[i1
];
786 e2
= dir2
->entries
[i2
];
787 cmp
= strcmp(e1
->name
, e2
->name
);
789 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
790 /* Both are directories; descend them in parallel. */
791 struct ref_dir
*subdir1
= get_ref_dir(e1
);
792 struct ref_dir
*subdir2
= get_ref_dir(e2
);
793 sort_ref_dir(subdir1
);
794 sort_ref_dir(subdir2
);
795 retval
= do_for_each_entry_in_dirs(
796 subdir1
, subdir2
, fn
, cb_data
);
799 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
800 /* Both are references; ignore the one from dir1. */
801 retval
= fn(e2
, cb_data
);
805 die("conflict between reference and directory: %s",
817 if (e
->flag
& REF_DIR
) {
818 struct ref_dir
*subdir
= get_ref_dir(e
);
819 sort_ref_dir(subdir
);
820 retval
= do_for_each_entry_in_dir(
821 subdir
, 0, fn
, cb_data
);
823 retval
= fn(e
, cb_data
);
832 * Load all of the refs from the dir into our in-memory cache. The hard work
833 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
834 * through all of the sub-directories. We do not even need to care about
835 * sorting, as traversal order does not matter to us.
837 static void prime_ref_dir(struct ref_dir
*dir
)
840 for (i
= 0; i
< dir
->nr
; i
++) {
841 struct ref_entry
*entry
= dir
->entries
[i
];
842 if (entry
->flag
& REF_DIR
)
843 prime_ref_dir(get_ref_dir(entry
));
847 struct nonmatching_ref_data
{
848 const struct string_list
*skip
;
849 const char *conflicting_refname
;
852 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
854 struct nonmatching_ref_data
*data
= vdata
;
856 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
859 data
->conflicting_refname
= entry
->name
;
864 * Return 0 if a reference named refname could be created without
865 * conflicting with the name of an existing reference in dir.
866 * Otherwise, return a negative value and write an explanation to err.
867 * If extras is non-NULL, it is a list of additional refnames with
868 * which refname is not allowed to conflict. If skip is non-NULL,
869 * ignore potential conflicts with refs in skip (e.g., because they
870 * are scheduled for deletion in the same operation). Behavior is
871 * undefined if the same name is listed in both extras and skip.
873 * Two reference names conflict if one of them exactly matches the
874 * leading components of the other; e.g., "refs/foo/bar" conflicts
875 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
876 * "refs/foo/bar" or "refs/foo/barbados".
878 * extras and skip must be sorted.
880 static int verify_refname_available(const char *refname
,
881 const struct string_list
*extras
,
882 const struct string_list
*skip
,
888 struct strbuf dirname
= STRBUF_INIT
;
892 * For the sake of comments in this function, suppose that
893 * refname is "refs/foo/bar".
898 strbuf_grow(&dirname
, strlen(refname
) + 1);
899 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
900 /* Expand dirname to the new prefix, not including the trailing slash: */
901 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
904 * We are still at a leading dir of the refname (e.g.,
905 * "refs/foo"; if there is a reference with that name,
906 * it is a conflict, *unless* it is in skip.
909 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
911 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
913 * We found a reference whose name is
914 * a proper prefix of refname; e.g.,
915 * "refs/foo", and is not in skip.
917 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
918 dirname
.buf
, refname
);
923 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
924 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
925 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
926 refname
, dirname
.buf
);
931 * Otherwise, we can try to continue our search with
932 * the next component. So try to look up the
933 * directory, e.g., "refs/foo/". If we come up empty,
934 * we know there is nothing under this whole prefix,
935 * but even in that case we still have to continue the
936 * search for conflicts with extras.
938 strbuf_addch(&dirname
, '/');
940 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
943 * There was no directory "refs/foo/",
944 * so there is nothing under this
945 * whole prefix. So there is no need
946 * to continue looking for conflicting
947 * references. But we need to continue
948 * looking for conflicting extras.
952 dir
= get_ref_dir(dir
->entries
[pos
]);
958 * We are at the leaf of our refname (e.g., "refs/foo/bar").
959 * There is no point in searching for a reference with that
960 * name, because a refname isn't considered to conflict with
961 * itself. But we still need to check for references whose
962 * names are in the "refs/foo/bar/" namespace, because they
965 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
966 strbuf_addch(&dirname
, '/');
969 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
973 * We found a directory named "$refname/"
974 * (e.g., "refs/foo/bar/"). It is a problem
975 * iff it contains any ref that is not in
978 struct nonmatching_ref_data data
;
981 data
.conflicting_refname
= NULL
;
982 dir
= get_ref_dir(dir
->entries
[pos
]);
984 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
985 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
986 data
.conflicting_refname
, refname
);
994 * Check for entries in extras that start with
995 * "$refname/". We do that by looking for the place
996 * where "$refname/" would be inserted in extras. If
997 * there is an entry at that position that starts with
998 * "$refname/" and is not in skip, then we have a
1001 for (pos
= string_list_find_insert_index(extras
, dirname
.buf
, 0);
1002 pos
< extras
->nr
; pos
++) {
1003 const char *extra_refname
= extras
->items
[pos
].string
;
1005 if (!starts_with(extra_refname
, dirname
.buf
))
1008 if (!skip
|| !string_list_has_string(skip
, extra_refname
)) {
1009 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
1010 refname
, extra_refname
);
1016 /* No conflicts were found */
1020 strbuf_release(&dirname
);
1024 struct packed_ref_cache
{
1025 struct ref_entry
*root
;
1028 * Count of references to the data structure in this instance,
1029 * including the pointer from ref_cache::packed if any. The
1030 * data will not be freed as long as the reference count is
1033 unsigned int referrers
;
1036 * Iff the packed-refs file associated with this instance is
1037 * currently locked for writing, this points at the associated
1038 * lock (which is owned by somebody else). The referrer count
1039 * is also incremented when the file is locked and decremented
1040 * when it is unlocked.
1042 struct lock_file
*lock
;
1044 /* The metadata from when this packed-refs cache was read */
1045 struct stat_validity validity
;
1049 * Future: need to be in "struct repository"
1050 * when doing a full libification.
1052 static struct ref_cache
{
1053 struct ref_cache
*next
;
1054 struct ref_entry
*loose
;
1055 struct packed_ref_cache
*packed
;
1057 * The submodule name, or "" for the main repo. We allocate
1058 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1059 * is initialized correctly.
1062 } ref_cache
, *submodule_ref_caches
;
1064 /* Lock used for the main packed-refs file: */
1065 static struct lock_file packlock
;
1068 * Increment the reference count of *packed_refs.
1070 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1072 packed_refs
->referrers
++;
1076 * Decrease the reference count of *packed_refs. If it goes to zero,
1077 * free *packed_refs and return true; otherwise return false.
1079 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1081 if (!--packed_refs
->referrers
) {
1082 free_ref_entry(packed_refs
->root
);
1083 stat_validity_clear(&packed_refs
->validity
);
1091 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1094 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1096 if (packed_refs
->lock
)
1097 die("internal error: packed-ref cache cleared while locked");
1098 refs
->packed
= NULL
;
1099 release_packed_ref_cache(packed_refs
);
1103 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1106 free_ref_entry(refs
->loose
);
1111 static struct ref_cache
*create_ref_cache(const char *submodule
)
1114 struct ref_cache
*refs
;
1117 len
= strlen(submodule
) + 1;
1118 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1119 memcpy(refs
->name
, submodule
, len
);
1124 * Return a pointer to a ref_cache for the specified submodule. For
1125 * the main repository, use submodule==NULL. The returned structure
1126 * will be allocated and initialized but not necessarily populated; it
1127 * should not be freed.
1129 static struct ref_cache
*get_ref_cache(const char *submodule
)
1131 struct ref_cache
*refs
;
1133 if (!submodule
|| !*submodule
)
1136 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1137 if (!strcmp(submodule
, refs
->name
))
1140 refs
= create_ref_cache(submodule
);
1141 refs
->next
= submodule_ref_caches
;
1142 submodule_ref_caches
= refs
;
1146 /* The length of a peeled reference line in packed-refs, including EOL: */
1147 #define PEELED_LINE_LENGTH 42
1150 * The packed-refs header line that we write out. Perhaps other
1151 * traits will be added later. The trailing space is required.
1153 static const char PACKED_REFS_HEADER
[] =
1154 "# pack-refs with: peeled fully-peeled \n";
1157 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1158 * Return a pointer to the refname within the line (null-terminated),
1159 * or NULL if there was a problem.
1161 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1166 * 42: the answer to everything.
1168 * In this case, it happens to be the answer to
1169 * 40 (length of sha1 hex representation)
1170 * +1 (space in between hex and name)
1171 * +1 (newline at the end of the line)
1173 if (line
->len
<= 42)
1176 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1178 if (!isspace(line
->buf
[40]))
1181 ref
= line
->buf
+ 41;
1185 if (line
->buf
[line
->len
- 1] != '\n')
1187 line
->buf
[--line
->len
] = 0;
1193 * Read f, which is a packed-refs file, into dir.
1195 * A comment line of the form "# pack-refs with: " may contain zero or
1196 * more traits. We interpret the traits as follows:
1200 * Probably no references are peeled. But if the file contains a
1201 * peeled value for a reference, we will use it.
1205 * References under "refs/tags/", if they *can* be peeled, *are*
1206 * peeled in this file. References outside of "refs/tags/" are
1207 * probably not peeled even if they could have been, but if we find
1208 * a peeled value for such a reference we will use it.
1212 * All references in the file that can be peeled are peeled.
1213 * Inversely (and this is more important), any references in the
1214 * file for which no peeled value is recorded is not peelable. This
1215 * trait should typically be written alongside "peeled" for
1216 * compatibility with older clients, but we do not require it
1217 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1219 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1221 struct ref_entry
*last
= NULL
;
1222 struct strbuf line
= STRBUF_INIT
;
1223 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1225 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1226 unsigned char sha1
[20];
1227 const char *refname
;
1230 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1231 if (strstr(traits
, " fully-peeled "))
1232 peeled
= PEELED_FULLY
;
1233 else if (strstr(traits
, " peeled "))
1234 peeled
= PEELED_TAGS
;
1235 /* perhaps other traits later as well */
1239 refname
= parse_ref_line(&line
, sha1
);
1241 int flag
= REF_ISPACKED
;
1243 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1244 if (!refname_is_safe(refname
))
1245 die("packed refname is dangerous: %s", refname
);
1247 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1249 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1250 if (peeled
== PEELED_FULLY
||
1251 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1252 last
->flag
|= REF_KNOWS_PEELED
;
1257 line
.buf
[0] == '^' &&
1258 line
.len
== PEELED_LINE_LENGTH
&&
1259 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1260 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1261 hashcpy(last
->u
.value
.peeled
, sha1
);
1263 * Regardless of what the file header said,
1264 * we definitely know the value of *this*
1267 last
->flag
|= REF_KNOWS_PEELED
;
1271 strbuf_release(&line
);
1275 * Get the packed_ref_cache for the specified ref_cache, creating it
1278 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1280 const char *packed_refs_file
;
1283 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1285 packed_refs_file
= git_path("packed-refs");
1288 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1289 clear_packed_ref_cache(refs
);
1291 if (!refs
->packed
) {
1294 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1295 acquire_packed_ref_cache(refs
->packed
);
1296 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1297 f
= fopen(packed_refs_file
, "r");
1299 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1300 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1304 return refs
->packed
;
1307 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1309 return get_ref_dir(packed_ref_cache
->root
);
1312 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1314 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1317 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1319 struct packed_ref_cache
*packed_ref_cache
=
1320 get_packed_ref_cache(&ref_cache
);
1322 if (!packed_ref_cache
->lock
)
1323 die("internal error: packed refs not locked");
1324 add_ref(get_packed_ref_dir(packed_ref_cache
),
1325 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1329 * Read the loose references from the namespace dirname into dir
1330 * (without recursing). dirname must end with '/'. dir must be the
1331 * directory entry corresponding to dirname.
1333 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1335 struct ref_cache
*refs
= dir
->ref_cache
;
1339 int dirnamelen
= strlen(dirname
);
1340 struct strbuf refname
;
1343 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1345 path
= git_path("%s", dirname
);
1351 strbuf_init(&refname
, dirnamelen
+ 257);
1352 strbuf_add(&refname
, dirname
, dirnamelen
);
1354 while ((de
= readdir(d
)) != NULL
) {
1355 unsigned char sha1
[20];
1360 if (de
->d_name
[0] == '.')
1362 if (ends_with(de
->d_name
, ".lock"))
1364 strbuf_addstr(&refname
, de
->d_name
);
1365 refdir
= *refs
->name
1366 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1367 : git_path("%s", refname
.buf
);
1368 if (stat(refdir
, &st
) < 0) {
1369 ; /* silently ignore */
1370 } else if (S_ISDIR(st
.st_mode
)) {
1371 strbuf_addch(&refname
, '/');
1372 add_entry_to_dir(dir
,
1373 create_dir_entry(refs
, refname
.buf
,
1379 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1381 flag
|= REF_ISBROKEN
;
1383 } else if (read_ref_full(refname
.buf
,
1384 RESOLVE_REF_READING
,
1387 flag
|= REF_ISBROKEN
;
1389 if (check_refname_format(refname
.buf
,
1390 REFNAME_ALLOW_ONELEVEL
)) {
1391 if (!refname_is_safe(refname
.buf
))
1392 die("loose refname is dangerous: %s", refname
.buf
);
1394 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1396 add_entry_to_dir(dir
,
1397 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1399 strbuf_setlen(&refname
, dirnamelen
);
1401 strbuf_release(&refname
);
1405 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1409 * Mark the top-level directory complete because we
1410 * are about to read the only subdirectory that can
1413 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1415 * Create an incomplete entry for "refs/":
1417 add_entry_to_dir(get_ref_dir(refs
->loose
),
1418 create_dir_entry(refs
, "refs/", 5, 1));
1420 return get_ref_dir(refs
->loose
);
1423 /* We allow "recursive" symbolic refs. Only within reason, though */
1425 #define MAXREFLEN (1024)
1428 * Called by resolve_gitlink_ref_recursive() after it failed to read
1429 * from the loose refs in ref_cache refs. Find <refname> in the
1430 * packed-refs file for the submodule.
1432 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1433 const char *refname
, unsigned char *sha1
)
1435 struct ref_entry
*ref
;
1436 struct ref_dir
*dir
= get_packed_refs(refs
);
1438 ref
= find_ref(dir
, refname
);
1442 hashcpy(sha1
, ref
->u
.value
.sha1
);
1446 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1447 const char *refname
, unsigned char *sha1
,
1451 char buffer
[128], *p
;
1454 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1457 ? git_path_submodule(refs
->name
, "%s", refname
)
1458 : git_path("%s", refname
);
1459 fd
= open(path
, O_RDONLY
);
1461 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1463 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1467 while (len
&& isspace(buffer
[len
-1]))
1471 /* Was it a detached head or an old-fashioned symlink? */
1472 if (!get_sha1_hex(buffer
, sha1
))
1476 if (strncmp(buffer
, "ref:", 4))
1482 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1485 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1487 int len
= strlen(path
), retval
;
1489 struct ref_cache
*refs
;
1491 while (len
&& path
[len
-1] == '/')
1495 submodule
= xstrndup(path
, len
);
1496 refs
= get_ref_cache(submodule
);
1499 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1504 * Return the ref_entry for the given refname from the packed
1505 * references. If it does not exist, return NULL.
1507 static struct ref_entry
*get_packed_ref(const char *refname
)
1509 return find_ref(get_packed_refs(&ref_cache
), refname
);
1513 * A loose ref file doesn't exist; check for a packed ref. The
1514 * options are forwarded from resolve_safe_unsafe().
1516 static int resolve_missing_loose_ref(const char *refname
,
1518 unsigned char *sha1
,
1521 struct ref_entry
*entry
;
1524 * The loose reference file does not exist; check for a packed
1527 entry
= get_packed_ref(refname
);
1529 hashcpy(sha1
, entry
->u
.value
.sha1
);
1531 *flags
|= REF_ISPACKED
;
1534 /* The reference is not a packed reference, either. */
1535 if (resolve_flags
& RESOLVE_REF_READING
) {
1544 /* This function needs to return a meaningful errno on failure */
1545 static const char *resolve_ref_unsafe_1(const char *refname
,
1547 unsigned char *sha1
,
1549 struct strbuf
*sb_path
)
1551 int depth
= MAXDEPTH
;
1554 static char refname_buffer
[256];
1560 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1562 *flags
|= REF_BAD_NAME
;
1564 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1565 !refname_is_safe(refname
)) {
1570 * dwim_ref() uses REF_ISBROKEN to distinguish between
1571 * missing refs and refs that were present but invalid,
1572 * to complain about the latter to stderr.
1574 * We don't know whether the ref exists, so don't set
1590 strbuf_reset(sb_path
);
1591 strbuf_git_path(sb_path
, "%s", refname
);
1592 path
= sb_path
->buf
;
1595 * We might have to loop back here to avoid a race
1596 * condition: first we lstat() the file, then we try
1597 * to read it as a link or as a file. But if somebody
1598 * changes the type of the file (file <-> directory
1599 * <-> symlink) between the lstat() and reading, then
1600 * we don't want to report that as an error but rather
1601 * try again starting with the lstat().
1604 if (lstat(path
, &st
) < 0) {
1605 if (errno
!= ENOENT
)
1607 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1613 *flags
|= REF_ISBROKEN
;
1618 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1619 if (S_ISLNK(st
.st_mode
)) {
1620 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1622 if (errno
== ENOENT
|| errno
== EINVAL
)
1623 /* inconsistent with lstat; retry */
1629 if (starts_with(buffer
, "refs/") &&
1630 !check_refname_format(buffer
, 0)) {
1631 strcpy(refname_buffer
, buffer
);
1632 refname
= refname_buffer
;
1634 *flags
|= REF_ISSYMREF
;
1635 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1643 /* Is it a directory? */
1644 if (S_ISDIR(st
.st_mode
)) {
1650 * Anything else, just open it and try to use it as
1653 fd
= open(path
, O_RDONLY
);
1655 if (errno
== ENOENT
)
1656 /* inconsistent with lstat; retry */
1661 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1663 int save_errno
= errno
;
1669 while (len
&& isspace(buffer
[len
-1]))
1674 * Is it a symbolic ref?
1676 if (!starts_with(buffer
, "ref:")) {
1678 * Please note that FETCH_HEAD has a second
1679 * line containing other data.
1681 if (get_sha1_hex(buffer
, sha1
) ||
1682 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1684 *flags
|= REF_ISBROKEN
;
1691 *flags
|= REF_ISBROKEN
;
1696 *flags
|= REF_ISSYMREF
;
1698 while (isspace(*buf
))
1700 refname
= strcpy(refname_buffer
, buf
);
1701 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1705 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1707 *flags
|= REF_ISBROKEN
;
1709 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1710 !refname_is_safe(buf
)) {
1719 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1720 unsigned char *sha1
, int *flags
)
1722 struct strbuf sb_path
= STRBUF_INIT
;
1723 const char *ret
= resolve_ref_unsafe_1(refname
, resolve_flags
,
1724 sha1
, flags
, &sb_path
);
1725 strbuf_release(&sb_path
);
1729 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1731 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1734 /* The argument to filter_refs */
1736 const char *pattern
;
1741 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1743 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1748 int read_ref(const char *refname
, unsigned char *sha1
)
1750 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1753 int ref_exists(const char *refname
)
1755 unsigned char sha1
[20];
1756 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1759 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1762 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1763 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1765 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1769 /* object was peeled successfully: */
1773 * object cannot be peeled because the named object (or an
1774 * object referred to by a tag in the peel chain), does not
1779 /* object cannot be peeled because it is not a tag: */
1782 /* ref_entry contains no peeled value because it is a symref: */
1783 PEEL_IS_SYMREF
= -3,
1786 * ref_entry cannot be peeled because it is broken (i.e., the
1787 * symbolic reference cannot even be resolved to an object
1794 * Peel the named object; i.e., if the object is a tag, resolve the
1795 * tag recursively until a non-tag is found. If successful, store the
1796 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1797 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1798 * and leave sha1 unchanged.
1800 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1802 struct object
*o
= lookup_unknown_object(name
);
1804 if (o
->type
== OBJ_NONE
) {
1805 int type
= sha1_object_info(name
, NULL
);
1806 if (type
< 0 || !object_as_type(o
, type
, 0))
1807 return PEEL_INVALID
;
1810 if (o
->type
!= OBJ_TAG
)
1811 return PEEL_NON_TAG
;
1813 o
= deref_tag_noverify(o
);
1815 return PEEL_INVALID
;
1817 hashcpy(sha1
, o
->sha1
);
1822 * Peel the entry (if possible) and return its new peel_status. If
1823 * repeel is true, re-peel the entry even if there is an old peeled
1824 * value that is already stored in it.
1826 * It is OK to call this function with a packed reference entry that
1827 * might be stale and might even refer to an object that has since
1828 * been garbage-collected. In such a case, if the entry has
1829 * REF_KNOWS_PEELED then leave the status unchanged and return
1830 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1832 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1834 enum peel_status status
;
1836 if (entry
->flag
& REF_KNOWS_PEELED
) {
1838 entry
->flag
&= ~REF_KNOWS_PEELED
;
1839 hashclr(entry
->u
.value
.peeled
);
1841 return is_null_sha1(entry
->u
.value
.peeled
) ?
1842 PEEL_NON_TAG
: PEEL_PEELED
;
1845 if (entry
->flag
& REF_ISBROKEN
)
1847 if (entry
->flag
& REF_ISSYMREF
)
1848 return PEEL_IS_SYMREF
;
1850 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1851 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1852 entry
->flag
|= REF_KNOWS_PEELED
;
1856 int peel_ref(const char *refname
, unsigned char *sha1
)
1859 unsigned char base
[20];
1861 if (current_ref
&& (current_ref
->name
== refname
1862 || !strcmp(current_ref
->name
, refname
))) {
1863 if (peel_entry(current_ref
, 0))
1865 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1869 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1873 * If the reference is packed, read its ref_entry from the
1874 * cache in the hope that we already know its peeled value.
1875 * We only try this optimization on packed references because
1876 * (a) forcing the filling of the loose reference cache could
1877 * be expensive and (b) loose references anyway usually do not
1878 * have REF_KNOWS_PEELED.
1880 if (flag
& REF_ISPACKED
) {
1881 struct ref_entry
*r
= get_packed_ref(refname
);
1883 if (peel_entry(r
, 0))
1885 hashcpy(sha1
, r
->u
.value
.peeled
);
1890 return peel_object(base
, sha1
);
1893 struct warn_if_dangling_data
{
1895 const char *refname
;
1896 const struct string_list
*refnames
;
1897 const char *msg_fmt
;
1900 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1901 int flags
, void *cb_data
)
1903 struct warn_if_dangling_data
*d
= cb_data
;
1904 const char *resolves_to
;
1905 unsigned char junk
[20];
1907 if (!(flags
& REF_ISSYMREF
))
1910 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1913 ? strcmp(resolves_to
, d
->refname
)
1914 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1918 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1923 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1925 struct warn_if_dangling_data data
;
1928 data
.refname
= refname
;
1929 data
.refnames
= NULL
;
1930 data
.msg_fmt
= msg_fmt
;
1931 for_each_rawref(warn_if_dangling_symref
, &data
);
1934 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1936 struct warn_if_dangling_data data
;
1939 data
.refname
= NULL
;
1940 data
.refnames
= refnames
;
1941 data
.msg_fmt
= msg_fmt
;
1942 for_each_rawref(warn_if_dangling_symref
, &data
);
1946 * Call fn for each reference in the specified ref_cache, omitting
1947 * references not in the containing_dir of base. fn is called for all
1948 * references, including broken ones. If fn ever returns a non-zero
1949 * value, stop the iteration and return that value; otherwise, return
1952 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1953 each_ref_entry_fn fn
, void *cb_data
)
1955 struct packed_ref_cache
*packed_ref_cache
;
1956 struct ref_dir
*loose_dir
;
1957 struct ref_dir
*packed_dir
;
1961 * We must make sure that all loose refs are read before accessing the
1962 * packed-refs file; this avoids a race condition in which loose refs
1963 * are migrated to the packed-refs file by a simultaneous process, but
1964 * our in-memory view is from before the migration. get_packed_ref_cache()
1965 * takes care of making sure our view is up to date with what is on
1968 loose_dir
= get_loose_refs(refs
);
1969 if (base
&& *base
) {
1970 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1973 prime_ref_dir(loose_dir
);
1975 packed_ref_cache
= get_packed_ref_cache(refs
);
1976 acquire_packed_ref_cache(packed_ref_cache
);
1977 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1978 if (base
&& *base
) {
1979 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1982 if (packed_dir
&& loose_dir
) {
1983 sort_ref_dir(packed_dir
);
1984 sort_ref_dir(loose_dir
);
1985 retval
= do_for_each_entry_in_dirs(
1986 packed_dir
, loose_dir
, fn
, cb_data
);
1987 } else if (packed_dir
) {
1988 sort_ref_dir(packed_dir
);
1989 retval
= do_for_each_entry_in_dir(
1990 packed_dir
, 0, fn
, cb_data
);
1991 } else if (loose_dir
) {
1992 sort_ref_dir(loose_dir
);
1993 retval
= do_for_each_entry_in_dir(
1994 loose_dir
, 0, fn
, cb_data
);
1997 release_packed_ref_cache(packed_ref_cache
);
2002 * Call fn for each reference in the specified ref_cache for which the
2003 * refname begins with base. If trim is non-zero, then trim that many
2004 * characters off the beginning of each refname before passing the
2005 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2006 * broken references in the iteration. If fn ever returns a non-zero
2007 * value, stop the iteration and return that value; otherwise, return
2010 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
2011 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
2013 struct ref_entry_cb data
;
2018 data
.cb_data
= cb_data
;
2020 if (ref_paranoia
< 0)
2021 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2023 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2025 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
2028 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2030 unsigned char sha1
[20];
2034 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
2035 return fn("HEAD", sha1
, 0, cb_data
);
2040 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
2041 return fn("HEAD", sha1
, flag
, cb_data
);
2046 int head_ref(each_ref_fn fn
, void *cb_data
)
2048 return do_head_ref(NULL
, fn
, cb_data
);
2051 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2053 return do_head_ref(submodule
, fn
, cb_data
);
2056 int for_each_ref(each_ref_fn fn
, void *cb_data
)
2058 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
2061 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2063 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2066 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2068 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2071 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2072 each_ref_fn fn
, void *cb_data
)
2074 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2077 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2079 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2082 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2084 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2087 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2089 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2092 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2094 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2097 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2099 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2102 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2104 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2107 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2109 return do_for_each_ref(&ref_cache
, git_replace_ref_base
, fn
,
2110 strlen(git_replace_ref_base
), 0, cb_data
);
2113 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2115 struct strbuf buf
= STRBUF_INIT
;
2117 unsigned char sha1
[20];
2120 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2121 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2122 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2123 strbuf_release(&buf
);
2128 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2130 struct strbuf buf
= STRBUF_INIT
;
2132 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2133 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2134 strbuf_release(&buf
);
2138 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2139 const char *prefix
, void *cb_data
)
2141 struct strbuf real_pattern
= STRBUF_INIT
;
2142 struct ref_filter filter
;
2145 if (!prefix
&& !starts_with(pattern
, "refs/"))
2146 strbuf_addstr(&real_pattern
, "refs/");
2148 strbuf_addstr(&real_pattern
, prefix
);
2149 strbuf_addstr(&real_pattern
, pattern
);
2151 if (!has_glob_specials(pattern
)) {
2152 /* Append implied '/' '*' if not present. */
2153 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2154 strbuf_addch(&real_pattern
, '/');
2155 /* No need to check for '*', there is none. */
2156 strbuf_addch(&real_pattern
, '*');
2159 filter
.pattern
= real_pattern
.buf
;
2161 filter
.cb_data
= cb_data
;
2162 ret
= for_each_ref(filter_refs
, &filter
);
2164 strbuf_release(&real_pattern
);
2168 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2170 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2173 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2175 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2176 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2179 const char *prettify_refname(const char *name
)
2182 starts_with(name
, "refs/heads/") ? 11 :
2183 starts_with(name
, "refs/tags/") ? 10 :
2184 starts_with(name
, "refs/remotes/") ? 13 :
2188 static const char *ref_rev_parse_rules
[] = {
2193 "refs/remotes/%.*s",
2194 "refs/remotes/%.*s/HEAD",
2198 int refname_match(const char *abbrev_name
, const char *full_name
)
2201 const int abbrev_name_len
= strlen(abbrev_name
);
2203 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2204 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2212 static void unlock_ref(struct ref_lock
*lock
)
2214 /* Do not free lock->lk -- atexit() still looks at them */
2216 rollback_lock_file(lock
->lk
);
2217 free(lock
->ref_name
);
2218 free(lock
->orig_ref_name
);
2222 /* This function should make sure errno is meaningful on error */
2223 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2224 const unsigned char *old_sha1
, int mustexist
)
2226 if (read_ref_full(lock
->ref_name
,
2227 mustexist
? RESOLVE_REF_READING
: 0,
2228 lock
->old_sha1
, NULL
)) {
2229 int save_errno
= errno
;
2230 error("Can't verify ref %s", lock
->ref_name
);
2235 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2236 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2237 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2245 static int remove_empty_directories(const char *file
)
2247 /* we want to create a file but there is a directory there;
2248 * if that is an empty directory (or a directory that contains
2249 * only empty directories), remove them.
2252 int result
, save_errno
;
2254 strbuf_init(&path
, 20);
2255 strbuf_addstr(&path
, file
);
2257 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2260 strbuf_release(&path
);
2267 * *string and *len will only be substituted, and *string returned (for
2268 * later free()ing) if the string passed in is a magic short-hand form
2271 static char *substitute_branch_name(const char **string
, int *len
)
2273 struct strbuf buf
= STRBUF_INIT
;
2274 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2278 *string
= strbuf_detach(&buf
, &size
);
2280 return (char *)*string
;
2286 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2288 char *last_branch
= substitute_branch_name(&str
, &len
);
2293 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2294 char fullref
[PATH_MAX
];
2295 unsigned char sha1_from_ref
[20];
2296 unsigned char *this_result
;
2299 this_result
= refs_found
? sha1_from_ref
: sha1
;
2300 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2301 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2302 this_result
, &flag
);
2306 if (!warn_ambiguous_refs
)
2308 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2309 warning("ignoring dangling symref %s.", fullref
);
2310 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2311 warning("ignoring broken ref %s.", fullref
);
2318 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2320 char *last_branch
= substitute_branch_name(&str
, &len
);
2325 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2326 unsigned char hash
[20];
2327 char path
[PATH_MAX
];
2328 const char *ref
, *it
;
2330 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2331 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2335 if (reflog_exists(path
))
2337 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2341 if (!logs_found
++) {
2343 hashcpy(sha1
, hash
);
2345 if (!warn_ambiguous_refs
)
2353 * Locks a ref returning the lock on success and NULL on failure.
2354 * On failure errno is set to something meaningful.
2356 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2357 const unsigned char *old_sha1
,
2358 const struct string_list
*extras
,
2359 const struct string_list
*skip
,
2360 unsigned int flags
, int *type_p
,
2363 const char *ref_file
;
2364 const char *orig_refname
= refname
;
2365 struct ref_lock
*lock
;
2368 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2369 int resolve_flags
= 0;
2370 int attempts_remaining
= 3;
2374 lock
= xcalloc(1, sizeof(struct ref_lock
));
2377 resolve_flags
|= RESOLVE_REF_READING
;
2378 if (flags
& REF_DELETING
) {
2379 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2380 if (flags
& REF_NODEREF
)
2381 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2384 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2385 lock
->old_sha1
, &type
);
2386 if (!refname
&& errno
== EISDIR
) {
2387 /* we are trying to lock foo but we used to
2388 * have foo/bar which now does not exist;
2389 * it is normal for the empty directory 'foo'
2392 ref_file
= git_path("%s", orig_refname
);
2393 if (remove_empty_directories(ref_file
)) {
2396 if (!verify_refname_available(orig_refname
, extras
, skip
,
2397 get_loose_refs(&ref_cache
), err
))
2398 strbuf_addf(err
, "there are still refs under '%s'",
2403 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2404 lock
->old_sha1
, &type
);
2410 if (last_errno
!= ENOTDIR
||
2411 !verify_refname_available(orig_refname
, extras
, skip
,
2412 get_loose_refs(&ref_cache
), err
))
2413 strbuf_addf(err
, "unable to resolve reference %s: %s",
2414 orig_refname
, strerror(last_errno
));
2419 * If the ref did not exist and we are creating it, make sure
2420 * there is no existing packed ref whose name begins with our
2421 * refname, nor a packed ref whose name is a proper prefix of
2424 if (is_null_sha1(lock
->old_sha1
) &&
2425 verify_refname_available(refname
, extras
, skip
,
2426 get_packed_refs(&ref_cache
), err
)) {
2427 last_errno
= ENOTDIR
;
2431 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2434 if (flags
& REF_NODEREF
) {
2435 refname
= orig_refname
;
2436 lflags
|= LOCK_NO_DEREF
;
2438 lock
->ref_name
= xstrdup(refname
);
2439 lock
->orig_ref_name
= xstrdup(orig_refname
);
2440 ref_file
= git_path("%s", refname
);
2443 switch (safe_create_leading_directories_const(ref_file
)) {
2445 break; /* success */
2447 if (--attempts_remaining
> 0)
2452 strbuf_addf(err
, "unable to create directory for %s", ref_file
);
2456 if (hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
) < 0) {
2458 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2460 * Maybe somebody just deleted one of the
2461 * directories leading to ref_file. Try
2466 unable_to_lock_message(ref_file
, errno
, err
);
2470 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2479 * Write an entry to the packed-refs file for the specified refname.
2480 * If peeled is non-NULL, write it as the entry's peeled value.
2482 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2483 unsigned char *peeled
)
2485 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2487 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2491 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2493 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2495 enum peel_status peel_status
= peel_entry(entry
, 0);
2497 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2498 error("internal error: %s is not a valid packed reference!",
2500 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2501 peel_status
== PEEL_PEELED
?
2502 entry
->u
.value
.peeled
: NULL
);
2506 /* This should return a meaningful errno on failure */
2507 int lock_packed_refs(int flags
)
2509 static int timeout_configured
= 0;
2510 static int timeout_value
= 1000;
2512 struct packed_ref_cache
*packed_ref_cache
;
2514 if (!timeout_configured
) {
2515 git_config_get_int("core.packedrefstimeout", &timeout_value
);
2516 timeout_configured
= 1;
2519 if (hold_lock_file_for_update_timeout(
2520 &packlock
, git_path("packed-refs"),
2521 flags
, timeout_value
) < 0)
2524 * Get the current packed-refs while holding the lock. If the
2525 * packed-refs file has been modified since we last read it,
2526 * this will automatically invalidate the cache and re-read
2527 * the packed-refs file.
2529 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2530 packed_ref_cache
->lock
= &packlock
;
2531 /* Increment the reference count to prevent it from being freed: */
2532 acquire_packed_ref_cache(packed_ref_cache
);
2537 * Commit the packed refs changes.
2538 * On error we must make sure that errno contains a meaningful value.
2540 int commit_packed_refs(void)
2542 struct packed_ref_cache
*packed_ref_cache
=
2543 get_packed_ref_cache(&ref_cache
);
2548 if (!packed_ref_cache
->lock
)
2549 die("internal error: packed-refs not locked");
2551 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2553 die_errno("unable to fdopen packed-refs descriptor");
2555 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2556 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2557 0, write_packed_entry_fn
, out
);
2559 if (commit_lock_file(packed_ref_cache
->lock
)) {
2563 packed_ref_cache
->lock
= NULL
;
2564 release_packed_ref_cache(packed_ref_cache
);
2569 void rollback_packed_refs(void)
2571 struct packed_ref_cache
*packed_ref_cache
=
2572 get_packed_ref_cache(&ref_cache
);
2574 if (!packed_ref_cache
->lock
)
2575 die("internal error: packed-refs not locked");
2576 rollback_lock_file(packed_ref_cache
->lock
);
2577 packed_ref_cache
->lock
= NULL
;
2578 release_packed_ref_cache(packed_ref_cache
);
2579 clear_packed_ref_cache(&ref_cache
);
2582 struct ref_to_prune
{
2583 struct ref_to_prune
*next
;
2584 unsigned char sha1
[20];
2585 char name
[FLEX_ARRAY
];
2588 struct pack_refs_cb_data
{
2590 struct ref_dir
*packed_refs
;
2591 struct ref_to_prune
*ref_to_prune
;
2595 * An each_ref_entry_fn that is run over loose references only. If
2596 * the loose reference can be packed, add an entry in the packed ref
2597 * cache. If the reference should be pruned, also add it to
2598 * ref_to_prune in the pack_refs_cb_data.
2600 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2602 struct pack_refs_cb_data
*cb
= cb_data
;
2603 enum peel_status peel_status
;
2604 struct ref_entry
*packed_entry
;
2605 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2607 /* ALWAYS pack tags */
2608 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2611 /* Do not pack symbolic or broken refs: */
2612 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2615 /* Add a packed ref cache entry equivalent to the loose entry. */
2616 peel_status
= peel_entry(entry
, 1);
2617 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2618 die("internal error peeling reference %s (%s)",
2619 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2620 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2622 /* Overwrite existing packed entry with info from loose entry */
2623 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2624 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2626 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2627 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2628 add_ref(cb
->packed_refs
, packed_entry
);
2630 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2632 /* Schedule the loose reference for pruning if requested. */
2633 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2634 int namelen
= strlen(entry
->name
) + 1;
2635 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2636 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2637 strcpy(n
->name
, entry
->name
);
2638 n
->next
= cb
->ref_to_prune
;
2639 cb
->ref_to_prune
= n
;
2645 * Remove empty parents, but spare refs/ and immediate subdirs.
2646 * Note: munges *name.
2648 static void try_remove_empty_parents(char *name
)
2653 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2654 while (*p
&& *p
!= '/')
2656 /* tolerate duplicate slashes; see check_refname_format() */
2660 for (q
= p
; *q
; q
++)
2663 while (q
> p
&& *q
!= '/')
2665 while (q
> p
&& *(q
-1) == '/')
2670 if (rmdir(git_path("%s", name
)))
2675 /* make sure nobody touched the ref, and unlink */
2676 static void prune_ref(struct ref_to_prune
*r
)
2678 struct ref_transaction
*transaction
;
2679 struct strbuf err
= STRBUF_INIT
;
2681 if (check_refname_format(r
->name
, 0))
2684 transaction
= ref_transaction_begin(&err
);
2686 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2687 REF_ISPRUNING
, NULL
, &err
) ||
2688 ref_transaction_commit(transaction
, &err
)) {
2689 ref_transaction_free(transaction
);
2690 error("%s", err
.buf
);
2691 strbuf_release(&err
);
2694 ref_transaction_free(transaction
);
2695 strbuf_release(&err
);
2696 try_remove_empty_parents(r
->name
);
2699 static void prune_refs(struct ref_to_prune
*r
)
2707 int pack_refs(unsigned int flags
)
2709 struct pack_refs_cb_data cbdata
;
2711 memset(&cbdata
, 0, sizeof(cbdata
));
2712 cbdata
.flags
= flags
;
2714 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2715 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2717 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2718 pack_if_possible_fn
, &cbdata
);
2720 if (commit_packed_refs())
2721 die_errno("unable to overwrite old ref-pack file");
2723 prune_refs(cbdata
.ref_to_prune
);
2727 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2729 struct ref_dir
*packed
;
2730 struct string_list_item
*refname
;
2731 int ret
, needs_repacking
= 0, removed
= 0;
2735 /* Look for a packed ref */
2736 for_each_string_list_item(refname
, refnames
) {
2737 if (get_packed_ref(refname
->string
)) {
2738 needs_repacking
= 1;
2743 /* Avoid locking if we have nothing to do */
2744 if (!needs_repacking
)
2745 return 0; /* no refname exists in packed refs */
2747 if (lock_packed_refs(0)) {
2748 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2751 packed
= get_packed_refs(&ref_cache
);
2753 /* Remove refnames from the cache */
2754 for_each_string_list_item(refname
, refnames
)
2755 if (remove_entry(packed
, refname
->string
) != -1)
2759 * All packed entries disappeared while we were
2760 * acquiring the lock.
2762 rollback_packed_refs();
2766 /* Write what remains */
2767 ret
= commit_packed_refs();
2769 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2774 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2778 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2780 * loose. The loose file name is the same as the
2781 * lockfile name, minus ".lock":
2783 char *loose_filename
= get_locked_file_path(lock
->lk
);
2784 int res
= unlink_or_msg(loose_filename
, err
);
2785 free(loose_filename
);
2792 int delete_ref(const char *refname
, const unsigned char *sha1
, unsigned int flags
)
2794 struct ref_transaction
*transaction
;
2795 struct strbuf err
= STRBUF_INIT
;
2797 transaction
= ref_transaction_begin(&err
);
2799 ref_transaction_delete(transaction
, refname
,
2800 (sha1
&& !is_null_sha1(sha1
)) ? sha1
: NULL
,
2801 flags
, NULL
, &err
) ||
2802 ref_transaction_commit(transaction
, &err
)) {
2803 error("%s", err
.buf
);
2804 ref_transaction_free(transaction
);
2805 strbuf_release(&err
);
2808 ref_transaction_free(transaction
);
2809 strbuf_release(&err
);
2814 * People using contrib's git-new-workdir have .git/logs/refs ->
2815 * /some/other/path/.git/logs/refs, and that may live on another device.
2817 * IOW, to avoid cross device rename errors, the temporary renamed log must
2818 * live into logs/refs.
2820 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2822 static int rename_tmp_log(const char *newrefname
)
2824 int attempts_remaining
= 4;
2827 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname
))) {
2829 break; /* success */
2831 if (--attempts_remaining
> 0)
2835 error("unable to create directory for %s", newrefname
);
2839 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2840 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2842 * rename(a, b) when b is an existing
2843 * directory ought to result in ISDIR, but
2844 * Solaris 5.8 gives ENOTDIR. Sheesh.
2846 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2847 error("Directory not empty: logs/%s", newrefname
);
2851 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2853 * Maybe another process just deleted one of
2854 * the directories in the path to newrefname.
2855 * Try again from the beginning.
2859 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2860 newrefname
, strerror(errno
));
2867 static int rename_ref_available(const char *oldname
, const char *newname
)
2869 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2870 struct strbuf err
= STRBUF_INIT
;
2873 string_list_insert(&skip
, oldname
);
2874 ret
= !verify_refname_available(newname
, NULL
, &skip
,
2875 get_packed_refs(&ref_cache
), &err
)
2876 && !verify_refname_available(newname
, NULL
, &skip
,
2877 get_loose_refs(&ref_cache
), &err
);
2879 error("%s", err
.buf
);
2881 string_list_clear(&skip
, 0);
2882 strbuf_release(&err
);
2886 static int write_ref_to_lockfile(struct ref_lock
*lock
, const unsigned char *sha1
);
2887 static int commit_ref_update(struct ref_lock
*lock
,
2888 const unsigned char *sha1
, const char *logmsg
);
2890 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2892 unsigned char sha1
[20], orig_sha1
[20];
2893 int flag
= 0, logmoved
= 0;
2894 struct ref_lock
*lock
;
2895 struct stat loginfo
;
2896 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2897 const char *symref
= NULL
;
2898 struct strbuf err
= STRBUF_INIT
;
2900 if (log
&& S_ISLNK(loginfo
.st_mode
))
2901 return error("reflog for %s is a symlink", oldrefname
);
2903 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2905 if (flag
& REF_ISSYMREF
)
2906 return error("refname %s is a symbolic ref, renaming it is not supported",
2909 return error("refname %s not found", oldrefname
);
2911 if (!rename_ref_available(oldrefname
, newrefname
))
2914 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2915 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2916 oldrefname
, strerror(errno
));
2918 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2919 error("unable to delete old %s", oldrefname
);
2923 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2924 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2925 if (errno
==EISDIR
) {
2926 if (remove_empty_directories(git_path("%s", newrefname
))) {
2927 error("Directory not empty: %s", newrefname
);
2931 error("unable to delete existing %s", newrefname
);
2936 if (log
&& rename_tmp_log(newrefname
))
2941 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2943 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
2944 strbuf_release(&err
);
2947 hashcpy(lock
->old_sha1
, orig_sha1
);
2949 if (write_ref_to_lockfile(lock
, orig_sha1
) ||
2950 commit_ref_update(lock
, orig_sha1
, logmsg
)) {
2951 error("unable to write current sha1 into %s", newrefname
);
2958 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2960 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
2961 strbuf_release(&err
);
2965 flag
= log_all_ref_updates
;
2966 log_all_ref_updates
= 0;
2967 if (write_ref_to_lockfile(lock
, orig_sha1
) ||
2968 commit_ref_update(lock
, orig_sha1
, NULL
))
2969 error("unable to write current sha1 into %s", oldrefname
);
2970 log_all_ref_updates
= flag
;
2973 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2974 error("unable to restore logfile %s from %s: %s",
2975 oldrefname
, newrefname
, strerror(errno
));
2976 if (!logmoved
&& log
&&
2977 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2978 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2979 oldrefname
, strerror(errno
));
2984 static int close_ref(struct ref_lock
*lock
)
2986 if (close_lock_file(lock
->lk
))
2991 static int commit_ref(struct ref_lock
*lock
)
2993 if (commit_lock_file(lock
->lk
))
2999 * copy the reflog message msg to buf, which has been allocated sufficiently
3000 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3001 * because reflog file is one line per entry.
3003 static int copy_msg(char *buf
, const char *msg
)
3010 while ((c
= *msg
++)) {
3011 if (wasspace
&& isspace(c
))
3013 wasspace
= isspace(c
);
3018 while (buf
< cp
&& isspace(cp
[-1]))
3024 /* This function must set a meaningful errno on failure */
3025 int log_ref_setup(const char *refname
, struct strbuf
*sb_logfile
)
3027 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
3030 strbuf_git_path(sb_logfile
, "logs/%s", refname
);
3031 logfile
= sb_logfile
->buf
;
3032 /* make sure the rest of the function can't change "logfile" */
3034 if (log_all_ref_updates
&&
3035 (starts_with(refname
, "refs/heads/") ||
3036 starts_with(refname
, "refs/remotes/") ||
3037 starts_with(refname
, "refs/notes/") ||
3038 !strcmp(refname
, "HEAD"))) {
3039 if (safe_create_leading_directories(logfile
) < 0) {
3040 int save_errno
= errno
;
3041 error("unable to create directory for %s", logfile
);
3048 logfd
= open(logfile
, oflags
, 0666);
3050 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3053 if (errno
== EISDIR
) {
3054 if (remove_empty_directories(logfile
)) {
3055 int save_errno
= errno
;
3056 error("There are still logs under '%s'",
3061 logfd
= open(logfile
, oflags
, 0666);
3065 int save_errno
= errno
;
3066 error("Unable to append to %s: %s", logfile
,
3073 adjust_shared_perm(logfile
);
3078 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3079 const unsigned char *new_sha1
,
3080 const char *committer
, const char *msg
)
3082 int msglen
, written
;
3083 unsigned maxlen
, len
;
3086 msglen
= msg
? strlen(msg
) : 0;
3087 maxlen
= strlen(committer
) + msglen
+ 100;
3088 logrec
= xmalloc(maxlen
);
3089 len
= sprintf(logrec
, "%s %s %s\n",
3090 sha1_to_hex(old_sha1
),
3091 sha1_to_hex(new_sha1
),
3094 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3096 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3104 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
3105 const unsigned char *new_sha1
, const char *msg
,
3106 struct strbuf
*sb_log_file
)
3108 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3111 if (log_all_ref_updates
< 0)
3112 log_all_ref_updates
= !is_bare_repository();
3114 result
= log_ref_setup(refname
, sb_log_file
);
3117 log_file
= sb_log_file
->buf
;
3118 /* make sure the rest of the function can't change "log_file" */
3121 logfd
= open(log_file
, oflags
);
3124 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3125 git_committer_info(0), msg
);
3127 int save_errno
= errno
;
3129 error("Unable to append to %s", log_file
);
3134 int save_errno
= errno
;
3135 error("Unable to append to %s", log_file
);
3142 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3143 const unsigned char *new_sha1
, const char *msg
)
3145 struct strbuf sb
= STRBUF_INIT
;
3146 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
);
3147 strbuf_release(&sb
);
3151 int is_branch(const char *refname
)
3153 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3157 * Write sha1 into the open lockfile, then close the lockfile. On
3158 * errors, rollback the lockfile and set errno to reflect the problem.
3160 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3161 const unsigned char *sha1
)
3163 static char term
= '\n';
3166 o
= parse_object(sha1
);
3168 error("Trying to write ref %s with nonexistent object %s",
3169 lock
->ref_name
, sha1_to_hex(sha1
));
3174 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3175 error("Trying to write non-commit object %s to branch %s",
3176 sha1_to_hex(sha1
), lock
->ref_name
);
3181 if (write_in_full(lock
->lk
->fd
, sha1_to_hex(sha1
), 40) != 40 ||
3182 write_in_full(lock
->lk
->fd
, &term
, 1) != 1 ||
3183 close_ref(lock
) < 0) {
3184 int save_errno
= errno
;
3185 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3194 * Commit a change to a loose reference that has already been written
3195 * to the loose reference lockfile. Also update the reflogs if
3196 * necessary, using the specified lockmsg (which can be NULL).
3198 static int commit_ref_update(struct ref_lock
*lock
,
3199 const unsigned char *sha1
, const char *logmsg
)
3201 clear_loose_ref_cache(&ref_cache
);
3202 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3203 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3204 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3208 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3210 * Special hack: If a branch is updated directly and HEAD
3211 * points to it (may happen on the remote side of a push
3212 * for example) then logically the HEAD reflog should be
3214 * A generic solution implies reverse symref information,
3215 * but finding all symrefs pointing to the given branch
3216 * would be rather costly for this rare event (the direct
3217 * update of a branch) to be worth it. So let's cheat and
3218 * check with HEAD only which should cover 99% of all usage
3219 * scenarios (even 100% of the default ones).
3221 unsigned char head_sha1
[20];
3223 const char *head_ref
;
3224 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3225 head_sha1
, &head_flag
);
3226 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3227 !strcmp(head_ref
, lock
->ref_name
))
3228 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3230 if (commit_ref(lock
)) {
3231 error("Couldn't set %s", lock
->ref_name
);
3239 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3242 const char *lockpath
;
3244 int fd
, len
, written
;
3245 char *git_HEAD
= git_pathdup("%s", ref_target
);
3246 unsigned char old_sha1
[20], new_sha1
[20];
3248 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3251 if (safe_create_leading_directories(git_HEAD
) < 0)
3252 return error("unable to create directory for %s", git_HEAD
);
3254 #ifndef NO_SYMLINK_HEAD
3255 if (prefer_symlink_refs
) {
3257 if (!symlink(refs_heads_master
, git_HEAD
))
3259 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3263 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3264 if (sizeof(ref
) <= len
) {
3265 error("refname too long: %s", refs_heads_master
);
3266 goto error_free_return
;
3268 lockpath
= mkpath("%s.lock", git_HEAD
);
3269 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3271 error("Unable to open %s for writing", lockpath
);
3272 goto error_free_return
;
3274 written
= write_in_full(fd
, ref
, len
);
3275 if (close(fd
) != 0 || written
!= len
) {
3276 error("Unable to write to %s", lockpath
);
3277 goto error_unlink_return
;
3279 if (rename(lockpath
, git_HEAD
) < 0) {
3280 error("Unable to create %s", git_HEAD
);
3281 goto error_unlink_return
;
3283 if (adjust_shared_perm(git_HEAD
)) {
3284 error("Unable to fix permissions on %s", lockpath
);
3285 error_unlink_return
:
3286 unlink_or_warn(lockpath
);
3292 #ifndef NO_SYMLINK_HEAD
3295 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3296 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3302 struct read_ref_at_cb
{
3303 const char *refname
;
3304 unsigned long at_time
;
3307 unsigned char *sha1
;
3310 unsigned char osha1
[20];
3311 unsigned char nsha1
[20];
3315 unsigned long *cutoff_time
;
3320 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3321 const char *email
, unsigned long timestamp
, int tz
,
3322 const char *message
, void *cb_data
)
3324 struct read_ref_at_cb
*cb
= cb_data
;
3328 cb
->date
= timestamp
;
3330 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3332 *cb
->msg
= xstrdup(message
);
3333 if (cb
->cutoff_time
)
3334 *cb
->cutoff_time
= timestamp
;
3336 *cb
->cutoff_tz
= tz
;
3338 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3340 * we have not yet updated cb->[n|o]sha1 so they still
3341 * hold the values for the previous record.
3343 if (!is_null_sha1(cb
->osha1
)) {
3344 hashcpy(cb
->sha1
, nsha1
);
3345 if (hashcmp(cb
->osha1
, nsha1
))
3346 warning("Log for ref %s has gap after %s.",
3347 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3349 else if (cb
->date
== cb
->at_time
)
3350 hashcpy(cb
->sha1
, nsha1
);
3351 else if (hashcmp(nsha1
, cb
->sha1
))
3352 warning("Log for ref %s unexpectedly ended on %s.",
3353 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3355 hashcpy(cb
->osha1
, osha1
);
3356 hashcpy(cb
->nsha1
, nsha1
);
3360 hashcpy(cb
->osha1
, osha1
);
3361 hashcpy(cb
->nsha1
, nsha1
);
3367 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3368 const char *email
, unsigned long timestamp
,
3369 int tz
, const char *message
, void *cb_data
)
3371 struct read_ref_at_cb
*cb
= cb_data
;
3374 *cb
->msg
= xstrdup(message
);
3375 if (cb
->cutoff_time
)
3376 *cb
->cutoff_time
= timestamp
;
3378 *cb
->cutoff_tz
= tz
;
3380 *cb
->cutoff_cnt
= cb
->reccnt
;
3381 hashcpy(cb
->sha1
, osha1
);
3382 if (is_null_sha1(cb
->sha1
))
3383 hashcpy(cb
->sha1
, nsha1
);
3384 /* We just want the first entry */
3388 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3389 unsigned char *sha1
, char **msg
,
3390 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3392 struct read_ref_at_cb cb
;
3394 memset(&cb
, 0, sizeof(cb
));
3395 cb
.refname
= refname
;
3396 cb
.at_time
= at_time
;
3399 cb
.cutoff_time
= cutoff_time
;
3400 cb
.cutoff_tz
= cutoff_tz
;
3401 cb
.cutoff_cnt
= cutoff_cnt
;
3404 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3407 if (flags
& GET_SHA1_QUIETLY
)
3410 die("Log for %s is empty.", refname
);
3415 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3420 int reflog_exists(const char *refname
)
3424 return !lstat(git_path("logs/%s", refname
), &st
) &&
3425 S_ISREG(st
.st_mode
);
3428 int delete_reflog(const char *refname
)
3430 return remove_path(git_path("logs/%s", refname
));
3433 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3435 unsigned char osha1
[20], nsha1
[20];
3436 char *email_end
, *message
;
3437 unsigned long timestamp
;
3440 /* old SP new SP name <email> SP time TAB msg LF */
3441 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3442 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3443 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3444 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3445 email_end
[1] != ' ' ||
3446 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3447 !message
|| message
[0] != ' ' ||
3448 (message
[1] != '+' && message
[1] != '-') ||
3449 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3450 !isdigit(message
[4]) || !isdigit(message
[5]))
3451 return 0; /* corrupt? */
3452 email_end
[1] = '\0';
3453 tz
= strtol(message
+ 1, NULL
, 10);
3454 if (message
[6] != '\t')
3458 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3461 static char *find_beginning_of_line(char *bob
, char *scan
)
3463 while (bob
< scan
&& *(--scan
) != '\n')
3464 ; /* keep scanning backwards */
3466 * Return either beginning of the buffer, or LF at the end of
3467 * the previous line.
3472 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3474 struct strbuf sb
= STRBUF_INIT
;
3477 int ret
= 0, at_tail
= 1;
3479 logfp
= fopen(git_path("logs/%s", refname
), "r");
3483 /* Jump to the end */
3484 if (fseek(logfp
, 0, SEEK_END
) < 0)
3485 return error("cannot seek back reflog for %s: %s",
3486 refname
, strerror(errno
));
3488 while (!ret
&& 0 < pos
) {
3494 /* Fill next block from the end */
3495 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3496 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3497 return error("cannot seek back reflog for %s: %s",
3498 refname
, strerror(errno
));
3499 nread
= fread(buf
, cnt
, 1, logfp
);
3501 return error("cannot read %d bytes from reflog for %s: %s",
3502 cnt
, refname
, strerror(errno
));
3505 scanp
= endp
= buf
+ cnt
;
3506 if (at_tail
&& scanp
[-1] == '\n')
3507 /* Looking at the final LF at the end of the file */
3511 while (buf
< scanp
) {
3513 * terminating LF of the previous line, or the beginning
3518 bp
= find_beginning_of_line(buf
, scanp
);
3522 * The newline is the end of the previous line,
3523 * so we know we have complete line starting
3524 * at (bp + 1). Prefix it onto any prior data
3525 * we collected for the line and process it.
3527 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3530 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3536 * We are at the start of the buffer, and the
3537 * start of the file; there is no previous
3538 * line, and we have everything for this one.
3539 * Process it, and we can end the loop.
3541 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3542 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3549 * We are at the start of the buffer, and there
3550 * is more file to read backwards. Which means
3551 * we are in the middle of a line. Note that we
3552 * may get here even if *bp was a newline; that
3553 * just means we are at the exact end of the
3554 * previous line, rather than some spot in the
3557 * Save away what we have to be combined with
3558 * the data from the next read.
3560 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3567 die("BUG: reverse reflog parser had leftover data");
3570 strbuf_release(&sb
);
3574 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3577 struct strbuf sb
= STRBUF_INIT
;
3580 logfp
= fopen(git_path("logs/%s", refname
), "r");
3584 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3585 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3587 strbuf_release(&sb
);
3591 * Call fn for each reflog in the namespace indicated by name. name
3592 * must be empty or end with '/'. Name will be used as a scratch
3593 * space, but its contents will be restored before return.
3595 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3597 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3600 int oldlen
= name
->len
;
3603 return name
->len
? errno
: 0;
3605 while ((de
= readdir(d
)) != NULL
) {
3608 if (de
->d_name
[0] == '.')
3610 if (ends_with(de
->d_name
, ".lock"))
3612 strbuf_addstr(name
, de
->d_name
);
3613 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3614 ; /* silently ignore */
3616 if (S_ISDIR(st
.st_mode
)) {
3617 strbuf_addch(name
, '/');
3618 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3620 unsigned char sha1
[20];
3621 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3622 retval
= error("bad ref for %s", name
->buf
);
3624 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3629 strbuf_setlen(name
, oldlen
);
3635 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3639 strbuf_init(&name
, PATH_MAX
);
3640 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3641 strbuf_release(&name
);
3646 * Information needed for a single ref update. Set new_sha1 to the new
3647 * value or to null_sha1 to delete the ref. To check the old value
3648 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3649 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3650 * not exist before update.
3654 * If (flags & REF_HAVE_NEW), set the reference to this value:
3656 unsigned char new_sha1
[20];
3658 * If (flags & REF_HAVE_OLD), check that the reference
3659 * previously had this value:
3661 unsigned char old_sha1
[20];
3663 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3664 * REF_DELETING, and REF_ISPRUNING:
3667 struct ref_lock
*lock
;
3670 const char refname
[FLEX_ARRAY
];
3674 * Transaction states.
3675 * OPEN: The transaction is in a valid state and can accept new updates.
3676 * An OPEN transaction can be committed.
3677 * CLOSED: A closed transaction is no longer active and no other operations
3678 * than free can be used on it in this state.
3679 * A transaction can either become closed by successfully committing
3680 * an active transaction or if there is a failure while building
3681 * the transaction thus rendering it failed/inactive.
3683 enum ref_transaction_state
{
3684 REF_TRANSACTION_OPEN
= 0,
3685 REF_TRANSACTION_CLOSED
= 1
3689 * Data structure for holding a reference transaction, which can
3690 * consist of checks and updates to multiple references, carried out
3691 * as atomically as possible. This structure is opaque to callers.
3693 struct ref_transaction
{
3694 struct ref_update
**updates
;
3697 enum ref_transaction_state state
;
3700 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3704 return xcalloc(1, sizeof(struct ref_transaction
));
3707 void ref_transaction_free(struct ref_transaction
*transaction
)
3714 for (i
= 0; i
< transaction
->nr
; i
++) {
3715 free(transaction
->updates
[i
]->msg
);
3716 free(transaction
->updates
[i
]);
3718 free(transaction
->updates
);
3722 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3723 const char *refname
)
3725 size_t len
= strlen(refname
);
3726 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3728 strcpy((char *)update
->refname
, refname
);
3729 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3730 transaction
->updates
[transaction
->nr
++] = update
;
3734 int ref_transaction_update(struct ref_transaction
*transaction
,
3735 const char *refname
,
3736 const unsigned char *new_sha1
,
3737 const unsigned char *old_sha1
,
3738 unsigned int flags
, const char *msg
,
3741 struct ref_update
*update
;
3745 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3746 die("BUG: update called for transaction that is not open");
3748 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
3749 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3750 strbuf_addf(err
, "refusing to update ref with bad name %s",
3755 update
= add_update(transaction
, refname
);
3757 hashcpy(update
->new_sha1
, new_sha1
);
3758 flags
|= REF_HAVE_NEW
;
3761 hashcpy(update
->old_sha1
, old_sha1
);
3762 flags
|= REF_HAVE_OLD
;
3764 update
->flags
= flags
;
3766 update
->msg
= xstrdup(msg
);
3770 int ref_transaction_create(struct ref_transaction
*transaction
,
3771 const char *refname
,
3772 const unsigned char *new_sha1
,
3773 unsigned int flags
, const char *msg
,
3776 if (!new_sha1
|| is_null_sha1(new_sha1
))
3777 die("BUG: create called without valid new_sha1");
3778 return ref_transaction_update(transaction
, refname
, new_sha1
,
3779 null_sha1
, flags
, msg
, err
);
3782 int ref_transaction_delete(struct ref_transaction
*transaction
,
3783 const char *refname
,
3784 const unsigned char *old_sha1
,
3785 unsigned int flags
, const char *msg
,
3788 if (old_sha1
&& is_null_sha1(old_sha1
))
3789 die("BUG: delete called with old_sha1 set to zeros");
3790 return ref_transaction_update(transaction
, refname
,
3791 null_sha1
, old_sha1
,
3795 int ref_transaction_verify(struct ref_transaction
*transaction
,
3796 const char *refname
,
3797 const unsigned char *old_sha1
,
3802 die("BUG: verify called with old_sha1 set to NULL");
3803 return ref_transaction_update(transaction
, refname
,
3808 int update_ref(const char *msg
, const char *refname
,
3809 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
3810 unsigned int flags
, enum action_on_err onerr
)
3812 struct ref_transaction
*t
;
3813 struct strbuf err
= STRBUF_INIT
;
3815 t
= ref_transaction_begin(&err
);
3817 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
3818 flags
, msg
, &err
) ||
3819 ref_transaction_commit(t
, &err
)) {
3820 const char *str
= "update_ref failed for ref '%s': %s";
3822 ref_transaction_free(t
);
3824 case UPDATE_REFS_MSG_ON_ERR
:
3825 error(str
, refname
, err
.buf
);
3827 case UPDATE_REFS_DIE_ON_ERR
:
3828 die(str
, refname
, err
.buf
);
3830 case UPDATE_REFS_QUIET_ON_ERR
:
3833 strbuf_release(&err
);
3836 strbuf_release(&err
);
3837 ref_transaction_free(t
);
3841 static int ref_update_reject_duplicates(struct string_list
*refnames
,
3844 int i
, n
= refnames
->nr
;
3848 for (i
= 1; i
< n
; i
++)
3849 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
3851 "Multiple updates for ref '%s' not allowed.",
3852 refnames
->items
[i
].string
);
3858 int ref_transaction_commit(struct ref_transaction
*transaction
,
3862 int n
= transaction
->nr
;
3863 struct ref_update
**updates
= transaction
->updates
;
3864 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3865 struct string_list_item
*ref_to_delete
;
3866 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3870 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3871 die("BUG: commit called for transaction that is not open");
3874 transaction
->state
= REF_TRANSACTION_CLOSED
;
3878 /* Fail if a refname appears more than once in the transaction: */
3879 for (i
= 0; i
< n
; i
++)
3880 string_list_append(&affected_refnames
, updates
[i
]->refname
);
3881 string_list_sort(&affected_refnames
);
3882 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
3883 ret
= TRANSACTION_GENERIC_ERROR
;
3888 * Acquire all locks, verify old values if provided, check
3889 * that new values are valid, and write new values to the
3890 * lockfiles, ready to be activated. Only keep one lockfile
3891 * open at a time to avoid running out of file descriptors.
3893 for (i
= 0; i
< n
; i
++) {
3894 struct ref_update
*update
= updates
[i
];
3896 if ((update
->flags
& REF_HAVE_NEW
) &&
3897 is_null_sha1(update
->new_sha1
))
3898 update
->flags
|= REF_DELETING
;
3899 update
->lock
= lock_ref_sha1_basic(
3901 ((update
->flags
& REF_HAVE_OLD
) ?
3902 update
->old_sha1
: NULL
),
3903 &affected_refnames
, NULL
,
3907 if (!update
->lock
) {
3910 ret
= (errno
== ENOTDIR
)
3911 ? TRANSACTION_NAME_CONFLICT
3912 : TRANSACTION_GENERIC_ERROR
;
3913 reason
= strbuf_detach(err
, NULL
);
3914 strbuf_addf(err
, "Cannot lock ref '%s': %s",
3915 update
->refname
, reason
);
3919 if ((update
->flags
& REF_HAVE_NEW
) &&
3920 !(update
->flags
& REF_DELETING
)) {
3921 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
3922 (update
->flags
& REF_NODEREF
));
3924 if (!overwriting_symref
&&
3925 !hashcmp(update
->lock
->old_sha1
, update
->new_sha1
)) {
3927 * The reference already has the desired
3928 * value, so we don't need to write it.
3930 } else if (write_ref_to_lockfile(update
->lock
,
3931 update
->new_sha1
)) {
3933 * The lock was freed upon failure of
3934 * write_ref_to_lockfile():
3936 update
->lock
= NULL
;
3937 strbuf_addf(err
, "Cannot update the ref '%s'.",
3939 ret
= TRANSACTION_GENERIC_ERROR
;
3942 update
->flags
|= REF_NEEDS_COMMIT
;
3945 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
3947 * We didn't have to write anything to the lockfile.
3948 * Close it to free up the file descriptor:
3950 if (close_ref(update
->lock
)) {
3951 strbuf_addf(err
, "Couldn't close %s.lock",
3958 /* Perform updates first so live commits remain referenced */
3959 for (i
= 0; i
< n
; i
++) {
3960 struct ref_update
*update
= updates
[i
];
3962 if (update
->flags
& REF_NEEDS_COMMIT
) {
3963 if (commit_ref_update(update
->lock
,
3964 update
->new_sha1
, update
->msg
)) {
3965 /* freed by commit_ref_update(): */
3966 update
->lock
= NULL
;
3967 strbuf_addf(err
, "Cannot update the ref '%s'.",
3969 ret
= TRANSACTION_GENERIC_ERROR
;
3972 /* freed by commit_ref_update(): */
3973 update
->lock
= NULL
;
3978 /* Perform deletes now that updates are safely completed */
3979 for (i
= 0; i
< n
; i
++) {
3980 struct ref_update
*update
= updates
[i
];
3982 if (update
->flags
& REF_DELETING
) {
3983 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3984 ret
= TRANSACTION_GENERIC_ERROR
;
3988 if (!(update
->flags
& REF_ISPRUNING
))
3989 string_list_append(&refs_to_delete
,
3990 update
->lock
->ref_name
);
3994 if (repack_without_refs(&refs_to_delete
, err
)) {
3995 ret
= TRANSACTION_GENERIC_ERROR
;
3998 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3999 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
4000 clear_loose_ref_cache(&ref_cache
);
4003 transaction
->state
= REF_TRANSACTION_CLOSED
;
4005 for (i
= 0; i
< n
; i
++)
4006 if (updates
[i
]->lock
)
4007 unlock_ref(updates
[i
]->lock
);
4008 string_list_clear(&refs_to_delete
, 0);
4009 string_list_clear(&affected_refnames
, 0);
4013 char *shorten_unambiguous_ref(const char *refname
, int strict
)
4016 static char **scanf_fmts
;
4017 static int nr_rules
;
4022 * Pre-generate scanf formats from ref_rev_parse_rules[].
4023 * Generate a format suitable for scanf from a
4024 * ref_rev_parse_rules rule by interpolating "%s" at the
4025 * location of the "%.*s".
4027 size_t total_len
= 0;
4030 /* the rule list is NULL terminated, count them first */
4031 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
4032 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4033 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
4035 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
4038 for (i
= 0; i
< nr_rules
; i
++) {
4039 assert(offset
< total_len
);
4040 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
4041 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
4042 ref_rev_parse_rules
[i
], 2, "%s") + 1;
4046 /* bail out if there are no rules */
4048 return xstrdup(refname
);
4050 /* buffer for scanf result, at most refname must fit */
4051 short_name
= xstrdup(refname
);
4053 /* skip first rule, it will always match */
4054 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
4056 int rules_to_fail
= i
;
4059 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
4062 short_name_len
= strlen(short_name
);
4065 * in strict mode, all (except the matched one) rules
4066 * must fail to resolve to a valid non-ambiguous ref
4069 rules_to_fail
= nr_rules
;
4072 * check if the short name resolves to a valid ref,
4073 * but use only rules prior to the matched one
4075 for (j
= 0; j
< rules_to_fail
; j
++) {
4076 const char *rule
= ref_rev_parse_rules
[j
];
4077 char refname
[PATH_MAX
];
4079 /* skip matched rule */
4084 * the short name is ambiguous, if it resolves
4085 * (with this previous rule) to a valid ref
4086 * read_ref() returns 0 on success
4088 mksnpath(refname
, sizeof(refname
),
4089 rule
, short_name_len
, short_name
);
4090 if (ref_exists(refname
))
4095 * short name is non-ambiguous if all previous rules
4096 * haven't resolved to a valid ref
4098 if (j
== rules_to_fail
)
4103 return xstrdup(refname
);
4106 static struct string_list
*hide_refs
;
4108 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
4110 if (!strcmp("transfer.hiderefs", var
) ||
4111 /* NEEDSWORK: use parse_config_key() once both are merged */
4112 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
4113 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
4118 return config_error_nonbool(var
);
4119 ref
= xstrdup(value
);
4121 while (len
&& ref
[len
- 1] == '/')
4124 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
4125 hide_refs
->strdup_strings
= 1;
4127 string_list_append(hide_refs
, ref
);
4132 int ref_is_hidden(const char *refname
)
4134 struct string_list_item
*item
;
4138 for_each_string_list_item(item
, hide_refs
) {
4140 if (!starts_with(refname
, item
->string
))
4142 len
= strlen(item
->string
);
4143 if (!refname
[len
] || refname
[len
] == '/')
4149 struct expire_reflog_cb
{
4151 reflog_expiry_should_prune_fn
*should_prune_fn
;
4154 unsigned char last_kept_sha1
[20];
4157 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4158 const char *email
, unsigned long timestamp
, int tz
,
4159 const char *message
, void *cb_data
)
4161 struct expire_reflog_cb
*cb
= cb_data
;
4162 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4164 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4165 osha1
= cb
->last_kept_sha1
;
4167 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4168 message
, policy_cb
)) {
4170 printf("would prune %s", message
);
4171 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4172 printf("prune %s", message
);
4175 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4176 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4177 email
, timestamp
, tz
, message
);
4178 hashcpy(cb
->last_kept_sha1
, nsha1
);
4180 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4181 printf("keep %s", message
);
4186 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4188 reflog_expiry_prepare_fn prepare_fn
,
4189 reflog_expiry_should_prune_fn should_prune_fn
,
4190 reflog_expiry_cleanup_fn cleanup_fn
,
4191 void *policy_cb_data
)
4193 static struct lock_file reflog_lock
;
4194 struct expire_reflog_cb cb
;
4195 struct ref_lock
*lock
;
4199 struct strbuf err
= STRBUF_INIT
;
4201 memset(&cb
, 0, sizeof(cb
));
4203 cb
.policy_cb
= policy_cb_data
;
4204 cb
.should_prune_fn
= should_prune_fn
;
4207 * The reflog file is locked by holding the lock on the
4208 * reference itself, plus we might need to update the
4209 * reference if --updateref was specified:
4211 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, 0, &type
, &err
);
4213 error("cannot lock ref '%s': %s", refname
, err
.buf
);
4214 strbuf_release(&err
);
4217 if (!reflog_exists(refname
)) {
4222 log_file
= git_pathdup("logs/%s", refname
);
4223 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4225 * Even though holding $GIT_DIR/logs/$reflog.lock has
4226 * no locking implications, we use the lock_file
4227 * machinery here anyway because it does a lot of the
4228 * work we need, including cleaning up if the program
4229 * exits unexpectedly.
4231 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4232 struct strbuf err
= STRBUF_INIT
;
4233 unable_to_lock_message(log_file
, errno
, &err
);
4234 error("%s", err
.buf
);
4235 strbuf_release(&err
);
4238 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4240 error("cannot fdopen %s (%s)",
4241 reflog_lock
.filename
.buf
, strerror(errno
));
4246 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4247 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4248 (*cleanup_fn
)(cb
.policy_cb
);
4250 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4252 * It doesn't make sense to adjust a reference pointed
4253 * to by a symbolic ref based on expiring entries in
4254 * the symbolic reference's reflog. Nor can we update
4255 * a reference if there are no remaining reflog
4258 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4259 !(type
& REF_ISSYMREF
) &&
4260 !is_null_sha1(cb
.last_kept_sha1
);
4262 if (close_lock_file(&reflog_lock
)) {
4263 status
|= error("couldn't write %s: %s", log_file
,
4265 } else if (update
&&
4266 (write_in_full(lock
->lk
->fd
,
4267 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4268 write_str_in_full(lock
->lk
->fd
, "\n") != 1 ||
4269 close_ref(lock
) < 0)) {
4270 status
|= error("couldn't write %s",
4271 lock
->lk
->filename
.buf
);
4272 rollback_lock_file(&reflog_lock
);
4273 } else if (commit_lock_file(&reflog_lock
)) {
4274 status
|= error("unable to commit reflog '%s' (%s)",
4275 log_file
, strerror(errno
));
4276 } else if (update
&& commit_ref(lock
)) {
4277 status
|= error("couldn't set %s", lock
->ref_name
);
4285 rollback_lock_file(&reflog_lock
);