7 #include "string-list.h"
13 unsigned char old_sha1
[20];
18 * How to handle various characters in refnames:
19 * 0: An acceptable character for refs
21 * 2: ., look for a preceding . to reject .. in refs
22 * 3: {, look for a preceding @ to reject @{ in refs
23 * 4: A bad character: ASCII control characters, and
24 * "*", ":", "?", "[", "\", "^", "~", SP, or TAB
26 static unsigned char refname_disposition
[256] = {
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
41 #define REF_DELETING 0x02
44 * Used as a flag in ref_update::flags when a loose ref is being
47 #define REF_ISPRUNING 0x04
50 * Used as a flag in ref_update::flags when the reference should be
51 * updated to new_sha1.
53 #define REF_HAVE_NEW 0x08
56 * Used as a flag in ref_update::flags when old_sha1 should be
59 #define REF_HAVE_OLD 0x10
62 * Used as a flag in ref_update::flags when the lockfile needs to be
65 #define REF_NEEDS_COMMIT 0x20
68 * Try to read one refname component from the front of refname.
69 * Return the length of the component found, or -1 if the component is
70 * not legal. It is legal if it is something reasonable to have under
71 * ".git/refs/"; We do not like it if:
73 * - any path component of it begins with ".", or
74 * - it has double dots "..", or
75 * - it has ASCII control characters, or
76 * - it has "*", ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
77 * - it ends with a "/", or
78 * - it ends with ".lock", or
79 * - it contains a "@{" portion
81 static int check_refname_component(const char *refname
, int flags
)
86 for (cp
= refname
; ; cp
++) {
88 unsigned char disp
= refname_disposition
[ch
];
94 return -1; /* Refname contains "..". */
98 return -1; /* Refname contains "@{". */
107 return 0; /* Component has zero length. */
108 if (refname
[0] == '.')
109 return -1; /* Component starts with '.'. */
110 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
111 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
112 return -1; /* Refname ends with ".lock". */
116 int check_refname_format(const char *refname
, int flags
)
118 int component_len
, component_count
= 0;
120 if (!strcmp(refname
, "@"))
121 /* Refname is a single character '@'. */
125 /* We are at the start of a path component. */
126 component_len
= check_refname_component(refname
, flags
);
127 if (component_len
<= 0) {
128 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
130 (refname
[1] == '\0' || refname
[1] == '/')) {
131 /* Accept one wildcard as a full refname component. */
132 flags
&= ~REFNAME_REFSPEC_PATTERN
;
139 if (refname
[component_len
] == '\0')
141 /* Skip to next component. */
142 refname
+= component_len
+ 1;
145 if (refname
[component_len
- 1] == '.')
146 return -1; /* Refname ends with '.'. */
147 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
148 return -1; /* Refname has only one component. */
155 * Information used (along with the information in ref_entry) to
156 * describe a single cached reference. This data structure only
157 * occurs embedded in a union in struct ref_entry, and only when
158 * (ref_entry->flag & REF_DIR) is zero.
162 * The name of the object to which this reference resolves
163 * (which may be a tag object). If REF_ISBROKEN, this is
164 * null. If REF_ISSYMREF, then this is the name of the object
165 * referred to by the last reference in the symlink chain.
167 unsigned char sha1
[20];
170 * If REF_KNOWS_PEELED, then this field holds the peeled value
171 * of this reference, or null if the reference is known not to
172 * be peelable. See the documentation for peel_ref() for an
173 * exact definition of "peelable".
175 unsigned char peeled
[20];
181 * Information used (along with the information in ref_entry) to
182 * describe a level in the hierarchy of references. This data
183 * structure only occurs embedded in a union in struct ref_entry, and
184 * only when (ref_entry.flag & REF_DIR) is set. In that case,
185 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
186 * in the directory have already been read:
188 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
189 * or packed references, already read.
191 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
192 * references that hasn't been read yet (nor has any of its
195 * Entries within a directory are stored within a growable array of
196 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
197 * sorted are sorted by their component name in strcmp() order and the
198 * remaining entries are unsorted.
200 * Loose references are read lazily, one directory at a time. When a
201 * directory of loose references is read, then all of the references
202 * in that directory are stored, and REF_INCOMPLETE stubs are created
203 * for any subdirectories, but the subdirectories themselves are not
204 * read. The reading is triggered by get_ref_dir().
210 * Entries with index 0 <= i < sorted are sorted by name. New
211 * entries are appended to the list unsorted, and are sorted
212 * only when required; thus we avoid the need to sort the list
213 * after the addition of every reference.
217 /* A pointer to the ref_cache that contains this ref_dir. */
218 struct ref_cache
*ref_cache
;
220 struct ref_entry
**entries
;
224 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
225 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
226 * public values; see refs.h.
230 * The field ref_entry->u.value.peeled of this value entry contains
231 * the correct peeled value for the reference, which might be
232 * null_sha1 if the reference is not a tag or if it is broken.
234 #define REF_KNOWS_PEELED 0x10
236 /* ref_entry represents a directory of references */
240 * Entry has not yet been read from disk (used only for REF_DIR
241 * entries representing loose references)
243 #define REF_INCOMPLETE 0x40
246 * A ref_entry represents either a reference or a "subdirectory" of
249 * Each directory in the reference namespace is represented by a
250 * ref_entry with (flags & REF_DIR) set and containing a subdir member
251 * that holds the entries in that directory that have been read so
252 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
253 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
254 * used for loose reference directories.
256 * References are represented by a ref_entry with (flags & REF_DIR)
257 * unset and a value member that describes the reference's value. The
258 * flag member is at the ref_entry level, but it is also needed to
259 * interpret the contents of the value field (in other words, a
260 * ref_value object is not very much use without the enclosing
263 * Reference names cannot end with slash and directories' names are
264 * always stored with a trailing slash (except for the top-level
265 * directory, which is always denoted by ""). This has two nice
266 * consequences: (1) when the entries in each subdir are sorted
267 * lexicographically by name (as they usually are), the references in
268 * a whole tree can be generated in lexicographic order by traversing
269 * the tree in left-to-right, depth-first order; (2) the names of
270 * references and subdirectories cannot conflict, and therefore the
271 * presence of an empty subdirectory does not block the creation of a
272 * similarly-named reference. (The fact that reference names with the
273 * same leading components can conflict *with each other* is a
274 * separate issue that is regulated by verify_refname_available().)
276 * Please note that the name field contains the fully-qualified
277 * reference (or subdirectory) name. Space could be saved by only
278 * storing the relative names. But that would require the full names
279 * to be generated on the fly when iterating in do_for_each_ref(), and
280 * would break callback functions, who have always been able to assume
281 * that the name strings that they are passed will not be freed during
285 unsigned char flag
; /* ISSYMREF? ISPACKED? */
287 struct ref_value value
; /* if not (flags&REF_DIR) */
288 struct ref_dir subdir
; /* if (flags&REF_DIR) */
291 * The full name of the reference (e.g., "refs/heads/master")
292 * or the full name of the directory with a trailing slash
293 * (e.g., "refs/heads/"):
295 char name
[FLEX_ARRAY
];
298 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
300 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
303 assert(entry
->flag
& REF_DIR
);
304 dir
= &entry
->u
.subdir
;
305 if (entry
->flag
& REF_INCOMPLETE
) {
306 read_loose_refs(entry
->name
, dir
);
307 entry
->flag
&= ~REF_INCOMPLETE
;
313 * Check if a refname is safe.
314 * For refs that start with "refs/" we consider it safe as long they do
315 * not try to resolve to outside of refs/.
317 * For all other refs we only consider them safe iff they only contain
318 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
321 static int refname_is_safe(const char *refname
)
323 if (starts_with(refname
, "refs/")) {
327 buf
= xmalloc(strlen(refname
) + 1);
329 * Does the refname try to escape refs/?
330 * For example: refs/foo/../bar is safe but refs/foo/../../bar
333 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
338 if (!isupper(*refname
) && *refname
!= '_')
345 static struct ref_entry
*create_ref_entry(const char *refname
,
346 const unsigned char *sha1
, int flag
,
350 struct ref_entry
*ref
;
353 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
354 die("Reference has invalid format: '%s'", refname
);
355 if (!check_name
&& !refname_is_safe(refname
))
356 die("Reference has invalid name: '%s'", refname
);
357 len
= strlen(refname
) + 1;
358 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
359 hashcpy(ref
->u
.value
.sha1
, sha1
);
360 hashclr(ref
->u
.value
.peeled
);
361 memcpy(ref
->name
, refname
, len
);
366 static void clear_ref_dir(struct ref_dir
*dir
);
368 static void free_ref_entry(struct ref_entry
*entry
)
370 if (entry
->flag
& REF_DIR
) {
372 * Do not use get_ref_dir() here, as that might
373 * trigger the reading of loose refs.
375 clear_ref_dir(&entry
->u
.subdir
);
381 * Add a ref_entry to the end of dir (unsorted). Entry is always
382 * stored directly in dir; no recursion into subdirectories is
385 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
387 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
388 dir
->entries
[dir
->nr
++] = entry
;
389 /* optimize for the case that entries are added in order */
391 (dir
->nr
== dir
->sorted
+ 1 &&
392 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
393 dir
->entries
[dir
->nr
- 1]->name
) < 0))
394 dir
->sorted
= dir
->nr
;
398 * Clear and free all entries in dir, recursively.
400 static void clear_ref_dir(struct ref_dir
*dir
)
403 for (i
= 0; i
< dir
->nr
; i
++)
404 free_ref_entry(dir
->entries
[i
]);
406 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
411 * Create a struct ref_entry object for the specified dirname.
412 * dirname is the name of the directory with a trailing slash (e.g.,
413 * "refs/heads/") or "" for the top-level directory.
415 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
416 const char *dirname
, size_t len
,
419 struct ref_entry
*direntry
;
420 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
421 memcpy(direntry
->name
, dirname
, len
);
422 direntry
->name
[len
] = '\0';
423 direntry
->u
.subdir
.ref_cache
= ref_cache
;
424 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
428 static int ref_entry_cmp(const void *a
, const void *b
)
430 struct ref_entry
*one
= *(struct ref_entry
**)a
;
431 struct ref_entry
*two
= *(struct ref_entry
**)b
;
432 return strcmp(one
->name
, two
->name
);
435 static void sort_ref_dir(struct ref_dir
*dir
);
437 struct string_slice
{
442 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
444 const struct string_slice
*key
= key_
;
445 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
446 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
449 return '\0' - (unsigned char)ent
->name
[key
->len
];
453 * Return the index of the entry with the given refname from the
454 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
455 * no such entry is found. dir must already be complete.
457 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
459 struct ref_entry
**r
;
460 struct string_slice key
;
462 if (refname
== NULL
|| !dir
->nr
)
468 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
469 ref_entry_cmp_sslice
);
474 return r
- dir
->entries
;
478 * Search for a directory entry directly within dir (without
479 * recursing). Sort dir if necessary. subdirname must be a directory
480 * name (i.e., end in '/'). If mkdir is set, then create the
481 * directory if it is missing; otherwise, return NULL if the desired
482 * directory cannot be found. dir must already be complete.
484 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
485 const char *subdirname
, size_t len
,
488 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
489 struct ref_entry
*entry
;
490 if (entry_index
== -1) {
494 * Since dir is complete, the absence of a subdir
495 * means that the subdir really doesn't exist;
496 * therefore, create an empty record for it but mark
497 * the record complete.
499 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
500 add_entry_to_dir(dir
, entry
);
502 entry
= dir
->entries
[entry_index
];
504 return get_ref_dir(entry
);
508 * If refname is a reference name, find the ref_dir within the dir
509 * tree that should hold refname. If refname is a directory name
510 * (i.e., ends in '/'), then return that ref_dir itself. dir must
511 * represent the top-level directory and must already be complete.
512 * Sort ref_dirs and recurse into subdirectories as necessary. If
513 * mkdir is set, then create any missing directories; otherwise,
514 * return NULL if the desired directory cannot be found.
516 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
517 const char *refname
, int mkdir
)
520 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
521 size_t dirnamelen
= slash
- refname
+ 1;
522 struct ref_dir
*subdir
;
523 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
535 * Find the value entry with the given name in dir, sorting ref_dirs
536 * and recursing into subdirectories as necessary. If the name is not
537 * found or it corresponds to a directory entry, return NULL.
539 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
542 struct ref_entry
*entry
;
543 dir
= find_containing_dir(dir
, refname
, 0);
546 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
547 if (entry_index
== -1)
549 entry
= dir
->entries
[entry_index
];
550 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
554 * Remove the entry with the given name from dir, recursing into
555 * subdirectories as necessary. If refname is the name of a directory
556 * (i.e., ends with '/'), then remove the directory and its contents.
557 * If the removal was successful, return the number of entries
558 * remaining in the directory entry that contained the deleted entry.
559 * If the name was not found, return -1. Please note that this
560 * function only deletes the entry from the cache; it does not delete
561 * it from the filesystem or ensure that other cache entries (which
562 * might be symbolic references to the removed entry) are updated.
563 * Nor does it remove any containing dir entries that might be made
564 * empty by the removal. dir must represent the top-level directory
565 * and must already be complete.
567 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
569 int refname_len
= strlen(refname
);
571 struct ref_entry
*entry
;
572 int is_dir
= refname
[refname_len
- 1] == '/';
575 * refname represents a reference directory. Remove
576 * the trailing slash; otherwise we will get the
577 * directory *representing* refname rather than the
578 * one *containing* it.
580 char *dirname
= xmemdupz(refname
, refname_len
- 1);
581 dir
= find_containing_dir(dir
, dirname
, 0);
584 dir
= find_containing_dir(dir
, refname
, 0);
588 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
589 if (entry_index
== -1)
591 entry
= dir
->entries
[entry_index
];
593 memmove(&dir
->entries
[entry_index
],
594 &dir
->entries
[entry_index
+ 1],
595 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
598 if (dir
->sorted
> entry_index
)
600 free_ref_entry(entry
);
605 * Add a ref_entry to the ref_dir (unsorted), recursing into
606 * subdirectories as necessary. dir must represent the top-level
607 * directory. Return 0 on success.
609 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
611 dir
= find_containing_dir(dir
, ref
->name
, 1);
614 add_entry_to_dir(dir
, ref
);
619 * Emit a warning and return true iff ref1 and ref2 have the same name
620 * and the same sha1. Die if they have the same name but different
623 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
625 if (strcmp(ref1
->name
, ref2
->name
))
628 /* Duplicate name; make sure that they don't conflict: */
630 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
631 /* This is impossible by construction */
632 die("Reference directory conflict: %s", ref1
->name
);
634 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
635 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
637 warning("Duplicated ref: %s", ref1
->name
);
642 * Sort the entries in dir non-recursively (if they are not already
643 * sorted) and remove any duplicate entries.
645 static void sort_ref_dir(struct ref_dir
*dir
)
648 struct ref_entry
*last
= NULL
;
651 * This check also prevents passing a zero-length array to qsort(),
652 * which is a problem on some platforms.
654 if (dir
->sorted
== dir
->nr
)
657 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
659 /* Remove any duplicates: */
660 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
661 struct ref_entry
*entry
= dir
->entries
[j
];
662 if (last
&& is_dup_ref(last
, entry
))
663 free_ref_entry(entry
);
665 last
= dir
->entries
[i
++] = entry
;
667 dir
->sorted
= dir
->nr
= i
;
670 /* Include broken references in a do_for_each_ref*() iteration: */
671 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
674 * Return true iff the reference described by entry can be resolved to
675 * an object in the database. Emit a warning if the referred-to
676 * object does not exist.
678 static int ref_resolves_to_object(struct ref_entry
*entry
)
680 if (entry
->flag
& REF_ISBROKEN
)
682 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
683 error("%s does not point to a valid object!", entry
->name
);
690 * current_ref is a performance hack: when iterating over references
691 * using the for_each_ref*() functions, current_ref is set to the
692 * current reference's entry before calling the callback function. If
693 * the callback function calls peel_ref(), then peel_ref() first
694 * checks whether the reference to be peeled is the current reference
695 * (it usually is) and if so, returns that reference's peeled version
696 * if it is available. This avoids a refname lookup in a common case.
698 static struct ref_entry
*current_ref
;
700 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
702 struct ref_entry_cb
{
711 * Handle one reference in a do_for_each_ref*()-style iteration,
712 * calling an each_ref_fn for each entry.
714 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
716 struct ref_entry_cb
*data
= cb_data
;
717 struct ref_entry
*old_current_ref
;
720 if (!starts_with(entry
->name
, data
->base
))
723 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
724 !ref_resolves_to_object(entry
))
727 /* Store the old value, in case this is a recursive call: */
728 old_current_ref
= current_ref
;
730 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
731 entry
->flag
, data
->cb_data
);
732 current_ref
= old_current_ref
;
737 * Call fn for each reference in dir that has index in the range
738 * offset <= index < dir->nr. Recurse into subdirectories that are in
739 * that index range, sorting them before iterating. This function
740 * does not sort dir itself; it should be sorted beforehand. fn is
741 * called for all references, including broken ones.
743 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
744 each_ref_entry_fn fn
, void *cb_data
)
747 assert(dir
->sorted
== dir
->nr
);
748 for (i
= offset
; i
< dir
->nr
; i
++) {
749 struct ref_entry
*entry
= dir
->entries
[i
];
751 if (entry
->flag
& REF_DIR
) {
752 struct ref_dir
*subdir
= get_ref_dir(entry
);
753 sort_ref_dir(subdir
);
754 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
756 retval
= fn(entry
, cb_data
);
765 * Call fn for each reference in the union of dir1 and dir2, in order
766 * by refname. Recurse into subdirectories. If a value entry appears
767 * in both dir1 and dir2, then only process the version that is in
768 * dir2. The input dirs must already be sorted, but subdirs will be
769 * sorted as needed. fn is called for all references, including
772 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
773 struct ref_dir
*dir2
,
774 each_ref_entry_fn fn
, void *cb_data
)
779 assert(dir1
->sorted
== dir1
->nr
);
780 assert(dir2
->sorted
== dir2
->nr
);
782 struct ref_entry
*e1
, *e2
;
784 if (i1
== dir1
->nr
) {
785 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
787 if (i2
== dir2
->nr
) {
788 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
790 e1
= dir1
->entries
[i1
];
791 e2
= dir2
->entries
[i2
];
792 cmp
= strcmp(e1
->name
, e2
->name
);
794 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
795 /* Both are directories; descend them in parallel. */
796 struct ref_dir
*subdir1
= get_ref_dir(e1
);
797 struct ref_dir
*subdir2
= get_ref_dir(e2
);
798 sort_ref_dir(subdir1
);
799 sort_ref_dir(subdir2
);
800 retval
= do_for_each_entry_in_dirs(
801 subdir1
, subdir2
, fn
, cb_data
);
804 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
805 /* Both are references; ignore the one from dir1. */
806 retval
= fn(e2
, cb_data
);
810 die("conflict between reference and directory: %s",
822 if (e
->flag
& REF_DIR
) {
823 struct ref_dir
*subdir
= get_ref_dir(e
);
824 sort_ref_dir(subdir
);
825 retval
= do_for_each_entry_in_dir(
826 subdir
, 0, fn
, cb_data
);
828 retval
= fn(e
, cb_data
);
837 * Load all of the refs from the dir into our in-memory cache. The hard work
838 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
839 * through all of the sub-directories. We do not even need to care about
840 * sorting, as traversal order does not matter to us.
842 static void prime_ref_dir(struct ref_dir
*dir
)
845 for (i
= 0; i
< dir
->nr
; i
++) {
846 struct ref_entry
*entry
= dir
->entries
[i
];
847 if (entry
->flag
& REF_DIR
)
848 prime_ref_dir(get_ref_dir(entry
));
852 struct nonmatching_ref_data
{
853 const struct string_list
*skip
;
854 const char *conflicting_refname
;
857 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
859 struct nonmatching_ref_data
*data
= vdata
;
861 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
864 data
->conflicting_refname
= entry
->name
;
869 * Return 0 if a reference named refname could be created without
870 * conflicting with the name of an existing reference in dir.
871 * Otherwise, return a negative value and write an explanation to err.
872 * If extras is non-NULL, it is a list of additional refnames with
873 * which refname is not allowed to conflict. If skip is non-NULL,
874 * ignore potential conflicts with refs in skip (e.g., because they
875 * are scheduled for deletion in the same operation). Behavior is
876 * undefined if the same name is listed in both extras and skip.
878 * Two reference names conflict if one of them exactly matches the
879 * leading components of the other; e.g., "refs/foo/bar" conflicts
880 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
881 * "refs/foo/bar" or "refs/foo/barbados".
883 * extras and skip must be sorted.
885 static int verify_refname_available(const char *refname
,
886 const struct string_list
*extras
,
887 const struct string_list
*skip
,
893 struct strbuf dirname
= STRBUF_INIT
;
897 * For the sake of comments in this function, suppose that
898 * refname is "refs/foo/bar".
903 strbuf_grow(&dirname
, strlen(refname
) + 1);
904 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
905 /* Expand dirname to the new prefix, not including the trailing slash: */
906 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
909 * We are still at a leading dir of the refname (e.g.,
910 * "refs/foo"; if there is a reference with that name,
911 * it is a conflict, *unless* it is in skip.
914 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
916 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
918 * We found a reference whose name is
919 * a proper prefix of refname; e.g.,
920 * "refs/foo", and is not in skip.
922 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
923 dirname
.buf
, refname
);
928 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
929 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
930 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
931 refname
, dirname
.buf
);
936 * Otherwise, we can try to continue our search with
937 * the next component. So try to look up the
938 * directory, e.g., "refs/foo/". If we come up empty,
939 * we know there is nothing under this whole prefix,
940 * but even in that case we still have to continue the
941 * search for conflicts with extras.
943 strbuf_addch(&dirname
, '/');
945 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
948 * There was no directory "refs/foo/",
949 * so there is nothing under this
950 * whole prefix. So there is no need
951 * to continue looking for conflicting
952 * references. But we need to continue
953 * looking for conflicting extras.
957 dir
= get_ref_dir(dir
->entries
[pos
]);
963 * We are at the leaf of our refname (e.g., "refs/foo/bar").
964 * There is no point in searching for a reference with that
965 * name, because a refname isn't considered to conflict with
966 * itself. But we still need to check for references whose
967 * names are in the "refs/foo/bar/" namespace, because they
970 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
971 strbuf_addch(&dirname
, '/');
974 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
978 * We found a directory named "$refname/"
979 * (e.g., "refs/foo/bar/"). It is a problem
980 * iff it contains any ref that is not in
983 struct nonmatching_ref_data data
;
986 data
.conflicting_refname
= NULL
;
987 dir
= get_ref_dir(dir
->entries
[pos
]);
989 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
990 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
991 data
.conflicting_refname
, refname
);
999 * Check for entries in extras that start with
1000 * "$refname/". We do that by looking for the place
1001 * where "$refname/" would be inserted in extras. If
1002 * there is an entry at that position that starts with
1003 * "$refname/" and is not in skip, then we have a
1006 for (pos
= string_list_find_insert_index(extras
, dirname
.buf
, 0);
1007 pos
< extras
->nr
; pos
++) {
1008 const char *extra_refname
= extras
->items
[pos
].string
;
1010 if (!starts_with(extra_refname
, dirname
.buf
))
1013 if (!skip
|| !string_list_has_string(skip
, extra_refname
)) {
1014 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
1015 refname
, extra_refname
);
1021 /* No conflicts were found */
1025 strbuf_release(&dirname
);
1029 struct packed_ref_cache
{
1030 struct ref_entry
*root
;
1033 * Count of references to the data structure in this instance,
1034 * including the pointer from ref_cache::packed if any. The
1035 * data will not be freed as long as the reference count is
1038 unsigned int referrers
;
1041 * Iff the packed-refs file associated with this instance is
1042 * currently locked for writing, this points at the associated
1043 * lock (which is owned by somebody else). The referrer count
1044 * is also incremented when the file is locked and decremented
1045 * when it is unlocked.
1047 struct lock_file
*lock
;
1049 /* The metadata from when this packed-refs cache was read */
1050 struct stat_validity validity
;
1054 * Future: need to be in "struct repository"
1055 * when doing a full libification.
1057 static struct ref_cache
{
1058 struct ref_cache
*next
;
1059 struct ref_entry
*loose
;
1060 struct packed_ref_cache
*packed
;
1062 * The submodule name, or "" for the main repo. We allocate
1063 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1064 * is initialized correctly.
1067 } ref_cache
, *submodule_ref_caches
;
1069 /* Lock used for the main packed-refs file: */
1070 static struct lock_file packlock
;
1073 * Increment the reference count of *packed_refs.
1075 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1077 packed_refs
->referrers
++;
1081 * Decrease the reference count of *packed_refs. If it goes to zero,
1082 * free *packed_refs and return true; otherwise return false.
1084 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1086 if (!--packed_refs
->referrers
) {
1087 free_ref_entry(packed_refs
->root
);
1088 stat_validity_clear(&packed_refs
->validity
);
1096 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1099 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1101 if (packed_refs
->lock
)
1102 die("internal error: packed-ref cache cleared while locked");
1103 refs
->packed
= NULL
;
1104 release_packed_ref_cache(packed_refs
);
1108 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1111 free_ref_entry(refs
->loose
);
1116 static struct ref_cache
*create_ref_cache(const char *submodule
)
1119 struct ref_cache
*refs
;
1122 len
= strlen(submodule
) + 1;
1123 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1124 memcpy(refs
->name
, submodule
, len
);
1129 * Return a pointer to a ref_cache for the specified submodule. For
1130 * the main repository, use submodule==NULL. The returned structure
1131 * will be allocated and initialized but not necessarily populated; it
1132 * should not be freed.
1134 static struct ref_cache
*get_ref_cache(const char *submodule
)
1136 struct ref_cache
*refs
;
1138 if (!submodule
|| !*submodule
)
1141 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1142 if (!strcmp(submodule
, refs
->name
))
1145 refs
= create_ref_cache(submodule
);
1146 refs
->next
= submodule_ref_caches
;
1147 submodule_ref_caches
= refs
;
1151 /* The length of a peeled reference line in packed-refs, including EOL: */
1152 #define PEELED_LINE_LENGTH 42
1155 * The packed-refs header line that we write out. Perhaps other
1156 * traits will be added later. The trailing space is required.
1158 static const char PACKED_REFS_HEADER
[] =
1159 "# pack-refs with: peeled fully-peeled \n";
1162 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1163 * Return a pointer to the refname within the line (null-terminated),
1164 * or NULL if there was a problem.
1166 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1171 * 42: the answer to everything.
1173 * In this case, it happens to be the answer to
1174 * 40 (length of sha1 hex representation)
1175 * +1 (space in between hex and name)
1176 * +1 (newline at the end of the line)
1178 if (line
->len
<= 42)
1181 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1183 if (!isspace(line
->buf
[40]))
1186 ref
= line
->buf
+ 41;
1190 if (line
->buf
[line
->len
- 1] != '\n')
1192 line
->buf
[--line
->len
] = 0;
1198 * Read f, which is a packed-refs file, into dir.
1200 * A comment line of the form "# pack-refs with: " may contain zero or
1201 * more traits. We interpret the traits as follows:
1205 * Probably no references are peeled. But if the file contains a
1206 * peeled value for a reference, we will use it.
1210 * References under "refs/tags/", if they *can* be peeled, *are*
1211 * peeled in this file. References outside of "refs/tags/" are
1212 * probably not peeled even if they could have been, but if we find
1213 * a peeled value for such a reference we will use it.
1217 * All references in the file that can be peeled are peeled.
1218 * Inversely (and this is more important), any references in the
1219 * file for which no peeled value is recorded is not peelable. This
1220 * trait should typically be written alongside "peeled" for
1221 * compatibility with older clients, but we do not require it
1222 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1224 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1226 struct ref_entry
*last
= NULL
;
1227 struct strbuf line
= STRBUF_INIT
;
1228 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1230 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1231 unsigned char sha1
[20];
1232 const char *refname
;
1235 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1236 if (strstr(traits
, " fully-peeled "))
1237 peeled
= PEELED_FULLY
;
1238 else if (strstr(traits
, " peeled "))
1239 peeled
= PEELED_TAGS
;
1240 /* perhaps other traits later as well */
1244 refname
= parse_ref_line(&line
, sha1
);
1246 int flag
= REF_ISPACKED
;
1248 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1250 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1252 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1253 if (peeled
== PEELED_FULLY
||
1254 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1255 last
->flag
|= REF_KNOWS_PEELED
;
1260 line
.buf
[0] == '^' &&
1261 line
.len
== PEELED_LINE_LENGTH
&&
1262 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1263 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1264 hashcpy(last
->u
.value
.peeled
, sha1
);
1266 * Regardless of what the file header said,
1267 * we definitely know the value of *this*
1270 last
->flag
|= REF_KNOWS_PEELED
;
1274 strbuf_release(&line
);
1278 * Get the packed_ref_cache for the specified ref_cache, creating it
1281 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1283 const char *packed_refs_file
;
1286 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1288 packed_refs_file
= git_path("packed-refs");
1291 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1292 clear_packed_ref_cache(refs
);
1294 if (!refs
->packed
) {
1297 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1298 acquire_packed_ref_cache(refs
->packed
);
1299 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1300 f
= fopen(packed_refs_file
, "r");
1302 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1303 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1307 return refs
->packed
;
1310 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1312 return get_ref_dir(packed_ref_cache
->root
);
1315 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1317 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1320 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1322 struct packed_ref_cache
*packed_ref_cache
=
1323 get_packed_ref_cache(&ref_cache
);
1325 if (!packed_ref_cache
->lock
)
1326 die("internal error: packed refs not locked");
1327 add_ref(get_packed_ref_dir(packed_ref_cache
),
1328 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1332 * Read the loose references from the namespace dirname into dir
1333 * (without recursing). dirname must end with '/'. dir must be the
1334 * directory entry corresponding to dirname.
1336 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1338 struct ref_cache
*refs
= dir
->ref_cache
;
1342 int dirnamelen
= strlen(dirname
);
1343 struct strbuf refname
;
1346 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1348 path
= git_path("%s", dirname
);
1354 strbuf_init(&refname
, dirnamelen
+ 257);
1355 strbuf_add(&refname
, dirname
, dirnamelen
);
1357 while ((de
= readdir(d
)) != NULL
) {
1358 unsigned char sha1
[20];
1363 if (de
->d_name
[0] == '.')
1365 if (ends_with(de
->d_name
, ".lock"))
1367 strbuf_addstr(&refname
, de
->d_name
);
1368 refdir
= *refs
->name
1369 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1370 : git_path("%s", refname
.buf
);
1371 if (stat(refdir
, &st
) < 0) {
1372 ; /* silently ignore */
1373 } else if (S_ISDIR(st
.st_mode
)) {
1374 strbuf_addch(&refname
, '/');
1375 add_entry_to_dir(dir
,
1376 create_dir_entry(refs
, refname
.buf
,
1382 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1384 flag
|= REF_ISBROKEN
;
1386 } else if (read_ref_full(refname
.buf
,
1387 RESOLVE_REF_READING
,
1390 flag
|= REF_ISBROKEN
;
1392 if (check_refname_format(refname
.buf
,
1393 REFNAME_ALLOW_ONELEVEL
)) {
1395 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1397 add_entry_to_dir(dir
,
1398 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1400 strbuf_setlen(&refname
, dirnamelen
);
1402 strbuf_release(&refname
);
1406 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1410 * Mark the top-level directory complete because we
1411 * are about to read the only subdirectory that can
1414 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1416 * Create an incomplete entry for "refs/":
1418 add_entry_to_dir(get_ref_dir(refs
->loose
),
1419 create_dir_entry(refs
, "refs/", 5, 1));
1421 return get_ref_dir(refs
->loose
);
1424 /* We allow "recursive" symbolic refs. Only within reason, though */
1426 #define MAXREFLEN (1024)
1429 * Called by resolve_gitlink_ref_recursive() after it failed to read
1430 * from the loose refs in ref_cache refs. Find <refname> in the
1431 * packed-refs file for the submodule.
1433 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1434 const char *refname
, unsigned char *sha1
)
1436 struct ref_entry
*ref
;
1437 struct ref_dir
*dir
= get_packed_refs(refs
);
1439 ref
= find_ref(dir
, refname
);
1443 hashcpy(sha1
, ref
->u
.value
.sha1
);
1447 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1448 const char *refname
, unsigned char *sha1
,
1452 char buffer
[128], *p
;
1455 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1458 ? git_path_submodule(refs
->name
, "%s", refname
)
1459 : git_path("%s", refname
);
1460 fd
= open(path
, O_RDONLY
);
1462 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1464 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1468 while (len
&& isspace(buffer
[len
-1]))
1472 /* Was it a detached head or an old-fashioned symlink? */
1473 if (!get_sha1_hex(buffer
, sha1
))
1477 if (strncmp(buffer
, "ref:", 4))
1483 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1486 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1488 int len
= strlen(path
), retval
;
1490 struct ref_cache
*refs
;
1492 while (len
&& path
[len
-1] == '/')
1496 submodule
= xstrndup(path
, len
);
1497 refs
= get_ref_cache(submodule
);
1500 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1505 * Return the ref_entry for the given refname from the packed
1506 * references. If it does not exist, return NULL.
1508 static struct ref_entry
*get_packed_ref(const char *refname
)
1510 return find_ref(get_packed_refs(&ref_cache
), refname
);
1514 * A loose ref file doesn't exist; check for a packed ref. The
1515 * options are forwarded from resolve_safe_unsafe().
1517 static int resolve_missing_loose_ref(const char *refname
,
1519 unsigned char *sha1
,
1522 struct ref_entry
*entry
;
1525 * The loose reference file does not exist; check for a packed
1528 entry
= get_packed_ref(refname
);
1530 hashcpy(sha1
, entry
->u
.value
.sha1
);
1532 *flags
|= REF_ISPACKED
;
1535 /* The reference is not a packed reference, either. */
1536 if (resolve_flags
& RESOLVE_REF_READING
) {
1545 /* This function needs to return a meaningful errno on failure */
1546 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1548 int depth
= MAXDEPTH
;
1551 static char refname_buffer
[256];
1557 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1559 *flags
|= REF_BAD_NAME
;
1561 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1562 !refname_is_safe(refname
)) {
1567 * dwim_ref() uses REF_ISBROKEN to distinguish between
1568 * missing refs and refs that were present but invalid,
1569 * to complain about the latter to stderr.
1571 * We don't know whether the ref exists, so don't set
1577 char path
[PATH_MAX
];
1587 git_snpath(path
, sizeof(path
), "%s", refname
);
1590 * We might have to loop back here to avoid a race
1591 * condition: first we lstat() the file, then we try
1592 * to read it as a link or as a file. But if somebody
1593 * changes the type of the file (file <-> directory
1594 * <-> symlink) between the lstat() and reading, then
1595 * we don't want to report that as an error but rather
1596 * try again starting with the lstat().
1599 if (lstat(path
, &st
) < 0) {
1600 if (errno
!= ENOENT
)
1602 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1608 *flags
|= REF_ISBROKEN
;
1613 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1614 if (S_ISLNK(st
.st_mode
)) {
1615 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1617 if (errno
== ENOENT
|| errno
== EINVAL
)
1618 /* inconsistent with lstat; retry */
1624 if (starts_with(buffer
, "refs/") &&
1625 !check_refname_format(buffer
, 0)) {
1626 strcpy(refname_buffer
, buffer
);
1627 refname
= refname_buffer
;
1629 *flags
|= REF_ISSYMREF
;
1630 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1638 /* Is it a directory? */
1639 if (S_ISDIR(st
.st_mode
)) {
1645 * Anything else, just open it and try to use it as
1648 fd
= open(path
, O_RDONLY
);
1650 if (errno
== ENOENT
)
1651 /* inconsistent with lstat; retry */
1656 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1658 int save_errno
= errno
;
1664 while (len
&& isspace(buffer
[len
-1]))
1669 * Is it a symbolic ref?
1671 if (!starts_with(buffer
, "ref:")) {
1673 * Please note that FETCH_HEAD has a second
1674 * line containing other data.
1676 if (get_sha1_hex(buffer
, sha1
) ||
1677 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1679 *flags
|= REF_ISBROKEN
;
1686 *flags
|= REF_ISBROKEN
;
1691 *flags
|= REF_ISSYMREF
;
1693 while (isspace(*buf
))
1695 refname
= strcpy(refname_buffer
, buf
);
1696 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1700 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1702 *flags
|= REF_ISBROKEN
;
1704 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1705 !refname_is_safe(buf
)) {
1714 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1716 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1719 /* The argument to filter_refs */
1721 const char *pattern
;
1726 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1728 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1733 int read_ref(const char *refname
, unsigned char *sha1
)
1735 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1738 int ref_exists(const char *refname
)
1740 unsigned char sha1
[20];
1741 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1744 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1747 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1748 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1750 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1754 /* object was peeled successfully: */
1758 * object cannot be peeled because the named object (or an
1759 * object referred to by a tag in the peel chain), does not
1764 /* object cannot be peeled because it is not a tag: */
1767 /* ref_entry contains no peeled value because it is a symref: */
1768 PEEL_IS_SYMREF
= -3,
1771 * ref_entry cannot be peeled because it is broken (i.e., the
1772 * symbolic reference cannot even be resolved to an object
1779 * Peel the named object; i.e., if the object is a tag, resolve the
1780 * tag recursively until a non-tag is found. If successful, store the
1781 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1782 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1783 * and leave sha1 unchanged.
1785 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1787 struct object
*o
= lookup_unknown_object(name
);
1789 if (o
->type
== OBJ_NONE
) {
1790 int type
= sha1_object_info(name
, NULL
);
1791 if (type
< 0 || !object_as_type(o
, type
, 0))
1792 return PEEL_INVALID
;
1795 if (o
->type
!= OBJ_TAG
)
1796 return PEEL_NON_TAG
;
1798 o
= deref_tag_noverify(o
);
1800 return PEEL_INVALID
;
1802 hashcpy(sha1
, o
->sha1
);
1807 * Peel the entry (if possible) and return its new peel_status. If
1808 * repeel is true, re-peel the entry even if there is an old peeled
1809 * value that is already stored in it.
1811 * It is OK to call this function with a packed reference entry that
1812 * might be stale and might even refer to an object that has since
1813 * been garbage-collected. In such a case, if the entry has
1814 * REF_KNOWS_PEELED then leave the status unchanged and return
1815 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1817 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1819 enum peel_status status
;
1821 if (entry
->flag
& REF_KNOWS_PEELED
) {
1823 entry
->flag
&= ~REF_KNOWS_PEELED
;
1824 hashclr(entry
->u
.value
.peeled
);
1826 return is_null_sha1(entry
->u
.value
.peeled
) ?
1827 PEEL_NON_TAG
: PEEL_PEELED
;
1830 if (entry
->flag
& REF_ISBROKEN
)
1832 if (entry
->flag
& REF_ISSYMREF
)
1833 return PEEL_IS_SYMREF
;
1835 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1836 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1837 entry
->flag
|= REF_KNOWS_PEELED
;
1841 int peel_ref(const char *refname
, unsigned char *sha1
)
1844 unsigned char base
[20];
1846 if (current_ref
&& (current_ref
->name
== refname
1847 || !strcmp(current_ref
->name
, refname
))) {
1848 if (peel_entry(current_ref
, 0))
1850 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1854 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1858 * If the reference is packed, read its ref_entry from the
1859 * cache in the hope that we already know its peeled value.
1860 * We only try this optimization on packed references because
1861 * (a) forcing the filling of the loose reference cache could
1862 * be expensive and (b) loose references anyway usually do not
1863 * have REF_KNOWS_PEELED.
1865 if (flag
& REF_ISPACKED
) {
1866 struct ref_entry
*r
= get_packed_ref(refname
);
1868 if (peel_entry(r
, 0))
1870 hashcpy(sha1
, r
->u
.value
.peeled
);
1875 return peel_object(base
, sha1
);
1878 struct warn_if_dangling_data
{
1880 const char *refname
;
1881 const struct string_list
*refnames
;
1882 const char *msg_fmt
;
1885 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1886 int flags
, void *cb_data
)
1888 struct warn_if_dangling_data
*d
= cb_data
;
1889 const char *resolves_to
;
1890 unsigned char junk
[20];
1892 if (!(flags
& REF_ISSYMREF
))
1895 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1898 ? strcmp(resolves_to
, d
->refname
)
1899 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1903 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1908 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1910 struct warn_if_dangling_data data
;
1913 data
.refname
= refname
;
1914 data
.refnames
= NULL
;
1915 data
.msg_fmt
= msg_fmt
;
1916 for_each_rawref(warn_if_dangling_symref
, &data
);
1919 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1921 struct warn_if_dangling_data data
;
1924 data
.refname
= NULL
;
1925 data
.refnames
= refnames
;
1926 data
.msg_fmt
= msg_fmt
;
1927 for_each_rawref(warn_if_dangling_symref
, &data
);
1931 * Call fn for each reference in the specified ref_cache, omitting
1932 * references not in the containing_dir of base. fn is called for all
1933 * references, including broken ones. If fn ever returns a non-zero
1934 * value, stop the iteration and return that value; otherwise, return
1937 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1938 each_ref_entry_fn fn
, void *cb_data
)
1940 struct packed_ref_cache
*packed_ref_cache
;
1941 struct ref_dir
*loose_dir
;
1942 struct ref_dir
*packed_dir
;
1946 * We must make sure that all loose refs are read before accessing the
1947 * packed-refs file; this avoids a race condition in which loose refs
1948 * are migrated to the packed-refs file by a simultaneous process, but
1949 * our in-memory view is from before the migration. get_packed_ref_cache()
1950 * takes care of making sure our view is up to date with what is on
1953 loose_dir
= get_loose_refs(refs
);
1954 if (base
&& *base
) {
1955 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1958 prime_ref_dir(loose_dir
);
1960 packed_ref_cache
= get_packed_ref_cache(refs
);
1961 acquire_packed_ref_cache(packed_ref_cache
);
1962 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1963 if (base
&& *base
) {
1964 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1967 if (packed_dir
&& loose_dir
) {
1968 sort_ref_dir(packed_dir
);
1969 sort_ref_dir(loose_dir
);
1970 retval
= do_for_each_entry_in_dirs(
1971 packed_dir
, loose_dir
, fn
, cb_data
);
1972 } else if (packed_dir
) {
1973 sort_ref_dir(packed_dir
);
1974 retval
= do_for_each_entry_in_dir(
1975 packed_dir
, 0, fn
, cb_data
);
1976 } else if (loose_dir
) {
1977 sort_ref_dir(loose_dir
);
1978 retval
= do_for_each_entry_in_dir(
1979 loose_dir
, 0, fn
, cb_data
);
1982 release_packed_ref_cache(packed_ref_cache
);
1987 * Call fn for each reference in the specified ref_cache for which the
1988 * refname begins with base. If trim is non-zero, then trim that many
1989 * characters off the beginning of each refname before passing the
1990 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1991 * broken references in the iteration. If fn ever returns a non-zero
1992 * value, stop the iteration and return that value; otherwise, return
1995 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
1996 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
1998 struct ref_entry_cb data
;
2003 data
.cb_data
= cb_data
;
2005 if (ref_paranoia
< 0)
2006 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2008 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2010 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
2013 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2015 unsigned char sha1
[20];
2019 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
2020 return fn("HEAD", sha1
, 0, cb_data
);
2025 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
2026 return fn("HEAD", sha1
, flag
, cb_data
);
2031 int head_ref(each_ref_fn fn
, void *cb_data
)
2033 return do_head_ref(NULL
, fn
, cb_data
);
2036 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2038 return do_head_ref(submodule
, fn
, cb_data
);
2041 int for_each_ref(each_ref_fn fn
, void *cb_data
)
2043 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
2046 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2048 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2051 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2053 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2056 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2057 each_ref_fn fn
, void *cb_data
)
2059 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2062 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2064 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2067 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2069 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2072 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2074 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2077 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2079 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2082 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2084 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2087 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2089 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2092 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2094 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2097 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2099 struct strbuf buf
= STRBUF_INIT
;
2101 unsigned char sha1
[20];
2104 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2105 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2106 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2107 strbuf_release(&buf
);
2112 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2114 struct strbuf buf
= STRBUF_INIT
;
2116 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2117 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2118 strbuf_release(&buf
);
2122 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2123 const char *prefix
, void *cb_data
)
2125 struct strbuf real_pattern
= STRBUF_INIT
;
2126 struct ref_filter filter
;
2129 if (!prefix
&& !starts_with(pattern
, "refs/"))
2130 strbuf_addstr(&real_pattern
, "refs/");
2132 strbuf_addstr(&real_pattern
, prefix
);
2133 strbuf_addstr(&real_pattern
, pattern
);
2135 if (!has_glob_specials(pattern
)) {
2136 /* Append implied '/' '*' if not present. */
2137 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2138 strbuf_addch(&real_pattern
, '/');
2139 /* No need to check for '*', there is none. */
2140 strbuf_addch(&real_pattern
, '*');
2143 filter
.pattern
= real_pattern
.buf
;
2145 filter
.cb_data
= cb_data
;
2146 ret
= for_each_ref(filter_refs
, &filter
);
2148 strbuf_release(&real_pattern
);
2152 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2154 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2157 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2159 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2160 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2163 const char *prettify_refname(const char *name
)
2166 starts_with(name
, "refs/heads/") ? 11 :
2167 starts_with(name
, "refs/tags/") ? 10 :
2168 starts_with(name
, "refs/remotes/") ? 13 :
2172 static const char *ref_rev_parse_rules
[] = {
2177 "refs/remotes/%.*s",
2178 "refs/remotes/%.*s/HEAD",
2182 int refname_match(const char *abbrev_name
, const char *full_name
)
2185 const int abbrev_name_len
= strlen(abbrev_name
);
2187 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2188 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2196 static void unlock_ref(struct ref_lock
*lock
)
2198 /* Do not free lock->lk -- atexit() still looks at them */
2200 rollback_lock_file(lock
->lk
);
2201 free(lock
->ref_name
);
2202 free(lock
->orig_ref_name
);
2206 /* This function should make sure errno is meaningful on error */
2207 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2208 const unsigned char *old_sha1
, int mustexist
)
2210 if (read_ref_full(lock
->ref_name
,
2211 mustexist
? RESOLVE_REF_READING
: 0,
2212 lock
->old_sha1
, NULL
)) {
2213 int save_errno
= errno
;
2214 error("Can't verify ref %s", lock
->ref_name
);
2219 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2220 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2221 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2229 static int remove_empty_directories(const char *file
)
2231 /* we want to create a file but there is a directory there;
2232 * if that is an empty directory (or a directory that contains
2233 * only empty directories), remove them.
2236 int result
, save_errno
;
2238 strbuf_init(&path
, 20);
2239 strbuf_addstr(&path
, file
);
2241 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2244 strbuf_release(&path
);
2251 * *string and *len will only be substituted, and *string returned (for
2252 * later free()ing) if the string passed in is a magic short-hand form
2255 static char *substitute_branch_name(const char **string
, int *len
)
2257 struct strbuf buf
= STRBUF_INIT
;
2258 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2262 *string
= strbuf_detach(&buf
, &size
);
2264 return (char *)*string
;
2270 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2272 char *last_branch
= substitute_branch_name(&str
, &len
);
2277 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2278 char fullref
[PATH_MAX
];
2279 unsigned char sha1_from_ref
[20];
2280 unsigned char *this_result
;
2283 this_result
= refs_found
? sha1_from_ref
: sha1
;
2284 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2285 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2286 this_result
, &flag
);
2290 if (!warn_ambiguous_refs
)
2292 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2293 warning("ignoring dangling symref %s.", fullref
);
2294 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2295 warning("ignoring broken ref %s.", fullref
);
2302 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2304 char *last_branch
= substitute_branch_name(&str
, &len
);
2309 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2310 unsigned char hash
[20];
2311 char path
[PATH_MAX
];
2312 const char *ref
, *it
;
2314 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2315 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2319 if (reflog_exists(path
))
2321 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2325 if (!logs_found
++) {
2327 hashcpy(sha1
, hash
);
2329 if (!warn_ambiguous_refs
)
2337 * Locks a ref returning the lock on success and NULL on failure.
2338 * On failure errno is set to something meaningful.
2340 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2341 const unsigned char *old_sha1
,
2342 const struct string_list
*extras
,
2343 const struct string_list
*skip
,
2344 unsigned int flags
, int *type_p
,
2348 const char *orig_refname
= refname
;
2349 struct ref_lock
*lock
;
2352 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2353 int resolve_flags
= 0;
2354 int attempts_remaining
= 3;
2358 lock
= xcalloc(1, sizeof(struct ref_lock
));
2362 resolve_flags
|= RESOLVE_REF_READING
;
2363 if (flags
& REF_DELETING
) {
2364 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2365 if (flags
& REF_NODEREF
)
2366 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2369 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2370 lock
->old_sha1
, &type
);
2371 if (!refname
&& errno
== EISDIR
) {
2372 /* we are trying to lock foo but we used to
2373 * have foo/bar which now does not exist;
2374 * it is normal for the empty directory 'foo'
2377 ref_file
= git_path("%s", orig_refname
);
2378 if (remove_empty_directories(ref_file
)) {
2381 if (!verify_refname_available(orig_refname
, extras
, skip
,
2382 get_loose_refs(&ref_cache
), err
))
2383 strbuf_addf(err
, "there are still refs under '%s'",
2388 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2389 lock
->old_sha1
, &type
);
2395 if (last_errno
!= ENOTDIR
||
2396 !verify_refname_available(orig_refname
, extras
, skip
,
2397 get_loose_refs(&ref_cache
), err
))
2398 strbuf_addf(err
, "unable to resolve reference %s: %s",
2399 orig_refname
, strerror(last_errno
));
2404 * If the ref did not exist and we are creating it, make sure
2405 * there is no existing packed ref whose name begins with our
2406 * refname, nor a packed ref whose name is a proper prefix of
2409 if (is_null_sha1(lock
->old_sha1
) &&
2410 verify_refname_available(refname
, extras
, skip
,
2411 get_packed_refs(&ref_cache
), err
)) {
2412 last_errno
= ENOTDIR
;
2416 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2419 if (flags
& REF_NODEREF
) {
2420 refname
= orig_refname
;
2421 lflags
|= LOCK_NO_DEREF
;
2423 lock
->ref_name
= xstrdup(refname
);
2424 lock
->orig_ref_name
= xstrdup(orig_refname
);
2425 ref_file
= git_path("%s", refname
);
2428 switch (safe_create_leading_directories(ref_file
)) {
2430 break; /* success */
2432 if (--attempts_remaining
> 0)
2437 strbuf_addf(err
, "unable to create directory for %s", ref_file
);
2441 lock
->lock_fd
= hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
);
2442 if (lock
->lock_fd
< 0) {
2444 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2446 * Maybe somebody just deleted one of the
2447 * directories leading to ref_file. Try
2452 unable_to_lock_message(ref_file
, errno
, err
);
2456 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2465 * Write an entry to the packed-refs file for the specified refname.
2466 * If peeled is non-NULL, write it as the entry's peeled value.
2468 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2469 unsigned char *peeled
)
2471 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2473 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2477 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2479 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2481 enum peel_status peel_status
= peel_entry(entry
, 0);
2483 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2484 error("internal error: %s is not a valid packed reference!",
2486 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2487 peel_status
== PEEL_PEELED
?
2488 entry
->u
.value
.peeled
: NULL
);
2492 /* This should return a meaningful errno on failure */
2493 int lock_packed_refs(int flags
)
2495 struct packed_ref_cache
*packed_ref_cache
;
2497 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2500 * Get the current packed-refs while holding the lock. If the
2501 * packed-refs file has been modified since we last read it,
2502 * this will automatically invalidate the cache and re-read
2503 * the packed-refs file.
2505 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2506 packed_ref_cache
->lock
= &packlock
;
2507 /* Increment the reference count to prevent it from being freed: */
2508 acquire_packed_ref_cache(packed_ref_cache
);
2513 * Commit the packed refs changes.
2514 * On error we must make sure that errno contains a meaningful value.
2516 int commit_packed_refs(void)
2518 struct packed_ref_cache
*packed_ref_cache
=
2519 get_packed_ref_cache(&ref_cache
);
2524 if (!packed_ref_cache
->lock
)
2525 die("internal error: packed-refs not locked");
2527 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2529 die_errno("unable to fdopen packed-refs descriptor");
2531 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2532 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2533 0, write_packed_entry_fn
, out
);
2535 if (commit_lock_file(packed_ref_cache
->lock
)) {
2539 packed_ref_cache
->lock
= NULL
;
2540 release_packed_ref_cache(packed_ref_cache
);
2545 void rollback_packed_refs(void)
2547 struct packed_ref_cache
*packed_ref_cache
=
2548 get_packed_ref_cache(&ref_cache
);
2550 if (!packed_ref_cache
->lock
)
2551 die("internal error: packed-refs not locked");
2552 rollback_lock_file(packed_ref_cache
->lock
);
2553 packed_ref_cache
->lock
= NULL
;
2554 release_packed_ref_cache(packed_ref_cache
);
2555 clear_packed_ref_cache(&ref_cache
);
2558 struct ref_to_prune
{
2559 struct ref_to_prune
*next
;
2560 unsigned char sha1
[20];
2561 char name
[FLEX_ARRAY
];
2564 struct pack_refs_cb_data
{
2566 struct ref_dir
*packed_refs
;
2567 struct ref_to_prune
*ref_to_prune
;
2571 * An each_ref_entry_fn that is run over loose references only. If
2572 * the loose reference can be packed, add an entry in the packed ref
2573 * cache. If the reference should be pruned, also add it to
2574 * ref_to_prune in the pack_refs_cb_data.
2576 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2578 struct pack_refs_cb_data
*cb
= cb_data
;
2579 enum peel_status peel_status
;
2580 struct ref_entry
*packed_entry
;
2581 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2583 /* ALWAYS pack tags */
2584 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2587 /* Do not pack symbolic or broken refs: */
2588 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2591 /* Add a packed ref cache entry equivalent to the loose entry. */
2592 peel_status
= peel_entry(entry
, 1);
2593 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2594 die("internal error peeling reference %s (%s)",
2595 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2596 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2598 /* Overwrite existing packed entry with info from loose entry */
2599 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2600 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2602 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2603 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2604 add_ref(cb
->packed_refs
, packed_entry
);
2606 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2608 /* Schedule the loose reference for pruning if requested. */
2609 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2610 int namelen
= strlen(entry
->name
) + 1;
2611 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2612 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2613 strcpy(n
->name
, entry
->name
);
2614 n
->next
= cb
->ref_to_prune
;
2615 cb
->ref_to_prune
= n
;
2621 * Remove empty parents, but spare refs/ and immediate subdirs.
2622 * Note: munges *name.
2624 static void try_remove_empty_parents(char *name
)
2629 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2630 while (*p
&& *p
!= '/')
2632 /* tolerate duplicate slashes; see check_refname_format() */
2636 for (q
= p
; *q
; q
++)
2639 while (q
> p
&& *q
!= '/')
2641 while (q
> p
&& *(q
-1) == '/')
2646 if (rmdir(git_path("%s", name
)))
2651 /* make sure nobody touched the ref, and unlink */
2652 static void prune_ref(struct ref_to_prune
*r
)
2654 struct ref_transaction
*transaction
;
2655 struct strbuf err
= STRBUF_INIT
;
2657 if (check_refname_format(r
->name
, 0))
2660 transaction
= ref_transaction_begin(&err
);
2662 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2663 REF_ISPRUNING
, NULL
, &err
) ||
2664 ref_transaction_commit(transaction
, &err
)) {
2665 ref_transaction_free(transaction
);
2666 error("%s", err
.buf
);
2667 strbuf_release(&err
);
2670 ref_transaction_free(transaction
);
2671 strbuf_release(&err
);
2672 try_remove_empty_parents(r
->name
);
2675 static void prune_refs(struct ref_to_prune
*r
)
2683 int pack_refs(unsigned int flags
)
2685 struct pack_refs_cb_data cbdata
;
2687 memset(&cbdata
, 0, sizeof(cbdata
));
2688 cbdata
.flags
= flags
;
2690 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2691 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2693 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2694 pack_if_possible_fn
, &cbdata
);
2696 if (commit_packed_refs())
2697 die_errno("unable to overwrite old ref-pack file");
2699 prune_refs(cbdata
.ref_to_prune
);
2703 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2705 struct ref_dir
*packed
;
2706 struct string_list_item
*refname
;
2707 int ret
, needs_repacking
= 0, removed
= 0;
2711 /* Look for a packed ref */
2712 for_each_string_list_item(refname
, refnames
) {
2713 if (get_packed_ref(refname
->string
)) {
2714 needs_repacking
= 1;
2719 /* Avoid locking if we have nothing to do */
2720 if (!needs_repacking
)
2721 return 0; /* no refname exists in packed refs */
2723 if (lock_packed_refs(0)) {
2724 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2727 packed
= get_packed_refs(&ref_cache
);
2729 /* Remove refnames from the cache */
2730 for_each_string_list_item(refname
, refnames
)
2731 if (remove_entry(packed
, refname
->string
) != -1)
2735 * All packed entries disappeared while we were
2736 * acquiring the lock.
2738 rollback_packed_refs();
2742 /* Write what remains */
2743 ret
= commit_packed_refs();
2745 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2750 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2754 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2756 * loose. The loose file name is the same as the
2757 * lockfile name, minus ".lock":
2759 char *loose_filename
= get_locked_file_path(lock
->lk
);
2760 int res
= unlink_or_msg(loose_filename
, err
);
2761 free(loose_filename
);
2768 int delete_ref(const char *refname
, const unsigned char *sha1
, unsigned int flags
)
2770 struct ref_transaction
*transaction
;
2771 struct strbuf err
= STRBUF_INIT
;
2773 transaction
= ref_transaction_begin(&err
);
2775 ref_transaction_delete(transaction
, refname
,
2776 (sha1
&& !is_null_sha1(sha1
)) ? sha1
: NULL
,
2777 flags
, NULL
, &err
) ||
2778 ref_transaction_commit(transaction
, &err
)) {
2779 error("%s", err
.buf
);
2780 ref_transaction_free(transaction
);
2781 strbuf_release(&err
);
2784 ref_transaction_free(transaction
);
2785 strbuf_release(&err
);
2790 * People using contrib's git-new-workdir have .git/logs/refs ->
2791 * /some/other/path/.git/logs/refs, and that may live on another device.
2793 * IOW, to avoid cross device rename errors, the temporary renamed log must
2794 * live into logs/refs.
2796 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2798 static int rename_tmp_log(const char *newrefname
)
2800 int attempts_remaining
= 4;
2803 switch (safe_create_leading_directories(git_path("logs/%s", newrefname
))) {
2805 break; /* success */
2807 if (--attempts_remaining
> 0)
2811 error("unable to create directory for %s", newrefname
);
2815 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2816 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2818 * rename(a, b) when b is an existing
2819 * directory ought to result in ISDIR, but
2820 * Solaris 5.8 gives ENOTDIR. Sheesh.
2822 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2823 error("Directory not empty: logs/%s", newrefname
);
2827 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2829 * Maybe another process just deleted one of
2830 * the directories in the path to newrefname.
2831 * Try again from the beginning.
2835 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2836 newrefname
, strerror(errno
));
2843 static int rename_ref_available(const char *oldname
, const char *newname
)
2845 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2846 struct strbuf err
= STRBUF_INIT
;
2849 string_list_insert(&skip
, oldname
);
2850 ret
= !verify_refname_available(newname
, NULL
, &skip
,
2851 get_packed_refs(&ref_cache
), &err
)
2852 && !verify_refname_available(newname
, NULL
, &skip
,
2853 get_loose_refs(&ref_cache
), &err
);
2855 error("%s", err
.buf
);
2857 string_list_clear(&skip
, 0);
2858 strbuf_release(&err
);
2862 static int write_ref_to_lockfile(struct ref_lock
*lock
, const unsigned char *sha1
);
2863 static int commit_ref_update(struct ref_lock
*lock
,
2864 const unsigned char *sha1
, const char *logmsg
);
2866 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2868 unsigned char sha1
[20], orig_sha1
[20];
2869 int flag
= 0, logmoved
= 0;
2870 struct ref_lock
*lock
;
2871 struct stat loginfo
;
2872 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2873 const char *symref
= NULL
;
2874 struct strbuf err
= STRBUF_INIT
;
2876 if (log
&& S_ISLNK(loginfo
.st_mode
))
2877 return error("reflog for %s is a symlink", oldrefname
);
2879 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2881 if (flag
& REF_ISSYMREF
)
2882 return error("refname %s is a symbolic ref, renaming it is not supported",
2885 return error("refname %s not found", oldrefname
);
2887 if (!rename_ref_available(oldrefname
, newrefname
))
2890 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2891 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2892 oldrefname
, strerror(errno
));
2894 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2895 error("unable to delete old %s", oldrefname
);
2899 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2900 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2901 if (errno
==EISDIR
) {
2902 if (remove_empty_directories(git_path("%s", newrefname
))) {
2903 error("Directory not empty: %s", newrefname
);
2907 error("unable to delete existing %s", newrefname
);
2912 if (log
&& rename_tmp_log(newrefname
))
2917 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2919 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
2920 strbuf_release(&err
);
2923 hashcpy(lock
->old_sha1
, orig_sha1
);
2925 if (write_ref_to_lockfile(lock
, orig_sha1
) ||
2926 commit_ref_update(lock
, orig_sha1
, logmsg
)) {
2927 error("unable to write current sha1 into %s", newrefname
);
2934 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2936 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
2937 strbuf_release(&err
);
2941 flag
= log_all_ref_updates
;
2942 log_all_ref_updates
= 0;
2943 if (write_ref_to_lockfile(lock
, orig_sha1
) ||
2944 commit_ref_update(lock
, orig_sha1
, NULL
))
2945 error("unable to write current sha1 into %s", oldrefname
);
2946 log_all_ref_updates
= flag
;
2949 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2950 error("unable to restore logfile %s from %s: %s",
2951 oldrefname
, newrefname
, strerror(errno
));
2952 if (!logmoved
&& log
&&
2953 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2954 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2955 oldrefname
, strerror(errno
));
2960 static int close_ref(struct ref_lock
*lock
)
2962 if (close_lock_file(lock
->lk
))
2968 static int commit_ref(struct ref_lock
*lock
)
2970 if (commit_lock_file(lock
->lk
))
2977 * copy the reflog message msg to buf, which has been allocated sufficiently
2978 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2979 * because reflog file is one line per entry.
2981 static int copy_msg(char *buf
, const char *msg
)
2988 while ((c
= *msg
++)) {
2989 if (wasspace
&& isspace(c
))
2991 wasspace
= isspace(c
);
2996 while (buf
< cp
&& isspace(cp
[-1]))
3002 /* This function must set a meaningful errno on failure */
3003 int log_ref_setup(const char *refname
, char *logfile
, int bufsize
)
3005 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
3007 git_snpath(logfile
, bufsize
, "logs/%s", refname
);
3008 if (log_all_ref_updates
&&
3009 (starts_with(refname
, "refs/heads/") ||
3010 starts_with(refname
, "refs/remotes/") ||
3011 starts_with(refname
, "refs/notes/") ||
3012 !strcmp(refname
, "HEAD"))) {
3013 if (safe_create_leading_directories(logfile
) < 0) {
3014 int save_errno
= errno
;
3015 error("unable to create directory for %s", logfile
);
3022 logfd
= open(logfile
, oflags
, 0666);
3024 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3027 if (errno
== EISDIR
) {
3028 if (remove_empty_directories(logfile
)) {
3029 int save_errno
= errno
;
3030 error("There are still logs under '%s'",
3035 logfd
= open(logfile
, oflags
, 0666);
3039 int save_errno
= errno
;
3040 error("Unable to append to %s: %s", logfile
,
3047 adjust_shared_perm(logfile
);
3052 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3053 const unsigned char *new_sha1
,
3054 const char *committer
, const char *msg
)
3056 int msglen
, written
;
3057 unsigned maxlen
, len
;
3060 msglen
= msg
? strlen(msg
) : 0;
3061 maxlen
= strlen(committer
) + msglen
+ 100;
3062 logrec
= xmalloc(maxlen
);
3063 len
= sprintf(logrec
, "%s %s %s\n",
3064 sha1_to_hex(old_sha1
),
3065 sha1_to_hex(new_sha1
),
3068 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3070 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3078 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3079 const unsigned char *new_sha1
, const char *msg
)
3081 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3082 char log_file
[PATH_MAX
];
3084 if (log_all_ref_updates
< 0)
3085 log_all_ref_updates
= !is_bare_repository();
3087 result
= log_ref_setup(refname
, log_file
, sizeof(log_file
));
3091 logfd
= open(log_file
, oflags
);
3094 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3095 git_committer_info(0), msg
);
3097 int save_errno
= errno
;
3099 error("Unable to append to %s", log_file
);
3104 int save_errno
= errno
;
3105 error("Unable to append to %s", log_file
);
3112 int is_branch(const char *refname
)
3114 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3118 * Write sha1 into the open lockfile, then close the lockfile. On
3119 * errors, rollback the lockfile and set errno to reflect the problem.
3121 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3122 const unsigned char *sha1
)
3124 static char term
= '\n';
3127 o
= parse_object(sha1
);
3129 error("Trying to write ref %s with nonexistent object %s",
3130 lock
->ref_name
, sha1_to_hex(sha1
));
3135 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3136 error("Trying to write non-commit object %s to branch %s",
3137 sha1_to_hex(sha1
), lock
->ref_name
);
3142 if (write_in_full(lock
->lock_fd
, sha1_to_hex(sha1
), 40) != 40 ||
3143 write_in_full(lock
->lock_fd
, &term
, 1) != 1 ||
3144 close_ref(lock
) < 0) {
3145 int save_errno
= errno
;
3146 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3155 * Commit a change to a loose reference that has already been written
3156 * to the loose reference lockfile. Also update the reflogs if
3157 * necessary, using the specified lockmsg (which can be NULL).
3159 static int commit_ref_update(struct ref_lock
*lock
,
3160 const unsigned char *sha1
, const char *logmsg
)
3162 clear_loose_ref_cache(&ref_cache
);
3163 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3164 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3165 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3169 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3171 * Special hack: If a branch is updated directly and HEAD
3172 * points to it (may happen on the remote side of a push
3173 * for example) then logically the HEAD reflog should be
3175 * A generic solution implies reverse symref information,
3176 * but finding all symrefs pointing to the given branch
3177 * would be rather costly for this rare event (the direct
3178 * update of a branch) to be worth it. So let's cheat and
3179 * check with HEAD only which should cover 99% of all usage
3180 * scenarios (even 100% of the default ones).
3182 unsigned char head_sha1
[20];
3184 const char *head_ref
;
3185 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3186 head_sha1
, &head_flag
);
3187 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3188 !strcmp(head_ref
, lock
->ref_name
))
3189 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3191 if (commit_ref(lock
)) {
3192 error("Couldn't set %s", lock
->ref_name
);
3200 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3203 const char *lockpath
;
3205 int fd
, len
, written
;
3206 char *git_HEAD
= git_pathdup("%s", ref_target
);
3207 unsigned char old_sha1
[20], new_sha1
[20];
3209 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3212 if (safe_create_leading_directories(git_HEAD
) < 0)
3213 return error("unable to create directory for %s", git_HEAD
);
3215 #ifndef NO_SYMLINK_HEAD
3216 if (prefer_symlink_refs
) {
3218 if (!symlink(refs_heads_master
, git_HEAD
))
3220 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3224 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3225 if (sizeof(ref
) <= len
) {
3226 error("refname too long: %s", refs_heads_master
);
3227 goto error_free_return
;
3229 lockpath
= mkpath("%s.lock", git_HEAD
);
3230 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3232 error("Unable to open %s for writing", lockpath
);
3233 goto error_free_return
;
3235 written
= write_in_full(fd
, ref
, len
);
3236 if (close(fd
) != 0 || written
!= len
) {
3237 error("Unable to write to %s", lockpath
);
3238 goto error_unlink_return
;
3240 if (rename(lockpath
, git_HEAD
) < 0) {
3241 error("Unable to create %s", git_HEAD
);
3242 goto error_unlink_return
;
3244 if (adjust_shared_perm(git_HEAD
)) {
3245 error("Unable to fix permissions on %s", lockpath
);
3246 error_unlink_return
:
3247 unlink_or_warn(lockpath
);
3253 #ifndef NO_SYMLINK_HEAD
3256 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3257 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3263 struct read_ref_at_cb
{
3264 const char *refname
;
3265 unsigned long at_time
;
3268 unsigned char *sha1
;
3271 unsigned char osha1
[20];
3272 unsigned char nsha1
[20];
3276 unsigned long *cutoff_time
;
3281 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3282 const char *email
, unsigned long timestamp
, int tz
,
3283 const char *message
, void *cb_data
)
3285 struct read_ref_at_cb
*cb
= cb_data
;
3289 cb
->date
= timestamp
;
3291 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3293 *cb
->msg
= xstrdup(message
);
3294 if (cb
->cutoff_time
)
3295 *cb
->cutoff_time
= timestamp
;
3297 *cb
->cutoff_tz
= tz
;
3299 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3301 * we have not yet updated cb->[n|o]sha1 so they still
3302 * hold the values for the previous record.
3304 if (!is_null_sha1(cb
->osha1
)) {
3305 hashcpy(cb
->sha1
, nsha1
);
3306 if (hashcmp(cb
->osha1
, nsha1
))
3307 warning("Log for ref %s has gap after %s.",
3308 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3310 else if (cb
->date
== cb
->at_time
)
3311 hashcpy(cb
->sha1
, nsha1
);
3312 else if (hashcmp(nsha1
, cb
->sha1
))
3313 warning("Log for ref %s unexpectedly ended on %s.",
3314 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3316 hashcpy(cb
->osha1
, osha1
);
3317 hashcpy(cb
->nsha1
, nsha1
);
3321 hashcpy(cb
->osha1
, osha1
);
3322 hashcpy(cb
->nsha1
, nsha1
);
3328 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3329 const char *email
, unsigned long timestamp
,
3330 int tz
, const char *message
, void *cb_data
)
3332 struct read_ref_at_cb
*cb
= cb_data
;
3335 *cb
->msg
= xstrdup(message
);
3336 if (cb
->cutoff_time
)
3337 *cb
->cutoff_time
= timestamp
;
3339 *cb
->cutoff_tz
= tz
;
3341 *cb
->cutoff_cnt
= cb
->reccnt
;
3342 hashcpy(cb
->sha1
, osha1
);
3343 if (is_null_sha1(cb
->sha1
))
3344 hashcpy(cb
->sha1
, nsha1
);
3345 /* We just want the first entry */
3349 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3350 unsigned char *sha1
, char **msg
,
3351 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3353 struct read_ref_at_cb cb
;
3355 memset(&cb
, 0, sizeof(cb
));
3356 cb
.refname
= refname
;
3357 cb
.at_time
= at_time
;
3360 cb
.cutoff_time
= cutoff_time
;
3361 cb
.cutoff_tz
= cutoff_tz
;
3362 cb
.cutoff_cnt
= cutoff_cnt
;
3365 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3368 if (flags
& GET_SHA1_QUIETLY
)
3371 die("Log for %s is empty.", refname
);
3376 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3381 int reflog_exists(const char *refname
)
3385 return !lstat(git_path("logs/%s", refname
), &st
) &&
3386 S_ISREG(st
.st_mode
);
3389 int delete_reflog(const char *refname
)
3391 return remove_path(git_path("logs/%s", refname
));
3394 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3396 unsigned char osha1
[20], nsha1
[20];
3397 char *email_end
, *message
;
3398 unsigned long timestamp
;
3401 /* old SP new SP name <email> SP time TAB msg LF */
3402 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3403 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3404 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3405 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3406 email_end
[1] != ' ' ||
3407 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3408 !message
|| message
[0] != ' ' ||
3409 (message
[1] != '+' && message
[1] != '-') ||
3410 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3411 !isdigit(message
[4]) || !isdigit(message
[5]))
3412 return 0; /* corrupt? */
3413 email_end
[1] = '\0';
3414 tz
= strtol(message
+ 1, NULL
, 10);
3415 if (message
[6] != '\t')
3419 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3422 static char *find_beginning_of_line(char *bob
, char *scan
)
3424 while (bob
< scan
&& *(--scan
) != '\n')
3425 ; /* keep scanning backwards */
3427 * Return either beginning of the buffer, or LF at the end of
3428 * the previous line.
3433 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3435 struct strbuf sb
= STRBUF_INIT
;
3438 int ret
= 0, at_tail
= 1;
3440 logfp
= fopen(git_path("logs/%s", refname
), "r");
3444 /* Jump to the end */
3445 if (fseek(logfp
, 0, SEEK_END
) < 0)
3446 return error("cannot seek back reflog for %s: %s",
3447 refname
, strerror(errno
));
3449 while (!ret
&& 0 < pos
) {
3455 /* Fill next block from the end */
3456 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3457 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3458 return error("cannot seek back reflog for %s: %s",
3459 refname
, strerror(errno
));
3460 nread
= fread(buf
, cnt
, 1, logfp
);
3462 return error("cannot read %d bytes from reflog for %s: %s",
3463 cnt
, refname
, strerror(errno
));
3466 scanp
= endp
= buf
+ cnt
;
3467 if (at_tail
&& scanp
[-1] == '\n')
3468 /* Looking at the final LF at the end of the file */
3472 while (buf
< scanp
) {
3474 * terminating LF of the previous line, or the beginning
3479 bp
= find_beginning_of_line(buf
, scanp
);
3483 * The newline is the end of the previous line,
3484 * so we know we have complete line starting
3485 * at (bp + 1). Prefix it onto any prior data
3486 * we collected for the line and process it.
3488 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3491 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3497 * We are at the start of the buffer, and the
3498 * start of the file; there is no previous
3499 * line, and we have everything for this one.
3500 * Process it, and we can end the loop.
3502 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3503 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3510 * We are at the start of the buffer, and there
3511 * is more file to read backwards. Which means
3512 * we are in the middle of a line. Note that we
3513 * may get here even if *bp was a newline; that
3514 * just means we are at the exact end of the
3515 * previous line, rather than some spot in the
3518 * Save away what we have to be combined with
3519 * the data from the next read.
3521 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3528 die("BUG: reverse reflog parser had leftover data");
3531 strbuf_release(&sb
);
3535 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3538 struct strbuf sb
= STRBUF_INIT
;
3541 logfp
= fopen(git_path("logs/%s", refname
), "r");
3545 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3546 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3548 strbuf_release(&sb
);
3552 * Call fn for each reflog in the namespace indicated by name. name
3553 * must be empty or end with '/'. Name will be used as a scratch
3554 * space, but its contents will be restored before return.
3556 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3558 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3561 int oldlen
= name
->len
;
3564 return name
->len
? errno
: 0;
3566 while ((de
= readdir(d
)) != NULL
) {
3569 if (de
->d_name
[0] == '.')
3571 if (ends_with(de
->d_name
, ".lock"))
3573 strbuf_addstr(name
, de
->d_name
);
3574 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3575 ; /* silently ignore */
3577 if (S_ISDIR(st
.st_mode
)) {
3578 strbuf_addch(name
, '/');
3579 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3581 unsigned char sha1
[20];
3582 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3583 retval
= error("bad ref for %s", name
->buf
);
3585 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3590 strbuf_setlen(name
, oldlen
);
3596 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3600 strbuf_init(&name
, PATH_MAX
);
3601 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3602 strbuf_release(&name
);
3607 * Information needed for a single ref update. Set new_sha1 to the new
3608 * value or to null_sha1 to delete the ref. To check the old value
3609 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3610 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3611 * not exist before update.
3615 * If (flags & REF_HAVE_NEW), set the reference to this value:
3617 unsigned char new_sha1
[20];
3619 * If (flags & REF_HAVE_OLD), check that the reference
3620 * previously had this value:
3622 unsigned char old_sha1
[20];
3624 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3625 * REF_DELETING, and REF_ISPRUNING:
3628 struct ref_lock
*lock
;
3631 const char refname
[FLEX_ARRAY
];
3635 * Transaction states.
3636 * OPEN: The transaction is in a valid state and can accept new updates.
3637 * An OPEN transaction can be committed.
3638 * CLOSED: A closed transaction is no longer active and no other operations
3639 * than free can be used on it in this state.
3640 * A transaction can either become closed by successfully committing
3641 * an active transaction or if there is a failure while building
3642 * the transaction thus rendering it failed/inactive.
3644 enum ref_transaction_state
{
3645 REF_TRANSACTION_OPEN
= 0,
3646 REF_TRANSACTION_CLOSED
= 1
3650 * Data structure for holding a reference transaction, which can
3651 * consist of checks and updates to multiple references, carried out
3652 * as atomically as possible. This structure is opaque to callers.
3654 struct ref_transaction
{
3655 struct ref_update
**updates
;
3658 enum ref_transaction_state state
;
3661 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3665 return xcalloc(1, sizeof(struct ref_transaction
));
3668 void ref_transaction_free(struct ref_transaction
*transaction
)
3675 for (i
= 0; i
< transaction
->nr
; i
++) {
3676 free(transaction
->updates
[i
]->msg
);
3677 free(transaction
->updates
[i
]);
3679 free(transaction
->updates
);
3683 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3684 const char *refname
)
3686 size_t len
= strlen(refname
);
3687 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3689 strcpy((char *)update
->refname
, refname
);
3690 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3691 transaction
->updates
[transaction
->nr
++] = update
;
3695 int ref_transaction_update(struct ref_transaction
*transaction
,
3696 const char *refname
,
3697 const unsigned char *new_sha1
,
3698 const unsigned char *old_sha1
,
3699 unsigned int flags
, const char *msg
,
3702 struct ref_update
*update
;
3706 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3707 die("BUG: update called for transaction that is not open");
3709 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
3710 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3711 strbuf_addf(err
, "refusing to update ref with bad name %s",
3716 update
= add_update(transaction
, refname
);
3718 hashcpy(update
->new_sha1
, new_sha1
);
3719 flags
|= REF_HAVE_NEW
;
3722 hashcpy(update
->old_sha1
, old_sha1
);
3723 flags
|= REF_HAVE_OLD
;
3725 update
->flags
= flags
;
3727 update
->msg
= xstrdup(msg
);
3731 int ref_transaction_create(struct ref_transaction
*transaction
,
3732 const char *refname
,
3733 const unsigned char *new_sha1
,
3734 unsigned int flags
, const char *msg
,
3737 if (!new_sha1
|| is_null_sha1(new_sha1
))
3738 die("BUG: create called without valid new_sha1");
3739 return ref_transaction_update(transaction
, refname
, new_sha1
,
3740 null_sha1
, flags
, msg
, err
);
3743 int ref_transaction_delete(struct ref_transaction
*transaction
,
3744 const char *refname
,
3745 const unsigned char *old_sha1
,
3746 unsigned int flags
, const char *msg
,
3749 if (old_sha1
&& is_null_sha1(old_sha1
))
3750 die("BUG: delete called with old_sha1 set to zeros");
3751 return ref_transaction_update(transaction
, refname
,
3752 null_sha1
, old_sha1
,
3756 int ref_transaction_verify(struct ref_transaction
*transaction
,
3757 const char *refname
,
3758 const unsigned char *old_sha1
,
3763 die("BUG: verify called with old_sha1 set to NULL");
3764 return ref_transaction_update(transaction
, refname
,
3769 int update_ref(const char *msg
, const char *refname
,
3770 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
3771 unsigned int flags
, enum action_on_err onerr
)
3773 struct ref_transaction
*t
;
3774 struct strbuf err
= STRBUF_INIT
;
3776 t
= ref_transaction_begin(&err
);
3778 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
3779 flags
, msg
, &err
) ||
3780 ref_transaction_commit(t
, &err
)) {
3781 const char *str
= "update_ref failed for ref '%s': %s";
3783 ref_transaction_free(t
);
3785 case UPDATE_REFS_MSG_ON_ERR
:
3786 error(str
, refname
, err
.buf
);
3788 case UPDATE_REFS_DIE_ON_ERR
:
3789 die(str
, refname
, err
.buf
);
3791 case UPDATE_REFS_QUIET_ON_ERR
:
3794 strbuf_release(&err
);
3797 strbuf_release(&err
);
3798 ref_transaction_free(t
);
3802 static int ref_update_reject_duplicates(struct string_list
*refnames
,
3805 int i
, n
= refnames
->nr
;
3809 for (i
= 1; i
< n
; i
++)
3810 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
3812 "Multiple updates for ref '%s' not allowed.",
3813 refnames
->items
[i
].string
);
3819 int ref_transaction_commit(struct ref_transaction
*transaction
,
3823 int n
= transaction
->nr
;
3824 struct ref_update
**updates
= transaction
->updates
;
3825 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3826 struct string_list_item
*ref_to_delete
;
3827 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3831 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3832 die("BUG: commit called for transaction that is not open");
3835 transaction
->state
= REF_TRANSACTION_CLOSED
;
3839 /* Fail if a refname appears more than once in the transaction: */
3840 for (i
= 0; i
< n
; i
++)
3841 string_list_append(&affected_refnames
, updates
[i
]->refname
);
3842 string_list_sort(&affected_refnames
);
3843 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
3844 ret
= TRANSACTION_GENERIC_ERROR
;
3849 * Acquire all locks, verify old values if provided, check
3850 * that new values are valid, and write new values to the
3851 * lockfiles, ready to be activated. Only keep one lockfile
3852 * open at a time to avoid running out of file descriptors.
3854 for (i
= 0; i
< n
; i
++) {
3855 struct ref_update
*update
= updates
[i
];
3857 if ((update
->flags
& REF_HAVE_NEW
) &&
3858 is_null_sha1(update
->new_sha1
))
3859 update
->flags
|= REF_DELETING
;
3860 update
->lock
= lock_ref_sha1_basic(
3862 ((update
->flags
& REF_HAVE_OLD
) ?
3863 update
->old_sha1
: NULL
),
3864 &affected_refnames
, NULL
,
3868 if (!update
->lock
) {
3871 ret
= (errno
== ENOTDIR
)
3872 ? TRANSACTION_NAME_CONFLICT
3873 : TRANSACTION_GENERIC_ERROR
;
3874 reason
= strbuf_detach(err
, NULL
);
3875 strbuf_addf(err
, "Cannot lock ref '%s': %s",
3876 update
->refname
, reason
);
3880 if ((update
->flags
& REF_HAVE_NEW
) &&
3881 !(update
->flags
& REF_DELETING
)) {
3882 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
3883 (update
->flags
& REF_NODEREF
));
3885 if (!overwriting_symref
&&
3886 !hashcmp(update
->lock
->old_sha1
, update
->new_sha1
)) {
3888 * The reference already has the desired
3889 * value, so we don't need to write it.
3891 } else if (write_ref_to_lockfile(update
->lock
,
3892 update
->new_sha1
)) {
3894 * The lock was freed upon failure of
3895 * write_ref_to_lockfile():
3897 update
->lock
= NULL
;
3898 strbuf_addf(err
, "Cannot update the ref '%s'.",
3900 ret
= TRANSACTION_GENERIC_ERROR
;
3903 update
->flags
|= REF_NEEDS_COMMIT
;
3906 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
3908 * We didn't have to write anything to the lockfile.
3909 * Close it to free up the file descriptor:
3911 if (close_ref(update
->lock
)) {
3912 strbuf_addf(err
, "Couldn't close %s.lock",
3919 /* Perform updates first so live commits remain referenced */
3920 for (i
= 0; i
< n
; i
++) {
3921 struct ref_update
*update
= updates
[i
];
3923 if (update
->flags
& REF_NEEDS_COMMIT
) {
3924 if (commit_ref_update(update
->lock
,
3925 update
->new_sha1
, update
->msg
)) {
3926 /* freed by commit_ref_update(): */
3927 update
->lock
= NULL
;
3928 strbuf_addf(err
, "Cannot update the ref '%s'.",
3930 ret
= TRANSACTION_GENERIC_ERROR
;
3933 /* freed by commit_ref_update(): */
3934 update
->lock
= NULL
;
3939 /* Perform deletes now that updates are safely completed */
3940 for (i
= 0; i
< n
; i
++) {
3941 struct ref_update
*update
= updates
[i
];
3943 if (update
->flags
& REF_DELETING
) {
3944 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3945 ret
= TRANSACTION_GENERIC_ERROR
;
3949 if (!(update
->flags
& REF_ISPRUNING
))
3950 string_list_append(&refs_to_delete
,
3951 update
->lock
->ref_name
);
3955 if (repack_without_refs(&refs_to_delete
, err
)) {
3956 ret
= TRANSACTION_GENERIC_ERROR
;
3959 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3960 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3961 clear_loose_ref_cache(&ref_cache
);
3964 transaction
->state
= REF_TRANSACTION_CLOSED
;
3966 for (i
= 0; i
< n
; i
++)
3967 if (updates
[i
]->lock
)
3968 unlock_ref(updates
[i
]->lock
);
3969 string_list_clear(&refs_to_delete
, 0);
3970 string_list_clear(&affected_refnames
, 0);
3974 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3977 static char **scanf_fmts
;
3978 static int nr_rules
;
3983 * Pre-generate scanf formats from ref_rev_parse_rules[].
3984 * Generate a format suitable for scanf from a
3985 * ref_rev_parse_rules rule by interpolating "%s" at the
3986 * location of the "%.*s".
3988 size_t total_len
= 0;
3991 /* the rule list is NULL terminated, count them first */
3992 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3993 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3994 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3996 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3999 for (i
= 0; i
< nr_rules
; i
++) {
4000 assert(offset
< total_len
);
4001 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
4002 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
4003 ref_rev_parse_rules
[i
], 2, "%s") + 1;
4007 /* bail out if there are no rules */
4009 return xstrdup(refname
);
4011 /* buffer for scanf result, at most refname must fit */
4012 short_name
= xstrdup(refname
);
4014 /* skip first rule, it will always match */
4015 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
4017 int rules_to_fail
= i
;
4020 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
4023 short_name_len
= strlen(short_name
);
4026 * in strict mode, all (except the matched one) rules
4027 * must fail to resolve to a valid non-ambiguous ref
4030 rules_to_fail
= nr_rules
;
4033 * check if the short name resolves to a valid ref,
4034 * but use only rules prior to the matched one
4036 for (j
= 0; j
< rules_to_fail
; j
++) {
4037 const char *rule
= ref_rev_parse_rules
[j
];
4038 char refname
[PATH_MAX
];
4040 /* skip matched rule */
4045 * the short name is ambiguous, if it resolves
4046 * (with this previous rule) to a valid ref
4047 * read_ref() returns 0 on success
4049 mksnpath(refname
, sizeof(refname
),
4050 rule
, short_name_len
, short_name
);
4051 if (ref_exists(refname
))
4056 * short name is non-ambiguous if all previous rules
4057 * haven't resolved to a valid ref
4059 if (j
== rules_to_fail
)
4064 return xstrdup(refname
);
4067 static struct string_list
*hide_refs
;
4069 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
4071 if (!strcmp("transfer.hiderefs", var
) ||
4072 /* NEEDSWORK: use parse_config_key() once both are merged */
4073 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
4074 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
4079 return config_error_nonbool(var
);
4080 ref
= xstrdup(value
);
4082 while (len
&& ref
[len
- 1] == '/')
4085 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
4086 hide_refs
->strdup_strings
= 1;
4088 string_list_append(hide_refs
, ref
);
4093 int ref_is_hidden(const char *refname
)
4095 struct string_list_item
*item
;
4099 for_each_string_list_item(item
, hide_refs
) {
4101 if (!starts_with(refname
, item
->string
))
4103 len
= strlen(item
->string
);
4104 if (!refname
[len
] || refname
[len
] == '/')
4110 struct expire_reflog_cb
{
4112 reflog_expiry_should_prune_fn
*should_prune_fn
;
4115 unsigned char last_kept_sha1
[20];
4118 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4119 const char *email
, unsigned long timestamp
, int tz
,
4120 const char *message
, void *cb_data
)
4122 struct expire_reflog_cb
*cb
= cb_data
;
4123 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4125 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4126 osha1
= cb
->last_kept_sha1
;
4128 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4129 message
, policy_cb
)) {
4131 printf("would prune %s", message
);
4132 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4133 printf("prune %s", message
);
4136 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4137 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4138 email
, timestamp
, tz
, message
);
4139 hashcpy(cb
->last_kept_sha1
, nsha1
);
4141 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4142 printf("keep %s", message
);
4147 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4149 reflog_expiry_prepare_fn prepare_fn
,
4150 reflog_expiry_should_prune_fn should_prune_fn
,
4151 reflog_expiry_cleanup_fn cleanup_fn
,
4152 void *policy_cb_data
)
4154 static struct lock_file reflog_lock
;
4155 struct expire_reflog_cb cb
;
4156 struct ref_lock
*lock
;
4160 struct strbuf err
= STRBUF_INIT
;
4162 memset(&cb
, 0, sizeof(cb
));
4164 cb
.policy_cb
= policy_cb_data
;
4165 cb
.should_prune_fn
= should_prune_fn
;
4168 * The reflog file is locked by holding the lock on the
4169 * reference itself, plus we might need to update the
4170 * reference if --updateref was specified:
4172 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, 0, &type
, &err
);
4174 error("cannot lock ref '%s': %s", refname
, err
.buf
);
4175 strbuf_release(&err
);
4178 if (!reflog_exists(refname
)) {
4183 log_file
= git_pathdup("logs/%s", refname
);
4184 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4186 * Even though holding $GIT_DIR/logs/$reflog.lock has
4187 * no locking implications, we use the lock_file
4188 * machinery here anyway because it does a lot of the
4189 * work we need, including cleaning up if the program
4190 * exits unexpectedly.
4192 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4193 struct strbuf err
= STRBUF_INIT
;
4194 unable_to_lock_message(log_file
, errno
, &err
);
4195 error("%s", err
.buf
);
4196 strbuf_release(&err
);
4199 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4201 error("cannot fdopen %s (%s)",
4202 reflog_lock
.filename
.buf
, strerror(errno
));
4207 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4208 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4209 (*cleanup_fn
)(cb
.policy_cb
);
4211 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4213 * It doesn't make sense to adjust a reference pointed
4214 * to by a symbolic ref based on expiring entries in
4215 * the symbolic reference's reflog. Nor can we update
4216 * a reference if there are no remaining reflog
4219 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4220 !(type
& REF_ISSYMREF
) &&
4221 !is_null_sha1(cb
.last_kept_sha1
);
4223 if (close_lock_file(&reflog_lock
)) {
4224 status
|= error("couldn't write %s: %s", log_file
,
4226 } else if (update
&&
4227 (write_in_full(lock
->lock_fd
,
4228 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4229 write_str_in_full(lock
->lock_fd
, "\n") != 1 ||
4230 close_ref(lock
) < 0)) {
4231 status
|= error("couldn't write %s",
4232 lock
->lk
->filename
.buf
);
4233 rollback_lock_file(&reflog_lock
);
4234 } else if (commit_lock_file(&reflog_lock
)) {
4235 status
|= error("unable to commit reflog '%s' (%s)",
4236 log_file
, strerror(errno
));
4237 } else if (update
&& commit_ref(lock
)) {
4238 status
|= error("couldn't set %s", lock
->ref_name
);
4246 rollback_lock_file(&reflog_lock
);