7 #include "string-list.h"
13 unsigned char old_sha1
[20];
17 * How to handle various characters in refnames:
18 * 0: An acceptable character for refs
20 * 2: ., look for a preceding . to reject .. in refs
21 * 3: {, look for a preceding @ to reject @{ in refs
22 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
24 static unsigned char refname_disposition
[256] = {
25 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
26 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
37 * refs (i.e., because the reference is about to be deleted anyway).
39 #define REF_DELETING 0x02
42 * Used as a flag in ref_update::flags when a loose ref is being
45 #define REF_ISPRUNING 0x04
48 * Used as a flag in ref_update::flags when the reference should be
49 * updated to new_sha1.
51 #define REF_HAVE_NEW 0x08
54 * Used as a flag in ref_update::flags when old_sha1 should be
57 #define REF_HAVE_OLD 0x10
60 * Try to read one refname component from the front of refname.
61 * Return the length of the component found, or -1 if the component is
62 * not legal. It is legal if it is something reasonable to have under
63 * ".git/refs/"; We do not like it if:
65 * - any path component of it begins with ".", or
66 * - it has double dots "..", or
67 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
68 * - it ends with a "/".
69 * - it ends with ".lock"
70 * - it contains a "\" (backslash)
72 static int check_refname_component(const char *refname
, int flags
)
77 for (cp
= refname
; ; cp
++) {
79 unsigned char disp
= refname_disposition
[ch
];
85 return -1; /* Refname contains "..". */
89 return -1; /* Refname contains "@{". */
98 return 0; /* Component has zero length. */
99 if (refname
[0] == '.')
100 return -1; /* Component starts with '.'. */
101 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
102 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
103 return -1; /* Refname ends with ".lock". */
107 int check_refname_format(const char *refname
, int flags
)
109 int component_len
, component_count
= 0;
111 if (!strcmp(refname
, "@"))
112 /* Refname is a single character '@'. */
116 /* We are at the start of a path component. */
117 component_len
= check_refname_component(refname
, flags
);
118 if (component_len
<= 0) {
119 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
121 (refname
[1] == '\0' || refname
[1] == '/')) {
122 /* Accept one wildcard as a full refname component. */
123 flags
&= ~REFNAME_REFSPEC_PATTERN
;
130 if (refname
[component_len
] == '\0')
132 /* Skip to next component. */
133 refname
+= component_len
+ 1;
136 if (refname
[component_len
- 1] == '.')
137 return -1; /* Refname ends with '.'. */
138 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
139 return -1; /* Refname has only one component. */
146 * Information used (along with the information in ref_entry) to
147 * describe a single cached reference. This data structure only
148 * occurs embedded in a union in struct ref_entry, and only when
149 * (ref_entry->flag & REF_DIR) is zero.
153 * The name of the object to which this reference resolves
154 * (which may be a tag object). If REF_ISBROKEN, this is
155 * null. If REF_ISSYMREF, then this is the name of the object
156 * referred to by the last reference in the symlink chain.
158 unsigned char sha1
[20];
161 * If REF_KNOWS_PEELED, then this field holds the peeled value
162 * of this reference, or null if the reference is known not to
163 * be peelable. See the documentation for peel_ref() for an
164 * exact definition of "peelable".
166 unsigned char peeled
[20];
172 * Information used (along with the information in ref_entry) to
173 * describe a level in the hierarchy of references. This data
174 * structure only occurs embedded in a union in struct ref_entry, and
175 * only when (ref_entry.flag & REF_DIR) is set. In that case,
176 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
177 * in the directory have already been read:
179 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
180 * or packed references, already read.
182 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
183 * references that hasn't been read yet (nor has any of its
186 * Entries within a directory are stored within a growable array of
187 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
188 * sorted are sorted by their component name in strcmp() order and the
189 * remaining entries are unsorted.
191 * Loose references are read lazily, one directory at a time. When a
192 * directory of loose references is read, then all of the references
193 * in that directory are stored, and REF_INCOMPLETE stubs are created
194 * for any subdirectories, but the subdirectories themselves are not
195 * read. The reading is triggered by get_ref_dir().
201 * Entries with index 0 <= i < sorted are sorted by name. New
202 * entries are appended to the list unsorted, and are sorted
203 * only when required; thus we avoid the need to sort the list
204 * after the addition of every reference.
208 /* A pointer to the ref_cache that contains this ref_dir. */
209 struct ref_cache
*ref_cache
;
211 struct ref_entry
**entries
;
215 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
216 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
217 * public values; see refs.h.
221 * The field ref_entry->u.value.peeled of this value entry contains
222 * the correct peeled value for the reference, which might be
223 * null_sha1 if the reference is not a tag or if it is broken.
225 #define REF_KNOWS_PEELED 0x10
227 /* ref_entry represents a directory of references */
231 * Entry has not yet been read from disk (used only for REF_DIR
232 * entries representing loose references)
234 #define REF_INCOMPLETE 0x40
237 * A ref_entry represents either a reference or a "subdirectory" of
240 * Each directory in the reference namespace is represented by a
241 * ref_entry with (flags & REF_DIR) set and containing a subdir member
242 * that holds the entries in that directory that have been read so
243 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
244 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
245 * used for loose reference directories.
247 * References are represented by a ref_entry with (flags & REF_DIR)
248 * unset and a value member that describes the reference's value. The
249 * flag member is at the ref_entry level, but it is also needed to
250 * interpret the contents of the value field (in other words, a
251 * ref_value object is not very much use without the enclosing
254 * Reference names cannot end with slash and directories' names are
255 * always stored with a trailing slash (except for the top-level
256 * directory, which is always denoted by ""). This has two nice
257 * consequences: (1) when the entries in each subdir are sorted
258 * lexicographically by name (as they usually are), the references in
259 * a whole tree can be generated in lexicographic order by traversing
260 * the tree in left-to-right, depth-first order; (2) the names of
261 * references and subdirectories cannot conflict, and therefore the
262 * presence of an empty subdirectory does not block the creation of a
263 * similarly-named reference. (The fact that reference names with the
264 * same leading components can conflict *with each other* is a
265 * separate issue that is regulated by verify_refname_available().)
267 * Please note that the name field contains the fully-qualified
268 * reference (or subdirectory) name. Space could be saved by only
269 * storing the relative names. But that would require the full names
270 * to be generated on the fly when iterating in do_for_each_ref(), and
271 * would break callback functions, who have always been able to assume
272 * that the name strings that they are passed will not be freed during
276 unsigned char flag
; /* ISSYMREF? ISPACKED? */
278 struct ref_value value
; /* if not (flags&REF_DIR) */
279 struct ref_dir subdir
; /* if (flags&REF_DIR) */
282 * The full name of the reference (e.g., "refs/heads/master")
283 * or the full name of the directory with a trailing slash
284 * (e.g., "refs/heads/"):
286 char name
[FLEX_ARRAY
];
289 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
291 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
294 assert(entry
->flag
& REF_DIR
);
295 dir
= &entry
->u
.subdir
;
296 if (entry
->flag
& REF_INCOMPLETE
) {
297 read_loose_refs(entry
->name
, dir
);
298 entry
->flag
&= ~REF_INCOMPLETE
;
304 * Check if a refname is safe.
305 * For refs that start with "refs/" we consider it safe as long they do
306 * not try to resolve to outside of refs/.
308 * For all other refs we only consider them safe iff they only contain
309 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
312 static int refname_is_safe(const char *refname
)
314 if (starts_with(refname
, "refs/")) {
318 buf
= xmalloc(strlen(refname
) + 1);
320 * Does the refname try to escape refs/?
321 * For example: refs/foo/../bar is safe but refs/foo/../../bar
324 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
329 if (!isupper(*refname
) && *refname
!= '_')
336 static struct ref_entry
*create_ref_entry(const char *refname
,
337 const unsigned char *sha1
, int flag
,
341 struct ref_entry
*ref
;
344 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
345 die("Reference has invalid format: '%s'", refname
);
346 len
= strlen(refname
) + 1;
347 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
348 hashcpy(ref
->u
.value
.sha1
, sha1
);
349 hashclr(ref
->u
.value
.peeled
);
350 memcpy(ref
->name
, refname
, len
);
355 static void clear_ref_dir(struct ref_dir
*dir
);
357 static void free_ref_entry(struct ref_entry
*entry
)
359 if (entry
->flag
& REF_DIR
) {
361 * Do not use get_ref_dir() here, as that might
362 * trigger the reading of loose refs.
364 clear_ref_dir(&entry
->u
.subdir
);
370 * Add a ref_entry to the end of dir (unsorted). Entry is always
371 * stored directly in dir; no recursion into subdirectories is
374 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
376 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
377 dir
->entries
[dir
->nr
++] = entry
;
378 /* optimize for the case that entries are added in order */
380 (dir
->nr
== dir
->sorted
+ 1 &&
381 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
382 dir
->entries
[dir
->nr
- 1]->name
) < 0))
383 dir
->sorted
= dir
->nr
;
387 * Clear and free all entries in dir, recursively.
389 static void clear_ref_dir(struct ref_dir
*dir
)
392 for (i
= 0; i
< dir
->nr
; i
++)
393 free_ref_entry(dir
->entries
[i
]);
395 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
400 * Create a struct ref_entry object for the specified dirname.
401 * dirname is the name of the directory with a trailing slash (e.g.,
402 * "refs/heads/") or "" for the top-level directory.
404 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
405 const char *dirname
, size_t len
,
408 struct ref_entry
*direntry
;
409 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
410 memcpy(direntry
->name
, dirname
, len
);
411 direntry
->name
[len
] = '\0';
412 direntry
->u
.subdir
.ref_cache
= ref_cache
;
413 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
417 static int ref_entry_cmp(const void *a
, const void *b
)
419 struct ref_entry
*one
= *(struct ref_entry
**)a
;
420 struct ref_entry
*two
= *(struct ref_entry
**)b
;
421 return strcmp(one
->name
, two
->name
);
424 static void sort_ref_dir(struct ref_dir
*dir
);
426 struct string_slice
{
431 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
433 const struct string_slice
*key
= key_
;
434 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
435 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
438 return '\0' - (unsigned char)ent
->name
[key
->len
];
442 * Return the index of the entry with the given refname from the
443 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
444 * no such entry is found. dir must already be complete.
446 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
448 struct ref_entry
**r
;
449 struct string_slice key
;
451 if (refname
== NULL
|| !dir
->nr
)
457 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
458 ref_entry_cmp_sslice
);
463 return r
- dir
->entries
;
467 * Search for a directory entry directly within dir (without
468 * recursing). Sort dir if necessary. subdirname must be a directory
469 * name (i.e., end in '/'). If mkdir is set, then create the
470 * directory if it is missing; otherwise, return NULL if the desired
471 * directory cannot be found. dir must already be complete.
473 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
474 const char *subdirname
, size_t len
,
477 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
478 struct ref_entry
*entry
;
479 if (entry_index
== -1) {
483 * Since dir is complete, the absence of a subdir
484 * means that the subdir really doesn't exist;
485 * therefore, create an empty record for it but mark
486 * the record complete.
488 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
489 add_entry_to_dir(dir
, entry
);
491 entry
= dir
->entries
[entry_index
];
493 return get_ref_dir(entry
);
497 * If refname is a reference name, find the ref_dir within the dir
498 * tree that should hold refname. If refname is a directory name
499 * (i.e., ends in '/'), then return that ref_dir itself. dir must
500 * represent the top-level directory and must already be complete.
501 * Sort ref_dirs and recurse into subdirectories as necessary. If
502 * mkdir is set, then create any missing directories; otherwise,
503 * return NULL if the desired directory cannot be found.
505 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
506 const char *refname
, int mkdir
)
509 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
510 size_t dirnamelen
= slash
- refname
+ 1;
511 struct ref_dir
*subdir
;
512 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
524 * Find the value entry with the given name in dir, sorting ref_dirs
525 * and recursing into subdirectories as necessary. If the name is not
526 * found or it corresponds to a directory entry, return NULL.
528 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
531 struct ref_entry
*entry
;
532 dir
= find_containing_dir(dir
, refname
, 0);
535 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
536 if (entry_index
== -1)
538 entry
= dir
->entries
[entry_index
];
539 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
543 * Remove the entry with the given name from dir, recursing into
544 * subdirectories as necessary. If refname is the name of a directory
545 * (i.e., ends with '/'), then remove the directory and its contents.
546 * If the removal was successful, return the number of entries
547 * remaining in the directory entry that contained the deleted entry.
548 * If the name was not found, return -1. Please note that this
549 * function only deletes the entry from the cache; it does not delete
550 * it from the filesystem or ensure that other cache entries (which
551 * might be symbolic references to the removed entry) are updated.
552 * Nor does it remove any containing dir entries that might be made
553 * empty by the removal. dir must represent the top-level directory
554 * and must already be complete.
556 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
558 int refname_len
= strlen(refname
);
560 struct ref_entry
*entry
;
561 int is_dir
= refname
[refname_len
- 1] == '/';
564 * refname represents a reference directory. Remove
565 * the trailing slash; otherwise we will get the
566 * directory *representing* refname rather than the
567 * one *containing* it.
569 char *dirname
= xmemdupz(refname
, refname_len
- 1);
570 dir
= find_containing_dir(dir
, dirname
, 0);
573 dir
= find_containing_dir(dir
, refname
, 0);
577 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
578 if (entry_index
== -1)
580 entry
= dir
->entries
[entry_index
];
582 memmove(&dir
->entries
[entry_index
],
583 &dir
->entries
[entry_index
+ 1],
584 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
587 if (dir
->sorted
> entry_index
)
589 free_ref_entry(entry
);
594 * Add a ref_entry to the ref_dir (unsorted), recursing into
595 * subdirectories as necessary. dir must represent the top-level
596 * directory. Return 0 on success.
598 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
600 dir
= find_containing_dir(dir
, ref
->name
, 1);
603 add_entry_to_dir(dir
, ref
);
608 * Emit a warning and return true iff ref1 and ref2 have the same name
609 * and the same sha1. Die if they have the same name but different
612 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
614 if (strcmp(ref1
->name
, ref2
->name
))
617 /* Duplicate name; make sure that they don't conflict: */
619 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
620 /* This is impossible by construction */
621 die("Reference directory conflict: %s", ref1
->name
);
623 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
624 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
626 warning("Duplicated ref: %s", ref1
->name
);
631 * Sort the entries in dir non-recursively (if they are not already
632 * sorted) and remove any duplicate entries.
634 static void sort_ref_dir(struct ref_dir
*dir
)
637 struct ref_entry
*last
= NULL
;
640 * This check also prevents passing a zero-length array to qsort(),
641 * which is a problem on some platforms.
643 if (dir
->sorted
== dir
->nr
)
646 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
648 /* Remove any duplicates: */
649 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
650 struct ref_entry
*entry
= dir
->entries
[j
];
651 if (last
&& is_dup_ref(last
, entry
))
652 free_ref_entry(entry
);
654 last
= dir
->entries
[i
++] = entry
;
656 dir
->sorted
= dir
->nr
= i
;
659 /* Include broken references in a do_for_each_ref*() iteration: */
660 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
663 * Return true iff the reference described by entry can be resolved to
664 * an object in the database. Emit a warning if the referred-to
665 * object does not exist.
667 static int ref_resolves_to_object(struct ref_entry
*entry
)
669 if (entry
->flag
& REF_ISBROKEN
)
671 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
672 error("%s does not point to a valid object!", entry
->name
);
679 * current_ref is a performance hack: when iterating over references
680 * using the for_each_ref*() functions, current_ref is set to the
681 * current reference's entry before calling the callback function. If
682 * the callback function calls peel_ref(), then peel_ref() first
683 * checks whether the reference to be peeled is the current reference
684 * (it usually is) and if so, returns that reference's peeled version
685 * if it is available. This avoids a refname lookup in a common case.
687 static struct ref_entry
*current_ref
;
689 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
691 struct ref_entry_cb
{
700 * Handle one reference in a do_for_each_ref*()-style iteration,
701 * calling an each_ref_fn for each entry.
703 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
705 struct ref_entry_cb
*data
= cb_data
;
706 struct ref_entry
*old_current_ref
;
709 if (!starts_with(entry
->name
, data
->base
))
712 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
713 !ref_resolves_to_object(entry
))
716 /* Store the old value, in case this is a recursive call: */
717 old_current_ref
= current_ref
;
719 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
720 entry
->flag
, data
->cb_data
);
721 current_ref
= old_current_ref
;
726 * Call fn for each reference in dir that has index in the range
727 * offset <= index < dir->nr. Recurse into subdirectories that are in
728 * that index range, sorting them before iterating. This function
729 * does not sort dir itself; it should be sorted beforehand. fn is
730 * called for all references, including broken ones.
732 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
733 each_ref_entry_fn fn
, void *cb_data
)
736 assert(dir
->sorted
== dir
->nr
);
737 for (i
= offset
; i
< dir
->nr
; i
++) {
738 struct ref_entry
*entry
= dir
->entries
[i
];
740 if (entry
->flag
& REF_DIR
) {
741 struct ref_dir
*subdir
= get_ref_dir(entry
);
742 sort_ref_dir(subdir
);
743 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
745 retval
= fn(entry
, cb_data
);
754 * Call fn for each reference in the union of dir1 and dir2, in order
755 * by refname. Recurse into subdirectories. If a value entry appears
756 * in both dir1 and dir2, then only process the version that is in
757 * dir2. The input dirs must already be sorted, but subdirs will be
758 * sorted as needed. fn is called for all references, including
761 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
762 struct ref_dir
*dir2
,
763 each_ref_entry_fn fn
, void *cb_data
)
768 assert(dir1
->sorted
== dir1
->nr
);
769 assert(dir2
->sorted
== dir2
->nr
);
771 struct ref_entry
*e1
, *e2
;
773 if (i1
== dir1
->nr
) {
774 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
776 if (i2
== dir2
->nr
) {
777 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
779 e1
= dir1
->entries
[i1
];
780 e2
= dir2
->entries
[i2
];
781 cmp
= strcmp(e1
->name
, e2
->name
);
783 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
784 /* Both are directories; descend them in parallel. */
785 struct ref_dir
*subdir1
= get_ref_dir(e1
);
786 struct ref_dir
*subdir2
= get_ref_dir(e2
);
787 sort_ref_dir(subdir1
);
788 sort_ref_dir(subdir2
);
789 retval
= do_for_each_entry_in_dirs(
790 subdir1
, subdir2
, fn
, cb_data
);
793 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
794 /* Both are references; ignore the one from dir1. */
795 retval
= fn(e2
, cb_data
);
799 die("conflict between reference and directory: %s",
811 if (e
->flag
& REF_DIR
) {
812 struct ref_dir
*subdir
= get_ref_dir(e
);
813 sort_ref_dir(subdir
);
814 retval
= do_for_each_entry_in_dir(
815 subdir
, 0, fn
, cb_data
);
817 retval
= fn(e
, cb_data
);
826 * Load all of the refs from the dir into our in-memory cache. The hard work
827 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
828 * through all of the sub-directories. We do not even need to care about
829 * sorting, as traversal order does not matter to us.
831 static void prime_ref_dir(struct ref_dir
*dir
)
834 for (i
= 0; i
< dir
->nr
; i
++) {
835 struct ref_entry
*entry
= dir
->entries
[i
];
836 if (entry
->flag
& REF_DIR
)
837 prime_ref_dir(get_ref_dir(entry
));
841 struct nonmatching_ref_data
{
842 const struct string_list
*skip
;
843 const char *conflicting_refname
;
846 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
848 struct nonmatching_ref_data
*data
= vdata
;
850 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
853 data
->conflicting_refname
= entry
->name
;
858 * Return 0 if a reference named refname could be created without
859 * conflicting with the name of an existing reference in dir.
860 * Otherwise, return a negative value and write an explanation to err.
861 * If extras is non-NULL, it is a list of additional refnames with
862 * which refname is not allowed to conflict. If skip is non-NULL,
863 * ignore potential conflicts with refs in skip (e.g., because they
864 * are scheduled for deletion in the same operation). Behavior is
865 * undefined if the same name is listed in both extras and skip.
867 * Two reference names conflict if one of them exactly matches the
868 * leading components of the other; e.g., "refs/foo/bar" conflicts
869 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
870 * "refs/foo/bar" or "refs/foo/barbados".
872 * extras and skip must be sorted.
874 static int verify_refname_available(const char *refname
,
875 const struct string_list
*extras
,
876 const struct string_list
*skip
,
882 struct strbuf dirname
= STRBUF_INIT
;
886 * For the sake of comments in this function, suppose that
887 * refname is "refs/foo/bar".
892 strbuf_grow(&dirname
, strlen(refname
) + 1);
893 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
894 /* Expand dirname to the new prefix, not including the trailing slash: */
895 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
898 * We are still at a leading dir of the refname (e.g.,
899 * "refs/foo"; if there is a reference with that name,
900 * it is a conflict, *unless* it is in skip.
903 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
905 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
907 * We found a reference whose name is
908 * a proper prefix of refname; e.g.,
909 * "refs/foo", and is not in skip.
911 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
912 dirname
.buf
, refname
);
917 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
918 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
919 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
920 refname
, dirname
.buf
);
925 * Otherwise, we can try to continue our search with
926 * the next component. So try to look up the
927 * directory, e.g., "refs/foo/". If we come up empty,
928 * we know there is nothing under this whole prefix,
929 * but even in that case we still have to continue the
930 * search for conflicts with extras.
932 strbuf_addch(&dirname
, '/');
934 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
937 * There was no directory "refs/foo/",
938 * so there is nothing under this
939 * whole prefix. So there is no need
940 * to continue looking for conflicting
941 * references. But we need to continue
942 * looking for conflicting extras.
946 dir
= get_ref_dir(dir
->entries
[pos
]);
952 * We are at the leaf of our refname (e.g., "refs/foo/bar").
953 * There is no point in searching for a reference with that
954 * name, because a refname isn't considered to conflict with
955 * itself. But we still need to check for references whose
956 * names are in the "refs/foo/bar/" namespace, because they
959 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
960 strbuf_addch(&dirname
, '/');
963 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
967 * We found a directory named "$refname/"
968 * (e.g., "refs/foo/bar/"). It is a problem
969 * iff it contains any ref that is not in
972 struct nonmatching_ref_data data
;
975 data
.conflicting_refname
= NULL
;
976 dir
= get_ref_dir(dir
->entries
[pos
]);
978 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
979 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
980 data
.conflicting_refname
, refname
);
988 * Check for entries in extras that start with
989 * "$refname/". We do that by looking for the place
990 * where "$refname/" would be inserted in extras. If
991 * there is an entry at that position that starts with
992 * "$refname/" and is not in skip, then we have a
995 for (pos
= string_list_find_insert_index(extras
, dirname
.buf
, 0);
996 pos
< extras
->nr
; pos
++) {
997 const char *extra_refname
= extras
->items
[pos
].string
;
999 if (!starts_with(extra_refname
, dirname
.buf
))
1002 if (!skip
|| !string_list_has_string(skip
, extra_refname
)) {
1003 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
1004 refname
, extra_refname
);
1010 /* No conflicts were found */
1014 strbuf_release(&dirname
);
1018 struct packed_ref_cache
{
1019 struct ref_entry
*root
;
1022 * Count of references to the data structure in this instance,
1023 * including the pointer from ref_cache::packed if any. The
1024 * data will not be freed as long as the reference count is
1027 unsigned int referrers
;
1030 * Iff the packed-refs file associated with this instance is
1031 * currently locked for writing, this points at the associated
1032 * lock (which is owned by somebody else). The referrer count
1033 * is also incremented when the file is locked and decremented
1034 * when it is unlocked.
1036 struct lock_file
*lock
;
1038 /* The metadata from when this packed-refs cache was read */
1039 struct stat_validity validity
;
1043 * Future: need to be in "struct repository"
1044 * when doing a full libification.
1046 static struct ref_cache
{
1047 struct ref_cache
*next
;
1048 struct ref_entry
*loose
;
1049 struct packed_ref_cache
*packed
;
1051 * The submodule name, or "" for the main repo. We allocate
1052 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1053 * is initialized correctly.
1056 } ref_cache
, *submodule_ref_caches
;
1058 /* Lock used for the main packed-refs file: */
1059 static struct lock_file packlock
;
1062 * Increment the reference count of *packed_refs.
1064 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1066 packed_refs
->referrers
++;
1070 * Decrease the reference count of *packed_refs. If it goes to zero,
1071 * free *packed_refs and return true; otherwise return false.
1073 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1075 if (!--packed_refs
->referrers
) {
1076 free_ref_entry(packed_refs
->root
);
1077 stat_validity_clear(&packed_refs
->validity
);
1085 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1088 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1090 if (packed_refs
->lock
)
1091 die("internal error: packed-ref cache cleared while locked");
1092 refs
->packed
= NULL
;
1093 release_packed_ref_cache(packed_refs
);
1097 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1100 free_ref_entry(refs
->loose
);
1105 static struct ref_cache
*create_ref_cache(const char *submodule
)
1108 struct ref_cache
*refs
;
1111 len
= strlen(submodule
) + 1;
1112 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1113 memcpy(refs
->name
, submodule
, len
);
1118 * Return a pointer to a ref_cache for the specified submodule. For
1119 * the main repository, use submodule==NULL. The returned structure
1120 * will be allocated and initialized but not necessarily populated; it
1121 * should not be freed.
1123 static struct ref_cache
*get_ref_cache(const char *submodule
)
1125 struct ref_cache
*refs
;
1127 if (!submodule
|| !*submodule
)
1130 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1131 if (!strcmp(submodule
, refs
->name
))
1134 refs
= create_ref_cache(submodule
);
1135 refs
->next
= submodule_ref_caches
;
1136 submodule_ref_caches
= refs
;
1140 /* The length of a peeled reference line in packed-refs, including EOL: */
1141 #define PEELED_LINE_LENGTH 42
1144 * The packed-refs header line that we write out. Perhaps other
1145 * traits will be added later. The trailing space is required.
1147 static const char PACKED_REFS_HEADER
[] =
1148 "# pack-refs with: peeled fully-peeled \n";
1151 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1152 * Return a pointer to the refname within the line (null-terminated),
1153 * or NULL if there was a problem.
1155 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1160 * 42: the answer to everything.
1162 * In this case, it happens to be the answer to
1163 * 40 (length of sha1 hex representation)
1164 * +1 (space in between hex and name)
1165 * +1 (newline at the end of the line)
1167 if (line
->len
<= 42)
1170 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1172 if (!isspace(line
->buf
[40]))
1175 ref
= line
->buf
+ 41;
1179 if (line
->buf
[line
->len
- 1] != '\n')
1181 line
->buf
[--line
->len
] = 0;
1187 * Read f, which is a packed-refs file, into dir.
1189 * A comment line of the form "# pack-refs with: " may contain zero or
1190 * more traits. We interpret the traits as follows:
1194 * Probably no references are peeled. But if the file contains a
1195 * peeled value for a reference, we will use it.
1199 * References under "refs/tags/", if they *can* be peeled, *are*
1200 * peeled in this file. References outside of "refs/tags/" are
1201 * probably not peeled even if they could have been, but if we find
1202 * a peeled value for such a reference we will use it.
1206 * All references in the file that can be peeled are peeled.
1207 * Inversely (and this is more important), any references in the
1208 * file for which no peeled value is recorded is not peelable. This
1209 * trait should typically be written alongside "peeled" for
1210 * compatibility with older clients, but we do not require it
1211 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1213 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1215 struct ref_entry
*last
= NULL
;
1216 struct strbuf line
= STRBUF_INIT
;
1217 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1219 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1220 unsigned char sha1
[20];
1221 const char *refname
;
1224 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1225 if (strstr(traits
, " fully-peeled "))
1226 peeled
= PEELED_FULLY
;
1227 else if (strstr(traits
, " peeled "))
1228 peeled
= PEELED_TAGS
;
1229 /* perhaps other traits later as well */
1233 refname
= parse_ref_line(&line
, sha1
);
1235 int flag
= REF_ISPACKED
;
1237 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1238 if (!refname_is_safe(refname
))
1239 die("packed refname is dangerous: %s", refname
);
1241 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1243 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1244 if (peeled
== PEELED_FULLY
||
1245 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1246 last
->flag
|= REF_KNOWS_PEELED
;
1251 line
.buf
[0] == '^' &&
1252 line
.len
== PEELED_LINE_LENGTH
&&
1253 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1254 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1255 hashcpy(last
->u
.value
.peeled
, sha1
);
1257 * Regardless of what the file header said,
1258 * we definitely know the value of *this*
1261 last
->flag
|= REF_KNOWS_PEELED
;
1265 strbuf_release(&line
);
1269 * Get the packed_ref_cache for the specified ref_cache, creating it
1272 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1274 const char *packed_refs_file
;
1277 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1279 packed_refs_file
= git_path("packed-refs");
1282 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1283 clear_packed_ref_cache(refs
);
1285 if (!refs
->packed
) {
1288 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1289 acquire_packed_ref_cache(refs
->packed
);
1290 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1291 f
= fopen(packed_refs_file
, "r");
1293 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1294 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1298 return refs
->packed
;
1301 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1303 return get_ref_dir(packed_ref_cache
->root
);
1306 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1308 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1311 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1313 struct packed_ref_cache
*packed_ref_cache
=
1314 get_packed_ref_cache(&ref_cache
);
1316 if (!packed_ref_cache
->lock
)
1317 die("internal error: packed refs not locked");
1318 add_ref(get_packed_ref_dir(packed_ref_cache
),
1319 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1323 * Read the loose references from the namespace dirname into dir
1324 * (without recursing). dirname must end with '/'. dir must be the
1325 * directory entry corresponding to dirname.
1327 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1329 struct ref_cache
*refs
= dir
->ref_cache
;
1333 int dirnamelen
= strlen(dirname
);
1334 struct strbuf refname
;
1337 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1339 path
= git_path("%s", dirname
);
1345 strbuf_init(&refname
, dirnamelen
+ 257);
1346 strbuf_add(&refname
, dirname
, dirnamelen
);
1348 while ((de
= readdir(d
)) != NULL
) {
1349 unsigned char sha1
[20];
1354 if (de
->d_name
[0] == '.')
1356 if (ends_with(de
->d_name
, ".lock"))
1358 strbuf_addstr(&refname
, de
->d_name
);
1359 refdir
= *refs
->name
1360 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1361 : git_path("%s", refname
.buf
);
1362 if (stat(refdir
, &st
) < 0) {
1363 ; /* silently ignore */
1364 } else if (S_ISDIR(st
.st_mode
)) {
1365 strbuf_addch(&refname
, '/');
1366 add_entry_to_dir(dir
,
1367 create_dir_entry(refs
, refname
.buf
,
1373 if (resolve_gitlink_ref(refs
->name
, refname
.buf
, sha1
) < 0) {
1375 flag
|= REF_ISBROKEN
;
1377 } else if (read_ref_full(refname
.buf
,
1378 RESOLVE_REF_READING
,
1381 flag
|= REF_ISBROKEN
;
1383 if (check_refname_format(refname
.buf
,
1384 REFNAME_ALLOW_ONELEVEL
)) {
1385 if (!refname_is_safe(refname
.buf
))
1386 die("loose refname is dangerous: %s", refname
.buf
);
1388 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1390 add_entry_to_dir(dir
,
1391 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1393 strbuf_setlen(&refname
, dirnamelen
);
1395 strbuf_release(&refname
);
1399 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1403 * Mark the top-level directory complete because we
1404 * are about to read the only subdirectory that can
1407 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1409 * Create an incomplete entry for "refs/":
1411 add_entry_to_dir(get_ref_dir(refs
->loose
),
1412 create_dir_entry(refs
, "refs/", 5, 1));
1414 return get_ref_dir(refs
->loose
);
1417 /* We allow "recursive" symbolic refs. Only within reason, though */
1419 #define MAXREFLEN (1024)
1422 * Called by resolve_gitlink_ref_recursive() after it failed to read
1423 * from the loose refs in ref_cache refs. Find <refname> in the
1424 * packed-refs file for the submodule.
1426 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1427 const char *refname
, unsigned char *sha1
)
1429 struct ref_entry
*ref
;
1430 struct ref_dir
*dir
= get_packed_refs(refs
);
1432 ref
= find_ref(dir
, refname
);
1436 hashcpy(sha1
, ref
->u
.value
.sha1
);
1440 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1441 const char *refname
, unsigned char *sha1
,
1445 char buffer
[128], *p
;
1448 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1451 ? git_path_submodule(refs
->name
, "%s", refname
)
1452 : git_path("%s", refname
);
1453 fd
= open(path
, O_RDONLY
);
1455 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1457 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1461 while (len
&& isspace(buffer
[len
-1]))
1465 /* Was it a detached head or an old-fashioned symlink? */
1466 if (!get_sha1_hex(buffer
, sha1
))
1470 if (strncmp(buffer
, "ref:", 4))
1476 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1479 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1481 int len
= strlen(path
), retval
;
1483 struct ref_cache
*refs
;
1485 while (len
&& path
[len
-1] == '/')
1489 submodule
= xstrndup(path
, len
);
1490 refs
= get_ref_cache(submodule
);
1493 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1498 * Return the ref_entry for the given refname from the packed
1499 * references. If it does not exist, return NULL.
1501 static struct ref_entry
*get_packed_ref(const char *refname
)
1503 return find_ref(get_packed_refs(&ref_cache
), refname
);
1507 * A loose ref file doesn't exist; check for a packed ref. The
1508 * options are forwarded from resolve_safe_unsafe().
1510 static int resolve_missing_loose_ref(const char *refname
,
1512 unsigned char *sha1
,
1515 struct ref_entry
*entry
;
1518 * The loose reference file does not exist; check for a packed
1521 entry
= get_packed_ref(refname
);
1523 hashcpy(sha1
, entry
->u
.value
.sha1
);
1525 *flags
|= REF_ISPACKED
;
1528 /* The reference is not a packed reference, either. */
1529 if (resolve_flags
& RESOLVE_REF_READING
) {
1538 /* This function needs to return a meaningful errno on failure */
1539 static const char *resolve_ref_unsafe_1(const char *refname
,
1541 unsigned char *sha1
,
1543 struct strbuf
*sb_path
)
1545 int depth
= MAXDEPTH
;
1548 static char refname_buffer
[256];
1554 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1556 *flags
|= REF_BAD_NAME
;
1558 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1559 !refname_is_safe(refname
)) {
1564 * dwim_ref() uses REF_ISBROKEN to distinguish between
1565 * missing refs and refs that were present but invalid,
1566 * to complain about the latter to stderr.
1568 * We don't know whether the ref exists, so don't set
1584 strbuf_reset(sb_path
);
1585 strbuf_git_path(sb_path
, "%s", refname
);
1586 path
= sb_path
->buf
;
1589 * We might have to loop back here to avoid a race
1590 * condition: first we lstat() the file, then we try
1591 * to read it as a link or as a file. But if somebody
1592 * changes the type of the file (file <-> directory
1593 * <-> symlink) between the lstat() and reading, then
1594 * we don't want to report that as an error but rather
1595 * try again starting with the lstat().
1598 if (lstat(path
, &st
) < 0) {
1599 if (errno
!= ENOENT
)
1601 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1607 *flags
|= REF_ISBROKEN
;
1612 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1613 if (S_ISLNK(st
.st_mode
)) {
1614 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1616 if (errno
== ENOENT
|| errno
== EINVAL
)
1617 /* inconsistent with lstat; retry */
1623 if (starts_with(buffer
, "refs/") &&
1624 !check_refname_format(buffer
, 0)) {
1625 strcpy(refname_buffer
, buffer
);
1626 refname
= refname_buffer
;
1628 *flags
|= REF_ISSYMREF
;
1629 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1637 /* Is it a directory? */
1638 if (S_ISDIR(st
.st_mode
)) {
1644 * Anything else, just open it and try to use it as
1647 fd
= open(path
, O_RDONLY
);
1649 if (errno
== ENOENT
)
1650 /* inconsistent with lstat; retry */
1655 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1657 int save_errno
= errno
;
1663 while (len
&& isspace(buffer
[len
-1]))
1668 * Is it a symbolic ref?
1670 if (!starts_with(buffer
, "ref:")) {
1672 * Please note that FETCH_HEAD has a second
1673 * line containing other data.
1675 if (get_sha1_hex(buffer
, sha1
) ||
1676 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1678 *flags
|= REF_ISBROKEN
;
1685 *flags
|= REF_ISBROKEN
;
1690 *flags
|= REF_ISSYMREF
;
1692 while (isspace(*buf
))
1694 refname
= strcpy(refname_buffer
, buf
);
1695 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1699 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1701 *flags
|= REF_ISBROKEN
;
1703 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1704 !refname_is_safe(buf
)) {
1713 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1714 unsigned char *sha1
, int *flags
)
1716 struct strbuf sb_path
= STRBUF_INIT
;
1717 const char *ret
= resolve_ref_unsafe_1(refname
, resolve_flags
,
1718 sha1
, flags
, &sb_path
);
1719 strbuf_release(&sb_path
);
1723 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1725 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1728 /* The argument to filter_refs */
1730 const char *pattern
;
1735 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1737 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1742 int read_ref(const char *refname
, unsigned char *sha1
)
1744 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1747 int ref_exists(const char *refname
)
1749 unsigned char sha1
[20];
1750 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1753 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1756 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1757 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1759 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1763 /* object was peeled successfully: */
1767 * object cannot be peeled because the named object (or an
1768 * object referred to by a tag in the peel chain), does not
1773 /* object cannot be peeled because it is not a tag: */
1776 /* ref_entry contains no peeled value because it is a symref: */
1777 PEEL_IS_SYMREF
= -3,
1780 * ref_entry cannot be peeled because it is broken (i.e., the
1781 * symbolic reference cannot even be resolved to an object
1788 * Peel the named object; i.e., if the object is a tag, resolve the
1789 * tag recursively until a non-tag is found. If successful, store the
1790 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1791 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1792 * and leave sha1 unchanged.
1794 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1796 struct object
*o
= lookup_unknown_object(name
);
1798 if (o
->type
== OBJ_NONE
) {
1799 int type
= sha1_object_info(name
, NULL
);
1800 if (type
< 0 || !object_as_type(o
, type
, 0))
1801 return PEEL_INVALID
;
1804 if (o
->type
!= OBJ_TAG
)
1805 return PEEL_NON_TAG
;
1807 o
= deref_tag_noverify(o
);
1809 return PEEL_INVALID
;
1811 hashcpy(sha1
, o
->sha1
);
1816 * Peel the entry (if possible) and return its new peel_status. If
1817 * repeel is true, re-peel the entry even if there is an old peeled
1818 * value that is already stored in it.
1820 * It is OK to call this function with a packed reference entry that
1821 * might be stale and might even refer to an object that has since
1822 * been garbage-collected. In such a case, if the entry has
1823 * REF_KNOWS_PEELED then leave the status unchanged and return
1824 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1826 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1828 enum peel_status status
;
1830 if (entry
->flag
& REF_KNOWS_PEELED
) {
1832 entry
->flag
&= ~REF_KNOWS_PEELED
;
1833 hashclr(entry
->u
.value
.peeled
);
1835 return is_null_sha1(entry
->u
.value
.peeled
) ?
1836 PEEL_NON_TAG
: PEEL_PEELED
;
1839 if (entry
->flag
& REF_ISBROKEN
)
1841 if (entry
->flag
& REF_ISSYMREF
)
1842 return PEEL_IS_SYMREF
;
1844 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1845 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1846 entry
->flag
|= REF_KNOWS_PEELED
;
1850 int peel_ref(const char *refname
, unsigned char *sha1
)
1853 unsigned char base
[20];
1855 if (current_ref
&& (current_ref
->name
== refname
1856 || !strcmp(current_ref
->name
, refname
))) {
1857 if (peel_entry(current_ref
, 0))
1859 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1863 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1867 * If the reference is packed, read its ref_entry from the
1868 * cache in the hope that we already know its peeled value.
1869 * We only try this optimization on packed references because
1870 * (a) forcing the filling of the loose reference cache could
1871 * be expensive and (b) loose references anyway usually do not
1872 * have REF_KNOWS_PEELED.
1874 if (flag
& REF_ISPACKED
) {
1875 struct ref_entry
*r
= get_packed_ref(refname
);
1877 if (peel_entry(r
, 0))
1879 hashcpy(sha1
, r
->u
.value
.peeled
);
1884 return peel_object(base
, sha1
);
1887 struct warn_if_dangling_data
{
1889 const char *refname
;
1890 const struct string_list
*refnames
;
1891 const char *msg_fmt
;
1894 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1895 int flags
, void *cb_data
)
1897 struct warn_if_dangling_data
*d
= cb_data
;
1898 const char *resolves_to
;
1899 unsigned char junk
[20];
1901 if (!(flags
& REF_ISSYMREF
))
1904 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1907 ? strcmp(resolves_to
, d
->refname
)
1908 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1912 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1917 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1919 struct warn_if_dangling_data data
;
1922 data
.refname
= refname
;
1923 data
.refnames
= NULL
;
1924 data
.msg_fmt
= msg_fmt
;
1925 for_each_rawref(warn_if_dangling_symref
, &data
);
1928 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1930 struct warn_if_dangling_data data
;
1933 data
.refname
= NULL
;
1934 data
.refnames
= refnames
;
1935 data
.msg_fmt
= msg_fmt
;
1936 for_each_rawref(warn_if_dangling_symref
, &data
);
1940 * Call fn for each reference in the specified ref_cache, omitting
1941 * references not in the containing_dir of base. fn is called for all
1942 * references, including broken ones. If fn ever returns a non-zero
1943 * value, stop the iteration and return that value; otherwise, return
1946 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1947 each_ref_entry_fn fn
, void *cb_data
)
1949 struct packed_ref_cache
*packed_ref_cache
;
1950 struct ref_dir
*loose_dir
;
1951 struct ref_dir
*packed_dir
;
1955 * We must make sure that all loose refs are read before accessing the
1956 * packed-refs file; this avoids a race condition in which loose refs
1957 * are migrated to the packed-refs file by a simultaneous process, but
1958 * our in-memory view is from before the migration. get_packed_ref_cache()
1959 * takes care of making sure our view is up to date with what is on
1962 loose_dir
= get_loose_refs(refs
);
1963 if (base
&& *base
) {
1964 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1967 prime_ref_dir(loose_dir
);
1969 packed_ref_cache
= get_packed_ref_cache(refs
);
1970 acquire_packed_ref_cache(packed_ref_cache
);
1971 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1972 if (base
&& *base
) {
1973 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1976 if (packed_dir
&& loose_dir
) {
1977 sort_ref_dir(packed_dir
);
1978 sort_ref_dir(loose_dir
);
1979 retval
= do_for_each_entry_in_dirs(
1980 packed_dir
, loose_dir
, fn
, cb_data
);
1981 } else if (packed_dir
) {
1982 sort_ref_dir(packed_dir
);
1983 retval
= do_for_each_entry_in_dir(
1984 packed_dir
, 0, fn
, cb_data
);
1985 } else if (loose_dir
) {
1986 sort_ref_dir(loose_dir
);
1987 retval
= do_for_each_entry_in_dir(
1988 loose_dir
, 0, fn
, cb_data
);
1991 release_packed_ref_cache(packed_ref_cache
);
1996 * Call fn for each reference in the specified ref_cache for which the
1997 * refname begins with base. If trim is non-zero, then trim that many
1998 * characters off the beginning of each refname before passing the
1999 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2000 * broken references in the iteration. If fn ever returns a non-zero
2001 * value, stop the iteration and return that value; otherwise, return
2004 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
2005 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
2007 struct ref_entry_cb data
;
2012 data
.cb_data
= cb_data
;
2014 if (ref_paranoia
< 0)
2015 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2017 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2019 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
2022 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2024 unsigned char sha1
[20];
2028 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
2029 return fn("HEAD", sha1
, 0, cb_data
);
2034 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
2035 return fn("HEAD", sha1
, flag
, cb_data
);
2040 int head_ref(each_ref_fn fn
, void *cb_data
)
2042 return do_head_ref(NULL
, fn
, cb_data
);
2045 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2047 return do_head_ref(submodule
, fn
, cb_data
);
2050 int for_each_ref(each_ref_fn fn
, void *cb_data
)
2052 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
2055 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2057 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2060 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2062 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2065 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2066 each_ref_fn fn
, void *cb_data
)
2068 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2071 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2073 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2076 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2078 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2081 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2083 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2086 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2088 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2091 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2093 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2096 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2098 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2101 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2103 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2106 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2108 struct strbuf buf
= STRBUF_INIT
;
2110 unsigned char sha1
[20];
2113 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2114 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2115 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2116 strbuf_release(&buf
);
2121 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2123 struct strbuf buf
= STRBUF_INIT
;
2125 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2126 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2127 strbuf_release(&buf
);
2131 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2132 const char *prefix
, void *cb_data
)
2134 struct strbuf real_pattern
= STRBUF_INIT
;
2135 struct ref_filter filter
;
2138 if (!prefix
&& !starts_with(pattern
, "refs/"))
2139 strbuf_addstr(&real_pattern
, "refs/");
2141 strbuf_addstr(&real_pattern
, prefix
);
2142 strbuf_addstr(&real_pattern
, pattern
);
2144 if (!has_glob_specials(pattern
)) {
2145 /* Append implied '/' '*' if not present. */
2146 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2147 strbuf_addch(&real_pattern
, '/');
2148 /* No need to check for '*', there is none. */
2149 strbuf_addch(&real_pattern
, '*');
2152 filter
.pattern
= real_pattern
.buf
;
2154 filter
.cb_data
= cb_data
;
2155 ret
= for_each_ref(filter_refs
, &filter
);
2157 strbuf_release(&real_pattern
);
2161 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2163 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2166 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2168 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2169 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2172 const char *prettify_refname(const char *name
)
2175 starts_with(name
, "refs/heads/") ? 11 :
2176 starts_with(name
, "refs/tags/") ? 10 :
2177 starts_with(name
, "refs/remotes/") ? 13 :
2181 static const char *ref_rev_parse_rules
[] = {
2186 "refs/remotes/%.*s",
2187 "refs/remotes/%.*s/HEAD",
2191 int refname_match(const char *abbrev_name
, const char *full_name
)
2194 const int abbrev_name_len
= strlen(abbrev_name
);
2196 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2197 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2205 static void unlock_ref(struct ref_lock
*lock
)
2207 /* Do not free lock->lk -- atexit() still looks at them */
2209 rollback_lock_file(lock
->lk
);
2210 free(lock
->ref_name
);
2211 free(lock
->orig_ref_name
);
2215 /* This function should make sure errno is meaningful on error */
2216 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2217 const unsigned char *old_sha1
, int mustexist
)
2219 if (read_ref_full(lock
->ref_name
,
2220 mustexist
? RESOLVE_REF_READING
: 0,
2221 lock
->old_sha1
, NULL
)) {
2222 int save_errno
= errno
;
2223 error("Can't verify ref %s", lock
->ref_name
);
2228 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2229 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2230 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2238 static int remove_empty_directories(const char *file
)
2240 /* we want to create a file but there is a directory there;
2241 * if that is an empty directory (or a directory that contains
2242 * only empty directories), remove them.
2245 int result
, save_errno
;
2247 strbuf_init(&path
, 20);
2248 strbuf_addstr(&path
, file
);
2250 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2253 strbuf_release(&path
);
2260 * *string and *len will only be substituted, and *string returned (for
2261 * later free()ing) if the string passed in is a magic short-hand form
2264 static char *substitute_branch_name(const char **string
, int *len
)
2266 struct strbuf buf
= STRBUF_INIT
;
2267 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2271 *string
= strbuf_detach(&buf
, &size
);
2273 return (char *)*string
;
2279 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2281 char *last_branch
= substitute_branch_name(&str
, &len
);
2286 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2287 char fullref
[PATH_MAX
];
2288 unsigned char sha1_from_ref
[20];
2289 unsigned char *this_result
;
2292 this_result
= refs_found
? sha1_from_ref
: sha1
;
2293 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2294 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2295 this_result
, &flag
);
2299 if (!warn_ambiguous_refs
)
2301 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2302 warning("ignoring dangling symref %s.", fullref
);
2303 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2304 warning("ignoring broken ref %s.", fullref
);
2311 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2313 char *last_branch
= substitute_branch_name(&str
, &len
);
2318 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2319 unsigned char hash
[20];
2320 char path
[PATH_MAX
];
2321 const char *ref
, *it
;
2323 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2324 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2328 if (reflog_exists(path
))
2330 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2334 if (!logs_found
++) {
2336 hashcpy(sha1
, hash
);
2338 if (!warn_ambiguous_refs
)
2346 * Locks a ref returning the lock on success and NULL on failure.
2347 * On failure errno is set to something meaningful.
2349 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2350 const unsigned char *old_sha1
,
2351 const struct string_list
*extras
,
2352 const struct string_list
*skip
,
2353 unsigned int flags
, int *type_p
,
2356 const char *ref_file
;
2357 const char *orig_refname
= refname
;
2358 struct ref_lock
*lock
;
2361 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2362 int resolve_flags
= 0;
2363 int attempts_remaining
= 3;
2367 lock
= xcalloc(1, sizeof(struct ref_lock
));
2370 resolve_flags
|= RESOLVE_REF_READING
;
2371 if (flags
& REF_DELETING
) {
2372 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2373 if (flags
& REF_NODEREF
)
2374 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2377 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2378 lock
->old_sha1
, &type
);
2379 if (!refname
&& errno
== EISDIR
) {
2380 /* we are trying to lock foo but we used to
2381 * have foo/bar which now does not exist;
2382 * it is normal for the empty directory 'foo'
2385 ref_file
= git_path("%s", orig_refname
);
2386 if (remove_empty_directories(ref_file
)) {
2389 if (!verify_refname_available(orig_refname
, extras
, skip
,
2390 get_loose_refs(&ref_cache
), err
))
2391 strbuf_addf(err
, "there are still refs under '%s'",
2396 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2397 lock
->old_sha1
, &type
);
2403 if (last_errno
!= ENOTDIR
||
2404 !verify_refname_available(orig_refname
, extras
, skip
,
2405 get_loose_refs(&ref_cache
), err
))
2406 strbuf_addf(err
, "unable to resolve reference %s: %s",
2407 orig_refname
, strerror(last_errno
));
2412 * If the ref did not exist and we are creating it, make sure
2413 * there is no existing packed ref whose name begins with our
2414 * refname, nor a packed ref whose name is a proper prefix of
2417 if (is_null_sha1(lock
->old_sha1
) &&
2418 verify_refname_available(refname
, extras
, skip
,
2419 get_packed_refs(&ref_cache
), err
)) {
2420 last_errno
= ENOTDIR
;
2424 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2427 if (flags
& REF_NODEREF
) {
2428 refname
= orig_refname
;
2429 lflags
|= LOCK_NO_DEREF
;
2431 lock
->ref_name
= xstrdup(refname
);
2432 lock
->orig_ref_name
= xstrdup(orig_refname
);
2433 ref_file
= git_path("%s", refname
);
2436 switch (safe_create_leading_directories_const(ref_file
)) {
2438 break; /* success */
2440 if (--attempts_remaining
> 0)
2445 strbuf_addf(err
, "unable to create directory for %s", ref_file
);
2449 if (hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
) < 0) {
2451 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2453 * Maybe somebody just deleted one of the
2454 * directories leading to ref_file. Try
2459 unable_to_lock_message(ref_file
, errno
, err
);
2463 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2472 * Write an entry to the packed-refs file for the specified refname.
2473 * If peeled is non-NULL, write it as the entry's peeled value.
2475 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2476 unsigned char *peeled
)
2478 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2480 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2484 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2486 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2488 enum peel_status peel_status
= peel_entry(entry
, 0);
2490 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2491 error("internal error: %s is not a valid packed reference!",
2493 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2494 peel_status
== PEEL_PEELED
?
2495 entry
->u
.value
.peeled
: NULL
);
2499 /* This should return a meaningful errno on failure */
2500 int lock_packed_refs(int flags
)
2502 struct packed_ref_cache
*packed_ref_cache
;
2504 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2507 * Get the current packed-refs while holding the lock. If the
2508 * packed-refs file has been modified since we last read it,
2509 * this will automatically invalidate the cache and re-read
2510 * the packed-refs file.
2512 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2513 packed_ref_cache
->lock
= &packlock
;
2514 /* Increment the reference count to prevent it from being freed: */
2515 acquire_packed_ref_cache(packed_ref_cache
);
2520 * Commit the packed refs changes.
2521 * On error we must make sure that errno contains a meaningful value.
2523 int commit_packed_refs(void)
2525 struct packed_ref_cache
*packed_ref_cache
=
2526 get_packed_ref_cache(&ref_cache
);
2531 if (!packed_ref_cache
->lock
)
2532 die("internal error: packed-refs not locked");
2534 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2536 die_errno("unable to fdopen packed-refs descriptor");
2538 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2539 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2540 0, write_packed_entry_fn
, out
);
2542 if (commit_lock_file(packed_ref_cache
->lock
)) {
2546 packed_ref_cache
->lock
= NULL
;
2547 release_packed_ref_cache(packed_ref_cache
);
2552 void rollback_packed_refs(void)
2554 struct packed_ref_cache
*packed_ref_cache
=
2555 get_packed_ref_cache(&ref_cache
);
2557 if (!packed_ref_cache
->lock
)
2558 die("internal error: packed-refs not locked");
2559 rollback_lock_file(packed_ref_cache
->lock
);
2560 packed_ref_cache
->lock
= NULL
;
2561 release_packed_ref_cache(packed_ref_cache
);
2562 clear_packed_ref_cache(&ref_cache
);
2565 struct ref_to_prune
{
2566 struct ref_to_prune
*next
;
2567 unsigned char sha1
[20];
2568 char name
[FLEX_ARRAY
];
2571 struct pack_refs_cb_data
{
2573 struct ref_dir
*packed_refs
;
2574 struct ref_to_prune
*ref_to_prune
;
2578 * An each_ref_entry_fn that is run over loose references only. If
2579 * the loose reference can be packed, add an entry in the packed ref
2580 * cache. If the reference should be pruned, also add it to
2581 * ref_to_prune in the pack_refs_cb_data.
2583 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2585 struct pack_refs_cb_data
*cb
= cb_data
;
2586 enum peel_status peel_status
;
2587 struct ref_entry
*packed_entry
;
2588 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2590 /* ALWAYS pack tags */
2591 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2594 /* Do not pack symbolic or broken refs: */
2595 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2598 /* Add a packed ref cache entry equivalent to the loose entry. */
2599 peel_status
= peel_entry(entry
, 1);
2600 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2601 die("internal error peeling reference %s (%s)",
2602 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2603 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2605 /* Overwrite existing packed entry with info from loose entry */
2606 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2607 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2609 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2610 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2611 add_ref(cb
->packed_refs
, packed_entry
);
2613 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2615 /* Schedule the loose reference for pruning if requested. */
2616 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2617 int namelen
= strlen(entry
->name
) + 1;
2618 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2619 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2620 strcpy(n
->name
, entry
->name
);
2621 n
->next
= cb
->ref_to_prune
;
2622 cb
->ref_to_prune
= n
;
2628 * Remove empty parents, but spare refs/ and immediate subdirs.
2629 * Note: munges *name.
2631 static void try_remove_empty_parents(char *name
)
2636 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2637 while (*p
&& *p
!= '/')
2639 /* tolerate duplicate slashes; see check_refname_format() */
2643 for (q
= p
; *q
; q
++)
2646 while (q
> p
&& *q
!= '/')
2648 while (q
> p
&& *(q
-1) == '/')
2653 if (rmdir(git_path("%s", name
)))
2658 /* make sure nobody touched the ref, and unlink */
2659 static void prune_ref(struct ref_to_prune
*r
)
2661 struct ref_transaction
*transaction
;
2662 struct strbuf err
= STRBUF_INIT
;
2664 if (check_refname_format(r
->name
, 0))
2667 transaction
= ref_transaction_begin(&err
);
2669 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2670 REF_ISPRUNING
, NULL
, &err
) ||
2671 ref_transaction_commit(transaction
, &err
)) {
2672 ref_transaction_free(transaction
);
2673 error("%s", err
.buf
);
2674 strbuf_release(&err
);
2677 ref_transaction_free(transaction
);
2678 strbuf_release(&err
);
2679 try_remove_empty_parents(r
->name
);
2682 static void prune_refs(struct ref_to_prune
*r
)
2690 int pack_refs(unsigned int flags
)
2692 struct pack_refs_cb_data cbdata
;
2694 memset(&cbdata
, 0, sizeof(cbdata
));
2695 cbdata
.flags
= flags
;
2697 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2698 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2700 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2701 pack_if_possible_fn
, &cbdata
);
2703 if (commit_packed_refs())
2704 die_errno("unable to overwrite old ref-pack file");
2706 prune_refs(cbdata
.ref_to_prune
);
2710 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2712 struct ref_dir
*packed
;
2713 struct string_list_item
*refname
;
2714 int ret
, needs_repacking
= 0, removed
= 0;
2718 /* Look for a packed ref */
2719 for_each_string_list_item(refname
, refnames
) {
2720 if (get_packed_ref(refname
->string
)) {
2721 needs_repacking
= 1;
2726 /* Avoid locking if we have nothing to do */
2727 if (!needs_repacking
)
2728 return 0; /* no refname exists in packed refs */
2730 if (lock_packed_refs(0)) {
2731 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2734 packed
= get_packed_refs(&ref_cache
);
2736 /* Remove refnames from the cache */
2737 for_each_string_list_item(refname
, refnames
)
2738 if (remove_entry(packed
, refname
->string
) != -1)
2742 * All packed entries disappeared while we were
2743 * acquiring the lock.
2745 rollback_packed_refs();
2749 /* Write what remains */
2750 ret
= commit_packed_refs();
2752 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2757 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2761 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2763 * loose. The loose file name is the same as the
2764 * lockfile name, minus ".lock":
2766 char *loose_filename
= get_locked_file_path(lock
->lk
);
2767 int res
= unlink_or_msg(loose_filename
, err
);
2768 free(loose_filename
);
2775 int delete_ref(const char *refname
, const unsigned char *sha1
, unsigned int flags
)
2777 struct ref_transaction
*transaction
;
2778 struct strbuf err
= STRBUF_INIT
;
2780 transaction
= ref_transaction_begin(&err
);
2782 ref_transaction_delete(transaction
, refname
,
2783 (sha1
&& !is_null_sha1(sha1
)) ? sha1
: NULL
,
2784 flags
, NULL
, &err
) ||
2785 ref_transaction_commit(transaction
, &err
)) {
2786 error("%s", err
.buf
);
2787 ref_transaction_free(transaction
);
2788 strbuf_release(&err
);
2791 ref_transaction_free(transaction
);
2792 strbuf_release(&err
);
2797 * People using contrib's git-new-workdir have .git/logs/refs ->
2798 * /some/other/path/.git/logs/refs, and that may live on another device.
2800 * IOW, to avoid cross device rename errors, the temporary renamed log must
2801 * live into logs/refs.
2803 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2805 static int rename_tmp_log(const char *newrefname
)
2807 int attempts_remaining
= 4;
2810 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname
))) {
2812 break; /* success */
2814 if (--attempts_remaining
> 0)
2818 error("unable to create directory for %s", newrefname
);
2822 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2823 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2825 * rename(a, b) when b is an existing
2826 * directory ought to result in ISDIR, but
2827 * Solaris 5.8 gives ENOTDIR. Sheesh.
2829 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2830 error("Directory not empty: logs/%s", newrefname
);
2834 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2836 * Maybe another process just deleted one of
2837 * the directories in the path to newrefname.
2838 * Try again from the beginning.
2842 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2843 newrefname
, strerror(errno
));
2850 static int rename_ref_available(const char *oldname
, const char *newname
)
2852 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2853 struct strbuf err
= STRBUF_INIT
;
2856 string_list_insert(&skip
, oldname
);
2857 ret
= !verify_refname_available(newname
, NULL
, &skip
,
2858 get_packed_refs(&ref_cache
), &err
)
2859 && !verify_refname_available(newname
, NULL
, &skip
,
2860 get_loose_refs(&ref_cache
), &err
);
2862 error("%s", err
.buf
);
2864 string_list_clear(&skip
, 0);
2865 strbuf_release(&err
);
2869 static int write_ref_sha1(struct ref_lock
*lock
, const unsigned char *sha1
,
2870 const char *logmsg
);
2872 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2874 unsigned char sha1
[20], orig_sha1
[20];
2875 int flag
= 0, logmoved
= 0;
2876 struct ref_lock
*lock
;
2877 struct stat loginfo
;
2878 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2879 const char *symref
= NULL
;
2880 struct strbuf err
= STRBUF_INIT
;
2882 if (log
&& S_ISLNK(loginfo
.st_mode
))
2883 return error("reflog for %s is a symlink", oldrefname
);
2885 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2887 if (flag
& REF_ISSYMREF
)
2888 return error("refname %s is a symbolic ref, renaming it is not supported",
2891 return error("refname %s not found", oldrefname
);
2893 if (!rename_ref_available(oldrefname
, newrefname
))
2896 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2897 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2898 oldrefname
, strerror(errno
));
2900 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2901 error("unable to delete old %s", oldrefname
);
2905 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2906 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2907 if (errno
==EISDIR
) {
2908 if (remove_empty_directories(git_path("%s", newrefname
))) {
2909 error("Directory not empty: %s", newrefname
);
2913 error("unable to delete existing %s", newrefname
);
2918 if (log
&& rename_tmp_log(newrefname
))
2923 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2925 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
2926 strbuf_release(&err
);
2929 hashcpy(lock
->old_sha1
, orig_sha1
);
2930 if (write_ref_sha1(lock
, orig_sha1
, logmsg
)) {
2931 error("unable to write current sha1 into %s", newrefname
);
2938 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2940 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
2941 strbuf_release(&err
);
2945 flag
= log_all_ref_updates
;
2946 log_all_ref_updates
= 0;
2947 if (write_ref_sha1(lock
, orig_sha1
, NULL
))
2948 error("unable to write current sha1 into %s", oldrefname
);
2949 log_all_ref_updates
= flag
;
2952 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2953 error("unable to restore logfile %s from %s: %s",
2954 oldrefname
, newrefname
, strerror(errno
));
2955 if (!logmoved
&& log
&&
2956 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2957 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2958 oldrefname
, strerror(errno
));
2963 static int close_ref(struct ref_lock
*lock
)
2965 if (close_lock_file(lock
->lk
))
2970 static int commit_ref(struct ref_lock
*lock
)
2972 if (commit_lock_file(lock
->lk
))
2978 * copy the reflog message msg to buf, which has been allocated sufficiently
2979 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2980 * because reflog file is one line per entry.
2982 static int copy_msg(char *buf
, const char *msg
)
2989 while ((c
= *msg
++)) {
2990 if (wasspace
&& isspace(c
))
2992 wasspace
= isspace(c
);
2997 while (buf
< cp
&& isspace(cp
[-1]))
3003 /* This function must set a meaningful errno on failure */
3004 int log_ref_setup(const char *refname
, struct strbuf
*sb_logfile
)
3006 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
3009 strbuf_git_path(sb_logfile
, "logs/%s", refname
);
3010 logfile
= sb_logfile
->buf
;
3011 /* make sure the rest of the function can't change "logfile" */
3013 if (log_all_ref_updates
&&
3014 (starts_with(refname
, "refs/heads/") ||
3015 starts_with(refname
, "refs/remotes/") ||
3016 starts_with(refname
, "refs/notes/") ||
3017 !strcmp(refname
, "HEAD"))) {
3018 if (safe_create_leading_directories(logfile
) < 0) {
3019 int save_errno
= errno
;
3020 error("unable to create directory for %s", logfile
);
3027 logfd
= open(logfile
, oflags
, 0666);
3029 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3032 if (errno
== EISDIR
) {
3033 if (remove_empty_directories(logfile
)) {
3034 int save_errno
= errno
;
3035 error("There are still logs under '%s'",
3040 logfd
= open(logfile
, oflags
, 0666);
3044 int save_errno
= errno
;
3045 error("Unable to append to %s: %s", logfile
,
3052 adjust_shared_perm(logfile
);
3057 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3058 const unsigned char *new_sha1
,
3059 const char *committer
, const char *msg
)
3061 int msglen
, written
;
3062 unsigned maxlen
, len
;
3065 msglen
= msg
? strlen(msg
) : 0;
3066 maxlen
= strlen(committer
) + msglen
+ 100;
3067 logrec
= xmalloc(maxlen
);
3068 len
= sprintf(logrec
, "%s %s %s\n",
3069 sha1_to_hex(old_sha1
),
3070 sha1_to_hex(new_sha1
),
3073 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3075 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3083 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
3084 const unsigned char *new_sha1
, const char *msg
,
3085 struct strbuf
*sb_log_file
)
3087 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3090 if (log_all_ref_updates
< 0)
3091 log_all_ref_updates
= !is_bare_repository();
3093 result
= log_ref_setup(refname
, sb_log_file
);
3096 log_file
= sb_log_file
->buf
;
3097 /* make sure the rest of the function can't change "log_file" */
3100 logfd
= open(log_file
, oflags
);
3103 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3104 git_committer_info(0), msg
);
3106 int save_errno
= errno
;
3108 error("Unable to append to %s", log_file
);
3113 int save_errno
= errno
;
3114 error("Unable to append to %s", log_file
);
3121 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3122 const unsigned char *new_sha1
, const char *msg
)
3124 struct strbuf sb
= STRBUF_INIT
;
3125 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
);
3126 strbuf_release(&sb
);
3130 int is_branch(const char *refname
)
3132 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3136 * Write sha1 into the ref specified by the lock. Make sure that errno
3139 static int write_ref_sha1(struct ref_lock
*lock
,
3140 const unsigned char *sha1
, const char *logmsg
)
3142 static char term
= '\n';
3145 o
= parse_object(sha1
);
3147 error("Trying to write ref %s with nonexistent object %s",
3148 lock
->ref_name
, sha1_to_hex(sha1
));
3153 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3154 error("Trying to write non-commit object %s to branch %s",
3155 sha1_to_hex(sha1
), lock
->ref_name
);
3160 if (write_in_full(lock
->lk
->fd
, sha1_to_hex(sha1
), 40) != 40 ||
3161 write_in_full(lock
->lk
->fd
, &term
, 1) != 1 ||
3162 close_ref(lock
) < 0) {
3163 int save_errno
= errno
;
3164 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3169 clear_loose_ref_cache(&ref_cache
);
3170 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3171 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3172 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3176 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3178 * Special hack: If a branch is updated directly and HEAD
3179 * points to it (may happen on the remote side of a push
3180 * for example) then logically the HEAD reflog should be
3182 * A generic solution implies reverse symref information,
3183 * but finding all symrefs pointing to the given branch
3184 * would be rather costly for this rare event (the direct
3185 * update of a branch) to be worth it. So let's cheat and
3186 * check with HEAD only which should cover 99% of all usage
3187 * scenarios (even 100% of the default ones).
3189 unsigned char head_sha1
[20];
3191 const char *head_ref
;
3192 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3193 head_sha1
, &head_flag
);
3194 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3195 !strcmp(head_ref
, lock
->ref_name
))
3196 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3198 if (commit_ref(lock
)) {
3199 error("Couldn't set %s", lock
->ref_name
);
3207 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3210 const char *lockpath
;
3212 int fd
, len
, written
;
3213 char *git_HEAD
= git_pathdup("%s", ref_target
);
3214 unsigned char old_sha1
[20], new_sha1
[20];
3216 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3219 if (safe_create_leading_directories(git_HEAD
) < 0)
3220 return error("unable to create directory for %s", git_HEAD
);
3222 #ifndef NO_SYMLINK_HEAD
3223 if (prefer_symlink_refs
) {
3225 if (!symlink(refs_heads_master
, git_HEAD
))
3227 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3231 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3232 if (sizeof(ref
) <= len
) {
3233 error("refname too long: %s", refs_heads_master
);
3234 goto error_free_return
;
3236 lockpath
= mkpath("%s.lock", git_HEAD
);
3237 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3239 error("Unable to open %s for writing", lockpath
);
3240 goto error_free_return
;
3242 written
= write_in_full(fd
, ref
, len
);
3243 if (close(fd
) != 0 || written
!= len
) {
3244 error("Unable to write to %s", lockpath
);
3245 goto error_unlink_return
;
3247 if (rename(lockpath
, git_HEAD
) < 0) {
3248 error("Unable to create %s", git_HEAD
);
3249 goto error_unlink_return
;
3251 if (adjust_shared_perm(git_HEAD
)) {
3252 error("Unable to fix permissions on %s", lockpath
);
3253 error_unlink_return
:
3254 unlink_or_warn(lockpath
);
3260 #ifndef NO_SYMLINK_HEAD
3263 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3264 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3270 struct read_ref_at_cb
{
3271 const char *refname
;
3272 unsigned long at_time
;
3275 unsigned char *sha1
;
3278 unsigned char osha1
[20];
3279 unsigned char nsha1
[20];
3283 unsigned long *cutoff_time
;
3288 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3289 const char *email
, unsigned long timestamp
, int tz
,
3290 const char *message
, void *cb_data
)
3292 struct read_ref_at_cb
*cb
= cb_data
;
3296 cb
->date
= timestamp
;
3298 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3300 *cb
->msg
= xstrdup(message
);
3301 if (cb
->cutoff_time
)
3302 *cb
->cutoff_time
= timestamp
;
3304 *cb
->cutoff_tz
= tz
;
3306 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3308 * we have not yet updated cb->[n|o]sha1 so they still
3309 * hold the values for the previous record.
3311 if (!is_null_sha1(cb
->osha1
)) {
3312 hashcpy(cb
->sha1
, nsha1
);
3313 if (hashcmp(cb
->osha1
, nsha1
))
3314 warning("Log for ref %s has gap after %s.",
3315 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3317 else if (cb
->date
== cb
->at_time
)
3318 hashcpy(cb
->sha1
, nsha1
);
3319 else if (hashcmp(nsha1
, cb
->sha1
))
3320 warning("Log for ref %s unexpectedly ended on %s.",
3321 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3323 hashcpy(cb
->osha1
, osha1
);
3324 hashcpy(cb
->nsha1
, nsha1
);
3328 hashcpy(cb
->osha1
, osha1
);
3329 hashcpy(cb
->nsha1
, nsha1
);
3335 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3336 const char *email
, unsigned long timestamp
,
3337 int tz
, const char *message
, void *cb_data
)
3339 struct read_ref_at_cb
*cb
= cb_data
;
3342 *cb
->msg
= xstrdup(message
);
3343 if (cb
->cutoff_time
)
3344 *cb
->cutoff_time
= timestamp
;
3346 *cb
->cutoff_tz
= tz
;
3348 *cb
->cutoff_cnt
= cb
->reccnt
;
3349 hashcpy(cb
->sha1
, osha1
);
3350 if (is_null_sha1(cb
->sha1
))
3351 hashcpy(cb
->sha1
, nsha1
);
3352 /* We just want the first entry */
3356 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3357 unsigned char *sha1
, char **msg
,
3358 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3360 struct read_ref_at_cb cb
;
3362 memset(&cb
, 0, sizeof(cb
));
3363 cb
.refname
= refname
;
3364 cb
.at_time
= at_time
;
3367 cb
.cutoff_time
= cutoff_time
;
3368 cb
.cutoff_tz
= cutoff_tz
;
3369 cb
.cutoff_cnt
= cutoff_cnt
;
3372 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3375 if (flags
& GET_SHA1_QUIETLY
)
3378 die("Log for %s is empty.", refname
);
3383 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3388 int reflog_exists(const char *refname
)
3392 return !lstat(git_path("logs/%s", refname
), &st
) &&
3393 S_ISREG(st
.st_mode
);
3396 int delete_reflog(const char *refname
)
3398 return remove_path(git_path("logs/%s", refname
));
3401 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3403 unsigned char osha1
[20], nsha1
[20];
3404 char *email_end
, *message
;
3405 unsigned long timestamp
;
3408 /* old SP new SP name <email> SP time TAB msg LF */
3409 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3410 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3411 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3412 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3413 email_end
[1] != ' ' ||
3414 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3415 !message
|| message
[0] != ' ' ||
3416 (message
[1] != '+' && message
[1] != '-') ||
3417 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3418 !isdigit(message
[4]) || !isdigit(message
[5]))
3419 return 0; /* corrupt? */
3420 email_end
[1] = '\0';
3421 tz
= strtol(message
+ 1, NULL
, 10);
3422 if (message
[6] != '\t')
3426 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3429 static char *find_beginning_of_line(char *bob
, char *scan
)
3431 while (bob
< scan
&& *(--scan
) != '\n')
3432 ; /* keep scanning backwards */
3434 * Return either beginning of the buffer, or LF at the end of
3435 * the previous line.
3440 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3442 struct strbuf sb
= STRBUF_INIT
;
3445 int ret
= 0, at_tail
= 1;
3447 logfp
= fopen(git_path("logs/%s", refname
), "r");
3451 /* Jump to the end */
3452 if (fseek(logfp
, 0, SEEK_END
) < 0)
3453 return error("cannot seek back reflog for %s: %s",
3454 refname
, strerror(errno
));
3456 while (!ret
&& 0 < pos
) {
3462 /* Fill next block from the end */
3463 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3464 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3465 return error("cannot seek back reflog for %s: %s",
3466 refname
, strerror(errno
));
3467 nread
= fread(buf
, cnt
, 1, logfp
);
3469 return error("cannot read %d bytes from reflog for %s: %s",
3470 cnt
, refname
, strerror(errno
));
3473 scanp
= endp
= buf
+ cnt
;
3474 if (at_tail
&& scanp
[-1] == '\n')
3475 /* Looking at the final LF at the end of the file */
3479 while (buf
< scanp
) {
3481 * terminating LF of the previous line, or the beginning
3486 bp
= find_beginning_of_line(buf
, scanp
);
3490 * The newline is the end of the previous line,
3491 * so we know we have complete line starting
3492 * at (bp + 1). Prefix it onto any prior data
3493 * we collected for the line and process it.
3495 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3498 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3504 * We are at the start of the buffer, and the
3505 * start of the file; there is no previous
3506 * line, and we have everything for this one.
3507 * Process it, and we can end the loop.
3509 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3510 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3517 * We are at the start of the buffer, and there
3518 * is more file to read backwards. Which means
3519 * we are in the middle of a line. Note that we
3520 * may get here even if *bp was a newline; that
3521 * just means we are at the exact end of the
3522 * previous line, rather than some spot in the
3525 * Save away what we have to be combined with
3526 * the data from the next read.
3528 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3535 die("BUG: reverse reflog parser had leftover data");
3538 strbuf_release(&sb
);
3542 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3545 struct strbuf sb
= STRBUF_INIT
;
3548 logfp
= fopen(git_path("logs/%s", refname
), "r");
3552 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3553 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3555 strbuf_release(&sb
);
3559 * Call fn for each reflog in the namespace indicated by name. name
3560 * must be empty or end with '/'. Name will be used as a scratch
3561 * space, but its contents will be restored before return.
3563 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3565 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3568 int oldlen
= name
->len
;
3571 return name
->len
? errno
: 0;
3573 while ((de
= readdir(d
)) != NULL
) {
3576 if (de
->d_name
[0] == '.')
3578 if (ends_with(de
->d_name
, ".lock"))
3580 strbuf_addstr(name
, de
->d_name
);
3581 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3582 ; /* silently ignore */
3584 if (S_ISDIR(st
.st_mode
)) {
3585 strbuf_addch(name
, '/');
3586 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3588 unsigned char sha1
[20];
3589 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3590 retval
= error("bad ref for %s", name
->buf
);
3592 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3597 strbuf_setlen(name
, oldlen
);
3603 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3607 strbuf_init(&name
, PATH_MAX
);
3608 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3609 strbuf_release(&name
);
3614 * Information needed for a single ref update. Set new_sha1 to the new
3615 * value or to null_sha1 to delete the ref. To check the old value
3616 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3617 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3618 * not exist before update.
3622 * If (flags & REF_HAVE_NEW), set the reference to this value:
3624 unsigned char new_sha1
[20];
3626 * If (flags & REF_HAVE_OLD), check that the reference
3627 * previously had this value:
3629 unsigned char old_sha1
[20];
3631 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3632 * REF_DELETING, and REF_ISPRUNING:
3635 struct ref_lock
*lock
;
3638 const char refname
[FLEX_ARRAY
];
3642 * Transaction states.
3643 * OPEN: The transaction is in a valid state and can accept new updates.
3644 * An OPEN transaction can be committed.
3645 * CLOSED: A closed transaction is no longer active and no other operations
3646 * than free can be used on it in this state.
3647 * A transaction can either become closed by successfully committing
3648 * an active transaction or if there is a failure while building
3649 * the transaction thus rendering it failed/inactive.
3651 enum ref_transaction_state
{
3652 REF_TRANSACTION_OPEN
= 0,
3653 REF_TRANSACTION_CLOSED
= 1
3657 * Data structure for holding a reference transaction, which can
3658 * consist of checks and updates to multiple references, carried out
3659 * as atomically as possible. This structure is opaque to callers.
3661 struct ref_transaction
{
3662 struct ref_update
**updates
;
3665 enum ref_transaction_state state
;
3668 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3672 return xcalloc(1, sizeof(struct ref_transaction
));
3675 void ref_transaction_free(struct ref_transaction
*transaction
)
3682 for (i
= 0; i
< transaction
->nr
; i
++) {
3683 free(transaction
->updates
[i
]->msg
);
3684 free(transaction
->updates
[i
]);
3686 free(transaction
->updates
);
3690 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3691 const char *refname
)
3693 size_t len
= strlen(refname
);
3694 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3696 strcpy((char *)update
->refname
, refname
);
3697 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3698 transaction
->updates
[transaction
->nr
++] = update
;
3702 int ref_transaction_update(struct ref_transaction
*transaction
,
3703 const char *refname
,
3704 const unsigned char *new_sha1
,
3705 const unsigned char *old_sha1
,
3706 unsigned int flags
, const char *msg
,
3709 struct ref_update
*update
;
3713 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3714 die("BUG: update called for transaction that is not open");
3716 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
3717 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3718 strbuf_addf(err
, "refusing to update ref with bad name %s",
3723 update
= add_update(transaction
, refname
);
3725 hashcpy(update
->new_sha1
, new_sha1
);
3726 flags
|= REF_HAVE_NEW
;
3729 hashcpy(update
->old_sha1
, old_sha1
);
3730 flags
|= REF_HAVE_OLD
;
3732 update
->flags
= flags
;
3734 update
->msg
= xstrdup(msg
);
3738 int ref_transaction_create(struct ref_transaction
*transaction
,
3739 const char *refname
,
3740 const unsigned char *new_sha1
,
3741 unsigned int flags
, const char *msg
,
3744 if (!new_sha1
|| is_null_sha1(new_sha1
))
3745 die("BUG: create called without valid new_sha1");
3746 return ref_transaction_update(transaction
, refname
, new_sha1
,
3747 null_sha1
, flags
, msg
, err
);
3750 int ref_transaction_delete(struct ref_transaction
*transaction
,
3751 const char *refname
,
3752 const unsigned char *old_sha1
,
3753 unsigned int flags
, const char *msg
,
3756 if (old_sha1
&& is_null_sha1(old_sha1
))
3757 die("BUG: delete called with old_sha1 set to zeros");
3758 return ref_transaction_update(transaction
, refname
,
3759 null_sha1
, old_sha1
,
3763 int ref_transaction_verify(struct ref_transaction
*transaction
,
3764 const char *refname
,
3765 const unsigned char *old_sha1
,
3770 die("BUG: verify called with old_sha1 set to NULL");
3771 return ref_transaction_update(transaction
, refname
,
3776 int update_ref(const char *msg
, const char *refname
,
3777 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
3778 unsigned int flags
, enum action_on_err onerr
)
3780 struct ref_transaction
*t
;
3781 struct strbuf err
= STRBUF_INIT
;
3783 t
= ref_transaction_begin(&err
);
3785 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
3786 flags
, msg
, &err
) ||
3787 ref_transaction_commit(t
, &err
)) {
3788 const char *str
= "update_ref failed for ref '%s': %s";
3790 ref_transaction_free(t
);
3792 case UPDATE_REFS_MSG_ON_ERR
:
3793 error(str
, refname
, err
.buf
);
3795 case UPDATE_REFS_DIE_ON_ERR
:
3796 die(str
, refname
, err
.buf
);
3798 case UPDATE_REFS_QUIET_ON_ERR
:
3801 strbuf_release(&err
);
3804 strbuf_release(&err
);
3805 ref_transaction_free(t
);
3809 static int ref_update_reject_duplicates(struct string_list
*refnames
,
3812 int i
, n
= refnames
->nr
;
3816 for (i
= 1; i
< n
; i
++)
3817 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
3819 "Multiple updates for ref '%s' not allowed.",
3820 refnames
->items
[i
].string
);
3826 int ref_transaction_commit(struct ref_transaction
*transaction
,
3830 int n
= transaction
->nr
;
3831 struct ref_update
**updates
= transaction
->updates
;
3832 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3833 struct string_list_item
*ref_to_delete
;
3834 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3838 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3839 die("BUG: commit called for transaction that is not open");
3842 transaction
->state
= REF_TRANSACTION_CLOSED
;
3846 /* Fail if a refname appears more than once in the transaction: */
3847 for (i
= 0; i
< n
; i
++)
3848 string_list_append(&affected_refnames
, updates
[i
]->refname
);
3849 string_list_sort(&affected_refnames
);
3850 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
3851 ret
= TRANSACTION_GENERIC_ERROR
;
3855 /* Acquire all locks while verifying old values */
3856 for (i
= 0; i
< n
; i
++) {
3857 struct ref_update
*update
= updates
[i
];
3858 unsigned int flags
= update
->flags
;
3860 if ((flags
& REF_HAVE_NEW
) && is_null_sha1(update
->new_sha1
))
3861 flags
|= REF_DELETING
;
3862 update
->lock
= lock_ref_sha1_basic(
3864 ((update
->flags
& REF_HAVE_OLD
) ?
3865 update
->old_sha1
: NULL
),
3866 &affected_refnames
, NULL
,
3870 if (!update
->lock
) {
3873 ret
= (errno
== ENOTDIR
)
3874 ? TRANSACTION_NAME_CONFLICT
3875 : TRANSACTION_GENERIC_ERROR
;
3876 reason
= strbuf_detach(err
, NULL
);
3877 strbuf_addf(err
, "Cannot lock ref '%s': %s",
3878 update
->refname
, reason
);
3884 /* Perform updates first so live commits remain referenced */
3885 for (i
= 0; i
< n
; i
++) {
3886 struct ref_update
*update
= updates
[i
];
3887 int flags
= update
->flags
;
3889 if ((flags
& REF_HAVE_NEW
) && !is_null_sha1(update
->new_sha1
)) {
3890 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
3891 (update
->flags
& REF_NODEREF
));
3893 if (!overwriting_symref
3894 && !hashcmp(update
->lock
->old_sha1
, update
->new_sha1
)) {
3896 * The reference already has the desired
3897 * value, so we don't need to write it.
3899 unlock_ref(update
->lock
);
3900 update
->lock
= NULL
;
3901 } else if (write_ref_sha1(update
->lock
, update
->new_sha1
,
3903 update
->lock
= NULL
; /* freed by write_ref_sha1 */
3904 strbuf_addf(err
, "Cannot update the ref '%s'.",
3906 ret
= TRANSACTION_GENERIC_ERROR
;
3909 /* freed by write_ref_sha1(): */
3910 update
->lock
= NULL
;
3915 /* Perform deletes now that updates are safely completed */
3916 for (i
= 0; i
< n
; i
++) {
3917 struct ref_update
*update
= updates
[i
];
3918 int flags
= update
->flags
;
3920 if ((flags
& REF_HAVE_NEW
) && is_null_sha1(update
->new_sha1
)) {
3921 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3922 ret
= TRANSACTION_GENERIC_ERROR
;
3926 if (!(flags
& REF_ISPRUNING
))
3927 string_list_append(&refs_to_delete
,
3928 update
->lock
->ref_name
);
3932 if (repack_without_refs(&refs_to_delete
, err
)) {
3933 ret
= TRANSACTION_GENERIC_ERROR
;
3936 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3937 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3938 clear_loose_ref_cache(&ref_cache
);
3941 transaction
->state
= REF_TRANSACTION_CLOSED
;
3943 for (i
= 0; i
< n
; i
++)
3944 if (updates
[i
]->lock
)
3945 unlock_ref(updates
[i
]->lock
);
3946 string_list_clear(&refs_to_delete
, 0);
3947 string_list_clear(&affected_refnames
, 0);
3951 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3954 static char **scanf_fmts
;
3955 static int nr_rules
;
3960 * Pre-generate scanf formats from ref_rev_parse_rules[].
3961 * Generate a format suitable for scanf from a
3962 * ref_rev_parse_rules rule by interpolating "%s" at the
3963 * location of the "%.*s".
3965 size_t total_len
= 0;
3968 /* the rule list is NULL terminated, count them first */
3969 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
3970 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3971 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
3973 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
3976 for (i
= 0; i
< nr_rules
; i
++) {
3977 assert(offset
< total_len
);
3978 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
3979 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
3980 ref_rev_parse_rules
[i
], 2, "%s") + 1;
3984 /* bail out if there are no rules */
3986 return xstrdup(refname
);
3988 /* buffer for scanf result, at most refname must fit */
3989 short_name
= xstrdup(refname
);
3991 /* skip first rule, it will always match */
3992 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
3994 int rules_to_fail
= i
;
3997 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
4000 short_name_len
= strlen(short_name
);
4003 * in strict mode, all (except the matched one) rules
4004 * must fail to resolve to a valid non-ambiguous ref
4007 rules_to_fail
= nr_rules
;
4010 * check if the short name resolves to a valid ref,
4011 * but use only rules prior to the matched one
4013 for (j
= 0; j
< rules_to_fail
; j
++) {
4014 const char *rule
= ref_rev_parse_rules
[j
];
4015 char refname
[PATH_MAX
];
4017 /* skip matched rule */
4022 * the short name is ambiguous, if it resolves
4023 * (with this previous rule) to a valid ref
4024 * read_ref() returns 0 on success
4026 mksnpath(refname
, sizeof(refname
),
4027 rule
, short_name_len
, short_name
);
4028 if (ref_exists(refname
))
4033 * short name is non-ambiguous if all previous rules
4034 * haven't resolved to a valid ref
4036 if (j
== rules_to_fail
)
4041 return xstrdup(refname
);
4044 static struct string_list
*hide_refs
;
4046 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
4048 if (!strcmp("transfer.hiderefs", var
) ||
4049 /* NEEDSWORK: use parse_config_key() once both are merged */
4050 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
4051 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
4056 return config_error_nonbool(var
);
4057 ref
= xstrdup(value
);
4059 while (len
&& ref
[len
- 1] == '/')
4062 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
4063 hide_refs
->strdup_strings
= 1;
4065 string_list_append(hide_refs
, ref
);
4070 int ref_is_hidden(const char *refname
)
4072 struct string_list_item
*item
;
4076 for_each_string_list_item(item
, hide_refs
) {
4078 if (!starts_with(refname
, item
->string
))
4080 len
= strlen(item
->string
);
4081 if (!refname
[len
] || refname
[len
] == '/')
4087 struct expire_reflog_cb
{
4089 reflog_expiry_should_prune_fn
*should_prune_fn
;
4092 unsigned char last_kept_sha1
[20];
4095 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4096 const char *email
, unsigned long timestamp
, int tz
,
4097 const char *message
, void *cb_data
)
4099 struct expire_reflog_cb
*cb
= cb_data
;
4100 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4102 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4103 osha1
= cb
->last_kept_sha1
;
4105 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4106 message
, policy_cb
)) {
4108 printf("would prune %s", message
);
4109 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4110 printf("prune %s", message
);
4113 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4114 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4115 email
, timestamp
, tz
, message
);
4116 hashcpy(cb
->last_kept_sha1
, nsha1
);
4118 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4119 printf("keep %s", message
);
4124 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4126 reflog_expiry_prepare_fn prepare_fn
,
4127 reflog_expiry_should_prune_fn should_prune_fn
,
4128 reflog_expiry_cleanup_fn cleanup_fn
,
4129 void *policy_cb_data
)
4131 static struct lock_file reflog_lock
;
4132 struct expire_reflog_cb cb
;
4133 struct ref_lock
*lock
;
4137 struct strbuf err
= STRBUF_INIT
;
4139 memset(&cb
, 0, sizeof(cb
));
4141 cb
.policy_cb
= policy_cb_data
;
4142 cb
.should_prune_fn
= should_prune_fn
;
4145 * The reflog file is locked by holding the lock on the
4146 * reference itself, plus we might need to update the
4147 * reference if --updateref was specified:
4149 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, 0, &type
, &err
);
4151 error("cannot lock ref '%s': %s", refname
, err
.buf
);
4152 strbuf_release(&err
);
4155 if (!reflog_exists(refname
)) {
4160 log_file
= git_pathdup("logs/%s", refname
);
4161 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4163 * Even though holding $GIT_DIR/logs/$reflog.lock has
4164 * no locking implications, we use the lock_file
4165 * machinery here anyway because it does a lot of the
4166 * work we need, including cleaning up if the program
4167 * exits unexpectedly.
4169 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4170 struct strbuf err
= STRBUF_INIT
;
4171 unable_to_lock_message(log_file
, errno
, &err
);
4172 error("%s", err
.buf
);
4173 strbuf_release(&err
);
4176 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4178 error("cannot fdopen %s (%s)",
4179 reflog_lock
.filename
.buf
, strerror(errno
));
4184 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4185 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4186 (*cleanup_fn
)(cb
.policy_cb
);
4188 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4190 * It doesn't make sense to adjust a reference pointed
4191 * to by a symbolic ref based on expiring entries in
4192 * the symbolic reference's reflog. Nor can we update
4193 * a reference if there are no remaining reflog
4196 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4197 !(type
& REF_ISSYMREF
) &&
4198 !is_null_sha1(cb
.last_kept_sha1
);
4200 if (close_lock_file(&reflog_lock
)) {
4201 status
|= error("couldn't write %s: %s", log_file
,
4203 } else if (update
&&
4204 (write_in_full(lock
->lk
->fd
,
4205 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4206 write_str_in_full(lock
->lk
->fd
, "\n") != 1 ||
4207 close_ref(lock
) < 0)) {
4208 status
|= error("couldn't write %s",
4209 lock
->lk
->filename
.buf
);
4210 rollback_lock_file(&reflog_lock
);
4211 } else if (commit_lock_file(&reflog_lock
)) {
4212 status
|= error("unable to commit reflog '%s' (%s)",
4213 log_file
, strerror(errno
));
4214 } else if (update
&& commit_ref(lock
)) {
4215 status
|= error("couldn't set %s", lock
->ref_name
);
4223 rollback_lock_file(&reflog_lock
);