7 #include "string-list.h"
13 unsigned char old_sha1
[20];
18 * How to handle various characters in refnames:
19 * 0: An acceptable character for refs
21 * 2: ., look for a preceding . to reject .. in refs
22 * 3: {, look for a preceding @ to reject @{ in refs
23 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
25 static unsigned char refname_disposition
[256] = {
26 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
37 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
38 * refs (i.e., because the reference is about to be deleted anyway).
40 #define REF_DELETING 0x02
43 * Used as a flag in ref_update::flags when a loose ref is being
46 #define REF_ISPRUNING 0x04
49 * Used as a flag in ref_update::flags when the reference should be
50 * updated to new_sha1.
52 #define REF_HAVE_NEW 0x08
55 * Used as a flag in ref_update::flags when old_sha1 should be
58 #define REF_HAVE_OLD 0x10
61 * Used as a flag in ref_update::flags when the lockfile needs to be
64 #define REF_NEEDS_COMMIT 0x20
67 * Try to read one refname component from the front of refname.
68 * Return the length of the component found, or -1 if the component is
69 * not legal. It is legal if it is something reasonable to have under
70 * ".git/refs/"; We do not like it if:
72 * - any path component of it begins with ".", or
73 * - it has double dots "..", or
74 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
75 * - it ends with a "/".
76 * - it ends with ".lock"
77 * - it contains a "\" (backslash)
79 static int check_refname_component(const char *refname
, int flags
)
84 for (cp
= refname
; ; cp
++) {
86 unsigned char disp
= refname_disposition
[ch
];
92 return -1; /* Refname contains "..". */
96 return -1; /* Refname contains "@{". */
105 return 0; /* Component has zero length. */
106 if (refname
[0] == '.')
107 return -1; /* Component starts with '.'. */
108 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
109 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
110 return -1; /* Refname ends with ".lock". */
114 int check_refname_format(const char *refname
, int flags
)
116 int component_len
, component_count
= 0;
118 if (!strcmp(refname
, "@"))
119 /* Refname is a single character '@'. */
123 /* We are at the start of a path component. */
124 component_len
= check_refname_component(refname
, flags
);
125 if (component_len
<= 0) {
126 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
128 (refname
[1] == '\0' || refname
[1] == '/')) {
129 /* Accept one wildcard as a full refname component. */
130 flags
&= ~REFNAME_REFSPEC_PATTERN
;
137 if (refname
[component_len
] == '\0')
139 /* Skip to next component. */
140 refname
+= component_len
+ 1;
143 if (refname
[component_len
- 1] == '.')
144 return -1; /* Refname ends with '.'. */
145 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
146 return -1; /* Refname has only one component. */
153 * Information used (along with the information in ref_entry) to
154 * describe a single cached reference. This data structure only
155 * occurs embedded in a union in struct ref_entry, and only when
156 * (ref_entry->flag & REF_DIR) is zero.
160 * The name of the object to which this reference resolves
161 * (which may be a tag object). If REF_ISBROKEN, this is
162 * null. If REF_ISSYMREF, then this is the name of the object
163 * referred to by the last reference in the symlink chain.
165 unsigned char sha1
[20];
168 * If REF_KNOWS_PEELED, then this field holds the peeled value
169 * of this reference, or null if the reference is known not to
170 * be peelable. See the documentation for peel_ref() for an
171 * exact definition of "peelable".
173 unsigned char peeled
[20];
179 * Information used (along with the information in ref_entry) to
180 * describe a level in the hierarchy of references. This data
181 * structure only occurs embedded in a union in struct ref_entry, and
182 * only when (ref_entry.flag & REF_DIR) is set. In that case,
183 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
184 * in the directory have already been read:
186 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
187 * or packed references, already read.
189 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
190 * references that hasn't been read yet (nor has any of its
193 * Entries within a directory are stored within a growable array of
194 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
195 * sorted are sorted by their component name in strcmp() order and the
196 * remaining entries are unsorted.
198 * Loose references are read lazily, one directory at a time. When a
199 * directory of loose references is read, then all of the references
200 * in that directory are stored, and REF_INCOMPLETE stubs are created
201 * for any subdirectories, but the subdirectories themselves are not
202 * read. The reading is triggered by get_ref_dir().
208 * Entries with index 0 <= i < sorted are sorted by name. New
209 * entries are appended to the list unsorted, and are sorted
210 * only when required; thus we avoid the need to sort the list
211 * after the addition of every reference.
215 /* A pointer to the ref_cache that contains this ref_dir. */
216 struct ref_cache
*ref_cache
;
218 struct ref_entry
**entries
;
222 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
223 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
224 * public values; see refs.h.
228 * The field ref_entry->u.value.peeled of this value entry contains
229 * the correct peeled value for the reference, which might be
230 * null_sha1 if the reference is not a tag or if it is broken.
232 #define REF_KNOWS_PEELED 0x10
234 /* ref_entry represents a directory of references */
238 * Entry has not yet been read from disk (used only for REF_DIR
239 * entries representing loose references)
241 #define REF_INCOMPLETE 0x40
244 * A ref_entry represents either a reference or a "subdirectory" of
247 * Each directory in the reference namespace is represented by a
248 * ref_entry with (flags & REF_DIR) set and containing a subdir member
249 * that holds the entries in that directory that have been read so
250 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
251 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
252 * used for loose reference directories.
254 * References are represented by a ref_entry with (flags & REF_DIR)
255 * unset and a value member that describes the reference's value. The
256 * flag member is at the ref_entry level, but it is also needed to
257 * interpret the contents of the value field (in other words, a
258 * ref_value object is not very much use without the enclosing
261 * Reference names cannot end with slash and directories' names are
262 * always stored with a trailing slash (except for the top-level
263 * directory, which is always denoted by ""). This has two nice
264 * consequences: (1) when the entries in each subdir are sorted
265 * lexicographically by name (as they usually are), the references in
266 * a whole tree can be generated in lexicographic order by traversing
267 * the tree in left-to-right, depth-first order; (2) the names of
268 * references and subdirectories cannot conflict, and therefore the
269 * presence of an empty subdirectory does not block the creation of a
270 * similarly-named reference. (The fact that reference names with the
271 * same leading components can conflict *with each other* is a
272 * separate issue that is regulated by verify_refname_available().)
274 * Please note that the name field contains the fully-qualified
275 * reference (or subdirectory) name. Space could be saved by only
276 * storing the relative names. But that would require the full names
277 * to be generated on the fly when iterating in do_for_each_ref(), and
278 * would break callback functions, who have always been able to assume
279 * that the name strings that they are passed will not be freed during
283 unsigned char flag
; /* ISSYMREF? ISPACKED? */
285 struct ref_value value
; /* if not (flags&REF_DIR) */
286 struct ref_dir subdir
; /* if (flags&REF_DIR) */
289 * The full name of the reference (e.g., "refs/heads/master")
290 * or the full name of the directory with a trailing slash
291 * (e.g., "refs/heads/"):
293 char name
[FLEX_ARRAY
];
296 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
298 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
301 assert(entry
->flag
& REF_DIR
);
302 dir
= &entry
->u
.subdir
;
303 if (entry
->flag
& REF_INCOMPLETE
) {
304 read_loose_refs(entry
->name
, dir
);
305 entry
->flag
&= ~REF_INCOMPLETE
;
311 * Check if a refname is safe.
312 * For refs that start with "refs/" we consider it safe as long they do
313 * not try to resolve to outside of refs/.
315 * For all other refs we only consider them safe iff they only contain
316 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
319 static int refname_is_safe(const char *refname
)
321 if (starts_with(refname
, "refs/")) {
325 buf
= xmalloc(strlen(refname
) + 1);
327 * Does the refname try to escape refs/?
328 * For example: refs/foo/../bar is safe but refs/foo/../../bar
331 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
336 if (!isupper(*refname
) && *refname
!= '_')
343 static struct ref_entry
*create_ref_entry(const char *refname
,
344 const unsigned char *sha1
, int flag
,
348 struct ref_entry
*ref
;
351 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
352 die("Reference has invalid format: '%s'", refname
);
353 if (!check_name
&& !refname_is_safe(refname
))
354 die("Reference has invalid name: '%s'", refname
);
355 len
= strlen(refname
) + 1;
356 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
357 hashcpy(ref
->u
.value
.sha1
, sha1
);
358 hashclr(ref
->u
.value
.peeled
);
359 memcpy(ref
->name
, refname
, len
);
364 static void clear_ref_dir(struct ref_dir
*dir
);
366 static void free_ref_entry(struct ref_entry
*entry
)
368 if (entry
->flag
& REF_DIR
) {
370 * Do not use get_ref_dir() here, as that might
371 * trigger the reading of loose refs.
373 clear_ref_dir(&entry
->u
.subdir
);
379 * Add a ref_entry to the end of dir (unsorted). Entry is always
380 * stored directly in dir; no recursion into subdirectories is
383 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
385 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
386 dir
->entries
[dir
->nr
++] = entry
;
387 /* optimize for the case that entries are added in order */
389 (dir
->nr
== dir
->sorted
+ 1 &&
390 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
391 dir
->entries
[dir
->nr
- 1]->name
) < 0))
392 dir
->sorted
= dir
->nr
;
396 * Clear and free all entries in dir, recursively.
398 static void clear_ref_dir(struct ref_dir
*dir
)
401 for (i
= 0; i
< dir
->nr
; i
++)
402 free_ref_entry(dir
->entries
[i
]);
404 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
409 * Create a struct ref_entry object for the specified dirname.
410 * dirname is the name of the directory with a trailing slash (e.g.,
411 * "refs/heads/") or "" for the top-level directory.
413 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
414 const char *dirname
, size_t len
,
417 struct ref_entry
*direntry
;
418 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
419 memcpy(direntry
->name
, dirname
, len
);
420 direntry
->name
[len
] = '\0';
421 direntry
->u
.subdir
.ref_cache
= ref_cache
;
422 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
426 static int ref_entry_cmp(const void *a
, const void *b
)
428 struct ref_entry
*one
= *(struct ref_entry
**)a
;
429 struct ref_entry
*two
= *(struct ref_entry
**)b
;
430 return strcmp(one
->name
, two
->name
);
433 static void sort_ref_dir(struct ref_dir
*dir
);
435 struct string_slice
{
440 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
442 const struct string_slice
*key
= key_
;
443 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
444 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
447 return '\0' - (unsigned char)ent
->name
[key
->len
];
451 * Return the index of the entry with the given refname from the
452 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
453 * no such entry is found. dir must already be complete.
455 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
457 struct ref_entry
**r
;
458 struct string_slice key
;
460 if (refname
== NULL
|| !dir
->nr
)
466 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
467 ref_entry_cmp_sslice
);
472 return r
- dir
->entries
;
476 * Search for a directory entry directly within dir (without
477 * recursing). Sort dir if necessary. subdirname must be a directory
478 * name (i.e., end in '/'). If mkdir is set, then create the
479 * directory if it is missing; otherwise, return NULL if the desired
480 * directory cannot be found. dir must already be complete.
482 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
483 const char *subdirname
, size_t len
,
486 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
487 struct ref_entry
*entry
;
488 if (entry_index
== -1) {
492 * Since dir is complete, the absence of a subdir
493 * means that the subdir really doesn't exist;
494 * therefore, create an empty record for it but mark
495 * the record complete.
497 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
498 add_entry_to_dir(dir
, entry
);
500 entry
= dir
->entries
[entry_index
];
502 return get_ref_dir(entry
);
506 * If refname is a reference name, find the ref_dir within the dir
507 * tree that should hold refname. If refname is a directory name
508 * (i.e., ends in '/'), then return that ref_dir itself. dir must
509 * represent the top-level directory and must already be complete.
510 * Sort ref_dirs and recurse into subdirectories as necessary. If
511 * mkdir is set, then create any missing directories; otherwise,
512 * return NULL if the desired directory cannot be found.
514 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
515 const char *refname
, int mkdir
)
518 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
519 size_t dirnamelen
= slash
- refname
+ 1;
520 struct ref_dir
*subdir
;
521 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
533 * Find the value entry with the given name in dir, sorting ref_dirs
534 * and recursing into subdirectories as necessary. If the name is not
535 * found or it corresponds to a directory entry, return NULL.
537 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
540 struct ref_entry
*entry
;
541 dir
= find_containing_dir(dir
, refname
, 0);
544 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
545 if (entry_index
== -1)
547 entry
= dir
->entries
[entry_index
];
548 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
552 * Remove the entry with the given name from dir, recursing into
553 * subdirectories as necessary. If refname is the name of a directory
554 * (i.e., ends with '/'), then remove the directory and its contents.
555 * If the removal was successful, return the number of entries
556 * remaining in the directory entry that contained the deleted entry.
557 * If the name was not found, return -1. Please note that this
558 * function only deletes the entry from the cache; it does not delete
559 * it from the filesystem or ensure that other cache entries (which
560 * might be symbolic references to the removed entry) are updated.
561 * Nor does it remove any containing dir entries that might be made
562 * empty by the removal. dir must represent the top-level directory
563 * and must already be complete.
565 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
567 int refname_len
= strlen(refname
);
569 struct ref_entry
*entry
;
570 int is_dir
= refname
[refname_len
- 1] == '/';
573 * refname represents a reference directory. Remove
574 * the trailing slash; otherwise we will get the
575 * directory *representing* refname rather than the
576 * one *containing* it.
578 char *dirname
= xmemdupz(refname
, refname_len
- 1);
579 dir
= find_containing_dir(dir
, dirname
, 0);
582 dir
= find_containing_dir(dir
, refname
, 0);
586 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
587 if (entry_index
== -1)
589 entry
= dir
->entries
[entry_index
];
591 memmove(&dir
->entries
[entry_index
],
592 &dir
->entries
[entry_index
+ 1],
593 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
596 if (dir
->sorted
> entry_index
)
598 free_ref_entry(entry
);
603 * Add a ref_entry to the ref_dir (unsorted), recursing into
604 * subdirectories as necessary. dir must represent the top-level
605 * directory. Return 0 on success.
607 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
609 dir
= find_containing_dir(dir
, ref
->name
, 1);
612 add_entry_to_dir(dir
, ref
);
617 * Emit a warning and return true iff ref1 and ref2 have the same name
618 * and the same sha1. Die if they have the same name but different
621 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
623 if (strcmp(ref1
->name
, ref2
->name
))
626 /* Duplicate name; make sure that they don't conflict: */
628 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
629 /* This is impossible by construction */
630 die("Reference directory conflict: %s", ref1
->name
);
632 if (hashcmp(ref1
->u
.value
.sha1
, ref2
->u
.value
.sha1
))
633 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
635 warning("Duplicated ref: %s", ref1
->name
);
640 * Sort the entries in dir non-recursively (if they are not already
641 * sorted) and remove any duplicate entries.
643 static void sort_ref_dir(struct ref_dir
*dir
)
646 struct ref_entry
*last
= NULL
;
649 * This check also prevents passing a zero-length array to qsort(),
650 * which is a problem on some platforms.
652 if (dir
->sorted
== dir
->nr
)
655 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
657 /* Remove any duplicates: */
658 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
659 struct ref_entry
*entry
= dir
->entries
[j
];
660 if (last
&& is_dup_ref(last
, entry
))
661 free_ref_entry(entry
);
663 last
= dir
->entries
[i
++] = entry
;
665 dir
->sorted
= dir
->nr
= i
;
668 /* Include broken references in a do_for_each_ref*() iteration: */
669 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
672 * Return true iff the reference described by entry can be resolved to
673 * an object in the database. Emit a warning if the referred-to
674 * object does not exist.
676 static int ref_resolves_to_object(struct ref_entry
*entry
)
678 if (entry
->flag
& REF_ISBROKEN
)
680 if (!has_sha1_file(entry
->u
.value
.sha1
)) {
681 error("%s does not point to a valid object!", entry
->name
);
688 * current_ref is a performance hack: when iterating over references
689 * using the for_each_ref*() functions, current_ref is set to the
690 * current reference's entry before calling the callback function. If
691 * the callback function calls peel_ref(), then peel_ref() first
692 * checks whether the reference to be peeled is the current reference
693 * (it usually is) and if so, returns that reference's peeled version
694 * if it is available. This avoids a refname lookup in a common case.
696 static struct ref_entry
*current_ref
;
698 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
700 struct ref_entry_cb
{
709 * Handle one reference in a do_for_each_ref*()-style iteration,
710 * calling an each_ref_fn for each entry.
712 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
714 struct ref_entry_cb
*data
= cb_data
;
715 struct ref_entry
*old_current_ref
;
718 if (!starts_with(entry
->name
, data
->base
))
721 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
722 !ref_resolves_to_object(entry
))
725 /* Store the old value, in case this is a recursive call: */
726 old_current_ref
= current_ref
;
728 retval
= data
->fn(entry
->name
+ data
->trim
, entry
->u
.value
.sha1
,
729 entry
->flag
, data
->cb_data
);
730 current_ref
= old_current_ref
;
735 * Call fn for each reference in dir that has index in the range
736 * offset <= index < dir->nr. Recurse into subdirectories that are in
737 * that index range, sorting them before iterating. This function
738 * does not sort dir itself; it should be sorted beforehand. fn is
739 * called for all references, including broken ones.
741 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
742 each_ref_entry_fn fn
, void *cb_data
)
745 assert(dir
->sorted
== dir
->nr
);
746 for (i
= offset
; i
< dir
->nr
; i
++) {
747 struct ref_entry
*entry
= dir
->entries
[i
];
749 if (entry
->flag
& REF_DIR
) {
750 struct ref_dir
*subdir
= get_ref_dir(entry
);
751 sort_ref_dir(subdir
);
752 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
754 retval
= fn(entry
, cb_data
);
763 * Call fn for each reference in the union of dir1 and dir2, in order
764 * by refname. Recurse into subdirectories. If a value entry appears
765 * in both dir1 and dir2, then only process the version that is in
766 * dir2. The input dirs must already be sorted, but subdirs will be
767 * sorted as needed. fn is called for all references, including
770 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
771 struct ref_dir
*dir2
,
772 each_ref_entry_fn fn
, void *cb_data
)
777 assert(dir1
->sorted
== dir1
->nr
);
778 assert(dir2
->sorted
== dir2
->nr
);
780 struct ref_entry
*e1
, *e2
;
782 if (i1
== dir1
->nr
) {
783 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
785 if (i2
== dir2
->nr
) {
786 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
788 e1
= dir1
->entries
[i1
];
789 e2
= dir2
->entries
[i2
];
790 cmp
= strcmp(e1
->name
, e2
->name
);
792 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
793 /* Both are directories; descend them in parallel. */
794 struct ref_dir
*subdir1
= get_ref_dir(e1
);
795 struct ref_dir
*subdir2
= get_ref_dir(e2
);
796 sort_ref_dir(subdir1
);
797 sort_ref_dir(subdir2
);
798 retval
= do_for_each_entry_in_dirs(
799 subdir1
, subdir2
, fn
, cb_data
);
802 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
803 /* Both are references; ignore the one from dir1. */
804 retval
= fn(e2
, cb_data
);
808 die("conflict between reference and directory: %s",
820 if (e
->flag
& REF_DIR
) {
821 struct ref_dir
*subdir
= get_ref_dir(e
);
822 sort_ref_dir(subdir
);
823 retval
= do_for_each_entry_in_dir(
824 subdir
, 0, fn
, cb_data
);
826 retval
= fn(e
, cb_data
);
835 * Load all of the refs from the dir into our in-memory cache. The hard work
836 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
837 * through all of the sub-directories. We do not even need to care about
838 * sorting, as traversal order does not matter to us.
840 static void prime_ref_dir(struct ref_dir
*dir
)
843 for (i
= 0; i
< dir
->nr
; i
++) {
844 struct ref_entry
*entry
= dir
->entries
[i
];
845 if (entry
->flag
& REF_DIR
)
846 prime_ref_dir(get_ref_dir(entry
));
850 struct nonmatching_ref_data
{
851 const struct string_list
*skip
;
852 const char *conflicting_refname
;
855 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
857 struct nonmatching_ref_data
*data
= vdata
;
859 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
862 data
->conflicting_refname
= entry
->name
;
867 * Return 0 if a reference named refname could be created without
868 * conflicting with the name of an existing reference in dir.
869 * Otherwise, return a negative value and write an explanation to err.
870 * If extras is non-NULL, it is a list of additional refnames with
871 * which refname is not allowed to conflict. If skip is non-NULL,
872 * ignore potential conflicts with refs in skip (e.g., because they
873 * are scheduled for deletion in the same operation). Behavior is
874 * undefined if the same name is listed in both extras and skip.
876 * Two reference names conflict if one of them exactly matches the
877 * leading components of the other; e.g., "refs/foo/bar" conflicts
878 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
879 * "refs/foo/bar" or "refs/foo/barbados".
881 * extras and skip must be sorted.
883 static int verify_refname_available(const char *refname
,
884 const struct string_list
*extras
,
885 const struct string_list
*skip
,
891 struct strbuf dirname
= STRBUF_INIT
;
895 * For the sake of comments in this function, suppose that
896 * refname is "refs/foo/bar".
901 strbuf_grow(&dirname
, strlen(refname
) + 1);
902 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
903 /* Expand dirname to the new prefix, not including the trailing slash: */
904 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
907 * We are still at a leading dir of the refname (e.g.,
908 * "refs/foo"; if there is a reference with that name,
909 * it is a conflict, *unless* it is in skip.
912 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
914 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
916 * We found a reference whose name is
917 * a proper prefix of refname; e.g.,
918 * "refs/foo", and is not in skip.
920 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
921 dirname
.buf
, refname
);
926 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
927 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
928 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
929 refname
, dirname
.buf
);
934 * Otherwise, we can try to continue our search with
935 * the next component. So try to look up the
936 * directory, e.g., "refs/foo/". If we come up empty,
937 * we know there is nothing under this whole prefix,
938 * but even in that case we still have to continue the
939 * search for conflicts with extras.
941 strbuf_addch(&dirname
, '/');
943 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
946 * There was no directory "refs/foo/",
947 * so there is nothing under this
948 * whole prefix. So there is no need
949 * to continue looking for conflicting
950 * references. But we need to continue
951 * looking for conflicting extras.
955 dir
= get_ref_dir(dir
->entries
[pos
]);
961 * We are at the leaf of our refname (e.g., "refs/foo/bar").
962 * There is no point in searching for a reference with that
963 * name, because a refname isn't considered to conflict with
964 * itself. But we still need to check for references whose
965 * names are in the "refs/foo/bar/" namespace, because they
968 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
969 strbuf_addch(&dirname
, '/');
972 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
976 * We found a directory named "$refname/"
977 * (e.g., "refs/foo/bar/"). It is a problem
978 * iff it contains any ref that is not in
981 struct nonmatching_ref_data data
;
984 data
.conflicting_refname
= NULL
;
985 dir
= get_ref_dir(dir
->entries
[pos
]);
987 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
988 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
989 data
.conflicting_refname
, refname
);
997 * Check for entries in extras that start with
998 * "$refname/". We do that by looking for the place
999 * where "$refname/" would be inserted in extras. If
1000 * there is an entry at that position that starts with
1001 * "$refname/" and is not in skip, then we have a
1004 for (pos
= string_list_find_insert_index(extras
, dirname
.buf
, 0);
1005 pos
< extras
->nr
; pos
++) {
1006 const char *extra_refname
= extras
->items
[pos
].string
;
1008 if (!starts_with(extra_refname
, dirname
.buf
))
1011 if (!skip
|| !string_list_has_string(skip
, extra_refname
)) {
1012 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
1013 refname
, extra_refname
);
1019 /* No conflicts were found */
1023 strbuf_release(&dirname
);
1027 struct packed_ref_cache
{
1028 struct ref_entry
*root
;
1031 * Count of references to the data structure in this instance,
1032 * including the pointer from ref_cache::packed if any. The
1033 * data will not be freed as long as the reference count is
1036 unsigned int referrers
;
1039 * Iff the packed-refs file associated with this instance is
1040 * currently locked for writing, this points at the associated
1041 * lock (which is owned by somebody else). The referrer count
1042 * is also incremented when the file is locked and decremented
1043 * when it is unlocked.
1045 struct lock_file
*lock
;
1047 /* The metadata from when this packed-refs cache was read */
1048 struct stat_validity validity
;
1052 * Future: need to be in "struct repository"
1053 * when doing a full libification.
1055 static struct ref_cache
{
1056 struct ref_cache
*next
;
1057 struct ref_entry
*loose
;
1058 struct packed_ref_cache
*packed
;
1060 * The submodule name, or "" for the main repo. We allocate
1061 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1062 * is initialized correctly.
1065 } ref_cache
, *submodule_ref_caches
;
1067 /* Lock used for the main packed-refs file: */
1068 static struct lock_file packlock
;
1071 * Increment the reference count of *packed_refs.
1073 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1075 packed_refs
->referrers
++;
1079 * Decrease the reference count of *packed_refs. If it goes to zero,
1080 * free *packed_refs and return true; otherwise return false.
1082 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1084 if (!--packed_refs
->referrers
) {
1085 free_ref_entry(packed_refs
->root
);
1086 stat_validity_clear(&packed_refs
->validity
);
1094 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1097 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1099 if (packed_refs
->lock
)
1100 die("internal error: packed-ref cache cleared while locked");
1101 refs
->packed
= NULL
;
1102 release_packed_ref_cache(packed_refs
);
1106 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1109 free_ref_entry(refs
->loose
);
1114 static struct ref_cache
*create_ref_cache(const char *submodule
)
1117 struct ref_cache
*refs
;
1120 len
= strlen(submodule
) + 1;
1121 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1122 memcpy(refs
->name
, submodule
, len
);
1127 * Return a pointer to a ref_cache for the specified submodule. For
1128 * the main repository, use submodule==NULL. The returned structure
1129 * will be allocated and initialized but not necessarily populated; it
1130 * should not be freed.
1132 static struct ref_cache
*get_ref_cache(const char *submodule
)
1134 struct ref_cache
*refs
;
1136 if (!submodule
|| !*submodule
)
1139 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1140 if (!strcmp(submodule
, refs
->name
))
1143 refs
= create_ref_cache(submodule
);
1144 refs
->next
= submodule_ref_caches
;
1145 submodule_ref_caches
= refs
;
1149 /* The length of a peeled reference line in packed-refs, including EOL: */
1150 #define PEELED_LINE_LENGTH 42
1153 * The packed-refs header line that we write out. Perhaps other
1154 * traits will be added later. The trailing space is required.
1156 static const char PACKED_REFS_HEADER
[] =
1157 "# pack-refs with: peeled fully-peeled \n";
1160 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1161 * Return a pointer to the refname within the line (null-terminated),
1162 * or NULL if there was a problem.
1164 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1169 * 42: the answer to everything.
1171 * In this case, it happens to be the answer to
1172 * 40 (length of sha1 hex representation)
1173 * +1 (space in between hex and name)
1174 * +1 (newline at the end of the line)
1176 if (line
->len
<= 42)
1179 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1181 if (!isspace(line
->buf
[40]))
1184 ref
= line
->buf
+ 41;
1188 if (line
->buf
[line
->len
- 1] != '\n')
1190 line
->buf
[--line
->len
] = 0;
1196 * Read f, which is a packed-refs file, into dir.
1198 * A comment line of the form "# pack-refs with: " may contain zero or
1199 * more traits. We interpret the traits as follows:
1203 * Probably no references are peeled. But if the file contains a
1204 * peeled value for a reference, we will use it.
1208 * References under "refs/tags/", if they *can* be peeled, *are*
1209 * peeled in this file. References outside of "refs/tags/" are
1210 * probably not peeled even if they could have been, but if we find
1211 * a peeled value for such a reference we will use it.
1215 * All references in the file that can be peeled are peeled.
1216 * Inversely (and this is more important), any references in the
1217 * file for which no peeled value is recorded is not peelable. This
1218 * trait should typically be written alongside "peeled" for
1219 * compatibility with older clients, but we do not require it
1220 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1222 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1224 struct ref_entry
*last
= NULL
;
1225 struct strbuf line
= STRBUF_INIT
;
1226 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1228 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1229 unsigned char sha1
[20];
1230 const char *refname
;
1233 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1234 if (strstr(traits
, " fully-peeled "))
1235 peeled
= PEELED_FULLY
;
1236 else if (strstr(traits
, " peeled "))
1237 peeled
= PEELED_TAGS
;
1238 /* perhaps other traits later as well */
1242 refname
= parse_ref_line(&line
, sha1
);
1244 int flag
= REF_ISPACKED
;
1246 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1248 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1250 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1251 if (peeled
== PEELED_FULLY
||
1252 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1253 last
->flag
|= REF_KNOWS_PEELED
;
1258 line
.buf
[0] == '^' &&
1259 line
.len
== PEELED_LINE_LENGTH
&&
1260 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1261 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1262 hashcpy(last
->u
.value
.peeled
, sha1
);
1264 * Regardless of what the file header said,
1265 * we definitely know the value of *this*
1268 last
->flag
|= REF_KNOWS_PEELED
;
1272 strbuf_release(&line
);
1276 * Get the packed_ref_cache for the specified ref_cache, creating it
1279 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1281 const char *packed_refs_file
;
1284 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1286 packed_refs_file
= git_path("packed-refs");
1289 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1290 clear_packed_ref_cache(refs
);
1292 if (!refs
->packed
) {
1295 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1296 acquire_packed_ref_cache(refs
->packed
);
1297 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1298 f
= fopen(packed_refs_file
, "r");
1300 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1301 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1305 return refs
->packed
;
1308 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1310 return get_ref_dir(packed_ref_cache
->root
);
1313 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1315 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1318 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1320 struct packed_ref_cache
*packed_ref_cache
=
1321 get_packed_ref_cache(&ref_cache
);
1323 if (!packed_ref_cache
->lock
)
1324 die("internal error: packed refs not locked");
1325 add_ref(get_packed_ref_dir(packed_ref_cache
),
1326 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1330 * Read the loose references from the namespace dirname into dir
1331 * (without recursing). dirname must end with '/'. dir must be the
1332 * directory entry corresponding to dirname.
1334 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1336 struct ref_cache
*refs
= dir
->ref_cache
;
1340 int dirnamelen
= strlen(dirname
);
1341 struct strbuf refname
;
1344 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1346 path
= git_path("%s", dirname
);
1352 strbuf_init(&refname
, dirnamelen
+ 257);
1353 strbuf_add(&refname
, dirname
, dirnamelen
);
1355 while ((de
= readdir(d
)) != NULL
) {
1356 unsigned char sha1
[20];
1361 if (de
->d_name
[0] == '.')
1363 if (ends_with(de
->d_name
, ".lock"))
1365 strbuf_addstr(&refname
, de
->d_name
);
1366 refdir
= *refs
->name
1367 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1368 : git_path("%s", refname
.buf
);
1369 if (stat(refdir
, &st
) < 0) {
1370 ; /* silently ignore */
1371 } else if (S_ISDIR(st
.st_mode
)) {
1372 strbuf_addch(&refname
, '/');
1373 add_entry_to_dir(dir
,
1374 create_dir_entry(refs
, refname
.buf
,
1382 read_ok
= !resolve_gitlink_ref(refs
->name
,
1385 read_ok
= !read_ref_full(refname
.buf
,
1386 RESOLVE_REF_READING
,
1392 flag
|= REF_ISBROKEN
;
1393 } else if (is_null_sha1(sha1
)) {
1395 * It is so astronomically unlikely
1396 * that NULL_SHA1 is the SHA-1 of an
1397 * actual object that we consider its
1398 * appearance in a loose reference
1399 * file to be repo corruption
1400 * (probably due to a software bug).
1402 flag
|= REF_ISBROKEN
;
1405 if (check_refname_format(refname
.buf
,
1406 REFNAME_ALLOW_ONELEVEL
)) {
1408 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1410 add_entry_to_dir(dir
,
1411 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1413 strbuf_setlen(&refname
, dirnamelen
);
1415 strbuf_release(&refname
);
1419 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1423 * Mark the top-level directory complete because we
1424 * are about to read the only subdirectory that can
1427 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1429 * Create an incomplete entry for "refs/":
1431 add_entry_to_dir(get_ref_dir(refs
->loose
),
1432 create_dir_entry(refs
, "refs/", 5, 1));
1434 return get_ref_dir(refs
->loose
);
1437 /* We allow "recursive" symbolic refs. Only within reason, though */
1439 #define MAXREFLEN (1024)
1442 * Called by resolve_gitlink_ref_recursive() after it failed to read
1443 * from the loose refs in ref_cache refs. Find <refname> in the
1444 * packed-refs file for the submodule.
1446 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1447 const char *refname
, unsigned char *sha1
)
1449 struct ref_entry
*ref
;
1450 struct ref_dir
*dir
= get_packed_refs(refs
);
1452 ref
= find_ref(dir
, refname
);
1456 hashcpy(sha1
, ref
->u
.value
.sha1
);
1460 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1461 const char *refname
, unsigned char *sha1
,
1465 char buffer
[128], *p
;
1468 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1471 ? git_path_submodule(refs
->name
, "%s", refname
)
1472 : git_path("%s", refname
);
1473 fd
= open(path
, O_RDONLY
);
1475 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1477 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1481 while (len
&& isspace(buffer
[len
-1]))
1485 /* Was it a detached head or an old-fashioned symlink? */
1486 if (!get_sha1_hex(buffer
, sha1
))
1490 if (strncmp(buffer
, "ref:", 4))
1496 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1499 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1501 int len
= strlen(path
), retval
;
1503 struct ref_cache
*refs
;
1505 while (len
&& path
[len
-1] == '/')
1509 submodule
= xstrndup(path
, len
);
1510 refs
= get_ref_cache(submodule
);
1513 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1518 * Return the ref_entry for the given refname from the packed
1519 * references. If it does not exist, return NULL.
1521 static struct ref_entry
*get_packed_ref(const char *refname
)
1523 return find_ref(get_packed_refs(&ref_cache
), refname
);
1527 * A loose ref file doesn't exist; check for a packed ref. The
1528 * options are forwarded from resolve_safe_unsafe().
1530 static int resolve_missing_loose_ref(const char *refname
,
1532 unsigned char *sha1
,
1535 struct ref_entry
*entry
;
1538 * The loose reference file does not exist; check for a packed
1541 entry
= get_packed_ref(refname
);
1543 hashcpy(sha1
, entry
->u
.value
.sha1
);
1545 *flags
|= REF_ISPACKED
;
1548 /* The reference is not a packed reference, either. */
1549 if (resolve_flags
& RESOLVE_REF_READING
) {
1558 /* This function needs to return a meaningful errno on failure */
1559 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1561 int depth
= MAXDEPTH
;
1564 static char refname_buffer
[256];
1570 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1572 *flags
|= REF_BAD_NAME
;
1574 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1575 !refname_is_safe(refname
)) {
1580 * dwim_ref() uses REF_ISBROKEN to distinguish between
1581 * missing refs and refs that were present but invalid,
1582 * to complain about the latter to stderr.
1584 * We don't know whether the ref exists, so don't set
1590 char path
[PATH_MAX
];
1600 git_snpath(path
, sizeof(path
), "%s", refname
);
1603 * We might have to loop back here to avoid a race
1604 * condition: first we lstat() the file, then we try
1605 * to read it as a link or as a file. But if somebody
1606 * changes the type of the file (file <-> directory
1607 * <-> symlink) between the lstat() and reading, then
1608 * we don't want to report that as an error but rather
1609 * try again starting with the lstat().
1612 if (lstat(path
, &st
) < 0) {
1613 if (errno
!= ENOENT
)
1615 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1621 *flags
|= REF_ISBROKEN
;
1626 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1627 if (S_ISLNK(st
.st_mode
)) {
1628 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1630 if (errno
== ENOENT
|| errno
== EINVAL
)
1631 /* inconsistent with lstat; retry */
1637 if (starts_with(buffer
, "refs/") &&
1638 !check_refname_format(buffer
, 0)) {
1639 strcpy(refname_buffer
, buffer
);
1640 refname
= refname_buffer
;
1642 *flags
|= REF_ISSYMREF
;
1643 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1651 /* Is it a directory? */
1652 if (S_ISDIR(st
.st_mode
)) {
1658 * Anything else, just open it and try to use it as
1661 fd
= open(path
, O_RDONLY
);
1663 if (errno
== ENOENT
)
1664 /* inconsistent with lstat; retry */
1669 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1671 int save_errno
= errno
;
1677 while (len
&& isspace(buffer
[len
-1]))
1682 * Is it a symbolic ref?
1684 if (!starts_with(buffer
, "ref:")) {
1686 * Please note that FETCH_HEAD has a second
1687 * line containing other data.
1689 if (get_sha1_hex(buffer
, sha1
) ||
1690 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1692 *flags
|= REF_ISBROKEN
;
1699 *flags
|= REF_ISBROKEN
;
1704 *flags
|= REF_ISSYMREF
;
1706 while (isspace(*buf
))
1708 refname
= strcpy(refname_buffer
, buf
);
1709 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1713 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1715 *flags
|= REF_ISBROKEN
;
1717 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1718 !refname_is_safe(buf
)) {
1727 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1729 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1732 /* The argument to filter_refs */
1734 const char *pattern
;
1739 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1741 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1746 int read_ref(const char *refname
, unsigned char *sha1
)
1748 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1751 int ref_exists(const char *refname
)
1753 unsigned char sha1
[20];
1754 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1757 static int filter_refs(const char *refname
, const unsigned char *sha1
, int flags
,
1760 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1761 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1763 return filter
->fn(refname
, sha1
, flags
, filter
->cb_data
);
1767 /* object was peeled successfully: */
1771 * object cannot be peeled because the named object (or an
1772 * object referred to by a tag in the peel chain), does not
1777 /* object cannot be peeled because it is not a tag: */
1780 /* ref_entry contains no peeled value because it is a symref: */
1781 PEEL_IS_SYMREF
= -3,
1784 * ref_entry cannot be peeled because it is broken (i.e., the
1785 * symbolic reference cannot even be resolved to an object
1792 * Peel the named object; i.e., if the object is a tag, resolve the
1793 * tag recursively until a non-tag is found. If successful, store the
1794 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1795 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1796 * and leave sha1 unchanged.
1798 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1800 struct object
*o
= lookup_unknown_object(name
);
1802 if (o
->type
== OBJ_NONE
) {
1803 int type
= sha1_object_info(name
, NULL
);
1804 if (type
< 0 || !object_as_type(o
, type
, 0))
1805 return PEEL_INVALID
;
1808 if (o
->type
!= OBJ_TAG
)
1809 return PEEL_NON_TAG
;
1811 o
= deref_tag_noverify(o
);
1813 return PEEL_INVALID
;
1815 hashcpy(sha1
, o
->sha1
);
1820 * Peel the entry (if possible) and return its new peel_status. If
1821 * repeel is true, re-peel the entry even if there is an old peeled
1822 * value that is already stored in it.
1824 * It is OK to call this function with a packed reference entry that
1825 * might be stale and might even refer to an object that has since
1826 * been garbage-collected. In such a case, if the entry has
1827 * REF_KNOWS_PEELED then leave the status unchanged and return
1828 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1830 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1832 enum peel_status status
;
1834 if (entry
->flag
& REF_KNOWS_PEELED
) {
1836 entry
->flag
&= ~REF_KNOWS_PEELED
;
1837 hashclr(entry
->u
.value
.peeled
);
1839 return is_null_sha1(entry
->u
.value
.peeled
) ?
1840 PEEL_NON_TAG
: PEEL_PEELED
;
1843 if (entry
->flag
& REF_ISBROKEN
)
1845 if (entry
->flag
& REF_ISSYMREF
)
1846 return PEEL_IS_SYMREF
;
1848 status
= peel_object(entry
->u
.value
.sha1
, entry
->u
.value
.peeled
);
1849 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1850 entry
->flag
|= REF_KNOWS_PEELED
;
1854 int peel_ref(const char *refname
, unsigned char *sha1
)
1857 unsigned char base
[20];
1859 if (current_ref
&& (current_ref
->name
== refname
1860 || !strcmp(current_ref
->name
, refname
))) {
1861 if (peel_entry(current_ref
, 0))
1863 hashcpy(sha1
, current_ref
->u
.value
.peeled
);
1867 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1871 * If the reference is packed, read its ref_entry from the
1872 * cache in the hope that we already know its peeled value.
1873 * We only try this optimization on packed references because
1874 * (a) forcing the filling of the loose reference cache could
1875 * be expensive and (b) loose references anyway usually do not
1876 * have REF_KNOWS_PEELED.
1878 if (flag
& REF_ISPACKED
) {
1879 struct ref_entry
*r
= get_packed_ref(refname
);
1881 if (peel_entry(r
, 0))
1883 hashcpy(sha1
, r
->u
.value
.peeled
);
1888 return peel_object(base
, sha1
);
1891 struct warn_if_dangling_data
{
1893 const char *refname
;
1894 const struct string_list
*refnames
;
1895 const char *msg_fmt
;
1898 static int warn_if_dangling_symref(const char *refname
, const unsigned char *sha1
,
1899 int flags
, void *cb_data
)
1901 struct warn_if_dangling_data
*d
= cb_data
;
1902 const char *resolves_to
;
1903 unsigned char junk
[20];
1905 if (!(flags
& REF_ISSYMREF
))
1908 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
, NULL
);
1911 ? strcmp(resolves_to
, d
->refname
)
1912 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1916 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1921 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1923 struct warn_if_dangling_data data
;
1926 data
.refname
= refname
;
1927 data
.refnames
= NULL
;
1928 data
.msg_fmt
= msg_fmt
;
1929 for_each_rawref(warn_if_dangling_symref
, &data
);
1932 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1934 struct warn_if_dangling_data data
;
1937 data
.refname
= NULL
;
1938 data
.refnames
= refnames
;
1939 data
.msg_fmt
= msg_fmt
;
1940 for_each_rawref(warn_if_dangling_symref
, &data
);
1944 * Call fn for each reference in the specified ref_cache, omitting
1945 * references not in the containing_dir of base. fn is called for all
1946 * references, including broken ones. If fn ever returns a non-zero
1947 * value, stop the iteration and return that value; otherwise, return
1950 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1951 each_ref_entry_fn fn
, void *cb_data
)
1953 struct packed_ref_cache
*packed_ref_cache
;
1954 struct ref_dir
*loose_dir
;
1955 struct ref_dir
*packed_dir
;
1959 * We must make sure that all loose refs are read before accessing the
1960 * packed-refs file; this avoids a race condition in which loose refs
1961 * are migrated to the packed-refs file by a simultaneous process, but
1962 * our in-memory view is from before the migration. get_packed_ref_cache()
1963 * takes care of making sure our view is up to date with what is on
1966 loose_dir
= get_loose_refs(refs
);
1967 if (base
&& *base
) {
1968 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1971 prime_ref_dir(loose_dir
);
1973 packed_ref_cache
= get_packed_ref_cache(refs
);
1974 acquire_packed_ref_cache(packed_ref_cache
);
1975 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1976 if (base
&& *base
) {
1977 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
1980 if (packed_dir
&& loose_dir
) {
1981 sort_ref_dir(packed_dir
);
1982 sort_ref_dir(loose_dir
);
1983 retval
= do_for_each_entry_in_dirs(
1984 packed_dir
, loose_dir
, fn
, cb_data
);
1985 } else if (packed_dir
) {
1986 sort_ref_dir(packed_dir
);
1987 retval
= do_for_each_entry_in_dir(
1988 packed_dir
, 0, fn
, cb_data
);
1989 } else if (loose_dir
) {
1990 sort_ref_dir(loose_dir
);
1991 retval
= do_for_each_entry_in_dir(
1992 loose_dir
, 0, fn
, cb_data
);
1995 release_packed_ref_cache(packed_ref_cache
);
2000 * Call fn for each reference in the specified ref_cache for which the
2001 * refname begins with base. If trim is non-zero, then trim that many
2002 * characters off the beginning of each refname before passing the
2003 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2004 * broken references in the iteration. If fn ever returns a non-zero
2005 * value, stop the iteration and return that value; otherwise, return
2008 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
2009 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
2011 struct ref_entry_cb data
;
2016 data
.cb_data
= cb_data
;
2018 if (ref_paranoia
< 0)
2019 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2021 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2023 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
2026 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2028 unsigned char sha1
[20];
2032 if (resolve_gitlink_ref(submodule
, "HEAD", sha1
) == 0)
2033 return fn("HEAD", sha1
, 0, cb_data
);
2038 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, sha1
, &flag
))
2039 return fn("HEAD", sha1
, flag
, cb_data
);
2044 int head_ref(each_ref_fn fn
, void *cb_data
)
2046 return do_head_ref(NULL
, fn
, cb_data
);
2049 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2051 return do_head_ref(submodule
, fn
, cb_data
);
2054 int for_each_ref(each_ref_fn fn
, void *cb_data
)
2056 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
2059 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2061 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2064 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2066 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2069 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2070 each_ref_fn fn
, void *cb_data
)
2072 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2075 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2077 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2080 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2082 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2085 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2087 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2090 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2092 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2095 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2097 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2100 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2102 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2105 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2107 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2110 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2112 struct strbuf buf
= STRBUF_INIT
;
2114 unsigned char sha1
[20];
2117 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2118 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, sha1
, &flag
))
2119 ret
= fn(buf
.buf
, sha1
, flag
, cb_data
);
2120 strbuf_release(&buf
);
2125 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2127 struct strbuf buf
= STRBUF_INIT
;
2129 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2130 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2131 strbuf_release(&buf
);
2135 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2136 const char *prefix
, void *cb_data
)
2138 struct strbuf real_pattern
= STRBUF_INIT
;
2139 struct ref_filter filter
;
2142 if (!prefix
&& !starts_with(pattern
, "refs/"))
2143 strbuf_addstr(&real_pattern
, "refs/");
2145 strbuf_addstr(&real_pattern
, prefix
);
2146 strbuf_addstr(&real_pattern
, pattern
);
2148 if (!has_glob_specials(pattern
)) {
2149 /* Append implied '/' '*' if not present. */
2150 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2151 strbuf_addch(&real_pattern
, '/');
2152 /* No need to check for '*', there is none. */
2153 strbuf_addch(&real_pattern
, '*');
2156 filter
.pattern
= real_pattern
.buf
;
2158 filter
.cb_data
= cb_data
;
2159 ret
= for_each_ref(filter_refs
, &filter
);
2161 strbuf_release(&real_pattern
);
2165 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2167 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2170 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2172 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2173 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2176 const char *prettify_refname(const char *name
)
2179 starts_with(name
, "refs/heads/") ? 11 :
2180 starts_with(name
, "refs/tags/") ? 10 :
2181 starts_with(name
, "refs/remotes/") ? 13 :
2185 static const char *ref_rev_parse_rules
[] = {
2190 "refs/remotes/%.*s",
2191 "refs/remotes/%.*s/HEAD",
2195 int refname_match(const char *abbrev_name
, const char *full_name
)
2198 const int abbrev_name_len
= strlen(abbrev_name
);
2200 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2201 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2209 static void unlock_ref(struct ref_lock
*lock
)
2211 /* Do not free lock->lk -- atexit() still looks at them */
2213 rollback_lock_file(lock
->lk
);
2214 free(lock
->ref_name
);
2215 free(lock
->orig_ref_name
);
2219 /* This function should make sure errno is meaningful on error */
2220 static struct ref_lock
*verify_lock(struct ref_lock
*lock
,
2221 const unsigned char *old_sha1
, int mustexist
)
2223 if (read_ref_full(lock
->ref_name
,
2224 mustexist
? RESOLVE_REF_READING
: 0,
2225 lock
->old_sha1
, NULL
)) {
2226 int save_errno
= errno
;
2227 error("Can't verify ref %s", lock
->ref_name
);
2232 if (hashcmp(lock
->old_sha1
, old_sha1
)) {
2233 error("Ref %s is at %s but expected %s", lock
->ref_name
,
2234 sha1_to_hex(lock
->old_sha1
), sha1_to_hex(old_sha1
));
2242 static int remove_empty_directories(const char *file
)
2244 /* we want to create a file but there is a directory there;
2245 * if that is an empty directory (or a directory that contains
2246 * only empty directories), remove them.
2249 int result
, save_errno
;
2251 strbuf_init(&path
, 20);
2252 strbuf_addstr(&path
, file
);
2254 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2257 strbuf_release(&path
);
2264 * *string and *len will only be substituted, and *string returned (for
2265 * later free()ing) if the string passed in is a magic short-hand form
2268 static char *substitute_branch_name(const char **string
, int *len
)
2270 struct strbuf buf
= STRBUF_INIT
;
2271 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2275 *string
= strbuf_detach(&buf
, &size
);
2277 return (char *)*string
;
2283 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2285 char *last_branch
= substitute_branch_name(&str
, &len
);
2290 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2291 char fullref
[PATH_MAX
];
2292 unsigned char sha1_from_ref
[20];
2293 unsigned char *this_result
;
2296 this_result
= refs_found
? sha1_from_ref
: sha1
;
2297 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2298 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2299 this_result
, &flag
);
2303 if (!warn_ambiguous_refs
)
2305 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2306 warning("ignoring dangling symref %s.", fullref
);
2307 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2308 warning("ignoring broken ref %s.", fullref
);
2315 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2317 char *last_branch
= substitute_branch_name(&str
, &len
);
2322 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2323 unsigned char hash
[20];
2324 char path
[PATH_MAX
];
2325 const char *ref
, *it
;
2327 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2328 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2332 if (reflog_exists(path
))
2334 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2338 if (!logs_found
++) {
2340 hashcpy(sha1
, hash
);
2342 if (!warn_ambiguous_refs
)
2350 * Locks a ref returning the lock on success and NULL on failure.
2351 * On failure errno is set to something meaningful.
2353 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2354 const unsigned char *old_sha1
,
2355 const struct string_list
*extras
,
2356 const struct string_list
*skip
,
2357 unsigned int flags
, int *type_p
,
2361 const char *orig_refname
= refname
;
2362 struct ref_lock
*lock
;
2365 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2366 int resolve_flags
= 0;
2367 int attempts_remaining
= 3;
2371 lock
= xcalloc(1, sizeof(struct ref_lock
));
2375 resolve_flags
|= RESOLVE_REF_READING
;
2376 if (flags
& REF_DELETING
) {
2377 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2378 if (flags
& REF_NODEREF
)
2379 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2382 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2383 lock
->old_sha1
, &type
);
2384 if (!refname
&& errno
== EISDIR
) {
2385 /* we are trying to lock foo but we used to
2386 * have foo/bar which now does not exist;
2387 * it is normal for the empty directory 'foo'
2390 ref_file
= git_path("%s", orig_refname
);
2391 if (remove_empty_directories(ref_file
)) {
2394 if (!verify_refname_available(orig_refname
, extras
, skip
,
2395 get_loose_refs(&ref_cache
), err
))
2396 strbuf_addf(err
, "there are still refs under '%s'",
2401 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2402 lock
->old_sha1
, &type
);
2408 if (last_errno
!= ENOTDIR
||
2409 !verify_refname_available(orig_refname
, extras
, skip
,
2410 get_loose_refs(&ref_cache
), err
))
2411 strbuf_addf(err
, "unable to resolve reference %s: %s",
2412 orig_refname
, strerror(last_errno
));
2417 * If the ref did not exist and we are creating it, make sure
2418 * there is no existing packed ref whose name begins with our
2419 * refname, nor a packed ref whose name is a proper prefix of
2422 if (is_null_sha1(lock
->old_sha1
) &&
2423 verify_refname_available(refname
, extras
, skip
,
2424 get_packed_refs(&ref_cache
), err
)) {
2425 last_errno
= ENOTDIR
;
2429 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2432 if (flags
& REF_NODEREF
) {
2433 refname
= orig_refname
;
2434 lflags
|= LOCK_NO_DEREF
;
2436 lock
->ref_name
= xstrdup(refname
);
2437 lock
->orig_ref_name
= xstrdup(orig_refname
);
2438 ref_file
= git_path("%s", refname
);
2441 switch (safe_create_leading_directories(ref_file
)) {
2443 break; /* success */
2445 if (--attempts_remaining
> 0)
2450 strbuf_addf(err
, "unable to create directory for %s", ref_file
);
2454 lock
->lock_fd
= hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
);
2455 if (lock
->lock_fd
< 0) {
2457 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2459 * Maybe somebody just deleted one of the
2460 * directories leading to ref_file. Try
2465 unable_to_lock_message(ref_file
, errno
, err
);
2469 return old_sha1
? verify_lock(lock
, old_sha1
, mustexist
) : lock
;
2478 * Write an entry to the packed-refs file for the specified refname.
2479 * If peeled is non-NULL, write it as the entry's peeled value.
2481 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2482 unsigned char *peeled
)
2484 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2486 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2490 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2492 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2494 enum peel_status peel_status
= peel_entry(entry
, 0);
2496 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2497 error("internal error: %s is not a valid packed reference!",
2499 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.sha1
,
2500 peel_status
== PEEL_PEELED
?
2501 entry
->u
.value
.peeled
: NULL
);
2505 /* This should return a meaningful errno on failure */
2506 int lock_packed_refs(int flags
)
2508 struct packed_ref_cache
*packed_ref_cache
;
2510 if (hold_lock_file_for_update(&packlock
, git_path("packed-refs"), flags
) < 0)
2513 * Get the current packed-refs while holding the lock. If the
2514 * packed-refs file has been modified since we last read it,
2515 * this will automatically invalidate the cache and re-read
2516 * the packed-refs file.
2518 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2519 packed_ref_cache
->lock
= &packlock
;
2520 /* Increment the reference count to prevent it from being freed: */
2521 acquire_packed_ref_cache(packed_ref_cache
);
2526 * Commit the packed refs changes.
2527 * On error we must make sure that errno contains a meaningful value.
2529 int commit_packed_refs(void)
2531 struct packed_ref_cache
*packed_ref_cache
=
2532 get_packed_ref_cache(&ref_cache
);
2537 if (!packed_ref_cache
->lock
)
2538 die("internal error: packed-refs not locked");
2540 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2542 die_errno("unable to fdopen packed-refs descriptor");
2544 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2545 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2546 0, write_packed_entry_fn
, out
);
2548 if (commit_lock_file(packed_ref_cache
->lock
)) {
2552 packed_ref_cache
->lock
= NULL
;
2553 release_packed_ref_cache(packed_ref_cache
);
2558 void rollback_packed_refs(void)
2560 struct packed_ref_cache
*packed_ref_cache
=
2561 get_packed_ref_cache(&ref_cache
);
2563 if (!packed_ref_cache
->lock
)
2564 die("internal error: packed-refs not locked");
2565 rollback_lock_file(packed_ref_cache
->lock
);
2566 packed_ref_cache
->lock
= NULL
;
2567 release_packed_ref_cache(packed_ref_cache
);
2568 clear_packed_ref_cache(&ref_cache
);
2571 struct ref_to_prune
{
2572 struct ref_to_prune
*next
;
2573 unsigned char sha1
[20];
2574 char name
[FLEX_ARRAY
];
2577 struct pack_refs_cb_data
{
2579 struct ref_dir
*packed_refs
;
2580 struct ref_to_prune
*ref_to_prune
;
2584 * An each_ref_entry_fn that is run over loose references only. If
2585 * the loose reference can be packed, add an entry in the packed ref
2586 * cache. If the reference should be pruned, also add it to
2587 * ref_to_prune in the pack_refs_cb_data.
2589 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2591 struct pack_refs_cb_data
*cb
= cb_data
;
2592 enum peel_status peel_status
;
2593 struct ref_entry
*packed_entry
;
2594 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2596 /* ALWAYS pack tags */
2597 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2600 /* Do not pack symbolic or broken refs: */
2601 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2604 /* Add a packed ref cache entry equivalent to the loose entry. */
2605 peel_status
= peel_entry(entry
, 1);
2606 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2607 die("internal error peeling reference %s (%s)",
2608 entry
->name
, sha1_to_hex(entry
->u
.value
.sha1
));
2609 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2611 /* Overwrite existing packed entry with info from loose entry */
2612 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2613 hashcpy(packed_entry
->u
.value
.sha1
, entry
->u
.value
.sha1
);
2615 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.sha1
,
2616 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2617 add_ref(cb
->packed_refs
, packed_entry
);
2619 hashcpy(packed_entry
->u
.value
.peeled
, entry
->u
.value
.peeled
);
2621 /* Schedule the loose reference for pruning if requested. */
2622 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2623 int namelen
= strlen(entry
->name
) + 1;
2624 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2625 hashcpy(n
->sha1
, entry
->u
.value
.sha1
);
2626 strcpy(n
->name
, entry
->name
);
2627 n
->next
= cb
->ref_to_prune
;
2628 cb
->ref_to_prune
= n
;
2634 * Remove empty parents, but spare refs/ and immediate subdirs.
2635 * Note: munges *name.
2637 static void try_remove_empty_parents(char *name
)
2642 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2643 while (*p
&& *p
!= '/')
2645 /* tolerate duplicate slashes; see check_refname_format() */
2649 for (q
= p
; *q
; q
++)
2652 while (q
> p
&& *q
!= '/')
2654 while (q
> p
&& *(q
-1) == '/')
2659 if (rmdir(git_path("%s", name
)))
2664 /* make sure nobody touched the ref, and unlink */
2665 static void prune_ref(struct ref_to_prune
*r
)
2667 struct ref_transaction
*transaction
;
2668 struct strbuf err
= STRBUF_INIT
;
2670 if (check_refname_format(r
->name
, 0))
2673 transaction
= ref_transaction_begin(&err
);
2675 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2676 REF_ISPRUNING
, NULL
, &err
) ||
2677 ref_transaction_commit(transaction
, &err
)) {
2678 ref_transaction_free(transaction
);
2679 error("%s", err
.buf
);
2680 strbuf_release(&err
);
2683 ref_transaction_free(transaction
);
2684 strbuf_release(&err
);
2685 try_remove_empty_parents(r
->name
);
2688 static void prune_refs(struct ref_to_prune
*r
)
2696 int pack_refs(unsigned int flags
)
2698 struct pack_refs_cb_data cbdata
;
2700 memset(&cbdata
, 0, sizeof(cbdata
));
2701 cbdata
.flags
= flags
;
2703 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2704 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2706 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2707 pack_if_possible_fn
, &cbdata
);
2709 if (commit_packed_refs())
2710 die_errno("unable to overwrite old ref-pack file");
2712 prune_refs(cbdata
.ref_to_prune
);
2716 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2718 struct ref_dir
*packed
;
2719 struct string_list_item
*refname
;
2720 int ret
, needs_repacking
= 0, removed
= 0;
2724 /* Look for a packed ref */
2725 for_each_string_list_item(refname
, refnames
) {
2726 if (get_packed_ref(refname
->string
)) {
2727 needs_repacking
= 1;
2732 /* Avoid locking if we have nothing to do */
2733 if (!needs_repacking
)
2734 return 0; /* no refname exists in packed refs */
2736 if (lock_packed_refs(0)) {
2737 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2740 packed
= get_packed_refs(&ref_cache
);
2742 /* Remove refnames from the cache */
2743 for_each_string_list_item(refname
, refnames
)
2744 if (remove_entry(packed
, refname
->string
) != -1)
2748 * All packed entries disappeared while we were
2749 * acquiring the lock.
2751 rollback_packed_refs();
2755 /* Write what remains */
2756 ret
= commit_packed_refs();
2758 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2763 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2767 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2769 * loose. The loose file name is the same as the
2770 * lockfile name, minus ".lock":
2772 char *loose_filename
= get_locked_file_path(lock
->lk
);
2773 int res
= unlink_or_msg(loose_filename
, err
);
2774 free(loose_filename
);
2781 int delete_ref(const char *refname
, const unsigned char *sha1
, unsigned int flags
)
2783 struct ref_transaction
*transaction
;
2784 struct strbuf err
= STRBUF_INIT
;
2786 transaction
= ref_transaction_begin(&err
);
2788 ref_transaction_delete(transaction
, refname
,
2789 (sha1
&& !is_null_sha1(sha1
)) ? sha1
: NULL
,
2790 flags
, NULL
, &err
) ||
2791 ref_transaction_commit(transaction
, &err
)) {
2792 error("%s", err
.buf
);
2793 ref_transaction_free(transaction
);
2794 strbuf_release(&err
);
2797 ref_transaction_free(transaction
);
2798 strbuf_release(&err
);
2803 * People using contrib's git-new-workdir have .git/logs/refs ->
2804 * /some/other/path/.git/logs/refs, and that may live on another device.
2806 * IOW, to avoid cross device rename errors, the temporary renamed log must
2807 * live into logs/refs.
2809 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2811 static int rename_tmp_log(const char *newrefname
)
2813 int attempts_remaining
= 4;
2816 switch (safe_create_leading_directories(git_path("logs/%s", newrefname
))) {
2818 break; /* success */
2820 if (--attempts_remaining
> 0)
2824 error("unable to create directory for %s", newrefname
);
2828 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2829 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2831 * rename(a, b) when b is an existing
2832 * directory ought to result in ISDIR, but
2833 * Solaris 5.8 gives ENOTDIR. Sheesh.
2835 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2836 error("Directory not empty: logs/%s", newrefname
);
2840 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2842 * Maybe another process just deleted one of
2843 * the directories in the path to newrefname.
2844 * Try again from the beginning.
2848 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2849 newrefname
, strerror(errno
));
2856 static int rename_ref_available(const char *oldname
, const char *newname
)
2858 struct string_list skip
= STRING_LIST_INIT_NODUP
;
2859 struct strbuf err
= STRBUF_INIT
;
2862 string_list_insert(&skip
, oldname
);
2863 ret
= !verify_refname_available(newname
, NULL
, &skip
,
2864 get_packed_refs(&ref_cache
), &err
)
2865 && !verify_refname_available(newname
, NULL
, &skip
,
2866 get_loose_refs(&ref_cache
), &err
);
2868 error("%s", err
.buf
);
2870 string_list_clear(&skip
, 0);
2871 strbuf_release(&err
);
2875 static int write_ref_to_lockfile(struct ref_lock
*lock
, const unsigned char *sha1
);
2876 static int commit_ref_update(struct ref_lock
*lock
,
2877 const unsigned char *sha1
, const char *logmsg
);
2879 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
2881 unsigned char sha1
[20], orig_sha1
[20];
2882 int flag
= 0, logmoved
= 0;
2883 struct ref_lock
*lock
;
2884 struct stat loginfo
;
2885 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
2886 const char *symref
= NULL
;
2887 struct strbuf err
= STRBUF_INIT
;
2889 if (log
&& S_ISLNK(loginfo
.st_mode
))
2890 return error("reflog for %s is a symlink", oldrefname
);
2892 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
2894 if (flag
& REF_ISSYMREF
)
2895 return error("refname %s is a symbolic ref, renaming it is not supported",
2898 return error("refname %s not found", oldrefname
);
2900 if (!rename_ref_available(oldrefname
, newrefname
))
2903 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
2904 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
2905 oldrefname
, strerror(errno
));
2907 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
2908 error("unable to delete old %s", oldrefname
);
2912 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
2913 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
2914 if (errno
==EISDIR
) {
2915 if (remove_empty_directories(git_path("%s", newrefname
))) {
2916 error("Directory not empty: %s", newrefname
);
2920 error("unable to delete existing %s", newrefname
);
2925 if (log
&& rename_tmp_log(newrefname
))
2930 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2932 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
2933 strbuf_release(&err
);
2936 hashcpy(lock
->old_sha1
, orig_sha1
);
2938 if (write_ref_to_lockfile(lock
, orig_sha1
) ||
2939 commit_ref_update(lock
, orig_sha1
, logmsg
)) {
2940 error("unable to write current sha1 into %s", newrefname
);
2947 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
2949 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
2950 strbuf_release(&err
);
2954 flag
= log_all_ref_updates
;
2955 log_all_ref_updates
= 0;
2956 if (write_ref_to_lockfile(lock
, orig_sha1
) ||
2957 commit_ref_update(lock
, orig_sha1
, NULL
))
2958 error("unable to write current sha1 into %s", oldrefname
);
2959 log_all_ref_updates
= flag
;
2962 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
2963 error("unable to restore logfile %s from %s: %s",
2964 oldrefname
, newrefname
, strerror(errno
));
2965 if (!logmoved
&& log
&&
2966 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
2967 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
2968 oldrefname
, strerror(errno
));
2973 static int close_ref(struct ref_lock
*lock
)
2975 if (close_lock_file(lock
->lk
))
2981 static int commit_ref(struct ref_lock
*lock
)
2983 if (commit_lock_file(lock
->lk
))
2990 * copy the reflog message msg to buf, which has been allocated sufficiently
2991 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2992 * because reflog file is one line per entry.
2994 static int copy_msg(char *buf
, const char *msg
)
3001 while ((c
= *msg
++)) {
3002 if (wasspace
&& isspace(c
))
3004 wasspace
= isspace(c
);
3009 while (buf
< cp
&& isspace(cp
[-1]))
3015 /* This function must set a meaningful errno on failure */
3016 int log_ref_setup(const char *refname
, char *logfile
, int bufsize
)
3018 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
3020 git_snpath(logfile
, bufsize
, "logs/%s", refname
);
3021 if (log_all_ref_updates
&&
3022 (starts_with(refname
, "refs/heads/") ||
3023 starts_with(refname
, "refs/remotes/") ||
3024 starts_with(refname
, "refs/notes/") ||
3025 !strcmp(refname
, "HEAD"))) {
3026 if (safe_create_leading_directories(logfile
) < 0) {
3027 int save_errno
= errno
;
3028 error("unable to create directory for %s", logfile
);
3035 logfd
= open(logfile
, oflags
, 0666);
3037 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3040 if (errno
== EISDIR
) {
3041 if (remove_empty_directories(logfile
)) {
3042 int save_errno
= errno
;
3043 error("There are still logs under '%s'",
3048 logfd
= open(logfile
, oflags
, 0666);
3052 int save_errno
= errno
;
3053 error("Unable to append to %s: %s", logfile
,
3060 adjust_shared_perm(logfile
);
3065 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3066 const unsigned char *new_sha1
,
3067 const char *committer
, const char *msg
)
3069 int msglen
, written
;
3070 unsigned maxlen
, len
;
3073 msglen
= msg
? strlen(msg
) : 0;
3074 maxlen
= strlen(committer
) + msglen
+ 100;
3075 logrec
= xmalloc(maxlen
);
3076 len
= sprintf(logrec
, "%s %s %s\n",
3077 sha1_to_hex(old_sha1
),
3078 sha1_to_hex(new_sha1
),
3081 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3083 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3091 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3092 const unsigned char *new_sha1
, const char *msg
)
3094 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3095 char log_file
[PATH_MAX
];
3097 if (log_all_ref_updates
< 0)
3098 log_all_ref_updates
= !is_bare_repository();
3100 result
= log_ref_setup(refname
, log_file
, sizeof(log_file
));
3104 logfd
= open(log_file
, oflags
);
3107 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3108 git_committer_info(0), msg
);
3110 int save_errno
= errno
;
3112 error("Unable to append to %s", log_file
);
3117 int save_errno
= errno
;
3118 error("Unable to append to %s", log_file
);
3125 int is_branch(const char *refname
)
3127 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3131 * Write sha1 into the open lockfile, then close the lockfile. On
3132 * errors, rollback the lockfile and set errno to reflect the problem.
3134 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3135 const unsigned char *sha1
)
3137 static char term
= '\n';
3140 o
= parse_object(sha1
);
3142 error("Trying to write ref %s with nonexistent object %s",
3143 lock
->ref_name
, sha1_to_hex(sha1
));
3148 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3149 error("Trying to write non-commit object %s to branch %s",
3150 sha1_to_hex(sha1
), lock
->ref_name
);
3155 if (write_in_full(lock
->lock_fd
, sha1_to_hex(sha1
), 40) != 40 ||
3156 write_in_full(lock
->lock_fd
, &term
, 1) != 1 ||
3157 close_ref(lock
) < 0) {
3158 int save_errno
= errno
;
3159 error("Couldn't write %s", lock
->lk
->filename
.buf
);
3168 * Commit a change to a loose reference that has already been written
3169 * to the loose reference lockfile. Also update the reflogs if
3170 * necessary, using the specified lockmsg (which can be NULL).
3172 static int commit_ref_update(struct ref_lock
*lock
,
3173 const unsigned char *sha1
, const char *logmsg
)
3175 clear_loose_ref_cache(&ref_cache
);
3176 if (log_ref_write(lock
->ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0 ||
3177 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3178 log_ref_write(lock
->orig_ref_name
, lock
->old_sha1
, sha1
, logmsg
) < 0)) {
3182 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3184 * Special hack: If a branch is updated directly and HEAD
3185 * points to it (may happen on the remote side of a push
3186 * for example) then logically the HEAD reflog should be
3188 * A generic solution implies reverse symref information,
3189 * but finding all symrefs pointing to the given branch
3190 * would be rather costly for this rare event (the direct
3191 * update of a branch) to be worth it. So let's cheat and
3192 * check with HEAD only which should cover 99% of all usage
3193 * scenarios (even 100% of the default ones).
3195 unsigned char head_sha1
[20];
3197 const char *head_ref
;
3198 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3199 head_sha1
, &head_flag
);
3200 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3201 !strcmp(head_ref
, lock
->ref_name
))
3202 log_ref_write("HEAD", lock
->old_sha1
, sha1
, logmsg
);
3204 if (commit_ref(lock
)) {
3205 error("Couldn't set %s", lock
->ref_name
);
3213 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3216 const char *lockpath
;
3218 int fd
, len
, written
;
3219 char *git_HEAD
= git_pathdup("%s", ref_target
);
3220 unsigned char old_sha1
[20], new_sha1
[20];
3222 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3225 if (safe_create_leading_directories(git_HEAD
) < 0)
3226 return error("unable to create directory for %s", git_HEAD
);
3228 #ifndef NO_SYMLINK_HEAD
3229 if (prefer_symlink_refs
) {
3231 if (!symlink(refs_heads_master
, git_HEAD
))
3233 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3237 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3238 if (sizeof(ref
) <= len
) {
3239 error("refname too long: %s", refs_heads_master
);
3240 goto error_free_return
;
3242 lockpath
= mkpath("%s.lock", git_HEAD
);
3243 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3245 error("Unable to open %s for writing", lockpath
);
3246 goto error_free_return
;
3248 written
= write_in_full(fd
, ref
, len
);
3249 if (close(fd
) != 0 || written
!= len
) {
3250 error("Unable to write to %s", lockpath
);
3251 goto error_unlink_return
;
3253 if (rename(lockpath
, git_HEAD
) < 0) {
3254 error("Unable to create %s", git_HEAD
);
3255 goto error_unlink_return
;
3257 if (adjust_shared_perm(git_HEAD
)) {
3258 error("Unable to fix permissions on %s", lockpath
);
3259 error_unlink_return
:
3260 unlink_or_warn(lockpath
);
3266 #ifndef NO_SYMLINK_HEAD
3269 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
))
3270 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
);
3276 struct read_ref_at_cb
{
3277 const char *refname
;
3278 unsigned long at_time
;
3281 unsigned char *sha1
;
3284 unsigned char osha1
[20];
3285 unsigned char nsha1
[20];
3289 unsigned long *cutoff_time
;
3294 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3295 const char *email
, unsigned long timestamp
, int tz
,
3296 const char *message
, void *cb_data
)
3298 struct read_ref_at_cb
*cb
= cb_data
;
3302 cb
->date
= timestamp
;
3304 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3306 *cb
->msg
= xstrdup(message
);
3307 if (cb
->cutoff_time
)
3308 *cb
->cutoff_time
= timestamp
;
3310 *cb
->cutoff_tz
= tz
;
3312 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3314 * we have not yet updated cb->[n|o]sha1 so they still
3315 * hold the values for the previous record.
3317 if (!is_null_sha1(cb
->osha1
)) {
3318 hashcpy(cb
->sha1
, nsha1
);
3319 if (hashcmp(cb
->osha1
, nsha1
))
3320 warning("Log for ref %s has gap after %s.",
3321 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3323 else if (cb
->date
== cb
->at_time
)
3324 hashcpy(cb
->sha1
, nsha1
);
3325 else if (hashcmp(nsha1
, cb
->sha1
))
3326 warning("Log for ref %s unexpectedly ended on %s.",
3327 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3329 hashcpy(cb
->osha1
, osha1
);
3330 hashcpy(cb
->nsha1
, nsha1
);
3334 hashcpy(cb
->osha1
, osha1
);
3335 hashcpy(cb
->nsha1
, nsha1
);
3341 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3342 const char *email
, unsigned long timestamp
,
3343 int tz
, const char *message
, void *cb_data
)
3345 struct read_ref_at_cb
*cb
= cb_data
;
3348 *cb
->msg
= xstrdup(message
);
3349 if (cb
->cutoff_time
)
3350 *cb
->cutoff_time
= timestamp
;
3352 *cb
->cutoff_tz
= tz
;
3354 *cb
->cutoff_cnt
= cb
->reccnt
;
3355 hashcpy(cb
->sha1
, osha1
);
3356 if (is_null_sha1(cb
->sha1
))
3357 hashcpy(cb
->sha1
, nsha1
);
3358 /* We just want the first entry */
3362 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3363 unsigned char *sha1
, char **msg
,
3364 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3366 struct read_ref_at_cb cb
;
3368 memset(&cb
, 0, sizeof(cb
));
3369 cb
.refname
= refname
;
3370 cb
.at_time
= at_time
;
3373 cb
.cutoff_time
= cutoff_time
;
3374 cb
.cutoff_tz
= cutoff_tz
;
3375 cb
.cutoff_cnt
= cutoff_cnt
;
3378 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3381 if (flags
& GET_SHA1_QUIETLY
)
3384 die("Log for %s is empty.", refname
);
3389 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3394 int reflog_exists(const char *refname
)
3398 return !lstat(git_path("logs/%s", refname
), &st
) &&
3399 S_ISREG(st
.st_mode
);
3402 int delete_reflog(const char *refname
)
3404 return remove_path(git_path("logs/%s", refname
));
3407 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3409 unsigned char osha1
[20], nsha1
[20];
3410 char *email_end
, *message
;
3411 unsigned long timestamp
;
3414 /* old SP new SP name <email> SP time TAB msg LF */
3415 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3416 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3417 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3418 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3419 email_end
[1] != ' ' ||
3420 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3421 !message
|| message
[0] != ' ' ||
3422 (message
[1] != '+' && message
[1] != '-') ||
3423 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3424 !isdigit(message
[4]) || !isdigit(message
[5]))
3425 return 0; /* corrupt? */
3426 email_end
[1] = '\0';
3427 tz
= strtol(message
+ 1, NULL
, 10);
3428 if (message
[6] != '\t')
3432 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3435 static char *find_beginning_of_line(char *bob
, char *scan
)
3437 while (bob
< scan
&& *(--scan
) != '\n')
3438 ; /* keep scanning backwards */
3440 * Return either beginning of the buffer, or LF at the end of
3441 * the previous line.
3446 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3448 struct strbuf sb
= STRBUF_INIT
;
3451 int ret
= 0, at_tail
= 1;
3453 logfp
= fopen(git_path("logs/%s", refname
), "r");
3457 /* Jump to the end */
3458 if (fseek(logfp
, 0, SEEK_END
) < 0)
3459 return error("cannot seek back reflog for %s: %s",
3460 refname
, strerror(errno
));
3462 while (!ret
&& 0 < pos
) {
3468 /* Fill next block from the end */
3469 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3470 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3471 return error("cannot seek back reflog for %s: %s",
3472 refname
, strerror(errno
));
3473 nread
= fread(buf
, cnt
, 1, logfp
);
3475 return error("cannot read %d bytes from reflog for %s: %s",
3476 cnt
, refname
, strerror(errno
));
3479 scanp
= endp
= buf
+ cnt
;
3480 if (at_tail
&& scanp
[-1] == '\n')
3481 /* Looking at the final LF at the end of the file */
3485 while (buf
< scanp
) {
3487 * terminating LF of the previous line, or the beginning
3492 bp
= find_beginning_of_line(buf
, scanp
);
3496 * The newline is the end of the previous line,
3497 * so we know we have complete line starting
3498 * at (bp + 1). Prefix it onto any prior data
3499 * we collected for the line and process it.
3501 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3504 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3510 * We are at the start of the buffer, and the
3511 * start of the file; there is no previous
3512 * line, and we have everything for this one.
3513 * Process it, and we can end the loop.
3515 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3516 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3523 * We are at the start of the buffer, and there
3524 * is more file to read backwards. Which means
3525 * we are in the middle of a line. Note that we
3526 * may get here even if *bp was a newline; that
3527 * just means we are at the exact end of the
3528 * previous line, rather than some spot in the
3531 * Save away what we have to be combined with
3532 * the data from the next read.
3534 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3541 die("BUG: reverse reflog parser had leftover data");
3544 strbuf_release(&sb
);
3548 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3551 struct strbuf sb
= STRBUF_INIT
;
3554 logfp
= fopen(git_path("logs/%s", refname
), "r");
3558 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3559 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3561 strbuf_release(&sb
);
3565 * Call fn for each reflog in the namespace indicated by name. name
3566 * must be empty or end with '/'. Name will be used as a scratch
3567 * space, but its contents will be restored before return.
3569 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3571 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3574 int oldlen
= name
->len
;
3577 return name
->len
? errno
: 0;
3579 while ((de
= readdir(d
)) != NULL
) {
3582 if (de
->d_name
[0] == '.')
3584 if (ends_with(de
->d_name
, ".lock"))
3586 strbuf_addstr(name
, de
->d_name
);
3587 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3588 ; /* silently ignore */
3590 if (S_ISDIR(st
.st_mode
)) {
3591 strbuf_addch(name
, '/');
3592 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3594 unsigned char sha1
[20];
3595 if (read_ref_full(name
->buf
, 0, sha1
, NULL
))
3596 retval
= error("bad ref for %s", name
->buf
);
3598 retval
= fn(name
->buf
, sha1
, 0, cb_data
);
3603 strbuf_setlen(name
, oldlen
);
3609 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3613 strbuf_init(&name
, PATH_MAX
);
3614 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3615 strbuf_release(&name
);
3620 * Information needed for a single ref update. Set new_sha1 to the new
3621 * value or to null_sha1 to delete the ref. To check the old value
3622 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3623 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3624 * not exist before update.
3628 * If (flags & REF_HAVE_NEW), set the reference to this value:
3630 unsigned char new_sha1
[20];
3632 * If (flags & REF_HAVE_OLD), check that the reference
3633 * previously had this value:
3635 unsigned char old_sha1
[20];
3637 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3638 * REF_DELETING, and REF_ISPRUNING:
3641 struct ref_lock
*lock
;
3644 const char refname
[FLEX_ARRAY
];
3648 * Transaction states.
3649 * OPEN: The transaction is in a valid state and can accept new updates.
3650 * An OPEN transaction can be committed.
3651 * CLOSED: A closed transaction is no longer active and no other operations
3652 * than free can be used on it in this state.
3653 * A transaction can either become closed by successfully committing
3654 * an active transaction or if there is a failure while building
3655 * the transaction thus rendering it failed/inactive.
3657 enum ref_transaction_state
{
3658 REF_TRANSACTION_OPEN
= 0,
3659 REF_TRANSACTION_CLOSED
= 1
3663 * Data structure for holding a reference transaction, which can
3664 * consist of checks and updates to multiple references, carried out
3665 * as atomically as possible. This structure is opaque to callers.
3667 struct ref_transaction
{
3668 struct ref_update
**updates
;
3671 enum ref_transaction_state state
;
3674 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3678 return xcalloc(1, sizeof(struct ref_transaction
));
3681 void ref_transaction_free(struct ref_transaction
*transaction
)
3688 for (i
= 0; i
< transaction
->nr
; i
++) {
3689 free(transaction
->updates
[i
]->msg
);
3690 free(transaction
->updates
[i
]);
3692 free(transaction
->updates
);
3696 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3697 const char *refname
)
3699 size_t len
= strlen(refname
);
3700 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3702 strcpy((char *)update
->refname
, refname
);
3703 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3704 transaction
->updates
[transaction
->nr
++] = update
;
3708 int ref_transaction_update(struct ref_transaction
*transaction
,
3709 const char *refname
,
3710 const unsigned char *new_sha1
,
3711 const unsigned char *old_sha1
,
3712 unsigned int flags
, const char *msg
,
3715 struct ref_update
*update
;
3719 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3720 die("BUG: update called for transaction that is not open");
3722 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
3723 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3724 strbuf_addf(err
, "refusing to update ref with bad name %s",
3729 update
= add_update(transaction
, refname
);
3731 hashcpy(update
->new_sha1
, new_sha1
);
3732 flags
|= REF_HAVE_NEW
;
3735 hashcpy(update
->old_sha1
, old_sha1
);
3736 flags
|= REF_HAVE_OLD
;
3738 update
->flags
= flags
;
3740 update
->msg
= xstrdup(msg
);
3744 int ref_transaction_create(struct ref_transaction
*transaction
,
3745 const char *refname
,
3746 const unsigned char *new_sha1
,
3747 unsigned int flags
, const char *msg
,
3750 if (!new_sha1
|| is_null_sha1(new_sha1
))
3751 die("BUG: create called without valid new_sha1");
3752 return ref_transaction_update(transaction
, refname
, new_sha1
,
3753 null_sha1
, flags
, msg
, err
);
3756 int ref_transaction_delete(struct ref_transaction
*transaction
,
3757 const char *refname
,
3758 const unsigned char *old_sha1
,
3759 unsigned int flags
, const char *msg
,
3762 if (old_sha1
&& is_null_sha1(old_sha1
))
3763 die("BUG: delete called with old_sha1 set to zeros");
3764 return ref_transaction_update(transaction
, refname
,
3765 null_sha1
, old_sha1
,
3769 int ref_transaction_verify(struct ref_transaction
*transaction
,
3770 const char *refname
,
3771 const unsigned char *old_sha1
,
3776 die("BUG: verify called with old_sha1 set to NULL");
3777 return ref_transaction_update(transaction
, refname
,
3782 int update_ref(const char *msg
, const char *refname
,
3783 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
3784 unsigned int flags
, enum action_on_err onerr
)
3786 struct ref_transaction
*t
;
3787 struct strbuf err
= STRBUF_INIT
;
3789 t
= ref_transaction_begin(&err
);
3791 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
3792 flags
, msg
, &err
) ||
3793 ref_transaction_commit(t
, &err
)) {
3794 const char *str
= "update_ref failed for ref '%s': %s";
3796 ref_transaction_free(t
);
3798 case UPDATE_REFS_MSG_ON_ERR
:
3799 error(str
, refname
, err
.buf
);
3801 case UPDATE_REFS_DIE_ON_ERR
:
3802 die(str
, refname
, err
.buf
);
3804 case UPDATE_REFS_QUIET_ON_ERR
:
3807 strbuf_release(&err
);
3810 strbuf_release(&err
);
3811 ref_transaction_free(t
);
3815 static int ref_update_reject_duplicates(struct string_list
*refnames
,
3818 int i
, n
= refnames
->nr
;
3822 for (i
= 1; i
< n
; i
++)
3823 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
3825 "Multiple updates for ref '%s' not allowed.",
3826 refnames
->items
[i
].string
);
3832 int ref_transaction_commit(struct ref_transaction
*transaction
,
3836 int n
= transaction
->nr
;
3837 struct ref_update
**updates
= transaction
->updates
;
3838 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
3839 struct string_list_item
*ref_to_delete
;
3840 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
3844 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3845 die("BUG: commit called for transaction that is not open");
3848 transaction
->state
= REF_TRANSACTION_CLOSED
;
3852 /* Fail if a refname appears more than once in the transaction: */
3853 for (i
= 0; i
< n
; i
++)
3854 string_list_append(&affected_refnames
, updates
[i
]->refname
);
3855 string_list_sort(&affected_refnames
);
3856 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
3857 ret
= TRANSACTION_GENERIC_ERROR
;
3862 * Acquire all locks, verify old values if provided, check
3863 * that new values are valid, and write new values to the
3864 * lockfiles, ready to be activated. Only keep one lockfile
3865 * open at a time to avoid running out of file descriptors.
3867 for (i
= 0; i
< n
; i
++) {
3868 struct ref_update
*update
= updates
[i
];
3870 if ((update
->flags
& REF_HAVE_NEW
) &&
3871 is_null_sha1(update
->new_sha1
))
3872 update
->flags
|= REF_DELETING
;
3873 update
->lock
= lock_ref_sha1_basic(
3875 ((update
->flags
& REF_HAVE_OLD
) ?
3876 update
->old_sha1
: NULL
),
3877 &affected_refnames
, NULL
,
3881 if (!update
->lock
) {
3884 ret
= (errno
== ENOTDIR
)
3885 ? TRANSACTION_NAME_CONFLICT
3886 : TRANSACTION_GENERIC_ERROR
;
3887 reason
= strbuf_detach(err
, NULL
);
3888 strbuf_addf(err
, "Cannot lock ref '%s': %s",
3889 update
->refname
, reason
);
3893 if ((update
->flags
& REF_HAVE_NEW
) &&
3894 !(update
->flags
& REF_DELETING
)) {
3895 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
3896 (update
->flags
& REF_NODEREF
));
3898 if (!overwriting_symref
&&
3899 !hashcmp(update
->lock
->old_sha1
, update
->new_sha1
)) {
3901 * The reference already has the desired
3902 * value, so we don't need to write it.
3904 } else if (write_ref_to_lockfile(update
->lock
,
3905 update
->new_sha1
)) {
3907 * The lock was freed upon failure of
3908 * write_ref_to_lockfile():
3910 update
->lock
= NULL
;
3911 strbuf_addf(err
, "Cannot update the ref '%s'.",
3913 ret
= TRANSACTION_GENERIC_ERROR
;
3916 update
->flags
|= REF_NEEDS_COMMIT
;
3919 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
3921 * We didn't have to write anything to the lockfile.
3922 * Close it to free up the file descriptor:
3924 if (close_ref(update
->lock
)) {
3925 strbuf_addf(err
, "Couldn't close %s.lock",
3932 /* Perform updates first so live commits remain referenced */
3933 for (i
= 0; i
< n
; i
++) {
3934 struct ref_update
*update
= updates
[i
];
3936 if (update
->flags
& REF_NEEDS_COMMIT
) {
3937 if (commit_ref_update(update
->lock
,
3938 update
->new_sha1
, update
->msg
)) {
3939 /* freed by commit_ref_update(): */
3940 update
->lock
= NULL
;
3941 strbuf_addf(err
, "Cannot update the ref '%s'.",
3943 ret
= TRANSACTION_GENERIC_ERROR
;
3946 /* freed by commit_ref_update(): */
3947 update
->lock
= NULL
;
3952 /* Perform deletes now that updates are safely completed */
3953 for (i
= 0; i
< n
; i
++) {
3954 struct ref_update
*update
= updates
[i
];
3956 if (update
->flags
& REF_DELETING
) {
3957 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
3958 ret
= TRANSACTION_GENERIC_ERROR
;
3962 if (!(update
->flags
& REF_ISPRUNING
))
3963 string_list_append(&refs_to_delete
,
3964 update
->lock
->ref_name
);
3968 if (repack_without_refs(&refs_to_delete
, err
)) {
3969 ret
= TRANSACTION_GENERIC_ERROR
;
3972 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
3973 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
3974 clear_loose_ref_cache(&ref_cache
);
3977 transaction
->state
= REF_TRANSACTION_CLOSED
;
3979 for (i
= 0; i
< n
; i
++)
3980 if (updates
[i
]->lock
)
3981 unlock_ref(updates
[i
]->lock
);
3982 string_list_clear(&refs_to_delete
, 0);
3983 string_list_clear(&affected_refnames
, 0);
3987 char *shorten_unambiguous_ref(const char *refname
, int strict
)
3990 static char **scanf_fmts
;
3991 static int nr_rules
;
3996 * Pre-generate scanf formats from ref_rev_parse_rules[].
3997 * Generate a format suitable for scanf from a
3998 * ref_rev_parse_rules rule by interpolating "%s" at the
3999 * location of the "%.*s".
4001 size_t total_len
= 0;
4004 /* the rule list is NULL terminated, count them first */
4005 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
4006 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4007 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
4009 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
4012 for (i
= 0; i
< nr_rules
; i
++) {
4013 assert(offset
< total_len
);
4014 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
4015 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
4016 ref_rev_parse_rules
[i
], 2, "%s") + 1;
4020 /* bail out if there are no rules */
4022 return xstrdup(refname
);
4024 /* buffer for scanf result, at most refname must fit */
4025 short_name
= xstrdup(refname
);
4027 /* skip first rule, it will always match */
4028 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
4030 int rules_to_fail
= i
;
4033 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
4036 short_name_len
= strlen(short_name
);
4039 * in strict mode, all (except the matched one) rules
4040 * must fail to resolve to a valid non-ambiguous ref
4043 rules_to_fail
= nr_rules
;
4046 * check if the short name resolves to a valid ref,
4047 * but use only rules prior to the matched one
4049 for (j
= 0; j
< rules_to_fail
; j
++) {
4050 const char *rule
= ref_rev_parse_rules
[j
];
4051 char refname
[PATH_MAX
];
4053 /* skip matched rule */
4058 * the short name is ambiguous, if it resolves
4059 * (with this previous rule) to a valid ref
4060 * read_ref() returns 0 on success
4062 mksnpath(refname
, sizeof(refname
),
4063 rule
, short_name_len
, short_name
);
4064 if (ref_exists(refname
))
4069 * short name is non-ambiguous if all previous rules
4070 * haven't resolved to a valid ref
4072 if (j
== rules_to_fail
)
4077 return xstrdup(refname
);
4080 static struct string_list
*hide_refs
;
4082 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
4084 if (!strcmp("transfer.hiderefs", var
) ||
4085 /* NEEDSWORK: use parse_config_key() once both are merged */
4086 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
4087 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
4092 return config_error_nonbool(var
);
4093 ref
= xstrdup(value
);
4095 while (len
&& ref
[len
- 1] == '/')
4098 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
4099 hide_refs
->strdup_strings
= 1;
4101 string_list_append(hide_refs
, ref
);
4106 int ref_is_hidden(const char *refname
)
4108 struct string_list_item
*item
;
4112 for_each_string_list_item(item
, hide_refs
) {
4114 if (!starts_with(refname
, item
->string
))
4116 len
= strlen(item
->string
);
4117 if (!refname
[len
] || refname
[len
] == '/')
4123 struct expire_reflog_cb
{
4125 reflog_expiry_should_prune_fn
*should_prune_fn
;
4128 unsigned char last_kept_sha1
[20];
4131 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4132 const char *email
, unsigned long timestamp
, int tz
,
4133 const char *message
, void *cb_data
)
4135 struct expire_reflog_cb
*cb
= cb_data
;
4136 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4138 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4139 osha1
= cb
->last_kept_sha1
;
4141 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4142 message
, policy_cb
)) {
4144 printf("would prune %s", message
);
4145 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4146 printf("prune %s", message
);
4149 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4150 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4151 email
, timestamp
, tz
, message
);
4152 hashcpy(cb
->last_kept_sha1
, nsha1
);
4154 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4155 printf("keep %s", message
);
4160 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4162 reflog_expiry_prepare_fn prepare_fn
,
4163 reflog_expiry_should_prune_fn should_prune_fn
,
4164 reflog_expiry_cleanup_fn cleanup_fn
,
4165 void *policy_cb_data
)
4167 static struct lock_file reflog_lock
;
4168 struct expire_reflog_cb cb
;
4169 struct ref_lock
*lock
;
4173 struct strbuf err
= STRBUF_INIT
;
4175 memset(&cb
, 0, sizeof(cb
));
4177 cb
.policy_cb
= policy_cb_data
;
4178 cb
.should_prune_fn
= should_prune_fn
;
4181 * The reflog file is locked by holding the lock on the
4182 * reference itself, plus we might need to update the
4183 * reference if --updateref was specified:
4185 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, 0, &type
, &err
);
4187 error("cannot lock ref '%s': %s", refname
, err
.buf
);
4188 strbuf_release(&err
);
4191 if (!reflog_exists(refname
)) {
4196 log_file
= git_pathdup("logs/%s", refname
);
4197 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4199 * Even though holding $GIT_DIR/logs/$reflog.lock has
4200 * no locking implications, we use the lock_file
4201 * machinery here anyway because it does a lot of the
4202 * work we need, including cleaning up if the program
4203 * exits unexpectedly.
4205 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4206 struct strbuf err
= STRBUF_INIT
;
4207 unable_to_lock_message(log_file
, errno
, &err
);
4208 error("%s", err
.buf
);
4209 strbuf_release(&err
);
4212 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4214 error("cannot fdopen %s (%s)",
4215 reflog_lock
.filename
.buf
, strerror(errno
));
4220 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4221 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4222 (*cleanup_fn
)(cb
.policy_cb
);
4224 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4226 * It doesn't make sense to adjust a reference pointed
4227 * to by a symbolic ref based on expiring entries in
4228 * the symbolic reference's reflog. Nor can we update
4229 * a reference if there are no remaining reflog
4232 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4233 !(type
& REF_ISSYMREF
) &&
4234 !is_null_sha1(cb
.last_kept_sha1
);
4236 if (close_lock_file(&reflog_lock
)) {
4237 status
|= error("couldn't write %s: %s", log_file
,
4239 } else if (update
&&
4240 (write_in_full(lock
->lock_fd
,
4241 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4242 write_str_in_full(lock
->lock_fd
, "\n") != 1 ||
4243 close_ref(lock
) < 0)) {
4244 status
|= error("couldn't write %s",
4245 lock
->lk
->filename
.buf
);
4246 rollback_lock_file(&reflog_lock
);
4247 } else if (commit_lock_file(&reflog_lock
)) {
4248 status
|= error("unable to commit reflog '%s' (%s)",
4249 log_file
, strerror(errno
));
4250 } else if (update
&& commit_ref(lock
)) {
4251 status
|= error("couldn't set %s", lock
->ref_name
);
4259 rollback_lock_file(&reflog_lock
);