7 #include "string-list.h"
13 struct object_id old_oid
;
17 * How to handle various characters in refnames:
18 * 0: An acceptable character for refs
20 * 2: ., look for a preceding . to reject .. in refs
21 * 3: {, look for a preceding @ to reject @{ in refs
22 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
24 static unsigned char refname_disposition
[256] = {
25 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
26 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
37 * refs (i.e., because the reference is about to be deleted anyway).
39 #define REF_DELETING 0x02
42 * Used as a flag in ref_update::flags when a loose ref is being
45 #define REF_ISPRUNING 0x04
48 * Used as a flag in ref_update::flags when the reference should be
49 * updated to new_sha1.
51 #define REF_HAVE_NEW 0x08
54 * Used as a flag in ref_update::flags when old_sha1 should be
57 #define REF_HAVE_OLD 0x10
60 * Used as a flag in ref_update::flags when the lockfile needs to be
63 #define REF_NEEDS_COMMIT 0x20
66 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a
67 * value to ref_update::flags
71 * Try to read one refname component from the front of refname.
72 * Return the length of the component found, or -1 if the component is
73 * not legal. It is legal if it is something reasonable to have under
74 * ".git/refs/"; We do not like it if:
76 * - any path component of it begins with ".", or
77 * - it has double dots "..", or
78 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
79 * - it ends with a "/".
80 * - it ends with ".lock"
81 * - it contains a "\" (backslash)
83 static int check_refname_component(const char *refname
, int flags
)
88 for (cp
= refname
; ; cp
++) {
90 unsigned char disp
= refname_disposition
[ch
];
96 return -1; /* Refname contains "..". */
100 return -1; /* Refname contains "@{". */
109 return 0; /* Component has zero length. */
110 if (refname
[0] == '.')
111 return -1; /* Component starts with '.'. */
112 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
113 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
114 return -1; /* Refname ends with ".lock". */
118 int check_refname_format(const char *refname
, int flags
)
120 int component_len
, component_count
= 0;
122 if (!strcmp(refname
, "@"))
123 /* Refname is a single character '@'. */
127 /* We are at the start of a path component. */
128 component_len
= check_refname_component(refname
, flags
);
129 if (component_len
<= 0) {
130 if ((flags
& REFNAME_REFSPEC_PATTERN
) &&
132 (refname
[1] == '\0' || refname
[1] == '/')) {
133 /* Accept one wildcard as a full refname component. */
134 flags
&= ~REFNAME_REFSPEC_PATTERN
;
141 if (refname
[component_len
] == '\0')
143 /* Skip to next component. */
144 refname
+= component_len
+ 1;
147 if (refname
[component_len
- 1] == '.')
148 return -1; /* Refname ends with '.'. */
149 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
150 return -1; /* Refname has only one component. */
157 * Information used (along with the information in ref_entry) to
158 * describe a single cached reference. This data structure only
159 * occurs embedded in a union in struct ref_entry, and only when
160 * (ref_entry->flag & REF_DIR) is zero.
164 * The name of the object to which this reference resolves
165 * (which may be a tag object). If REF_ISBROKEN, this is
166 * null. If REF_ISSYMREF, then this is the name of the object
167 * referred to by the last reference in the symlink chain.
169 struct object_id oid
;
172 * If REF_KNOWS_PEELED, then this field holds the peeled value
173 * of this reference, or null if the reference is known not to
174 * be peelable. See the documentation for peel_ref() for an
175 * exact definition of "peelable".
177 struct object_id peeled
;
183 * Information used (along with the information in ref_entry) to
184 * describe a level in the hierarchy of references. This data
185 * structure only occurs embedded in a union in struct ref_entry, and
186 * only when (ref_entry.flag & REF_DIR) is set. In that case,
187 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
188 * in the directory have already been read:
190 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
191 * or packed references, already read.
193 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
194 * references that hasn't been read yet (nor has any of its
197 * Entries within a directory are stored within a growable array of
198 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
199 * sorted are sorted by their component name in strcmp() order and the
200 * remaining entries are unsorted.
202 * Loose references are read lazily, one directory at a time. When a
203 * directory of loose references is read, then all of the references
204 * in that directory are stored, and REF_INCOMPLETE stubs are created
205 * for any subdirectories, but the subdirectories themselves are not
206 * read. The reading is triggered by get_ref_dir().
212 * Entries with index 0 <= i < sorted are sorted by name. New
213 * entries are appended to the list unsorted, and are sorted
214 * only when required; thus we avoid the need to sort the list
215 * after the addition of every reference.
219 /* A pointer to the ref_cache that contains this ref_dir. */
220 struct ref_cache
*ref_cache
;
222 struct ref_entry
**entries
;
226 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
227 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
228 * public values; see refs.h.
232 * The field ref_entry->u.value.peeled of this value entry contains
233 * the correct peeled value for the reference, which might be
234 * null_sha1 if the reference is not a tag or if it is broken.
236 #define REF_KNOWS_PEELED 0x10
238 /* ref_entry represents a directory of references */
242 * Entry has not yet been read from disk (used only for REF_DIR
243 * entries representing loose references)
245 #define REF_INCOMPLETE 0x40
248 * A ref_entry represents either a reference or a "subdirectory" of
251 * Each directory in the reference namespace is represented by a
252 * ref_entry with (flags & REF_DIR) set and containing a subdir member
253 * that holds the entries in that directory that have been read so
254 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
255 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
256 * used for loose reference directories.
258 * References are represented by a ref_entry with (flags & REF_DIR)
259 * unset and a value member that describes the reference's value. The
260 * flag member is at the ref_entry level, but it is also needed to
261 * interpret the contents of the value field (in other words, a
262 * ref_value object is not very much use without the enclosing
265 * Reference names cannot end with slash and directories' names are
266 * always stored with a trailing slash (except for the top-level
267 * directory, which is always denoted by ""). This has two nice
268 * consequences: (1) when the entries in each subdir are sorted
269 * lexicographically by name (as they usually are), the references in
270 * a whole tree can be generated in lexicographic order by traversing
271 * the tree in left-to-right, depth-first order; (2) the names of
272 * references and subdirectories cannot conflict, and therefore the
273 * presence of an empty subdirectory does not block the creation of a
274 * similarly-named reference. (The fact that reference names with the
275 * same leading components can conflict *with each other* is a
276 * separate issue that is regulated by verify_refname_available().)
278 * Please note that the name field contains the fully-qualified
279 * reference (or subdirectory) name. Space could be saved by only
280 * storing the relative names. But that would require the full names
281 * to be generated on the fly when iterating in do_for_each_ref(), and
282 * would break callback functions, who have always been able to assume
283 * that the name strings that they are passed will not be freed during
287 unsigned char flag
; /* ISSYMREF? ISPACKED? */
289 struct ref_value value
; /* if not (flags&REF_DIR) */
290 struct ref_dir subdir
; /* if (flags&REF_DIR) */
293 * The full name of the reference (e.g., "refs/heads/master")
294 * or the full name of the directory with a trailing slash
295 * (e.g., "refs/heads/"):
297 char name
[FLEX_ARRAY
];
300 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
302 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
305 assert(entry
->flag
& REF_DIR
);
306 dir
= &entry
->u
.subdir
;
307 if (entry
->flag
& REF_INCOMPLETE
) {
308 read_loose_refs(entry
->name
, dir
);
309 entry
->flag
&= ~REF_INCOMPLETE
;
315 * Check if a refname is safe.
316 * For refs that start with "refs/" we consider it safe as long they do
317 * not try to resolve to outside of refs/.
319 * For all other refs we only consider them safe iff they only contain
320 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
323 static int refname_is_safe(const char *refname
)
325 if (starts_with(refname
, "refs/")) {
329 buf
= xmalloc(strlen(refname
) + 1);
331 * Does the refname try to escape refs/?
332 * For example: refs/foo/../bar is safe but refs/foo/../../bar
335 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
340 if (!isupper(*refname
) && *refname
!= '_')
347 static struct ref_entry
*create_ref_entry(const char *refname
,
348 const unsigned char *sha1
, int flag
,
352 struct ref_entry
*ref
;
355 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
356 die("Reference has invalid format: '%s'", refname
);
357 len
= strlen(refname
) + 1;
358 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
359 hashcpy(ref
->u
.value
.oid
.hash
, sha1
);
360 oidclr(&ref
->u
.value
.peeled
);
361 memcpy(ref
->name
, refname
, len
);
366 static void clear_ref_dir(struct ref_dir
*dir
);
368 static void free_ref_entry(struct ref_entry
*entry
)
370 if (entry
->flag
& REF_DIR
) {
372 * Do not use get_ref_dir() here, as that might
373 * trigger the reading of loose refs.
375 clear_ref_dir(&entry
->u
.subdir
);
381 * Add a ref_entry to the end of dir (unsorted). Entry is always
382 * stored directly in dir; no recursion into subdirectories is
385 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
387 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
388 dir
->entries
[dir
->nr
++] = entry
;
389 /* optimize for the case that entries are added in order */
391 (dir
->nr
== dir
->sorted
+ 1 &&
392 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
393 dir
->entries
[dir
->nr
- 1]->name
) < 0))
394 dir
->sorted
= dir
->nr
;
398 * Clear and free all entries in dir, recursively.
400 static void clear_ref_dir(struct ref_dir
*dir
)
403 for (i
= 0; i
< dir
->nr
; i
++)
404 free_ref_entry(dir
->entries
[i
]);
406 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
411 * Create a struct ref_entry object for the specified dirname.
412 * dirname is the name of the directory with a trailing slash (e.g.,
413 * "refs/heads/") or "" for the top-level directory.
415 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
416 const char *dirname
, size_t len
,
419 struct ref_entry
*direntry
;
420 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
421 memcpy(direntry
->name
, dirname
, len
);
422 direntry
->name
[len
] = '\0';
423 direntry
->u
.subdir
.ref_cache
= ref_cache
;
424 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
428 static int ref_entry_cmp(const void *a
, const void *b
)
430 struct ref_entry
*one
= *(struct ref_entry
**)a
;
431 struct ref_entry
*two
= *(struct ref_entry
**)b
;
432 return strcmp(one
->name
, two
->name
);
435 static void sort_ref_dir(struct ref_dir
*dir
);
437 struct string_slice
{
442 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
444 const struct string_slice
*key
= key_
;
445 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
446 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
449 return '\0' - (unsigned char)ent
->name
[key
->len
];
453 * Return the index of the entry with the given refname from the
454 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
455 * no such entry is found. dir must already be complete.
457 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
459 struct ref_entry
**r
;
460 struct string_slice key
;
462 if (refname
== NULL
|| !dir
->nr
)
468 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
469 ref_entry_cmp_sslice
);
474 return r
- dir
->entries
;
478 * Search for a directory entry directly within dir (without
479 * recursing). Sort dir if necessary. subdirname must be a directory
480 * name (i.e., end in '/'). If mkdir is set, then create the
481 * directory if it is missing; otherwise, return NULL if the desired
482 * directory cannot be found. dir must already be complete.
484 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
485 const char *subdirname
, size_t len
,
488 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
489 struct ref_entry
*entry
;
490 if (entry_index
== -1) {
494 * Since dir is complete, the absence of a subdir
495 * means that the subdir really doesn't exist;
496 * therefore, create an empty record for it but mark
497 * the record complete.
499 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
500 add_entry_to_dir(dir
, entry
);
502 entry
= dir
->entries
[entry_index
];
504 return get_ref_dir(entry
);
508 * If refname is a reference name, find the ref_dir within the dir
509 * tree that should hold refname. If refname is a directory name
510 * (i.e., ends in '/'), then return that ref_dir itself. dir must
511 * represent the top-level directory and must already be complete.
512 * Sort ref_dirs and recurse into subdirectories as necessary. If
513 * mkdir is set, then create any missing directories; otherwise,
514 * return NULL if the desired directory cannot be found.
516 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
517 const char *refname
, int mkdir
)
520 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
521 size_t dirnamelen
= slash
- refname
+ 1;
522 struct ref_dir
*subdir
;
523 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
535 * Find the value entry with the given name in dir, sorting ref_dirs
536 * and recursing into subdirectories as necessary. If the name is not
537 * found or it corresponds to a directory entry, return NULL.
539 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
542 struct ref_entry
*entry
;
543 dir
= find_containing_dir(dir
, refname
, 0);
546 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
547 if (entry_index
== -1)
549 entry
= dir
->entries
[entry_index
];
550 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
554 * Remove the entry with the given name from dir, recursing into
555 * subdirectories as necessary. If refname is the name of a directory
556 * (i.e., ends with '/'), then remove the directory and its contents.
557 * If the removal was successful, return the number of entries
558 * remaining in the directory entry that contained the deleted entry.
559 * If the name was not found, return -1. Please note that this
560 * function only deletes the entry from the cache; it does not delete
561 * it from the filesystem or ensure that other cache entries (which
562 * might be symbolic references to the removed entry) are updated.
563 * Nor does it remove any containing dir entries that might be made
564 * empty by the removal. dir must represent the top-level directory
565 * and must already be complete.
567 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
569 int refname_len
= strlen(refname
);
571 struct ref_entry
*entry
;
572 int is_dir
= refname
[refname_len
- 1] == '/';
575 * refname represents a reference directory. Remove
576 * the trailing slash; otherwise we will get the
577 * directory *representing* refname rather than the
578 * one *containing* it.
580 char *dirname
= xmemdupz(refname
, refname_len
- 1);
581 dir
= find_containing_dir(dir
, dirname
, 0);
584 dir
= find_containing_dir(dir
, refname
, 0);
588 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
589 if (entry_index
== -1)
591 entry
= dir
->entries
[entry_index
];
593 memmove(&dir
->entries
[entry_index
],
594 &dir
->entries
[entry_index
+ 1],
595 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
598 if (dir
->sorted
> entry_index
)
600 free_ref_entry(entry
);
605 * Add a ref_entry to the ref_dir (unsorted), recursing into
606 * subdirectories as necessary. dir must represent the top-level
607 * directory. Return 0 on success.
609 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
611 dir
= find_containing_dir(dir
, ref
->name
, 1);
614 add_entry_to_dir(dir
, ref
);
619 * Emit a warning and return true iff ref1 and ref2 have the same name
620 * and the same sha1. Die if they have the same name but different
623 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
625 if (strcmp(ref1
->name
, ref2
->name
))
628 /* Duplicate name; make sure that they don't conflict: */
630 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
631 /* This is impossible by construction */
632 die("Reference directory conflict: %s", ref1
->name
);
634 if (oidcmp(&ref1
->u
.value
.oid
, &ref2
->u
.value
.oid
))
635 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
637 warning("Duplicated ref: %s", ref1
->name
);
642 * Sort the entries in dir non-recursively (if they are not already
643 * sorted) and remove any duplicate entries.
645 static void sort_ref_dir(struct ref_dir
*dir
)
648 struct ref_entry
*last
= NULL
;
651 * This check also prevents passing a zero-length array to qsort(),
652 * which is a problem on some platforms.
654 if (dir
->sorted
== dir
->nr
)
657 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
659 /* Remove any duplicates: */
660 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
661 struct ref_entry
*entry
= dir
->entries
[j
];
662 if (last
&& is_dup_ref(last
, entry
))
663 free_ref_entry(entry
);
665 last
= dir
->entries
[i
++] = entry
;
667 dir
->sorted
= dir
->nr
= i
;
670 /* Include broken references in a do_for_each_ref*() iteration: */
671 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
674 * Return true iff the reference described by entry can be resolved to
675 * an object in the database. Emit a warning if the referred-to
676 * object does not exist.
678 static int ref_resolves_to_object(struct ref_entry
*entry
)
680 if (entry
->flag
& REF_ISBROKEN
)
682 if (!has_sha1_file(entry
->u
.value
.oid
.hash
)) {
683 error("%s does not point to a valid object!", entry
->name
);
690 * current_ref is a performance hack: when iterating over references
691 * using the for_each_ref*() functions, current_ref is set to the
692 * current reference's entry before calling the callback function. If
693 * the callback function calls peel_ref(), then peel_ref() first
694 * checks whether the reference to be peeled is the current reference
695 * (it usually is) and if so, returns that reference's peeled version
696 * if it is available. This avoids a refname lookup in a common case.
698 static struct ref_entry
*current_ref
;
700 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
702 struct ref_entry_cb
{
711 * Handle one reference in a do_for_each_ref*()-style iteration,
712 * calling an each_ref_fn for each entry.
714 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
716 struct ref_entry_cb
*data
= cb_data
;
717 struct ref_entry
*old_current_ref
;
720 if (!starts_with(entry
->name
, data
->base
))
723 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
724 !ref_resolves_to_object(entry
))
727 /* Store the old value, in case this is a recursive call: */
728 old_current_ref
= current_ref
;
730 retval
= data
->fn(entry
->name
+ data
->trim
, &entry
->u
.value
.oid
,
731 entry
->flag
, data
->cb_data
);
732 current_ref
= old_current_ref
;
737 * Call fn for each reference in dir that has index in the range
738 * offset <= index < dir->nr. Recurse into subdirectories that are in
739 * that index range, sorting them before iterating. This function
740 * does not sort dir itself; it should be sorted beforehand. fn is
741 * called for all references, including broken ones.
743 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
744 each_ref_entry_fn fn
, void *cb_data
)
747 assert(dir
->sorted
== dir
->nr
);
748 for (i
= offset
; i
< dir
->nr
; i
++) {
749 struct ref_entry
*entry
= dir
->entries
[i
];
751 if (entry
->flag
& REF_DIR
) {
752 struct ref_dir
*subdir
= get_ref_dir(entry
);
753 sort_ref_dir(subdir
);
754 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
756 retval
= fn(entry
, cb_data
);
765 * Call fn for each reference in the union of dir1 and dir2, in order
766 * by refname. Recurse into subdirectories. If a value entry appears
767 * in both dir1 and dir2, then only process the version that is in
768 * dir2. The input dirs must already be sorted, but subdirs will be
769 * sorted as needed. fn is called for all references, including
772 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
773 struct ref_dir
*dir2
,
774 each_ref_entry_fn fn
, void *cb_data
)
779 assert(dir1
->sorted
== dir1
->nr
);
780 assert(dir2
->sorted
== dir2
->nr
);
782 struct ref_entry
*e1
, *e2
;
784 if (i1
== dir1
->nr
) {
785 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
787 if (i2
== dir2
->nr
) {
788 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
790 e1
= dir1
->entries
[i1
];
791 e2
= dir2
->entries
[i2
];
792 cmp
= strcmp(e1
->name
, e2
->name
);
794 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
795 /* Both are directories; descend them in parallel. */
796 struct ref_dir
*subdir1
= get_ref_dir(e1
);
797 struct ref_dir
*subdir2
= get_ref_dir(e2
);
798 sort_ref_dir(subdir1
);
799 sort_ref_dir(subdir2
);
800 retval
= do_for_each_entry_in_dirs(
801 subdir1
, subdir2
, fn
, cb_data
);
804 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
805 /* Both are references; ignore the one from dir1. */
806 retval
= fn(e2
, cb_data
);
810 die("conflict between reference and directory: %s",
822 if (e
->flag
& REF_DIR
) {
823 struct ref_dir
*subdir
= get_ref_dir(e
);
824 sort_ref_dir(subdir
);
825 retval
= do_for_each_entry_in_dir(
826 subdir
, 0, fn
, cb_data
);
828 retval
= fn(e
, cb_data
);
837 * Load all of the refs from the dir into our in-memory cache. The hard work
838 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
839 * through all of the sub-directories. We do not even need to care about
840 * sorting, as traversal order does not matter to us.
842 static void prime_ref_dir(struct ref_dir
*dir
)
845 for (i
= 0; i
< dir
->nr
; i
++) {
846 struct ref_entry
*entry
= dir
->entries
[i
];
847 if (entry
->flag
& REF_DIR
)
848 prime_ref_dir(get_ref_dir(entry
));
852 struct nonmatching_ref_data
{
853 const struct string_list
*skip
;
854 const char *conflicting_refname
;
857 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
859 struct nonmatching_ref_data
*data
= vdata
;
861 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
864 data
->conflicting_refname
= entry
->name
;
869 * Return 0 if a reference named refname could be created without
870 * conflicting with the name of an existing reference in dir.
871 * Otherwise, return a negative value and write an explanation to err.
872 * If extras is non-NULL, it is a list of additional refnames with
873 * which refname is not allowed to conflict. If skip is non-NULL,
874 * ignore potential conflicts with refs in skip (e.g., because they
875 * are scheduled for deletion in the same operation). Behavior is
876 * undefined if the same name is listed in both extras and skip.
878 * Two reference names conflict if one of them exactly matches the
879 * leading components of the other; e.g., "refs/foo/bar" conflicts
880 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
881 * "refs/foo/bar" or "refs/foo/barbados".
883 * extras and skip must be sorted.
885 static int verify_refname_available(const char *refname
,
886 const struct string_list
*extras
,
887 const struct string_list
*skip
,
893 struct strbuf dirname
= STRBUF_INIT
;
897 * For the sake of comments in this function, suppose that
898 * refname is "refs/foo/bar".
903 strbuf_grow(&dirname
, strlen(refname
) + 1);
904 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
905 /* Expand dirname to the new prefix, not including the trailing slash: */
906 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
909 * We are still at a leading dir of the refname (e.g.,
910 * "refs/foo"; if there is a reference with that name,
911 * it is a conflict, *unless* it is in skip.
914 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
916 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
918 * We found a reference whose name is
919 * a proper prefix of refname; e.g.,
920 * "refs/foo", and is not in skip.
922 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
923 dirname
.buf
, refname
);
928 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
929 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
930 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
931 refname
, dirname
.buf
);
936 * Otherwise, we can try to continue our search with
937 * the next component. So try to look up the
938 * directory, e.g., "refs/foo/". If we come up empty,
939 * we know there is nothing under this whole prefix,
940 * but even in that case we still have to continue the
941 * search for conflicts with extras.
943 strbuf_addch(&dirname
, '/');
945 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
948 * There was no directory "refs/foo/",
949 * so there is nothing under this
950 * whole prefix. So there is no need
951 * to continue looking for conflicting
952 * references. But we need to continue
953 * looking for conflicting extras.
957 dir
= get_ref_dir(dir
->entries
[pos
]);
963 * We are at the leaf of our refname (e.g., "refs/foo/bar").
964 * There is no point in searching for a reference with that
965 * name, because a refname isn't considered to conflict with
966 * itself. But we still need to check for references whose
967 * names are in the "refs/foo/bar/" namespace, because they
970 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
971 strbuf_addch(&dirname
, '/');
974 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
978 * We found a directory named "$refname/"
979 * (e.g., "refs/foo/bar/"). It is a problem
980 * iff it contains any ref that is not in
983 struct nonmatching_ref_data data
;
986 data
.conflicting_refname
= NULL
;
987 dir
= get_ref_dir(dir
->entries
[pos
]);
989 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
990 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
991 data
.conflicting_refname
, refname
);
999 * Check for entries in extras that start with
1000 * "$refname/". We do that by looking for the place
1001 * where "$refname/" would be inserted in extras. If
1002 * there is an entry at that position that starts with
1003 * "$refname/" and is not in skip, then we have a
1006 for (pos
= string_list_find_insert_index(extras
, dirname
.buf
, 0);
1007 pos
< extras
->nr
; pos
++) {
1008 const char *extra_refname
= extras
->items
[pos
].string
;
1010 if (!starts_with(extra_refname
, dirname
.buf
))
1013 if (!skip
|| !string_list_has_string(skip
, extra_refname
)) {
1014 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
1015 refname
, extra_refname
);
1021 /* No conflicts were found */
1025 strbuf_release(&dirname
);
1029 struct packed_ref_cache
{
1030 struct ref_entry
*root
;
1033 * Count of references to the data structure in this instance,
1034 * including the pointer from ref_cache::packed if any. The
1035 * data will not be freed as long as the reference count is
1038 unsigned int referrers
;
1041 * Iff the packed-refs file associated with this instance is
1042 * currently locked for writing, this points at the associated
1043 * lock (which is owned by somebody else). The referrer count
1044 * is also incremented when the file is locked and decremented
1045 * when it is unlocked.
1047 struct lock_file
*lock
;
1049 /* The metadata from when this packed-refs cache was read */
1050 struct stat_validity validity
;
1054 * Future: need to be in "struct repository"
1055 * when doing a full libification.
1057 static struct ref_cache
{
1058 struct ref_cache
*next
;
1059 struct ref_entry
*loose
;
1060 struct packed_ref_cache
*packed
;
1062 * The submodule name, or "" for the main repo. We allocate
1063 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1064 * is initialized correctly.
1067 } ref_cache
, *submodule_ref_caches
;
1069 /* Lock used for the main packed-refs file: */
1070 static struct lock_file packlock
;
1073 * Increment the reference count of *packed_refs.
1075 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1077 packed_refs
->referrers
++;
1081 * Decrease the reference count of *packed_refs. If it goes to zero,
1082 * free *packed_refs and return true; otherwise return false.
1084 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1086 if (!--packed_refs
->referrers
) {
1087 free_ref_entry(packed_refs
->root
);
1088 stat_validity_clear(&packed_refs
->validity
);
1096 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1099 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1101 if (packed_refs
->lock
)
1102 die("internal error: packed-ref cache cleared while locked");
1103 refs
->packed
= NULL
;
1104 release_packed_ref_cache(packed_refs
);
1108 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1111 free_ref_entry(refs
->loose
);
1116 static struct ref_cache
*create_ref_cache(const char *submodule
)
1119 struct ref_cache
*refs
;
1122 len
= strlen(submodule
) + 1;
1123 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1124 memcpy(refs
->name
, submodule
, len
);
1129 * Return a pointer to a ref_cache for the specified submodule. For
1130 * the main repository, use submodule==NULL. The returned structure
1131 * will be allocated and initialized but not necessarily populated; it
1132 * should not be freed.
1134 static struct ref_cache
*get_ref_cache(const char *submodule
)
1136 struct ref_cache
*refs
;
1138 if (!submodule
|| !*submodule
)
1141 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1142 if (!strcmp(submodule
, refs
->name
))
1145 refs
= create_ref_cache(submodule
);
1146 refs
->next
= submodule_ref_caches
;
1147 submodule_ref_caches
= refs
;
1151 /* The length of a peeled reference line in packed-refs, including EOL: */
1152 #define PEELED_LINE_LENGTH 42
1155 * The packed-refs header line that we write out. Perhaps other
1156 * traits will be added later. The trailing space is required.
1158 static const char PACKED_REFS_HEADER
[] =
1159 "# pack-refs with: peeled fully-peeled \n";
1162 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1163 * Return a pointer to the refname within the line (null-terminated),
1164 * or NULL if there was a problem.
1166 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1171 * 42: the answer to everything.
1173 * In this case, it happens to be the answer to
1174 * 40 (length of sha1 hex representation)
1175 * +1 (space in between hex and name)
1176 * +1 (newline at the end of the line)
1178 if (line
->len
<= 42)
1181 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1183 if (!isspace(line
->buf
[40]))
1186 ref
= line
->buf
+ 41;
1190 if (line
->buf
[line
->len
- 1] != '\n')
1192 line
->buf
[--line
->len
] = 0;
1198 * Read f, which is a packed-refs file, into dir.
1200 * A comment line of the form "# pack-refs with: " may contain zero or
1201 * more traits. We interpret the traits as follows:
1205 * Probably no references are peeled. But if the file contains a
1206 * peeled value for a reference, we will use it.
1210 * References under "refs/tags/", if they *can* be peeled, *are*
1211 * peeled in this file. References outside of "refs/tags/" are
1212 * probably not peeled even if they could have been, but if we find
1213 * a peeled value for such a reference we will use it.
1217 * All references in the file that can be peeled are peeled.
1218 * Inversely (and this is more important), any references in the
1219 * file for which no peeled value is recorded is not peelable. This
1220 * trait should typically be written alongside "peeled" for
1221 * compatibility with older clients, but we do not require it
1222 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1224 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1226 struct ref_entry
*last
= NULL
;
1227 struct strbuf line
= STRBUF_INIT
;
1228 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1230 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1231 unsigned char sha1
[20];
1232 const char *refname
;
1235 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1236 if (strstr(traits
, " fully-peeled "))
1237 peeled
= PEELED_FULLY
;
1238 else if (strstr(traits
, " peeled "))
1239 peeled
= PEELED_TAGS
;
1240 /* perhaps other traits later as well */
1244 refname
= parse_ref_line(&line
, sha1
);
1246 int flag
= REF_ISPACKED
;
1248 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1249 if (!refname_is_safe(refname
))
1250 die("packed refname is dangerous: %s", refname
);
1252 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1254 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1255 if (peeled
== PEELED_FULLY
||
1256 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1257 last
->flag
|= REF_KNOWS_PEELED
;
1262 line
.buf
[0] == '^' &&
1263 line
.len
== PEELED_LINE_LENGTH
&&
1264 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1265 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1266 hashcpy(last
->u
.value
.peeled
.hash
, sha1
);
1268 * Regardless of what the file header said,
1269 * we definitely know the value of *this*
1272 last
->flag
|= REF_KNOWS_PEELED
;
1276 strbuf_release(&line
);
1280 * Get the packed_ref_cache for the specified ref_cache, creating it
1283 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1285 const char *packed_refs_file
;
1288 packed_refs_file
= git_path_submodule(refs
->name
, "packed-refs");
1290 packed_refs_file
= git_path("packed-refs");
1293 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1294 clear_packed_ref_cache(refs
);
1296 if (!refs
->packed
) {
1299 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1300 acquire_packed_ref_cache(refs
->packed
);
1301 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1302 f
= fopen(packed_refs_file
, "r");
1304 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1305 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1309 return refs
->packed
;
1312 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1314 return get_ref_dir(packed_ref_cache
->root
);
1317 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1319 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1322 void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1324 struct packed_ref_cache
*packed_ref_cache
=
1325 get_packed_ref_cache(&ref_cache
);
1327 if (!packed_ref_cache
->lock
)
1328 die("internal error: packed refs not locked");
1329 add_ref(get_packed_ref_dir(packed_ref_cache
),
1330 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1334 * Read the loose references from the namespace dirname into dir
1335 * (without recursing). dirname must end with '/'. dir must be the
1336 * directory entry corresponding to dirname.
1338 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1340 struct ref_cache
*refs
= dir
->ref_cache
;
1344 int dirnamelen
= strlen(dirname
);
1345 struct strbuf refname
;
1348 path
= git_path_submodule(refs
->name
, "%s", dirname
);
1350 path
= git_path("%s", dirname
);
1356 strbuf_init(&refname
, dirnamelen
+ 257);
1357 strbuf_add(&refname
, dirname
, dirnamelen
);
1359 while ((de
= readdir(d
)) != NULL
) {
1360 unsigned char sha1
[20];
1365 if (de
->d_name
[0] == '.')
1367 if (ends_with(de
->d_name
, ".lock"))
1369 strbuf_addstr(&refname
, de
->d_name
);
1370 refdir
= *refs
->name
1371 ? git_path_submodule(refs
->name
, "%s", refname
.buf
)
1372 : git_path("%s", refname
.buf
);
1373 if (stat(refdir
, &st
) < 0) {
1374 ; /* silently ignore */
1375 } else if (S_ISDIR(st
.st_mode
)) {
1376 strbuf_addch(&refname
, '/');
1377 add_entry_to_dir(dir
,
1378 create_dir_entry(refs
, refname
.buf
,
1386 read_ok
= !resolve_gitlink_ref(refs
->name
,
1389 read_ok
= !read_ref_full(refname
.buf
,
1390 RESOLVE_REF_READING
,
1396 flag
|= REF_ISBROKEN
;
1397 } else if (is_null_sha1(sha1
)) {
1399 * It is so astronomically unlikely
1400 * that NULL_SHA1 is the SHA-1 of an
1401 * actual object that we consider its
1402 * appearance in a loose reference
1403 * file to be repo corruption
1404 * (probably due to a software bug).
1406 flag
|= REF_ISBROKEN
;
1409 if (check_refname_format(refname
.buf
,
1410 REFNAME_ALLOW_ONELEVEL
)) {
1411 if (!refname_is_safe(refname
.buf
))
1412 die("loose refname is dangerous: %s", refname
.buf
);
1414 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1416 add_entry_to_dir(dir
,
1417 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1419 strbuf_setlen(&refname
, dirnamelen
);
1421 strbuf_release(&refname
);
1425 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1429 * Mark the top-level directory complete because we
1430 * are about to read the only subdirectory that can
1433 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1435 * Create an incomplete entry for "refs/":
1437 add_entry_to_dir(get_ref_dir(refs
->loose
),
1438 create_dir_entry(refs
, "refs/", 5, 1));
1440 return get_ref_dir(refs
->loose
);
1443 /* We allow "recursive" symbolic refs. Only within reason, though */
1445 #define MAXREFLEN (1024)
1448 * Called by resolve_gitlink_ref_recursive() after it failed to read
1449 * from the loose refs in ref_cache refs. Find <refname> in the
1450 * packed-refs file for the submodule.
1452 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1453 const char *refname
, unsigned char *sha1
)
1455 struct ref_entry
*ref
;
1456 struct ref_dir
*dir
= get_packed_refs(refs
);
1458 ref
= find_ref(dir
, refname
);
1462 hashcpy(sha1
, ref
->u
.value
.oid
.hash
);
1466 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1467 const char *refname
, unsigned char *sha1
,
1471 char buffer
[128], *p
;
1474 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1477 ? git_path_submodule(refs
->name
, "%s", refname
)
1478 : git_path("%s", refname
);
1479 fd
= open(path
, O_RDONLY
);
1481 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1483 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1487 while (len
&& isspace(buffer
[len
-1]))
1491 /* Was it a detached head or an old-fashioned symlink? */
1492 if (!get_sha1_hex(buffer
, sha1
))
1496 if (strncmp(buffer
, "ref:", 4))
1502 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1505 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1507 int len
= strlen(path
), retval
;
1509 struct ref_cache
*refs
;
1511 while (len
&& path
[len
-1] == '/')
1515 submodule
= xstrndup(path
, len
);
1516 refs
= get_ref_cache(submodule
);
1519 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1524 * Return the ref_entry for the given refname from the packed
1525 * references. If it does not exist, return NULL.
1527 static struct ref_entry
*get_packed_ref(const char *refname
)
1529 return find_ref(get_packed_refs(&ref_cache
), refname
);
1533 * A loose ref file doesn't exist; check for a packed ref. The
1534 * options are forwarded from resolve_safe_unsafe().
1536 static int resolve_missing_loose_ref(const char *refname
,
1538 unsigned char *sha1
,
1541 struct ref_entry
*entry
;
1544 * The loose reference file does not exist; check for a packed
1547 entry
= get_packed_ref(refname
);
1549 hashcpy(sha1
, entry
->u
.value
.oid
.hash
);
1551 *flags
|= REF_ISPACKED
;
1554 /* The reference is not a packed reference, either. */
1555 if (resolve_flags
& RESOLVE_REF_READING
) {
1564 /* This function needs to return a meaningful errno on failure */
1565 static const char *resolve_ref_unsafe_1(const char *refname
,
1567 unsigned char *sha1
,
1569 struct strbuf
*sb_path
)
1571 int depth
= MAXDEPTH
;
1574 static char refname_buffer
[256];
1580 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1582 *flags
|= REF_BAD_NAME
;
1584 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1585 !refname_is_safe(refname
)) {
1590 * dwim_ref() uses REF_ISBROKEN to distinguish between
1591 * missing refs and refs that were present but invalid,
1592 * to complain about the latter to stderr.
1594 * We don't know whether the ref exists, so don't set
1610 strbuf_reset(sb_path
);
1611 strbuf_git_path(sb_path
, "%s", refname
);
1612 path
= sb_path
->buf
;
1615 * We might have to loop back here to avoid a race
1616 * condition: first we lstat() the file, then we try
1617 * to read it as a link or as a file. But if somebody
1618 * changes the type of the file (file <-> directory
1619 * <-> symlink) between the lstat() and reading, then
1620 * we don't want to report that as an error but rather
1621 * try again starting with the lstat().
1624 if (lstat(path
, &st
) < 0) {
1625 if (errno
!= ENOENT
)
1627 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1633 *flags
|= REF_ISBROKEN
;
1638 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1639 if (S_ISLNK(st
.st_mode
)) {
1640 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
1642 if (errno
== ENOENT
|| errno
== EINVAL
)
1643 /* inconsistent with lstat; retry */
1649 if (starts_with(buffer
, "refs/") &&
1650 !check_refname_format(buffer
, 0)) {
1651 strcpy(refname_buffer
, buffer
);
1652 refname
= refname_buffer
;
1654 *flags
|= REF_ISSYMREF
;
1655 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1663 /* Is it a directory? */
1664 if (S_ISDIR(st
.st_mode
)) {
1670 * Anything else, just open it and try to use it as
1673 fd
= open(path
, O_RDONLY
);
1675 if (errno
== ENOENT
)
1676 /* inconsistent with lstat; retry */
1681 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
1683 int save_errno
= errno
;
1689 while (len
&& isspace(buffer
[len
-1]))
1694 * Is it a symbolic ref?
1696 if (!starts_with(buffer
, "ref:")) {
1698 * Please note that FETCH_HEAD has a second
1699 * line containing other data.
1701 if (get_sha1_hex(buffer
, sha1
) ||
1702 (buffer
[40] != '\0' && !isspace(buffer
[40]))) {
1704 *flags
|= REF_ISBROKEN
;
1711 *flags
|= REF_ISBROKEN
;
1716 *flags
|= REF_ISSYMREF
;
1718 while (isspace(*buf
))
1720 refname
= strcpy(refname_buffer
, buf
);
1721 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1725 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1727 *flags
|= REF_ISBROKEN
;
1729 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1730 !refname_is_safe(buf
)) {
1739 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1740 unsigned char *sha1
, int *flags
)
1742 struct strbuf sb_path
= STRBUF_INIT
;
1743 const char *ret
= resolve_ref_unsafe_1(refname
, resolve_flags
,
1744 sha1
, flags
, &sb_path
);
1745 strbuf_release(&sb_path
);
1749 char *resolve_refdup(const char *ref
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1751 return xstrdup_or_null(resolve_ref_unsafe(ref
, resolve_flags
, sha1
, flags
));
1754 /* The argument to filter_refs */
1756 const char *pattern
;
1761 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1763 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1768 int read_ref(const char *refname
, unsigned char *sha1
)
1770 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1773 int ref_exists(const char *refname
)
1775 unsigned char sha1
[20];
1776 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1779 static int filter_refs(const char *refname
, const struct object_id
*oid
,
1780 int flags
, void *data
)
1782 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1784 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1786 return filter
->fn(refname
, oid
, flags
, filter
->cb_data
);
1790 /* object was peeled successfully: */
1794 * object cannot be peeled because the named object (or an
1795 * object referred to by a tag in the peel chain), does not
1800 /* object cannot be peeled because it is not a tag: */
1803 /* ref_entry contains no peeled value because it is a symref: */
1804 PEEL_IS_SYMREF
= -3,
1807 * ref_entry cannot be peeled because it is broken (i.e., the
1808 * symbolic reference cannot even be resolved to an object
1815 * Peel the named object; i.e., if the object is a tag, resolve the
1816 * tag recursively until a non-tag is found. If successful, store the
1817 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1818 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1819 * and leave sha1 unchanged.
1821 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1823 struct object
*o
= lookup_unknown_object(name
);
1825 if (o
->type
== OBJ_NONE
) {
1826 int type
= sha1_object_info(name
, NULL
);
1827 if (type
< 0 || !object_as_type(o
, type
, 0))
1828 return PEEL_INVALID
;
1831 if (o
->type
!= OBJ_TAG
)
1832 return PEEL_NON_TAG
;
1834 o
= deref_tag_noverify(o
);
1836 return PEEL_INVALID
;
1838 hashcpy(sha1
, o
->sha1
);
1843 * Peel the entry (if possible) and return its new peel_status. If
1844 * repeel is true, re-peel the entry even if there is an old peeled
1845 * value that is already stored in it.
1847 * It is OK to call this function with a packed reference entry that
1848 * might be stale and might even refer to an object that has since
1849 * been garbage-collected. In such a case, if the entry has
1850 * REF_KNOWS_PEELED then leave the status unchanged and return
1851 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1853 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1855 enum peel_status status
;
1857 if (entry
->flag
& REF_KNOWS_PEELED
) {
1859 entry
->flag
&= ~REF_KNOWS_PEELED
;
1860 oidclr(&entry
->u
.value
.peeled
);
1862 return is_null_oid(&entry
->u
.value
.peeled
) ?
1863 PEEL_NON_TAG
: PEEL_PEELED
;
1866 if (entry
->flag
& REF_ISBROKEN
)
1868 if (entry
->flag
& REF_ISSYMREF
)
1869 return PEEL_IS_SYMREF
;
1871 status
= peel_object(entry
->u
.value
.oid
.hash
, entry
->u
.value
.peeled
.hash
);
1872 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1873 entry
->flag
|= REF_KNOWS_PEELED
;
1877 int peel_ref(const char *refname
, unsigned char *sha1
)
1880 unsigned char base
[20];
1882 if (current_ref
&& (current_ref
->name
== refname
1883 || !strcmp(current_ref
->name
, refname
))) {
1884 if (peel_entry(current_ref
, 0))
1886 hashcpy(sha1
, current_ref
->u
.value
.peeled
.hash
);
1890 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1894 * If the reference is packed, read its ref_entry from the
1895 * cache in the hope that we already know its peeled value.
1896 * We only try this optimization on packed references because
1897 * (a) forcing the filling of the loose reference cache could
1898 * be expensive and (b) loose references anyway usually do not
1899 * have REF_KNOWS_PEELED.
1901 if (flag
& REF_ISPACKED
) {
1902 struct ref_entry
*r
= get_packed_ref(refname
);
1904 if (peel_entry(r
, 0))
1906 hashcpy(sha1
, r
->u
.value
.peeled
.hash
);
1911 return peel_object(base
, sha1
);
1914 struct warn_if_dangling_data
{
1916 const char *refname
;
1917 const struct string_list
*refnames
;
1918 const char *msg_fmt
;
1921 static int warn_if_dangling_symref(const char *refname
, const struct object_id
*oid
,
1922 int flags
, void *cb_data
)
1924 struct warn_if_dangling_data
*d
= cb_data
;
1925 const char *resolves_to
;
1926 struct object_id junk
;
1928 if (!(flags
& REF_ISSYMREF
))
1931 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
.hash
, NULL
);
1934 ? strcmp(resolves_to
, d
->refname
)
1935 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1939 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1944 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1946 struct warn_if_dangling_data data
;
1949 data
.refname
= refname
;
1950 data
.refnames
= NULL
;
1951 data
.msg_fmt
= msg_fmt
;
1952 for_each_rawref(warn_if_dangling_symref
, &data
);
1955 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1957 struct warn_if_dangling_data data
;
1960 data
.refname
= NULL
;
1961 data
.refnames
= refnames
;
1962 data
.msg_fmt
= msg_fmt
;
1963 for_each_rawref(warn_if_dangling_symref
, &data
);
1967 * Call fn for each reference in the specified ref_cache, omitting
1968 * references not in the containing_dir of base. fn is called for all
1969 * references, including broken ones. If fn ever returns a non-zero
1970 * value, stop the iteration and return that value; otherwise, return
1973 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1974 each_ref_entry_fn fn
, void *cb_data
)
1976 struct packed_ref_cache
*packed_ref_cache
;
1977 struct ref_dir
*loose_dir
;
1978 struct ref_dir
*packed_dir
;
1982 * We must make sure that all loose refs are read before accessing the
1983 * packed-refs file; this avoids a race condition in which loose refs
1984 * are migrated to the packed-refs file by a simultaneous process, but
1985 * our in-memory view is from before the migration. get_packed_ref_cache()
1986 * takes care of making sure our view is up to date with what is on
1989 loose_dir
= get_loose_refs(refs
);
1990 if (base
&& *base
) {
1991 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
1994 prime_ref_dir(loose_dir
);
1996 packed_ref_cache
= get_packed_ref_cache(refs
);
1997 acquire_packed_ref_cache(packed_ref_cache
);
1998 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
1999 if (base
&& *base
) {
2000 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
2003 if (packed_dir
&& loose_dir
) {
2004 sort_ref_dir(packed_dir
);
2005 sort_ref_dir(loose_dir
);
2006 retval
= do_for_each_entry_in_dirs(
2007 packed_dir
, loose_dir
, fn
, cb_data
);
2008 } else if (packed_dir
) {
2009 sort_ref_dir(packed_dir
);
2010 retval
= do_for_each_entry_in_dir(
2011 packed_dir
, 0, fn
, cb_data
);
2012 } else if (loose_dir
) {
2013 sort_ref_dir(loose_dir
);
2014 retval
= do_for_each_entry_in_dir(
2015 loose_dir
, 0, fn
, cb_data
);
2018 release_packed_ref_cache(packed_ref_cache
);
2023 * Call fn for each reference in the specified ref_cache for which the
2024 * refname begins with base. If trim is non-zero, then trim that many
2025 * characters off the beginning of each refname before passing the
2026 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2027 * broken references in the iteration. If fn ever returns a non-zero
2028 * value, stop the iteration and return that value; otherwise, return
2031 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
2032 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
2034 struct ref_entry_cb data
;
2039 data
.cb_data
= cb_data
;
2041 if (ref_paranoia
< 0)
2042 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2044 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2046 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
2049 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2051 struct object_id oid
;
2055 if (resolve_gitlink_ref(submodule
, "HEAD", oid
.hash
) == 0)
2056 return fn("HEAD", &oid
, 0, cb_data
);
2061 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, oid
.hash
, &flag
))
2062 return fn("HEAD", &oid
, flag
, cb_data
);
2067 int head_ref(each_ref_fn fn
, void *cb_data
)
2069 return do_head_ref(NULL
, fn
, cb_data
);
2072 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2074 return do_head_ref(submodule
, fn
, cb_data
);
2077 int for_each_ref(each_ref_fn fn
, void *cb_data
)
2079 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
2082 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2084 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2087 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2089 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2092 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2093 each_ref_fn fn
, void *cb_data
)
2095 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2098 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2100 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2103 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2105 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2108 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2110 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2113 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2115 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2118 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2120 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2123 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2125 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2128 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2130 return do_for_each_ref(&ref_cache
, "refs/replace/", fn
, 13, 0, cb_data
);
2133 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2135 struct strbuf buf
= STRBUF_INIT
;
2137 struct object_id oid
;
2140 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2141 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, oid
.hash
, &flag
))
2142 ret
= fn(buf
.buf
, &oid
, flag
, cb_data
);
2143 strbuf_release(&buf
);
2148 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2150 struct strbuf buf
= STRBUF_INIT
;
2152 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2153 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2154 strbuf_release(&buf
);
2158 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2159 const char *prefix
, void *cb_data
)
2161 struct strbuf real_pattern
= STRBUF_INIT
;
2162 struct ref_filter filter
;
2165 if (!prefix
&& !starts_with(pattern
, "refs/"))
2166 strbuf_addstr(&real_pattern
, "refs/");
2168 strbuf_addstr(&real_pattern
, prefix
);
2169 strbuf_addstr(&real_pattern
, pattern
);
2171 if (!has_glob_specials(pattern
)) {
2172 /* Append implied '/' '*' if not present. */
2173 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2174 strbuf_addch(&real_pattern
, '/');
2175 /* No need to check for '*', there is none. */
2176 strbuf_addch(&real_pattern
, '*');
2179 filter
.pattern
= real_pattern
.buf
;
2181 filter
.cb_data
= cb_data
;
2182 ret
= for_each_ref(filter_refs
, &filter
);
2184 strbuf_release(&real_pattern
);
2188 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2190 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2193 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2195 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2196 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2199 const char *prettify_refname(const char *name
)
2202 starts_with(name
, "refs/heads/") ? 11 :
2203 starts_with(name
, "refs/tags/") ? 10 :
2204 starts_with(name
, "refs/remotes/") ? 13 :
2208 static const char *ref_rev_parse_rules
[] = {
2213 "refs/remotes/%.*s",
2214 "refs/remotes/%.*s/HEAD",
2218 int refname_match(const char *abbrev_name
, const char *full_name
)
2221 const int abbrev_name_len
= strlen(abbrev_name
);
2223 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2224 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2232 static void unlock_ref(struct ref_lock
*lock
)
2234 /* Do not free lock->lk -- atexit() still looks at them */
2236 rollback_lock_file(lock
->lk
);
2237 free(lock
->ref_name
);
2238 free(lock
->orig_ref_name
);
2243 * Verify that the reference locked by lock has the value old_sha1.
2244 * Fail if the reference doesn't exist and mustexist is set. Return 0
2245 * on success. On error, write an error message to err, set errno, and
2246 * return a negative value.
2248 static int verify_lock(struct ref_lock
*lock
,
2249 const unsigned char *old_sha1
, int mustexist
,
2254 if (read_ref_full(lock
->ref_name
,
2255 mustexist
? RESOLVE_REF_READING
: 0,
2256 lock
->old_oid
.hash
, NULL
)) {
2257 int save_errno
= errno
;
2258 strbuf_addf(err
, "can't verify ref %s", lock
->ref_name
);
2262 if (hashcmp(lock
->old_oid
.hash
, old_sha1
)) {
2263 strbuf_addf(err
, "ref %s is at %s but expected %s",
2265 sha1_to_hex(lock
->old_oid
.hash
),
2266 sha1_to_hex(old_sha1
));
2273 static int remove_empty_directories(const char *file
)
2275 /* we want to create a file but there is a directory there;
2276 * if that is an empty directory (or a directory that contains
2277 * only empty directories), remove them.
2280 int result
, save_errno
;
2282 strbuf_init(&path
, 20);
2283 strbuf_addstr(&path
, file
);
2285 result
= remove_dir_recursively(&path
, REMOVE_DIR_EMPTY_ONLY
);
2288 strbuf_release(&path
);
2295 * *string and *len will only be substituted, and *string returned (for
2296 * later free()ing) if the string passed in is a magic short-hand form
2299 static char *substitute_branch_name(const char **string
, int *len
)
2301 struct strbuf buf
= STRBUF_INIT
;
2302 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2306 *string
= strbuf_detach(&buf
, &size
);
2308 return (char *)*string
;
2314 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2316 char *last_branch
= substitute_branch_name(&str
, &len
);
2321 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2322 char fullref
[PATH_MAX
];
2323 unsigned char sha1_from_ref
[20];
2324 unsigned char *this_result
;
2327 this_result
= refs_found
? sha1_from_ref
: sha1
;
2328 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2329 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2330 this_result
, &flag
);
2334 if (!warn_ambiguous_refs
)
2336 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2337 warning("ignoring dangling symref %s.", fullref
);
2338 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2339 warning("ignoring broken ref %s.", fullref
);
2346 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2348 char *last_branch
= substitute_branch_name(&str
, &len
);
2353 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2354 unsigned char hash
[20];
2355 char path
[PATH_MAX
];
2356 const char *ref
, *it
;
2358 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2359 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2363 if (reflog_exists(path
))
2365 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2369 if (!logs_found
++) {
2371 hashcpy(sha1
, hash
);
2373 if (!warn_ambiguous_refs
)
2381 * Locks a ref returning the lock on success and NULL on failure.
2382 * On failure errno is set to something meaningful.
2384 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2385 const unsigned char *old_sha1
,
2386 const struct string_list
*extras
,
2387 const struct string_list
*skip
,
2388 unsigned int flags
, int *type_p
,
2391 const char *ref_file
;
2392 const char *orig_refname
= refname
;
2393 struct ref_lock
*lock
;
2396 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2397 int resolve_flags
= 0;
2398 int attempts_remaining
= 3;
2402 lock
= xcalloc(1, sizeof(struct ref_lock
));
2405 resolve_flags
|= RESOLVE_REF_READING
;
2406 if (flags
& REF_DELETING
) {
2407 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2408 if (flags
& REF_NODEREF
)
2409 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2412 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2413 lock
->old_oid
.hash
, &type
);
2414 if (!refname
&& errno
== EISDIR
) {
2415 /* we are trying to lock foo but we used to
2416 * have foo/bar which now does not exist;
2417 * it is normal for the empty directory 'foo'
2420 ref_file
= git_path("%s", orig_refname
);
2421 if (remove_empty_directories(ref_file
)) {
2424 if (!verify_refname_available(orig_refname
, extras
, skip
,
2425 get_loose_refs(&ref_cache
), err
))
2426 strbuf_addf(err
, "there are still refs under '%s'",
2431 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2432 lock
->old_oid
.hash
, &type
);
2438 if (last_errno
!= ENOTDIR
||
2439 !verify_refname_available(orig_refname
, extras
, skip
,
2440 get_loose_refs(&ref_cache
), err
))
2441 strbuf_addf(err
, "unable to resolve reference %s: %s",
2442 orig_refname
, strerror(last_errno
));
2447 * If the ref did not exist and we are creating it, make sure
2448 * there is no existing packed ref whose name begins with our
2449 * refname, nor a packed ref whose name is a proper prefix of
2452 if (is_null_oid(&lock
->old_oid
) &&
2453 verify_refname_available(refname
, extras
, skip
,
2454 get_packed_refs(&ref_cache
), err
)) {
2455 last_errno
= ENOTDIR
;
2459 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2462 if (flags
& REF_NODEREF
) {
2463 refname
= orig_refname
;
2464 lflags
|= LOCK_NO_DEREF
;
2466 lock
->ref_name
= xstrdup(refname
);
2467 lock
->orig_ref_name
= xstrdup(orig_refname
);
2468 ref_file
= git_path("%s", refname
);
2471 switch (safe_create_leading_directories_const(ref_file
)) {
2473 break; /* success */
2475 if (--attempts_remaining
> 0)
2480 strbuf_addf(err
, "unable to create directory for %s", ref_file
);
2484 if (hold_lock_file_for_update(lock
->lk
, ref_file
, lflags
) < 0) {
2486 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2488 * Maybe somebody just deleted one of the
2489 * directories leading to ref_file. Try
2494 unable_to_lock_message(ref_file
, errno
, err
);
2498 if (old_sha1
&& verify_lock(lock
, old_sha1
, mustexist
, err
)) {
2511 * Write an entry to the packed-refs file for the specified refname.
2512 * If peeled is non-NULL, write it as the entry's peeled value.
2514 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2515 unsigned char *peeled
)
2517 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2519 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2523 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2525 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2527 enum peel_status peel_status
= peel_entry(entry
, 0);
2529 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2530 error("internal error: %s is not a valid packed reference!",
2532 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.oid
.hash
,
2533 peel_status
== PEEL_PEELED
?
2534 entry
->u
.value
.peeled
.hash
: NULL
);
2538 /* This should return a meaningful errno on failure */
2539 int lock_packed_refs(int flags
)
2541 static int timeout_configured
= 0;
2542 static int timeout_value
= 1000;
2544 struct packed_ref_cache
*packed_ref_cache
;
2546 if (!timeout_configured
) {
2547 git_config_get_int("core.packedrefstimeout", &timeout_value
);
2548 timeout_configured
= 1;
2551 if (hold_lock_file_for_update_timeout(
2552 &packlock
, git_path("packed-refs"),
2553 flags
, timeout_value
) < 0)
2556 * Get the current packed-refs while holding the lock. If the
2557 * packed-refs file has been modified since we last read it,
2558 * this will automatically invalidate the cache and re-read
2559 * the packed-refs file.
2561 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2562 packed_ref_cache
->lock
= &packlock
;
2563 /* Increment the reference count to prevent it from being freed: */
2564 acquire_packed_ref_cache(packed_ref_cache
);
2569 * Commit the packed refs changes.
2570 * On error we must make sure that errno contains a meaningful value.
2572 int commit_packed_refs(void)
2574 struct packed_ref_cache
*packed_ref_cache
=
2575 get_packed_ref_cache(&ref_cache
);
2580 if (!packed_ref_cache
->lock
)
2581 die("internal error: packed-refs not locked");
2583 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2585 die_errno("unable to fdopen packed-refs descriptor");
2587 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2588 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2589 0, write_packed_entry_fn
, out
);
2591 if (commit_lock_file(packed_ref_cache
->lock
)) {
2595 packed_ref_cache
->lock
= NULL
;
2596 release_packed_ref_cache(packed_ref_cache
);
2601 void rollback_packed_refs(void)
2603 struct packed_ref_cache
*packed_ref_cache
=
2604 get_packed_ref_cache(&ref_cache
);
2606 if (!packed_ref_cache
->lock
)
2607 die("internal error: packed-refs not locked");
2608 rollback_lock_file(packed_ref_cache
->lock
);
2609 packed_ref_cache
->lock
= NULL
;
2610 release_packed_ref_cache(packed_ref_cache
);
2611 clear_packed_ref_cache(&ref_cache
);
2614 struct ref_to_prune
{
2615 struct ref_to_prune
*next
;
2616 unsigned char sha1
[20];
2617 char name
[FLEX_ARRAY
];
2620 struct pack_refs_cb_data
{
2622 struct ref_dir
*packed_refs
;
2623 struct ref_to_prune
*ref_to_prune
;
2627 * An each_ref_entry_fn that is run over loose references only. If
2628 * the loose reference can be packed, add an entry in the packed ref
2629 * cache. If the reference should be pruned, also add it to
2630 * ref_to_prune in the pack_refs_cb_data.
2632 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2634 struct pack_refs_cb_data
*cb
= cb_data
;
2635 enum peel_status peel_status
;
2636 struct ref_entry
*packed_entry
;
2637 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2639 /* ALWAYS pack tags */
2640 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2643 /* Do not pack symbolic or broken refs: */
2644 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2647 /* Add a packed ref cache entry equivalent to the loose entry. */
2648 peel_status
= peel_entry(entry
, 1);
2649 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2650 die("internal error peeling reference %s (%s)",
2651 entry
->name
, oid_to_hex(&entry
->u
.value
.oid
));
2652 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2654 /* Overwrite existing packed entry with info from loose entry */
2655 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2656 oidcpy(&packed_entry
->u
.value
.oid
, &entry
->u
.value
.oid
);
2658 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.oid
.hash
,
2659 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2660 add_ref(cb
->packed_refs
, packed_entry
);
2662 oidcpy(&packed_entry
->u
.value
.peeled
, &entry
->u
.value
.peeled
);
2664 /* Schedule the loose reference for pruning if requested. */
2665 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2666 int namelen
= strlen(entry
->name
) + 1;
2667 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2668 hashcpy(n
->sha1
, entry
->u
.value
.oid
.hash
);
2669 strcpy(n
->name
, entry
->name
);
2670 n
->next
= cb
->ref_to_prune
;
2671 cb
->ref_to_prune
= n
;
2677 * Remove empty parents, but spare refs/ and immediate subdirs.
2678 * Note: munges *name.
2680 static void try_remove_empty_parents(char *name
)
2685 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2686 while (*p
&& *p
!= '/')
2688 /* tolerate duplicate slashes; see check_refname_format() */
2692 for (q
= p
; *q
; q
++)
2695 while (q
> p
&& *q
!= '/')
2697 while (q
> p
&& *(q
-1) == '/')
2702 if (rmdir(git_path("%s", name
)))
2707 /* make sure nobody touched the ref, and unlink */
2708 static void prune_ref(struct ref_to_prune
*r
)
2710 struct ref_transaction
*transaction
;
2711 struct strbuf err
= STRBUF_INIT
;
2713 if (check_refname_format(r
->name
, 0))
2716 transaction
= ref_transaction_begin(&err
);
2718 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2719 REF_ISPRUNING
, NULL
, &err
) ||
2720 ref_transaction_commit(transaction
, &err
)) {
2721 ref_transaction_free(transaction
);
2722 error("%s", err
.buf
);
2723 strbuf_release(&err
);
2726 ref_transaction_free(transaction
);
2727 strbuf_release(&err
);
2728 try_remove_empty_parents(r
->name
);
2731 static void prune_refs(struct ref_to_prune
*r
)
2739 int pack_refs(unsigned int flags
)
2741 struct pack_refs_cb_data cbdata
;
2743 memset(&cbdata
, 0, sizeof(cbdata
));
2744 cbdata
.flags
= flags
;
2746 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2747 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2749 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2750 pack_if_possible_fn
, &cbdata
);
2752 if (commit_packed_refs())
2753 die_errno("unable to overwrite old ref-pack file");
2755 prune_refs(cbdata
.ref_to_prune
);
2759 int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2761 struct ref_dir
*packed
;
2762 struct string_list_item
*refname
;
2763 int ret
, needs_repacking
= 0, removed
= 0;
2767 /* Look for a packed ref */
2768 for_each_string_list_item(refname
, refnames
) {
2769 if (get_packed_ref(refname
->string
)) {
2770 needs_repacking
= 1;
2775 /* Avoid locking if we have nothing to do */
2776 if (!needs_repacking
)
2777 return 0; /* no refname exists in packed refs */
2779 if (lock_packed_refs(0)) {
2780 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2783 packed
= get_packed_refs(&ref_cache
);
2785 /* Remove refnames from the cache */
2786 for_each_string_list_item(refname
, refnames
)
2787 if (remove_entry(packed
, refname
->string
) != -1)
2791 * All packed entries disappeared while we were
2792 * acquiring the lock.
2794 rollback_packed_refs();
2798 /* Write what remains */
2799 ret
= commit_packed_refs();
2801 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2806 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2810 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2812 * loose. The loose file name is the same as the
2813 * lockfile name, minus ".lock":
2815 char *loose_filename
= get_locked_file_path(lock
->lk
);
2816 int res
= unlink_or_msg(loose_filename
, err
);
2817 free(loose_filename
);
2824 static int is_per_worktree_ref(const char *refname
)
2826 return !strcmp(refname
, "HEAD");
2829 static int is_pseudoref_syntax(const char *refname
)
2833 for (c
= refname
; *c
; c
++) {
2834 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
2841 enum ref_type
ref_type(const char *refname
)
2843 if (is_per_worktree_ref(refname
))
2844 return REF_TYPE_PER_WORKTREE
;
2845 if (is_pseudoref_syntax(refname
))
2846 return REF_TYPE_PSEUDOREF
;
2847 return REF_TYPE_NORMAL
;
2850 static int write_pseudoref(const char *pseudoref
, const unsigned char *sha1
,
2851 const unsigned char *old_sha1
, struct strbuf
*err
)
2853 const char *filename
;
2855 static struct lock_file lock
;
2856 struct strbuf buf
= STRBUF_INIT
;
2859 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
2861 filename
= git_path("%s", pseudoref
);
2862 fd
= hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
2864 strbuf_addf(err
, "Could not open '%s' for writing: %s",
2865 filename
, strerror(errno
));
2870 unsigned char actual_old_sha1
[20];
2872 if (read_ref(pseudoref
, actual_old_sha1
))
2873 die("could not read ref '%s'", pseudoref
);
2874 if (hashcmp(actual_old_sha1
, old_sha1
)) {
2875 strbuf_addf(err
, "Unexpected sha1 when writing %s", pseudoref
);
2876 rollback_lock_file(&lock
);
2881 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
) {
2882 strbuf_addf(err
, "Could not write to '%s'", filename
);
2883 rollback_lock_file(&lock
);
2887 commit_lock_file(&lock
);
2890 strbuf_release(&buf
);
2894 static int delete_pseudoref(const char *pseudoref
, const unsigned char *old_sha1
)
2896 static struct lock_file lock
;
2897 const char *filename
;
2899 filename
= git_path("%s", pseudoref
);
2901 if (old_sha1
&& !is_null_sha1(old_sha1
)) {
2903 unsigned char actual_old_sha1
[20];
2905 fd
= hold_lock_file_for_update(&lock
, filename
,
2908 die_errno(_("Could not open '%s' for writing"), filename
);
2909 if (read_ref(pseudoref
, actual_old_sha1
))
2910 die("could not read ref '%s'", pseudoref
);
2911 if (hashcmp(actual_old_sha1
, old_sha1
)) {
2912 warning("Unexpected sha1 when deleting %s", pseudoref
);
2913 rollback_lock_file(&lock
);
2918 rollback_lock_file(&lock
);
2926 int delete_ref(const char *refname
, const unsigned char *sha1
, unsigned int flags
)
2928 struct ref_transaction
*transaction
;
2929 struct strbuf err
= STRBUF_INIT
;
2931 if (ref_type(refname
) == REF_TYPE_PSEUDOREF
)
2932 return delete_pseudoref(refname
, sha1
);
2934 transaction
= ref_transaction_begin(&err
);
2936 ref_transaction_delete(transaction
, refname
,
2937 (sha1
&& !is_null_sha1(sha1
)) ? sha1
: NULL
,
2938 flags
, NULL
, &err
) ||
2939 ref_transaction_commit(transaction
, &err
)) {
2940 error("%s", err
.buf
);
2941 ref_transaction_free(transaction
);
2942 strbuf_release(&err
);
2945 ref_transaction_free(transaction
);
2946 strbuf_release(&err
);
2951 * People using contrib's git-new-workdir have .git/logs/refs ->
2952 * /some/other/path/.git/logs/refs, and that may live on another device.
2954 * IOW, to avoid cross device rename errors, the temporary renamed log must
2955 * live into logs/refs.
2957 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2959 static int rename_tmp_log(const char *newrefname
)
2961 int attempts_remaining
= 4;
2964 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname
))) {
2966 break; /* success */
2968 if (--attempts_remaining
> 0)
2972 error("unable to create directory for %s", newrefname
);
2976 if (rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", newrefname
))) {
2977 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
2979 * rename(a, b) when b is an existing
2980 * directory ought to result in ISDIR, but
2981 * Solaris 5.8 gives ENOTDIR. Sheesh.
2983 if (remove_empty_directories(git_path("logs/%s", newrefname
))) {
2984 error("Directory not empty: logs/%s", newrefname
);
2988 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
2990 * Maybe another process just deleted one of
2991 * the directories in the path to newrefname.
2992 * Try again from the beginning.
2996 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
2997 newrefname
, strerror(errno
));
3004 static int rename_ref_available(const char *oldname
, const char *newname
)
3006 struct string_list skip
= STRING_LIST_INIT_NODUP
;
3007 struct strbuf err
= STRBUF_INIT
;
3010 string_list_insert(&skip
, oldname
);
3011 ret
= !verify_refname_available(newname
, NULL
, &skip
,
3012 get_packed_refs(&ref_cache
), &err
)
3013 && !verify_refname_available(newname
, NULL
, &skip
,
3014 get_loose_refs(&ref_cache
), &err
);
3016 error("%s", err
.buf
);
3018 string_list_clear(&skip
, 0);
3019 strbuf_release(&err
);
3023 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3024 const unsigned char *sha1
, struct strbuf
*err
);
3025 static int commit_ref_update(struct ref_lock
*lock
,
3026 const unsigned char *sha1
, const char *logmsg
,
3027 int flags
, struct strbuf
*err
);
3029 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
3031 unsigned char sha1
[20], orig_sha1
[20];
3032 int flag
= 0, logmoved
= 0;
3033 struct ref_lock
*lock
;
3034 struct stat loginfo
;
3035 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
3036 const char *symref
= NULL
;
3037 struct strbuf err
= STRBUF_INIT
;
3039 if (log
&& S_ISLNK(loginfo
.st_mode
))
3040 return error("reflog for %s is a symlink", oldrefname
);
3042 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
3044 if (flag
& REF_ISSYMREF
)
3045 return error("refname %s is a symbolic ref, renaming it is not supported",
3048 return error("refname %s not found", oldrefname
);
3050 if (!rename_ref_available(oldrefname
, newrefname
))
3053 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
3054 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
3055 oldrefname
, strerror(errno
));
3057 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
3058 error("unable to delete old %s", oldrefname
);
3062 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
3063 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
3064 if (errno
==EISDIR
) {
3065 if (remove_empty_directories(git_path("%s", newrefname
))) {
3066 error("Directory not empty: %s", newrefname
);
3070 error("unable to delete existing %s", newrefname
);
3075 if (log
&& rename_tmp_log(newrefname
))
3080 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
3082 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
3083 strbuf_release(&err
);
3086 hashcpy(lock
->old_oid
.hash
, orig_sha1
);
3088 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
3089 commit_ref_update(lock
, orig_sha1
, logmsg
, 0, &err
)) {
3090 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
3091 strbuf_release(&err
);
3098 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
3100 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
3101 strbuf_release(&err
);
3105 flag
= log_all_ref_updates
;
3106 log_all_ref_updates
= 0;
3107 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
3108 commit_ref_update(lock
, orig_sha1
, NULL
, 0, &err
)) {
3109 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
3110 strbuf_release(&err
);
3112 log_all_ref_updates
= flag
;
3115 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
3116 error("unable to restore logfile %s from %s: %s",
3117 oldrefname
, newrefname
, strerror(errno
));
3118 if (!logmoved
&& log
&&
3119 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
3120 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
3121 oldrefname
, strerror(errno
));
3126 static int close_ref(struct ref_lock
*lock
)
3128 if (close_lock_file(lock
->lk
))
3133 static int commit_ref(struct ref_lock
*lock
)
3135 if (commit_lock_file(lock
->lk
))
3141 * copy the reflog message msg to buf, which has been allocated sufficiently
3142 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3143 * because reflog file is one line per entry.
3145 static int copy_msg(char *buf
, const char *msg
)
3152 while ((c
= *msg
++)) {
3153 if (wasspace
&& isspace(c
))
3155 wasspace
= isspace(c
);
3160 while (buf
< cp
&& isspace(cp
[-1]))
3166 static int should_autocreate_reflog(const char *refname
)
3168 if (!log_all_ref_updates
)
3170 return starts_with(refname
, "refs/heads/") ||
3171 starts_with(refname
, "refs/remotes/") ||
3172 starts_with(refname
, "refs/notes/") ||
3173 !strcmp(refname
, "HEAD");
3177 * Create a reflog for a ref. If force_create = 0, the reflog will
3178 * only be created for certain refs (those for which
3179 * should_autocreate_reflog returns non-zero. Otherwise, create it
3180 * regardless of the ref name. Fill in *err and return -1 on failure.
3182 static int log_ref_setup(const char *refname
, struct strbuf
*sb_logfile
, struct strbuf
*err
, int force_create
)
3184 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
3187 strbuf_git_path(sb_logfile
, "logs/%s", refname
);
3188 logfile
= sb_logfile
->buf
;
3189 /* make sure the rest of the function can't change "logfile" */
3191 if (force_create
|| should_autocreate_reflog(refname
)) {
3192 if (safe_create_leading_directories(logfile
) < 0) {
3193 strbuf_addf(err
, "unable to create directory for %s: "
3194 "%s", logfile
, strerror(errno
));
3200 logfd
= open(logfile
, oflags
, 0666);
3202 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3205 if (errno
== EISDIR
) {
3206 if (remove_empty_directories(logfile
)) {
3207 strbuf_addf(err
, "There are still logs under "
3211 logfd
= open(logfile
, oflags
, 0666);
3215 strbuf_addf(err
, "unable to append to %s: %s",
3216 logfile
, strerror(errno
));
3221 adjust_shared_perm(logfile
);
3227 int safe_create_reflog(const char *refname
, int force_create
, struct strbuf
*err
)
3230 struct strbuf sb
= STRBUF_INIT
;
3232 ret
= log_ref_setup(refname
, &sb
, err
, force_create
);
3233 strbuf_release(&sb
);
3237 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3238 const unsigned char *new_sha1
,
3239 const char *committer
, const char *msg
)
3241 int msglen
, written
;
3242 unsigned maxlen
, len
;
3245 msglen
= msg
? strlen(msg
) : 0;
3246 maxlen
= strlen(committer
) + msglen
+ 100;
3247 logrec
= xmalloc(maxlen
);
3248 len
= sprintf(logrec
, "%s %s %s\n",
3249 sha1_to_hex(old_sha1
),
3250 sha1_to_hex(new_sha1
),
3253 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3255 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3263 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
3264 const unsigned char *new_sha1
, const char *msg
,
3265 struct strbuf
*sb_log_file
, int flags
,
3268 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3271 if (log_all_ref_updates
< 0)
3272 log_all_ref_updates
= !is_bare_repository();
3274 result
= log_ref_setup(refname
, sb_log_file
, err
, flags
& REF_FORCE_CREATE_REFLOG
);
3278 log_file
= sb_log_file
->buf
;
3279 /* make sure the rest of the function can't change "log_file" */
3282 logfd
= open(log_file
, oflags
);
3285 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3286 git_committer_info(0), msg
);
3288 strbuf_addf(err
, "unable to append to %s: %s", log_file
,
3294 strbuf_addf(err
, "unable to append to %s: %s", log_file
,
3301 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3302 const unsigned char *new_sha1
, const char *msg
,
3303 int flags
, struct strbuf
*err
)
3305 struct strbuf sb
= STRBUF_INIT
;
3306 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
, flags
,
3308 strbuf_release(&sb
);
3312 int is_branch(const char *refname
)
3314 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3318 * Write sha1 into the open lockfile, then close the lockfile. On
3319 * errors, rollback the lockfile, fill in *err and
3322 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3323 const unsigned char *sha1
, struct strbuf
*err
)
3325 static char term
= '\n';
3328 o
= parse_object(sha1
);
3331 "Trying to write ref %s with nonexistent object %s",
3332 lock
->ref_name
, sha1_to_hex(sha1
));
3336 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3338 "Trying to write non-commit object %s to branch %s",
3339 sha1_to_hex(sha1
), lock
->ref_name
);
3343 if (write_in_full(lock
->lk
->fd
, sha1_to_hex(sha1
), 40) != 40 ||
3344 write_in_full(lock
->lk
->fd
, &term
, 1) != 1 ||
3345 close_ref(lock
) < 0) {
3347 "Couldn't write %s", lock
->lk
->filename
.buf
);
3355 * Commit a change to a loose reference that has already been written
3356 * to the loose reference lockfile. Also update the reflogs if
3357 * necessary, using the specified lockmsg (which can be NULL).
3359 static int commit_ref_update(struct ref_lock
*lock
,
3360 const unsigned char *sha1
, const char *logmsg
,
3361 int flags
, struct strbuf
*err
)
3363 clear_loose_ref_cache(&ref_cache
);
3364 if (log_ref_write(lock
->ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, flags
, err
) < 0 ||
3365 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3366 log_ref_write(lock
->orig_ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, flags
, err
) < 0)) {
3367 char *old_msg
= strbuf_detach(err
, NULL
);
3368 strbuf_addf(err
, "Cannot update the ref '%s': %s",
3369 lock
->ref_name
, old_msg
);
3374 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3376 * Special hack: If a branch is updated directly and HEAD
3377 * points to it (may happen on the remote side of a push
3378 * for example) then logically the HEAD reflog should be
3380 * A generic solution implies reverse symref information,
3381 * but finding all symrefs pointing to the given branch
3382 * would be rather costly for this rare event (the direct
3383 * update of a branch) to be worth it. So let's cheat and
3384 * check with HEAD only which should cover 99% of all usage
3385 * scenarios (even 100% of the default ones).
3387 unsigned char head_sha1
[20];
3389 const char *head_ref
;
3390 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3391 head_sha1
, &head_flag
);
3392 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3393 !strcmp(head_ref
, lock
->ref_name
)) {
3394 struct strbuf log_err
= STRBUF_INIT
;
3395 if (log_ref_write("HEAD", lock
->old_oid
.hash
, sha1
,
3396 logmsg
, 0, &log_err
)) {
3397 error("%s", log_err
.buf
);
3398 strbuf_release(&log_err
);
3402 if (commit_ref(lock
)) {
3403 error("Couldn't set %s", lock
->ref_name
);
3412 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3415 const char *lockpath
;
3417 int fd
, len
, written
;
3418 char *git_HEAD
= git_pathdup("%s", ref_target
);
3419 unsigned char old_sha1
[20], new_sha1
[20];
3420 struct strbuf err
= STRBUF_INIT
;
3422 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3425 if (safe_create_leading_directories(git_HEAD
) < 0)
3426 return error("unable to create directory for %s", git_HEAD
);
3428 #ifndef NO_SYMLINK_HEAD
3429 if (prefer_symlink_refs
) {
3431 if (!symlink(refs_heads_master
, git_HEAD
))
3433 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3437 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3438 if (sizeof(ref
) <= len
) {
3439 error("refname too long: %s", refs_heads_master
);
3440 goto error_free_return
;
3442 lockpath
= mkpath("%s.lock", git_HEAD
);
3443 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3445 error("Unable to open %s for writing", lockpath
);
3446 goto error_free_return
;
3448 written
= write_in_full(fd
, ref
, len
);
3449 if (close(fd
) != 0 || written
!= len
) {
3450 error("Unable to write to %s", lockpath
);
3451 goto error_unlink_return
;
3453 if (rename(lockpath
, git_HEAD
) < 0) {
3454 error("Unable to create %s", git_HEAD
);
3455 goto error_unlink_return
;
3457 if (adjust_shared_perm(git_HEAD
)) {
3458 error("Unable to fix permissions on %s", lockpath
);
3459 error_unlink_return
:
3460 unlink_or_warn(lockpath
);
3466 #ifndef NO_SYMLINK_HEAD
3469 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
) &&
3470 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
, 0, &err
)) {
3471 error("%s", err
.buf
);
3472 strbuf_release(&err
);
3479 struct read_ref_at_cb
{
3480 const char *refname
;
3481 unsigned long at_time
;
3484 unsigned char *sha1
;
3487 unsigned char osha1
[20];
3488 unsigned char nsha1
[20];
3492 unsigned long *cutoff_time
;
3497 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3498 const char *email
, unsigned long timestamp
, int tz
,
3499 const char *message
, void *cb_data
)
3501 struct read_ref_at_cb
*cb
= cb_data
;
3505 cb
->date
= timestamp
;
3507 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3509 *cb
->msg
= xstrdup(message
);
3510 if (cb
->cutoff_time
)
3511 *cb
->cutoff_time
= timestamp
;
3513 *cb
->cutoff_tz
= tz
;
3515 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3517 * we have not yet updated cb->[n|o]sha1 so they still
3518 * hold the values for the previous record.
3520 if (!is_null_sha1(cb
->osha1
)) {
3521 hashcpy(cb
->sha1
, nsha1
);
3522 if (hashcmp(cb
->osha1
, nsha1
))
3523 warning("Log for ref %s has gap after %s.",
3524 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_RFC2822
));
3526 else if (cb
->date
== cb
->at_time
)
3527 hashcpy(cb
->sha1
, nsha1
);
3528 else if (hashcmp(nsha1
, cb
->sha1
))
3529 warning("Log for ref %s unexpectedly ended on %s.",
3530 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3532 hashcpy(cb
->osha1
, osha1
);
3533 hashcpy(cb
->nsha1
, nsha1
);
3537 hashcpy(cb
->osha1
, osha1
);
3538 hashcpy(cb
->nsha1
, nsha1
);
3544 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3545 const char *email
, unsigned long timestamp
,
3546 int tz
, const char *message
, void *cb_data
)
3548 struct read_ref_at_cb
*cb
= cb_data
;
3551 *cb
->msg
= xstrdup(message
);
3552 if (cb
->cutoff_time
)
3553 *cb
->cutoff_time
= timestamp
;
3555 *cb
->cutoff_tz
= tz
;
3557 *cb
->cutoff_cnt
= cb
->reccnt
;
3558 hashcpy(cb
->sha1
, osha1
);
3559 if (is_null_sha1(cb
->sha1
))
3560 hashcpy(cb
->sha1
, nsha1
);
3561 /* We just want the first entry */
3565 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3566 unsigned char *sha1
, char **msg
,
3567 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3569 struct read_ref_at_cb cb
;
3571 memset(&cb
, 0, sizeof(cb
));
3572 cb
.refname
= refname
;
3573 cb
.at_time
= at_time
;
3576 cb
.cutoff_time
= cutoff_time
;
3577 cb
.cutoff_tz
= cutoff_tz
;
3578 cb
.cutoff_cnt
= cutoff_cnt
;
3581 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3584 if (flags
& GET_SHA1_QUIETLY
)
3587 die("Log for %s is empty.", refname
);
3592 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3597 int reflog_exists(const char *refname
)
3601 return !lstat(git_path("logs/%s", refname
), &st
) &&
3602 S_ISREG(st
.st_mode
);
3605 int delete_reflog(const char *refname
)
3607 return remove_path(git_path("logs/%s", refname
));
3610 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3612 unsigned char osha1
[20], nsha1
[20];
3613 char *email_end
, *message
;
3614 unsigned long timestamp
;
3617 /* old SP new SP name <email> SP time TAB msg LF */
3618 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3619 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3620 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3621 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3622 email_end
[1] != ' ' ||
3623 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3624 !message
|| message
[0] != ' ' ||
3625 (message
[1] != '+' && message
[1] != '-') ||
3626 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3627 !isdigit(message
[4]) || !isdigit(message
[5]))
3628 return 0; /* corrupt? */
3629 email_end
[1] = '\0';
3630 tz
= strtol(message
+ 1, NULL
, 10);
3631 if (message
[6] != '\t')
3635 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3638 static char *find_beginning_of_line(char *bob
, char *scan
)
3640 while (bob
< scan
&& *(--scan
) != '\n')
3641 ; /* keep scanning backwards */
3643 * Return either beginning of the buffer, or LF at the end of
3644 * the previous line.
3649 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3651 struct strbuf sb
= STRBUF_INIT
;
3654 int ret
= 0, at_tail
= 1;
3656 logfp
= fopen(git_path("logs/%s", refname
), "r");
3660 /* Jump to the end */
3661 if (fseek(logfp
, 0, SEEK_END
) < 0)
3662 return error("cannot seek back reflog for %s: %s",
3663 refname
, strerror(errno
));
3665 while (!ret
&& 0 < pos
) {
3671 /* Fill next block from the end */
3672 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3673 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3674 return error("cannot seek back reflog for %s: %s",
3675 refname
, strerror(errno
));
3676 nread
= fread(buf
, cnt
, 1, logfp
);
3678 return error("cannot read %d bytes from reflog for %s: %s",
3679 cnt
, refname
, strerror(errno
));
3682 scanp
= endp
= buf
+ cnt
;
3683 if (at_tail
&& scanp
[-1] == '\n')
3684 /* Looking at the final LF at the end of the file */
3688 while (buf
< scanp
) {
3690 * terminating LF of the previous line, or the beginning
3695 bp
= find_beginning_of_line(buf
, scanp
);
3699 * The newline is the end of the previous line,
3700 * so we know we have complete line starting
3701 * at (bp + 1). Prefix it onto any prior data
3702 * we collected for the line and process it.
3704 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3707 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3713 * We are at the start of the buffer, and the
3714 * start of the file; there is no previous
3715 * line, and we have everything for this one.
3716 * Process it, and we can end the loop.
3718 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3719 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3726 * We are at the start of the buffer, and there
3727 * is more file to read backwards. Which means
3728 * we are in the middle of a line. Note that we
3729 * may get here even if *bp was a newline; that
3730 * just means we are at the exact end of the
3731 * previous line, rather than some spot in the
3734 * Save away what we have to be combined with
3735 * the data from the next read.
3737 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3744 die("BUG: reverse reflog parser had leftover data");
3747 strbuf_release(&sb
);
3751 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3754 struct strbuf sb
= STRBUF_INIT
;
3757 logfp
= fopen(git_path("logs/%s", refname
), "r");
3761 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3762 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3764 strbuf_release(&sb
);
3768 * Call fn for each reflog in the namespace indicated by name. name
3769 * must be empty or end with '/'. Name will be used as a scratch
3770 * space, but its contents will be restored before return.
3772 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3774 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3777 int oldlen
= name
->len
;
3780 return name
->len
? errno
: 0;
3782 while ((de
= readdir(d
)) != NULL
) {
3785 if (de
->d_name
[0] == '.')
3787 if (ends_with(de
->d_name
, ".lock"))
3789 strbuf_addstr(name
, de
->d_name
);
3790 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3791 ; /* silently ignore */
3793 if (S_ISDIR(st
.st_mode
)) {
3794 strbuf_addch(name
, '/');
3795 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3797 struct object_id oid
;
3799 if (read_ref_full(name
->buf
, 0, oid
.hash
, NULL
))
3800 retval
= error("bad ref for %s", name
->buf
);
3802 retval
= fn(name
->buf
, &oid
, 0, cb_data
);
3807 strbuf_setlen(name
, oldlen
);
3813 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3817 strbuf_init(&name
, PATH_MAX
);
3818 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3819 strbuf_release(&name
);
3824 * Information needed for a single ref update. Set new_sha1 to the new
3825 * value or to null_sha1 to delete the ref. To check the old value
3826 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3827 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3828 * not exist before update.
3832 * If (flags & REF_HAVE_NEW), set the reference to this value:
3834 unsigned char new_sha1
[20];
3836 * If (flags & REF_HAVE_OLD), check that the reference
3837 * previously had this value:
3839 unsigned char old_sha1
[20];
3841 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3842 * REF_DELETING, and REF_ISPRUNING:
3845 struct ref_lock
*lock
;
3848 const char refname
[FLEX_ARRAY
];
3852 * Transaction states.
3853 * OPEN: The transaction is in a valid state and can accept new updates.
3854 * An OPEN transaction can be committed.
3855 * CLOSED: A closed transaction is no longer active and no other operations
3856 * than free can be used on it in this state.
3857 * A transaction can either become closed by successfully committing
3858 * an active transaction or if there is a failure while building
3859 * the transaction thus rendering it failed/inactive.
3861 enum ref_transaction_state
{
3862 REF_TRANSACTION_OPEN
= 0,
3863 REF_TRANSACTION_CLOSED
= 1
3867 * Data structure for holding a reference transaction, which can
3868 * consist of checks and updates to multiple references, carried out
3869 * as atomically as possible. This structure is opaque to callers.
3871 struct ref_transaction
{
3872 struct ref_update
**updates
;
3875 enum ref_transaction_state state
;
3878 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3882 return xcalloc(1, sizeof(struct ref_transaction
));
3885 void ref_transaction_free(struct ref_transaction
*transaction
)
3892 for (i
= 0; i
< transaction
->nr
; i
++) {
3893 free(transaction
->updates
[i
]->msg
);
3894 free(transaction
->updates
[i
]);
3896 free(transaction
->updates
);
3900 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3901 const char *refname
)
3903 size_t len
= strlen(refname
);
3904 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3906 strcpy((char *)update
->refname
, refname
);
3907 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3908 transaction
->updates
[transaction
->nr
++] = update
;
3912 int ref_transaction_update(struct ref_transaction
*transaction
,
3913 const char *refname
,
3914 const unsigned char *new_sha1
,
3915 const unsigned char *old_sha1
,
3916 unsigned int flags
, const char *msg
,
3919 struct ref_update
*update
;
3923 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
3924 die("BUG: update called for transaction that is not open");
3926 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
3927 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
3928 strbuf_addf(err
, "refusing to update ref with bad name %s",
3933 update
= add_update(transaction
, refname
);
3935 hashcpy(update
->new_sha1
, new_sha1
);
3936 flags
|= REF_HAVE_NEW
;
3939 hashcpy(update
->old_sha1
, old_sha1
);
3940 flags
|= REF_HAVE_OLD
;
3942 update
->flags
= flags
;
3944 update
->msg
= xstrdup(msg
);
3948 int ref_transaction_create(struct ref_transaction
*transaction
,
3949 const char *refname
,
3950 const unsigned char *new_sha1
,
3951 unsigned int flags
, const char *msg
,
3954 if (!new_sha1
|| is_null_sha1(new_sha1
))
3955 die("BUG: create called without valid new_sha1");
3956 return ref_transaction_update(transaction
, refname
, new_sha1
,
3957 null_sha1
, flags
, msg
, err
);
3960 int ref_transaction_delete(struct ref_transaction
*transaction
,
3961 const char *refname
,
3962 const unsigned char *old_sha1
,
3963 unsigned int flags
, const char *msg
,
3966 if (old_sha1
&& is_null_sha1(old_sha1
))
3967 die("BUG: delete called with old_sha1 set to zeros");
3968 return ref_transaction_update(transaction
, refname
,
3969 null_sha1
, old_sha1
,
3973 int ref_transaction_verify(struct ref_transaction
*transaction
,
3974 const char *refname
,
3975 const unsigned char *old_sha1
,
3980 die("BUG: verify called with old_sha1 set to NULL");
3981 return ref_transaction_update(transaction
, refname
,
3986 int update_ref(const char *msg
, const char *refname
,
3987 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
3988 unsigned int flags
, enum action_on_err onerr
)
3990 struct ref_transaction
*t
= NULL
;
3991 struct strbuf err
= STRBUF_INIT
;
3994 if (ref_type(refname
) == REF_TYPE_PSEUDOREF
) {
3995 ret
= write_pseudoref(refname
, new_sha1
, old_sha1
, &err
);
3997 t
= ref_transaction_begin(&err
);
3999 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
4000 flags
, msg
, &err
) ||
4001 ref_transaction_commit(t
, &err
)) {
4003 ref_transaction_free(t
);
4007 const char *str
= "update_ref failed for ref '%s': %s";
4010 case UPDATE_REFS_MSG_ON_ERR
:
4011 error(str
, refname
, err
.buf
);
4013 case UPDATE_REFS_DIE_ON_ERR
:
4014 die(str
, refname
, err
.buf
);
4016 case UPDATE_REFS_QUIET_ON_ERR
:
4019 strbuf_release(&err
);
4022 strbuf_release(&err
);
4024 ref_transaction_free(t
);
4028 static int ref_update_reject_duplicates(struct string_list
*refnames
,
4031 int i
, n
= refnames
->nr
;
4035 for (i
= 1; i
< n
; i
++)
4036 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
4038 "Multiple updates for ref '%s' not allowed.",
4039 refnames
->items
[i
].string
);
4045 int ref_transaction_commit(struct ref_transaction
*transaction
,
4049 int n
= transaction
->nr
;
4050 struct ref_update
**updates
= transaction
->updates
;
4051 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
4052 struct string_list_item
*ref_to_delete
;
4053 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
4057 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
4058 die("BUG: commit called for transaction that is not open");
4061 transaction
->state
= REF_TRANSACTION_CLOSED
;
4065 /* Fail if a refname appears more than once in the transaction: */
4066 for (i
= 0; i
< n
; i
++)
4067 string_list_append(&affected_refnames
, updates
[i
]->refname
);
4068 string_list_sort(&affected_refnames
);
4069 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
4070 ret
= TRANSACTION_GENERIC_ERROR
;
4075 * Acquire all locks, verify old values if provided, check
4076 * that new values are valid, and write new values to the
4077 * lockfiles, ready to be activated. Only keep one lockfile
4078 * open at a time to avoid running out of file descriptors.
4080 for (i
= 0; i
< n
; i
++) {
4081 struct ref_update
*update
= updates
[i
];
4083 if ((update
->flags
& REF_HAVE_NEW
) &&
4084 is_null_sha1(update
->new_sha1
))
4085 update
->flags
|= REF_DELETING
;
4086 update
->lock
= lock_ref_sha1_basic(
4088 ((update
->flags
& REF_HAVE_OLD
) ?
4089 update
->old_sha1
: NULL
),
4090 &affected_refnames
, NULL
,
4094 if (!update
->lock
) {
4097 ret
= (errno
== ENOTDIR
)
4098 ? TRANSACTION_NAME_CONFLICT
4099 : TRANSACTION_GENERIC_ERROR
;
4100 reason
= strbuf_detach(err
, NULL
);
4101 strbuf_addf(err
, "cannot lock ref '%s': %s",
4102 update
->refname
, reason
);
4106 if ((update
->flags
& REF_HAVE_NEW
) &&
4107 !(update
->flags
& REF_DELETING
)) {
4108 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
4109 (update
->flags
& REF_NODEREF
));
4111 if (!overwriting_symref
&&
4112 !hashcmp(update
->lock
->old_oid
.hash
, update
->new_sha1
)) {
4114 * The reference already has the desired
4115 * value, so we don't need to write it.
4117 } else if (write_ref_to_lockfile(update
->lock
,
4120 char *write_err
= strbuf_detach(err
, NULL
);
4123 * The lock was freed upon failure of
4124 * write_ref_to_lockfile():
4126 update
->lock
= NULL
;
4128 "cannot update the ref '%s': %s",
4129 update
->refname
, write_err
);
4131 ret
= TRANSACTION_GENERIC_ERROR
;
4134 update
->flags
|= REF_NEEDS_COMMIT
;
4137 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
4139 * We didn't have to write anything to the lockfile.
4140 * Close it to free up the file descriptor:
4142 if (close_ref(update
->lock
)) {
4143 strbuf_addf(err
, "Couldn't close %s.lock",
4150 /* Perform updates first so live commits remain referenced */
4151 for (i
= 0; i
< n
; i
++) {
4152 struct ref_update
*update
= updates
[i
];
4154 if (update
->flags
& REF_NEEDS_COMMIT
) {
4155 if (commit_ref_update(update
->lock
,
4156 update
->new_sha1
, update
->msg
,
4157 update
->flags
, err
)) {
4158 /* freed by commit_ref_update(): */
4159 update
->lock
= NULL
;
4160 ret
= TRANSACTION_GENERIC_ERROR
;
4163 /* freed by commit_ref_update(): */
4164 update
->lock
= NULL
;
4169 /* Perform deletes now that updates are safely completed */
4170 for (i
= 0; i
< n
; i
++) {
4171 struct ref_update
*update
= updates
[i
];
4173 if (update
->flags
& REF_DELETING
) {
4174 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
4175 ret
= TRANSACTION_GENERIC_ERROR
;
4179 if (!(update
->flags
& REF_ISPRUNING
))
4180 string_list_append(&refs_to_delete
,
4181 update
->lock
->ref_name
);
4185 if (repack_without_refs(&refs_to_delete
, err
)) {
4186 ret
= TRANSACTION_GENERIC_ERROR
;
4189 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
4190 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
4191 clear_loose_ref_cache(&ref_cache
);
4194 transaction
->state
= REF_TRANSACTION_CLOSED
;
4196 for (i
= 0; i
< n
; i
++)
4197 if (updates
[i
]->lock
)
4198 unlock_ref(updates
[i
]->lock
);
4199 string_list_clear(&refs_to_delete
, 0);
4200 string_list_clear(&affected_refnames
, 0);
4204 char *shorten_unambiguous_ref(const char *refname
, int strict
)
4207 static char **scanf_fmts
;
4208 static int nr_rules
;
4213 * Pre-generate scanf formats from ref_rev_parse_rules[].
4214 * Generate a format suitable for scanf from a
4215 * ref_rev_parse_rules rule by interpolating "%s" at the
4216 * location of the "%.*s".
4218 size_t total_len
= 0;
4221 /* the rule list is NULL terminated, count them first */
4222 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
4223 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4224 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
4226 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
4229 for (i
= 0; i
< nr_rules
; i
++) {
4230 assert(offset
< total_len
);
4231 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
4232 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
4233 ref_rev_parse_rules
[i
], 2, "%s") + 1;
4237 /* bail out if there are no rules */
4239 return xstrdup(refname
);
4241 /* buffer for scanf result, at most refname must fit */
4242 short_name
= xstrdup(refname
);
4244 /* skip first rule, it will always match */
4245 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
4247 int rules_to_fail
= i
;
4250 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
4253 short_name_len
= strlen(short_name
);
4256 * in strict mode, all (except the matched one) rules
4257 * must fail to resolve to a valid non-ambiguous ref
4260 rules_to_fail
= nr_rules
;
4263 * check if the short name resolves to a valid ref,
4264 * but use only rules prior to the matched one
4266 for (j
= 0; j
< rules_to_fail
; j
++) {
4267 const char *rule
= ref_rev_parse_rules
[j
];
4268 char refname
[PATH_MAX
];
4270 /* skip matched rule */
4275 * the short name is ambiguous, if it resolves
4276 * (with this previous rule) to a valid ref
4277 * read_ref() returns 0 on success
4279 mksnpath(refname
, sizeof(refname
),
4280 rule
, short_name_len
, short_name
);
4281 if (ref_exists(refname
))
4286 * short name is non-ambiguous if all previous rules
4287 * haven't resolved to a valid ref
4289 if (j
== rules_to_fail
)
4294 return xstrdup(refname
);
4297 static struct string_list
*hide_refs
;
4299 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
4301 if (!strcmp("transfer.hiderefs", var
) ||
4302 /* NEEDSWORK: use parse_config_key() once both are merged */
4303 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
4304 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
4309 return config_error_nonbool(var
);
4310 ref
= xstrdup(value
);
4312 while (len
&& ref
[len
- 1] == '/')
4315 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
4316 hide_refs
->strdup_strings
= 1;
4318 string_list_append(hide_refs
, ref
);
4323 int ref_is_hidden(const char *refname
)
4325 struct string_list_item
*item
;
4329 for_each_string_list_item(item
, hide_refs
) {
4331 if (!starts_with(refname
, item
->string
))
4333 len
= strlen(item
->string
);
4334 if (!refname
[len
] || refname
[len
] == '/')
4340 struct expire_reflog_cb
{
4342 reflog_expiry_should_prune_fn
*should_prune_fn
;
4345 unsigned char last_kept_sha1
[20];
4348 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4349 const char *email
, unsigned long timestamp
, int tz
,
4350 const char *message
, void *cb_data
)
4352 struct expire_reflog_cb
*cb
= cb_data
;
4353 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4355 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4356 osha1
= cb
->last_kept_sha1
;
4358 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4359 message
, policy_cb
)) {
4361 printf("would prune %s", message
);
4362 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4363 printf("prune %s", message
);
4366 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4367 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4368 email
, timestamp
, tz
, message
);
4369 hashcpy(cb
->last_kept_sha1
, nsha1
);
4371 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4372 printf("keep %s", message
);
4377 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4379 reflog_expiry_prepare_fn prepare_fn
,
4380 reflog_expiry_should_prune_fn should_prune_fn
,
4381 reflog_expiry_cleanup_fn cleanup_fn
,
4382 void *policy_cb_data
)
4384 static struct lock_file reflog_lock
;
4385 struct expire_reflog_cb cb
;
4386 struct ref_lock
*lock
;
4390 struct strbuf err
= STRBUF_INIT
;
4392 memset(&cb
, 0, sizeof(cb
));
4394 cb
.policy_cb
= policy_cb_data
;
4395 cb
.should_prune_fn
= should_prune_fn
;
4398 * The reflog file is locked by holding the lock on the
4399 * reference itself, plus we might need to update the
4400 * reference if --updateref was specified:
4402 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, 0, &type
, &err
);
4404 error("cannot lock ref '%s': %s", refname
, err
.buf
);
4405 strbuf_release(&err
);
4408 if (!reflog_exists(refname
)) {
4413 log_file
= git_pathdup("logs/%s", refname
);
4414 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4416 * Even though holding $GIT_DIR/logs/$reflog.lock has
4417 * no locking implications, we use the lock_file
4418 * machinery here anyway because it does a lot of the
4419 * work we need, including cleaning up if the program
4420 * exits unexpectedly.
4422 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4423 struct strbuf err
= STRBUF_INIT
;
4424 unable_to_lock_message(log_file
, errno
, &err
);
4425 error("%s", err
.buf
);
4426 strbuf_release(&err
);
4429 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4431 error("cannot fdopen %s (%s)",
4432 reflog_lock
.filename
.buf
, strerror(errno
));
4437 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4438 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4439 (*cleanup_fn
)(cb
.policy_cb
);
4441 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4443 * It doesn't make sense to adjust a reference pointed
4444 * to by a symbolic ref based on expiring entries in
4445 * the symbolic reference's reflog. Nor can we update
4446 * a reference if there are no remaining reflog
4449 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4450 !(type
& REF_ISSYMREF
) &&
4451 !is_null_sha1(cb
.last_kept_sha1
);
4453 if (close_lock_file(&reflog_lock
)) {
4454 status
|= error("couldn't write %s: %s", log_file
,
4456 } else if (update
&&
4457 (write_in_full(lock
->lk
->fd
,
4458 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4459 write_str_in_full(lock
->lk
->fd
, "\n") != 1 ||
4460 close_ref(lock
) < 0)) {
4461 status
|= error("couldn't write %s",
4462 lock
->lk
->filename
.buf
);
4463 rollback_lock_file(&reflog_lock
);
4464 } else if (commit_lock_file(&reflog_lock
)) {
4465 status
|= error("unable to commit reflog '%s' (%s)",
4466 log_file
, strerror(errno
));
4467 } else if (update
&& commit_ref(lock
)) {
4468 status
|= error("couldn't set %s", lock
->ref_name
);
4476 rollback_lock_file(&reflog_lock
);