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, and
23 * ":", "?", "[", "\", "^", "~", SP, or TAB
24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
26 static unsigned char refname_disposition
[256] = {
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
41 #define REF_DELETING 0x02
44 * Used as a flag in ref_update::flags when a loose ref is being
47 #define REF_ISPRUNING 0x04
50 * Used as a flag in ref_update::flags when the reference should be
51 * updated to new_sha1.
53 #define REF_HAVE_NEW 0x08
56 * Used as a flag in ref_update::flags when old_sha1 should be
59 #define REF_HAVE_OLD 0x10
62 * Used as a flag in ref_update::flags when the lockfile needs to be
65 #define REF_NEEDS_COMMIT 0x20
68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a
69 * value to ref_update::flags
73 * Try to read one refname component from the front of refname.
74 * Return the length of the component found, or -1 if the component is
75 * not legal. It is legal if it is something reasonable to have under
76 * ".git/refs/"; We do not like it if:
78 * - any path component of it begins with ".", or
79 * - it has double dots "..", or
80 * - it has ASCII control characters, or
81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
83 * - it ends with a "/", or
84 * - it ends with ".lock", or
85 * - it contains a "@{" portion
87 static int check_refname_component(const char *refname
, int *flags
)
92 for (cp
= refname
; ; cp
++) {
94 unsigned char disp
= refname_disposition
[ch
];
100 return -1; /* Refname contains "..". */
104 return -1; /* Refname contains "@{". */
109 if (!(*flags
& REFNAME_REFSPEC_PATTERN
))
110 return -1; /* refspec can't be a pattern */
113 * Unset the pattern flag so that we only accept
114 * a single asterisk for one side of refspec.
116 *flags
&= ~ REFNAME_REFSPEC_PATTERN
;
123 return 0; /* Component has zero length. */
124 if (refname
[0] == '.')
125 return -1; /* Component starts with '.'. */
126 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
127 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
))
128 return -1; /* Refname ends with ".lock". */
132 int check_refname_format(const char *refname
, int flags
)
134 int component_len
, component_count
= 0;
136 if (!strcmp(refname
, "@"))
137 /* Refname is a single character '@'. */
141 /* We are at the start of a path component. */
142 component_len
= check_refname_component(refname
, &flags
);
143 if (component_len
<= 0)
147 if (refname
[component_len
] == '\0')
149 /* Skip to next component. */
150 refname
+= component_len
+ 1;
153 if (refname
[component_len
- 1] == '.')
154 return -1; /* Refname ends with '.'. */
155 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
156 return -1; /* Refname has only one component. */
163 * Information used (along with the information in ref_entry) to
164 * describe a single cached reference. This data structure only
165 * occurs embedded in a union in struct ref_entry, and only when
166 * (ref_entry->flag & REF_DIR) is zero.
170 * The name of the object to which this reference resolves
171 * (which may be a tag object). If REF_ISBROKEN, this is
172 * null. If REF_ISSYMREF, then this is the name of the object
173 * referred to by the last reference in the symlink chain.
175 struct object_id oid
;
178 * If REF_KNOWS_PEELED, then this field holds the peeled value
179 * of this reference, or null if the reference is known not to
180 * be peelable. See the documentation for peel_ref() for an
181 * exact definition of "peelable".
183 struct object_id peeled
;
189 * Information used (along with the information in ref_entry) to
190 * describe a level in the hierarchy of references. This data
191 * structure only occurs embedded in a union in struct ref_entry, and
192 * only when (ref_entry.flag & REF_DIR) is set. In that case,
193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
194 * in the directory have already been read:
196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
197 * or packed references, already read.
199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
200 * references that hasn't been read yet (nor has any of its
203 * Entries within a directory are stored within a growable array of
204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
205 * sorted are sorted by their component name in strcmp() order and the
206 * remaining entries are unsorted.
208 * Loose references are read lazily, one directory at a time. When a
209 * directory of loose references is read, then all of the references
210 * in that directory are stored, and REF_INCOMPLETE stubs are created
211 * for any subdirectories, but the subdirectories themselves are not
212 * read. The reading is triggered by get_ref_dir().
218 * Entries with index 0 <= i < sorted are sorted by name. New
219 * entries are appended to the list unsorted, and are sorted
220 * only when required; thus we avoid the need to sort the list
221 * after the addition of every reference.
225 /* A pointer to the ref_cache that contains this ref_dir. */
226 struct ref_cache
*ref_cache
;
228 struct ref_entry
**entries
;
232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
234 * public values; see refs.h.
238 * The field ref_entry->u.value.peeled of this value entry contains
239 * the correct peeled value for the reference, which might be
240 * null_sha1 if the reference is not a tag or if it is broken.
242 #define REF_KNOWS_PEELED 0x10
244 /* ref_entry represents a directory of references */
248 * Entry has not yet been read from disk (used only for REF_DIR
249 * entries representing loose references)
251 #define REF_INCOMPLETE 0x40
254 * A ref_entry represents either a reference or a "subdirectory" of
257 * Each directory in the reference namespace is represented by a
258 * ref_entry with (flags & REF_DIR) set and containing a subdir member
259 * that holds the entries in that directory that have been read so
260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
262 * used for loose reference directories.
264 * References are represented by a ref_entry with (flags & REF_DIR)
265 * unset and a value member that describes the reference's value. The
266 * flag member is at the ref_entry level, but it is also needed to
267 * interpret the contents of the value field (in other words, a
268 * ref_value object is not very much use without the enclosing
271 * Reference names cannot end with slash and directories' names are
272 * always stored with a trailing slash (except for the top-level
273 * directory, which is always denoted by ""). This has two nice
274 * consequences: (1) when the entries in each subdir are sorted
275 * lexicographically by name (as they usually are), the references in
276 * a whole tree can be generated in lexicographic order by traversing
277 * the tree in left-to-right, depth-first order; (2) the names of
278 * references and subdirectories cannot conflict, and therefore the
279 * presence of an empty subdirectory does not block the creation of a
280 * similarly-named reference. (The fact that reference names with the
281 * same leading components can conflict *with each other* is a
282 * separate issue that is regulated by verify_refname_available().)
284 * Please note that the name field contains the fully-qualified
285 * reference (or subdirectory) name. Space could be saved by only
286 * storing the relative names. But that would require the full names
287 * to be generated on the fly when iterating in do_for_each_ref(), and
288 * would break callback functions, who have always been able to assume
289 * that the name strings that they are passed will not be freed during
293 unsigned char flag
; /* ISSYMREF? ISPACKED? */
295 struct ref_value value
; /* if not (flags&REF_DIR) */
296 struct ref_dir subdir
; /* if (flags&REF_DIR) */
299 * The full name of the reference (e.g., "refs/heads/master")
300 * or the full name of the directory with a trailing slash
301 * (e.g., "refs/heads/"):
303 char name
[FLEX_ARRAY
];
306 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
);
308 static struct ref_dir
*get_ref_dir(struct ref_entry
*entry
)
311 assert(entry
->flag
& REF_DIR
);
312 dir
= &entry
->u
.subdir
;
313 if (entry
->flag
& REF_INCOMPLETE
) {
314 read_loose_refs(entry
->name
, dir
);
315 entry
->flag
&= ~REF_INCOMPLETE
;
321 * Check if a refname is safe.
322 * For refs that start with "refs/" we consider it safe as long they do
323 * not try to resolve to outside of refs/.
325 * For all other refs we only consider them safe iff they only contain
326 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
329 static int refname_is_safe(const char *refname
)
331 if (starts_with(refname
, "refs/")) {
335 buf
= xmalloc(strlen(refname
) + 1);
337 * Does the refname try to escape refs/?
338 * For example: refs/foo/../bar is safe but refs/foo/../../bar
341 result
= !normalize_path_copy(buf
, refname
+ strlen("refs/"));
346 if (!isupper(*refname
) && *refname
!= '_')
353 static struct ref_entry
*create_ref_entry(const char *refname
,
354 const unsigned char *sha1
, int flag
,
358 struct ref_entry
*ref
;
361 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
))
362 die("Reference has invalid format: '%s'", refname
);
363 len
= strlen(refname
) + 1;
364 ref
= xmalloc(sizeof(struct ref_entry
) + len
);
365 hashcpy(ref
->u
.value
.oid
.hash
, sha1
);
366 oidclr(&ref
->u
.value
.peeled
);
367 memcpy(ref
->name
, refname
, len
);
372 static void clear_ref_dir(struct ref_dir
*dir
);
374 static void free_ref_entry(struct ref_entry
*entry
)
376 if (entry
->flag
& REF_DIR
) {
378 * Do not use get_ref_dir() here, as that might
379 * trigger the reading of loose refs.
381 clear_ref_dir(&entry
->u
.subdir
);
387 * Add a ref_entry to the end of dir (unsorted). Entry is always
388 * stored directly in dir; no recursion into subdirectories is
391 static void add_entry_to_dir(struct ref_dir
*dir
, struct ref_entry
*entry
)
393 ALLOC_GROW(dir
->entries
, dir
->nr
+ 1, dir
->alloc
);
394 dir
->entries
[dir
->nr
++] = entry
;
395 /* optimize for the case that entries are added in order */
397 (dir
->nr
== dir
->sorted
+ 1 &&
398 strcmp(dir
->entries
[dir
->nr
- 2]->name
,
399 dir
->entries
[dir
->nr
- 1]->name
) < 0))
400 dir
->sorted
= dir
->nr
;
404 * Clear and free all entries in dir, recursively.
406 static void clear_ref_dir(struct ref_dir
*dir
)
409 for (i
= 0; i
< dir
->nr
; i
++)
410 free_ref_entry(dir
->entries
[i
]);
412 dir
->sorted
= dir
->nr
= dir
->alloc
= 0;
417 * Create a struct ref_entry object for the specified dirname.
418 * dirname is the name of the directory with a trailing slash (e.g.,
419 * "refs/heads/") or "" for the top-level directory.
421 static struct ref_entry
*create_dir_entry(struct ref_cache
*ref_cache
,
422 const char *dirname
, size_t len
,
425 struct ref_entry
*direntry
;
426 direntry
= xcalloc(1, sizeof(struct ref_entry
) + len
+ 1);
427 memcpy(direntry
->name
, dirname
, len
);
428 direntry
->name
[len
] = '\0';
429 direntry
->u
.subdir
.ref_cache
= ref_cache
;
430 direntry
->flag
= REF_DIR
| (incomplete
? REF_INCOMPLETE
: 0);
434 static int ref_entry_cmp(const void *a
, const void *b
)
436 struct ref_entry
*one
= *(struct ref_entry
**)a
;
437 struct ref_entry
*two
= *(struct ref_entry
**)b
;
438 return strcmp(one
->name
, two
->name
);
441 static void sort_ref_dir(struct ref_dir
*dir
);
443 struct string_slice
{
448 static int ref_entry_cmp_sslice(const void *key_
, const void *ent_
)
450 const struct string_slice
*key
= key_
;
451 const struct ref_entry
*ent
= *(const struct ref_entry
* const *)ent_
;
452 int cmp
= strncmp(key
->str
, ent
->name
, key
->len
);
455 return '\0' - (unsigned char)ent
->name
[key
->len
];
459 * Return the index of the entry with the given refname from the
460 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
461 * no such entry is found. dir must already be complete.
463 static int search_ref_dir(struct ref_dir
*dir
, const char *refname
, size_t len
)
465 struct ref_entry
**r
;
466 struct string_slice key
;
468 if (refname
== NULL
|| !dir
->nr
)
474 r
= bsearch(&key
, dir
->entries
, dir
->nr
, sizeof(*dir
->entries
),
475 ref_entry_cmp_sslice
);
480 return r
- dir
->entries
;
484 * Search for a directory entry directly within dir (without
485 * recursing). Sort dir if necessary. subdirname must be a directory
486 * name (i.e., end in '/'). If mkdir is set, then create the
487 * directory if it is missing; otherwise, return NULL if the desired
488 * directory cannot be found. dir must already be complete.
490 static struct ref_dir
*search_for_subdir(struct ref_dir
*dir
,
491 const char *subdirname
, size_t len
,
494 int entry_index
= search_ref_dir(dir
, subdirname
, len
);
495 struct ref_entry
*entry
;
496 if (entry_index
== -1) {
500 * Since dir is complete, the absence of a subdir
501 * means that the subdir really doesn't exist;
502 * therefore, create an empty record for it but mark
503 * the record complete.
505 entry
= create_dir_entry(dir
->ref_cache
, subdirname
, len
, 0);
506 add_entry_to_dir(dir
, entry
);
508 entry
= dir
->entries
[entry_index
];
510 return get_ref_dir(entry
);
514 * If refname is a reference name, find the ref_dir within the dir
515 * tree that should hold refname. If refname is a directory name
516 * (i.e., ends in '/'), then return that ref_dir itself. dir must
517 * represent the top-level directory and must already be complete.
518 * Sort ref_dirs and recurse into subdirectories as necessary. If
519 * mkdir is set, then create any missing directories; otherwise,
520 * return NULL if the desired directory cannot be found.
522 static struct ref_dir
*find_containing_dir(struct ref_dir
*dir
,
523 const char *refname
, int mkdir
)
526 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
527 size_t dirnamelen
= slash
- refname
+ 1;
528 struct ref_dir
*subdir
;
529 subdir
= search_for_subdir(dir
, refname
, dirnamelen
, mkdir
);
541 * Find the value entry with the given name in dir, sorting ref_dirs
542 * and recursing into subdirectories as necessary. If the name is not
543 * found or it corresponds to a directory entry, return NULL.
545 static struct ref_entry
*find_ref(struct ref_dir
*dir
, const char *refname
)
548 struct ref_entry
*entry
;
549 dir
= find_containing_dir(dir
, refname
, 0);
552 entry_index
= search_ref_dir(dir
, refname
, strlen(refname
));
553 if (entry_index
== -1)
555 entry
= dir
->entries
[entry_index
];
556 return (entry
->flag
& REF_DIR
) ? NULL
: entry
;
560 * Remove the entry with the given name from dir, recursing into
561 * subdirectories as necessary. If refname is the name of a directory
562 * (i.e., ends with '/'), then remove the directory and its contents.
563 * If the removal was successful, return the number of entries
564 * remaining in the directory entry that contained the deleted entry.
565 * If the name was not found, return -1. Please note that this
566 * function only deletes the entry from the cache; it does not delete
567 * it from the filesystem or ensure that other cache entries (which
568 * might be symbolic references to the removed entry) are updated.
569 * Nor does it remove any containing dir entries that might be made
570 * empty by the removal. dir must represent the top-level directory
571 * and must already be complete.
573 static int remove_entry(struct ref_dir
*dir
, const char *refname
)
575 int refname_len
= strlen(refname
);
577 struct ref_entry
*entry
;
578 int is_dir
= refname
[refname_len
- 1] == '/';
581 * refname represents a reference directory. Remove
582 * the trailing slash; otherwise we will get the
583 * directory *representing* refname rather than the
584 * one *containing* it.
586 char *dirname
= xmemdupz(refname
, refname_len
- 1);
587 dir
= find_containing_dir(dir
, dirname
, 0);
590 dir
= find_containing_dir(dir
, refname
, 0);
594 entry_index
= search_ref_dir(dir
, refname
, refname_len
);
595 if (entry_index
== -1)
597 entry
= dir
->entries
[entry_index
];
599 memmove(&dir
->entries
[entry_index
],
600 &dir
->entries
[entry_index
+ 1],
601 (dir
->nr
- entry_index
- 1) * sizeof(*dir
->entries
)
604 if (dir
->sorted
> entry_index
)
606 free_ref_entry(entry
);
611 * Add a ref_entry to the ref_dir (unsorted), recursing into
612 * subdirectories as necessary. dir must represent the top-level
613 * directory. Return 0 on success.
615 static int add_ref(struct ref_dir
*dir
, struct ref_entry
*ref
)
617 dir
= find_containing_dir(dir
, ref
->name
, 1);
620 add_entry_to_dir(dir
, ref
);
625 * Emit a warning and return true iff ref1 and ref2 have the same name
626 * and the same sha1. Die if they have the same name but different
629 static int is_dup_ref(const struct ref_entry
*ref1
, const struct ref_entry
*ref2
)
631 if (strcmp(ref1
->name
, ref2
->name
))
634 /* Duplicate name; make sure that they don't conflict: */
636 if ((ref1
->flag
& REF_DIR
) || (ref2
->flag
& REF_DIR
))
637 /* This is impossible by construction */
638 die("Reference directory conflict: %s", ref1
->name
);
640 if (oidcmp(&ref1
->u
.value
.oid
, &ref2
->u
.value
.oid
))
641 die("Duplicated ref, and SHA1s don't match: %s", ref1
->name
);
643 warning("Duplicated ref: %s", ref1
->name
);
648 * Sort the entries in dir non-recursively (if they are not already
649 * sorted) and remove any duplicate entries.
651 static void sort_ref_dir(struct ref_dir
*dir
)
654 struct ref_entry
*last
= NULL
;
657 * This check also prevents passing a zero-length array to qsort(),
658 * which is a problem on some platforms.
660 if (dir
->sorted
== dir
->nr
)
663 qsort(dir
->entries
, dir
->nr
, sizeof(*dir
->entries
), ref_entry_cmp
);
665 /* Remove any duplicates: */
666 for (i
= 0, j
= 0; j
< dir
->nr
; j
++) {
667 struct ref_entry
*entry
= dir
->entries
[j
];
668 if (last
&& is_dup_ref(last
, entry
))
669 free_ref_entry(entry
);
671 last
= dir
->entries
[i
++] = entry
;
673 dir
->sorted
= dir
->nr
= i
;
676 /* Include broken references in a do_for_each_ref*() iteration: */
677 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
680 * Return true iff the reference described by entry can be resolved to
681 * an object in the database. Emit a warning if the referred-to
682 * object does not exist.
684 static int ref_resolves_to_object(struct ref_entry
*entry
)
686 if (entry
->flag
& REF_ISBROKEN
)
688 if (!has_sha1_file(entry
->u
.value
.oid
.hash
)) {
689 error("%s does not point to a valid object!", entry
->name
);
696 * current_ref is a performance hack: when iterating over references
697 * using the for_each_ref*() functions, current_ref is set to the
698 * current reference's entry before calling the callback function. If
699 * the callback function calls peel_ref(), then peel_ref() first
700 * checks whether the reference to be peeled is the current reference
701 * (it usually is) and if so, returns that reference's peeled version
702 * if it is available. This avoids a refname lookup in a common case.
704 static struct ref_entry
*current_ref
;
706 typedef int each_ref_entry_fn(struct ref_entry
*entry
, void *cb_data
);
708 struct ref_entry_cb
{
717 * Handle one reference in a do_for_each_ref*()-style iteration,
718 * calling an each_ref_fn for each entry.
720 static int do_one_ref(struct ref_entry
*entry
, void *cb_data
)
722 struct ref_entry_cb
*data
= cb_data
;
723 struct ref_entry
*old_current_ref
;
726 if (!starts_with(entry
->name
, data
->base
))
729 if (!(data
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
730 !ref_resolves_to_object(entry
))
733 /* Store the old value, in case this is a recursive call: */
734 old_current_ref
= current_ref
;
736 retval
= data
->fn(entry
->name
+ data
->trim
, &entry
->u
.value
.oid
,
737 entry
->flag
, data
->cb_data
);
738 current_ref
= old_current_ref
;
743 * Call fn for each reference in dir that has index in the range
744 * offset <= index < dir->nr. Recurse into subdirectories that are in
745 * that index range, sorting them before iterating. This function
746 * does not sort dir itself; it should be sorted beforehand. fn is
747 * called for all references, including broken ones.
749 static int do_for_each_entry_in_dir(struct ref_dir
*dir
, int offset
,
750 each_ref_entry_fn fn
, void *cb_data
)
753 assert(dir
->sorted
== dir
->nr
);
754 for (i
= offset
; i
< dir
->nr
; i
++) {
755 struct ref_entry
*entry
= dir
->entries
[i
];
757 if (entry
->flag
& REF_DIR
) {
758 struct ref_dir
*subdir
= get_ref_dir(entry
);
759 sort_ref_dir(subdir
);
760 retval
= do_for_each_entry_in_dir(subdir
, 0, fn
, cb_data
);
762 retval
= fn(entry
, cb_data
);
771 * Call fn for each reference in the union of dir1 and dir2, in order
772 * by refname. Recurse into subdirectories. If a value entry appears
773 * in both dir1 and dir2, then only process the version that is in
774 * dir2. The input dirs must already be sorted, but subdirs will be
775 * sorted as needed. fn is called for all references, including
778 static int do_for_each_entry_in_dirs(struct ref_dir
*dir1
,
779 struct ref_dir
*dir2
,
780 each_ref_entry_fn fn
, void *cb_data
)
785 assert(dir1
->sorted
== dir1
->nr
);
786 assert(dir2
->sorted
== dir2
->nr
);
788 struct ref_entry
*e1
, *e2
;
790 if (i1
== dir1
->nr
) {
791 return do_for_each_entry_in_dir(dir2
, i2
, fn
, cb_data
);
793 if (i2
== dir2
->nr
) {
794 return do_for_each_entry_in_dir(dir1
, i1
, fn
, cb_data
);
796 e1
= dir1
->entries
[i1
];
797 e2
= dir2
->entries
[i2
];
798 cmp
= strcmp(e1
->name
, e2
->name
);
800 if ((e1
->flag
& REF_DIR
) && (e2
->flag
& REF_DIR
)) {
801 /* Both are directories; descend them in parallel. */
802 struct ref_dir
*subdir1
= get_ref_dir(e1
);
803 struct ref_dir
*subdir2
= get_ref_dir(e2
);
804 sort_ref_dir(subdir1
);
805 sort_ref_dir(subdir2
);
806 retval
= do_for_each_entry_in_dirs(
807 subdir1
, subdir2
, fn
, cb_data
);
810 } else if (!(e1
->flag
& REF_DIR
) && !(e2
->flag
& REF_DIR
)) {
811 /* Both are references; ignore the one from dir1. */
812 retval
= fn(e2
, cb_data
);
816 die("conflict between reference and directory: %s",
828 if (e
->flag
& REF_DIR
) {
829 struct ref_dir
*subdir
= get_ref_dir(e
);
830 sort_ref_dir(subdir
);
831 retval
= do_for_each_entry_in_dir(
832 subdir
, 0, fn
, cb_data
);
834 retval
= fn(e
, cb_data
);
843 * Load all of the refs from the dir into our in-memory cache. The hard work
844 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
845 * through all of the sub-directories. We do not even need to care about
846 * sorting, as traversal order does not matter to us.
848 static void prime_ref_dir(struct ref_dir
*dir
)
851 for (i
= 0; i
< dir
->nr
; i
++) {
852 struct ref_entry
*entry
= dir
->entries
[i
];
853 if (entry
->flag
& REF_DIR
)
854 prime_ref_dir(get_ref_dir(entry
));
858 struct nonmatching_ref_data
{
859 const struct string_list
*skip
;
860 const char *conflicting_refname
;
863 static int nonmatching_ref_fn(struct ref_entry
*entry
, void *vdata
)
865 struct nonmatching_ref_data
*data
= vdata
;
867 if (data
->skip
&& string_list_has_string(data
->skip
, entry
->name
))
870 data
->conflicting_refname
= entry
->name
;
875 * Return 0 if a reference named refname could be created without
876 * conflicting with the name of an existing reference in dir.
877 * Otherwise, return a negative value and write an explanation to err.
878 * If extras is non-NULL, it is a list of additional refnames with
879 * which refname is not allowed to conflict. If skip is non-NULL,
880 * ignore potential conflicts with refs in skip (e.g., because they
881 * are scheduled for deletion in the same operation). Behavior is
882 * undefined if the same name is listed in both extras and skip.
884 * Two reference names conflict if one of them exactly matches the
885 * leading components of the other; e.g., "refs/foo/bar" conflicts
886 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
887 * "refs/foo/bar" or "refs/foo/barbados".
889 * extras and skip must be sorted.
891 static int verify_refname_available(const char *refname
,
892 const struct string_list
*extras
,
893 const struct string_list
*skip
,
899 struct strbuf dirname
= STRBUF_INIT
;
903 * For the sake of comments in this function, suppose that
904 * refname is "refs/foo/bar".
909 strbuf_grow(&dirname
, strlen(refname
) + 1);
910 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
911 /* Expand dirname to the new prefix, not including the trailing slash: */
912 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
915 * We are still at a leading dir of the refname (e.g.,
916 * "refs/foo"; if there is a reference with that name,
917 * it is a conflict, *unless* it is in skip.
920 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
922 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
924 * We found a reference whose name is
925 * a proper prefix of refname; e.g.,
926 * "refs/foo", and is not in skip.
928 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
929 dirname
.buf
, refname
);
934 if (extras
&& string_list_has_string(extras
, dirname
.buf
) &&
935 (!skip
|| !string_list_has_string(skip
, dirname
.buf
))) {
936 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
937 refname
, dirname
.buf
);
942 * Otherwise, we can try to continue our search with
943 * the next component. So try to look up the
944 * directory, e.g., "refs/foo/". If we come up empty,
945 * we know there is nothing under this whole prefix,
946 * but even in that case we still have to continue the
947 * search for conflicts with extras.
949 strbuf_addch(&dirname
, '/');
951 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
954 * There was no directory "refs/foo/",
955 * so there is nothing under this
956 * whole prefix. So there is no need
957 * to continue looking for conflicting
958 * references. But we need to continue
959 * looking for conflicting extras.
963 dir
= get_ref_dir(dir
->entries
[pos
]);
969 * We are at the leaf of our refname (e.g., "refs/foo/bar").
970 * There is no point in searching for a reference with that
971 * name, because a refname isn't considered to conflict with
972 * itself. But we still need to check for references whose
973 * names are in the "refs/foo/bar/" namespace, because they
976 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
977 strbuf_addch(&dirname
, '/');
980 pos
= search_ref_dir(dir
, dirname
.buf
, dirname
.len
);
984 * We found a directory named "$refname/"
985 * (e.g., "refs/foo/bar/"). It is a problem
986 * iff it contains any ref that is not in
989 struct nonmatching_ref_data data
;
992 data
.conflicting_refname
= NULL
;
993 dir
= get_ref_dir(dir
->entries
[pos
]);
995 if (do_for_each_entry_in_dir(dir
, 0, nonmatching_ref_fn
, &data
)) {
996 strbuf_addf(err
, "'%s' exists; cannot create '%s'",
997 data
.conflicting_refname
, refname
);
1005 * Check for entries in extras that start with
1006 * "$refname/". We do that by looking for the place
1007 * where "$refname/" would be inserted in extras. If
1008 * there is an entry at that position that starts with
1009 * "$refname/" and is not in skip, then we have a
1012 for (pos
= string_list_find_insert_index(extras
, dirname
.buf
, 0);
1013 pos
< extras
->nr
; pos
++) {
1014 const char *extra_refname
= extras
->items
[pos
].string
;
1016 if (!starts_with(extra_refname
, dirname
.buf
))
1019 if (!skip
|| !string_list_has_string(skip
, extra_refname
)) {
1020 strbuf_addf(err
, "cannot process '%s' and '%s' at the same time",
1021 refname
, extra_refname
);
1027 /* No conflicts were found */
1031 strbuf_release(&dirname
);
1035 struct packed_ref_cache
{
1036 struct ref_entry
*root
;
1039 * Count of references to the data structure in this instance,
1040 * including the pointer from ref_cache::packed if any. The
1041 * data will not be freed as long as the reference count is
1044 unsigned int referrers
;
1047 * Iff the packed-refs file associated with this instance is
1048 * currently locked for writing, this points at the associated
1049 * lock (which is owned by somebody else). The referrer count
1050 * is also incremented when the file is locked and decremented
1051 * when it is unlocked.
1053 struct lock_file
*lock
;
1055 /* The metadata from when this packed-refs cache was read */
1056 struct stat_validity validity
;
1060 * Future: need to be in "struct repository"
1061 * when doing a full libification.
1063 static struct ref_cache
{
1064 struct ref_cache
*next
;
1065 struct ref_entry
*loose
;
1066 struct packed_ref_cache
*packed
;
1068 * The submodule name, or "" for the main repo. We allocate
1069 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1070 * is initialized correctly.
1073 } ref_cache
, *submodule_ref_caches
;
1075 /* Lock used for the main packed-refs file: */
1076 static struct lock_file packlock
;
1079 * Increment the reference count of *packed_refs.
1081 static void acquire_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1083 packed_refs
->referrers
++;
1087 * Decrease the reference count of *packed_refs. If it goes to zero,
1088 * free *packed_refs and return true; otherwise return false.
1090 static int release_packed_ref_cache(struct packed_ref_cache
*packed_refs
)
1092 if (!--packed_refs
->referrers
) {
1093 free_ref_entry(packed_refs
->root
);
1094 stat_validity_clear(&packed_refs
->validity
);
1102 static void clear_packed_ref_cache(struct ref_cache
*refs
)
1105 struct packed_ref_cache
*packed_refs
= refs
->packed
;
1107 if (packed_refs
->lock
)
1108 die("internal error: packed-ref cache cleared while locked");
1109 refs
->packed
= NULL
;
1110 release_packed_ref_cache(packed_refs
);
1114 static void clear_loose_ref_cache(struct ref_cache
*refs
)
1117 free_ref_entry(refs
->loose
);
1122 static struct ref_cache
*create_ref_cache(const char *submodule
)
1125 struct ref_cache
*refs
;
1128 len
= strlen(submodule
) + 1;
1129 refs
= xcalloc(1, sizeof(struct ref_cache
) + len
);
1130 memcpy(refs
->name
, submodule
, len
);
1135 * Return a pointer to a ref_cache for the specified submodule. For
1136 * the main repository, use submodule==NULL. The returned structure
1137 * will be allocated and initialized but not necessarily populated; it
1138 * should not be freed.
1140 static struct ref_cache
*get_ref_cache(const char *submodule
)
1142 struct ref_cache
*refs
;
1144 if (!submodule
|| !*submodule
)
1147 for (refs
= submodule_ref_caches
; refs
; refs
= refs
->next
)
1148 if (!strcmp(submodule
, refs
->name
))
1151 refs
= create_ref_cache(submodule
);
1152 refs
->next
= submodule_ref_caches
;
1153 submodule_ref_caches
= refs
;
1157 /* The length of a peeled reference line in packed-refs, including EOL: */
1158 #define PEELED_LINE_LENGTH 42
1161 * The packed-refs header line that we write out. Perhaps other
1162 * traits will be added later. The trailing space is required.
1164 static const char PACKED_REFS_HEADER
[] =
1165 "# pack-refs with: peeled fully-peeled \n";
1168 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1169 * Return a pointer to the refname within the line (null-terminated),
1170 * or NULL if there was a problem.
1172 static const char *parse_ref_line(struct strbuf
*line
, unsigned char *sha1
)
1177 * 42: the answer to everything.
1179 * In this case, it happens to be the answer to
1180 * 40 (length of sha1 hex representation)
1181 * +1 (space in between hex and name)
1182 * +1 (newline at the end of the line)
1184 if (line
->len
<= 42)
1187 if (get_sha1_hex(line
->buf
, sha1
) < 0)
1189 if (!isspace(line
->buf
[40]))
1192 ref
= line
->buf
+ 41;
1196 if (line
->buf
[line
->len
- 1] != '\n')
1198 line
->buf
[--line
->len
] = 0;
1204 * Read f, which is a packed-refs file, into dir.
1206 * A comment line of the form "# pack-refs with: " may contain zero or
1207 * more traits. We interpret the traits as follows:
1211 * Probably no references are peeled. But if the file contains a
1212 * peeled value for a reference, we will use it.
1216 * References under "refs/tags/", if they *can* be peeled, *are*
1217 * peeled in this file. References outside of "refs/tags/" are
1218 * probably not peeled even if they could have been, but if we find
1219 * a peeled value for such a reference we will use it.
1223 * All references in the file that can be peeled are peeled.
1224 * Inversely (and this is more important), any references in the
1225 * file for which no peeled value is recorded is not peelable. This
1226 * trait should typically be written alongside "peeled" for
1227 * compatibility with older clients, but we do not require it
1228 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1230 static void read_packed_refs(FILE *f
, struct ref_dir
*dir
)
1232 struct ref_entry
*last
= NULL
;
1233 struct strbuf line
= STRBUF_INIT
;
1234 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
= PEELED_NONE
;
1236 while (strbuf_getwholeline(&line
, f
, '\n') != EOF
) {
1237 unsigned char sha1
[20];
1238 const char *refname
;
1241 if (skip_prefix(line
.buf
, "# pack-refs with:", &traits
)) {
1242 if (strstr(traits
, " fully-peeled "))
1243 peeled
= PEELED_FULLY
;
1244 else if (strstr(traits
, " peeled "))
1245 peeled
= PEELED_TAGS
;
1246 /* perhaps other traits later as well */
1250 refname
= parse_ref_line(&line
, sha1
);
1252 int flag
= REF_ISPACKED
;
1254 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1255 if (!refname_is_safe(refname
))
1256 die("packed refname is dangerous: %s", refname
);
1258 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1260 last
= create_ref_entry(refname
, sha1
, flag
, 0);
1261 if (peeled
== PEELED_FULLY
||
1262 (peeled
== PEELED_TAGS
&& starts_with(refname
, "refs/tags/")))
1263 last
->flag
|= REF_KNOWS_PEELED
;
1268 line
.buf
[0] == '^' &&
1269 line
.len
== PEELED_LINE_LENGTH
&&
1270 line
.buf
[PEELED_LINE_LENGTH
- 1] == '\n' &&
1271 !get_sha1_hex(line
.buf
+ 1, sha1
)) {
1272 hashcpy(last
->u
.value
.peeled
.hash
, sha1
);
1274 * Regardless of what the file header said,
1275 * we definitely know the value of *this*
1278 last
->flag
|= REF_KNOWS_PEELED
;
1282 strbuf_release(&line
);
1286 * Get the packed_ref_cache for the specified ref_cache, creating it
1289 static struct packed_ref_cache
*get_packed_ref_cache(struct ref_cache
*refs
)
1291 char *packed_refs_file
;
1294 packed_refs_file
= git_pathdup_submodule(refs
->name
, "packed-refs");
1296 packed_refs_file
= git_pathdup("packed-refs");
1299 !stat_validity_check(&refs
->packed
->validity
, packed_refs_file
))
1300 clear_packed_ref_cache(refs
);
1302 if (!refs
->packed
) {
1305 refs
->packed
= xcalloc(1, sizeof(*refs
->packed
));
1306 acquire_packed_ref_cache(refs
->packed
);
1307 refs
->packed
->root
= create_dir_entry(refs
, "", 0, 0);
1308 f
= fopen(packed_refs_file
, "r");
1310 stat_validity_update(&refs
->packed
->validity
, fileno(f
));
1311 read_packed_refs(f
, get_ref_dir(refs
->packed
->root
));
1315 free(packed_refs_file
);
1316 return refs
->packed
;
1319 static struct ref_dir
*get_packed_ref_dir(struct packed_ref_cache
*packed_ref_cache
)
1321 return get_ref_dir(packed_ref_cache
->root
);
1324 static struct ref_dir
*get_packed_refs(struct ref_cache
*refs
)
1326 return get_packed_ref_dir(get_packed_ref_cache(refs
));
1330 * Add a reference to the in-memory packed reference cache. This may
1331 * only be called while the packed-refs file is locked (see
1332 * lock_packed_refs()). To actually write the packed-refs file, call
1333 * commit_packed_refs().
1335 static void add_packed_ref(const char *refname
, const unsigned char *sha1
)
1337 struct packed_ref_cache
*packed_ref_cache
=
1338 get_packed_ref_cache(&ref_cache
);
1340 if (!packed_ref_cache
->lock
)
1341 die("internal error: packed refs not locked");
1342 add_ref(get_packed_ref_dir(packed_ref_cache
),
1343 create_ref_entry(refname
, sha1
, REF_ISPACKED
, 1));
1347 * Read the loose references from the namespace dirname into dir
1348 * (without recursing). dirname must end with '/'. dir must be the
1349 * directory entry corresponding to dirname.
1351 static void read_loose_refs(const char *dirname
, struct ref_dir
*dir
)
1353 struct ref_cache
*refs
= dir
->ref_cache
;
1356 int dirnamelen
= strlen(dirname
);
1357 struct strbuf refname
;
1358 struct strbuf path
= STRBUF_INIT
;
1359 size_t path_baselen
;
1362 strbuf_git_path_submodule(&path
, refs
->name
, "%s", dirname
);
1364 strbuf_git_path(&path
, "%s", dirname
);
1365 path_baselen
= path
.len
;
1367 d
= opendir(path
.buf
);
1369 strbuf_release(&path
);
1373 strbuf_init(&refname
, dirnamelen
+ 257);
1374 strbuf_add(&refname
, dirname
, dirnamelen
);
1376 while ((de
= readdir(d
)) != NULL
) {
1377 unsigned char sha1
[20];
1381 if (de
->d_name
[0] == '.')
1383 if (ends_with(de
->d_name
, ".lock"))
1385 strbuf_addstr(&refname
, de
->d_name
);
1386 strbuf_addstr(&path
, de
->d_name
);
1387 if (stat(path
.buf
, &st
) < 0) {
1388 ; /* silently ignore */
1389 } else if (S_ISDIR(st
.st_mode
)) {
1390 strbuf_addch(&refname
, '/');
1391 add_entry_to_dir(dir
,
1392 create_dir_entry(refs
, refname
.buf
,
1400 read_ok
= !resolve_gitlink_ref(refs
->name
,
1403 read_ok
= !read_ref_full(refname
.buf
,
1404 RESOLVE_REF_READING
,
1410 flag
|= REF_ISBROKEN
;
1411 } else if (is_null_sha1(sha1
)) {
1413 * It is so astronomically unlikely
1414 * that NULL_SHA1 is the SHA-1 of an
1415 * actual object that we consider its
1416 * appearance in a loose reference
1417 * file to be repo corruption
1418 * (probably due to a software bug).
1420 flag
|= REF_ISBROKEN
;
1423 if (check_refname_format(refname
.buf
,
1424 REFNAME_ALLOW_ONELEVEL
)) {
1425 if (!refname_is_safe(refname
.buf
))
1426 die("loose refname is dangerous: %s", refname
.buf
);
1428 flag
|= REF_BAD_NAME
| REF_ISBROKEN
;
1430 add_entry_to_dir(dir
,
1431 create_ref_entry(refname
.buf
, sha1
, flag
, 0));
1433 strbuf_setlen(&refname
, dirnamelen
);
1434 strbuf_setlen(&path
, path_baselen
);
1436 strbuf_release(&refname
);
1437 strbuf_release(&path
);
1441 static struct ref_dir
*get_loose_refs(struct ref_cache
*refs
)
1445 * Mark the top-level directory complete because we
1446 * are about to read the only subdirectory that can
1449 refs
->loose
= create_dir_entry(refs
, "", 0, 0);
1451 * Create an incomplete entry for "refs/":
1453 add_entry_to_dir(get_ref_dir(refs
->loose
),
1454 create_dir_entry(refs
, "refs/", 5, 1));
1456 return get_ref_dir(refs
->loose
);
1459 /* We allow "recursive" symbolic refs. Only within reason, though */
1461 #define MAXREFLEN (1024)
1464 * Called by resolve_gitlink_ref_recursive() after it failed to read
1465 * from the loose refs in ref_cache refs. Find <refname> in the
1466 * packed-refs file for the submodule.
1468 static int resolve_gitlink_packed_ref(struct ref_cache
*refs
,
1469 const char *refname
, unsigned char *sha1
)
1471 struct ref_entry
*ref
;
1472 struct ref_dir
*dir
= get_packed_refs(refs
);
1474 ref
= find_ref(dir
, refname
);
1478 hashcpy(sha1
, ref
->u
.value
.oid
.hash
);
1482 static int resolve_gitlink_ref_recursive(struct ref_cache
*refs
,
1483 const char *refname
, unsigned char *sha1
,
1487 char buffer
[128], *p
;
1490 if (recursion
> MAXDEPTH
|| strlen(refname
) > MAXREFLEN
)
1493 ? git_pathdup_submodule(refs
->name
, "%s", refname
)
1494 : git_pathdup("%s", refname
);
1495 fd
= open(path
, O_RDONLY
);
1498 return resolve_gitlink_packed_ref(refs
, refname
, sha1
);
1500 len
= read(fd
, buffer
, sizeof(buffer
)-1);
1504 while (len
&& isspace(buffer
[len
-1]))
1508 /* Was it a detached head or an old-fashioned symlink? */
1509 if (!get_sha1_hex(buffer
, sha1
))
1513 if (strncmp(buffer
, "ref:", 4))
1519 return resolve_gitlink_ref_recursive(refs
, p
, sha1
, recursion
+1);
1522 int resolve_gitlink_ref(const char *path
, const char *refname
, unsigned char *sha1
)
1524 int len
= strlen(path
), retval
;
1526 struct ref_cache
*refs
;
1528 while (len
&& path
[len
-1] == '/')
1532 submodule
= xstrndup(path
, len
);
1533 refs
= get_ref_cache(submodule
);
1536 retval
= resolve_gitlink_ref_recursive(refs
, refname
, sha1
, 0);
1541 * Return the ref_entry for the given refname from the packed
1542 * references. If it does not exist, return NULL.
1544 static struct ref_entry
*get_packed_ref(const char *refname
)
1546 return find_ref(get_packed_refs(&ref_cache
), refname
);
1550 * A loose ref file doesn't exist; check for a packed ref. The
1551 * options are forwarded from resolve_safe_unsafe().
1553 static int resolve_missing_loose_ref(const char *refname
,
1555 unsigned char *sha1
,
1558 struct ref_entry
*entry
;
1561 * The loose reference file does not exist; check for a packed
1564 entry
= get_packed_ref(refname
);
1566 hashcpy(sha1
, entry
->u
.value
.oid
.hash
);
1568 *flags
|= REF_ISPACKED
;
1571 /* The reference is not a packed reference, either. */
1572 if (resolve_flags
& RESOLVE_REF_READING
) {
1581 /* This function needs to return a meaningful errno on failure */
1582 static const char *resolve_ref_1(const char *refname
,
1584 unsigned char *sha1
,
1586 struct strbuf
*sb_refname
,
1587 struct strbuf
*sb_path
,
1588 struct strbuf
*sb_contents
)
1590 int depth
= MAXDEPTH
;
1596 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1598 *flags
|= REF_BAD_NAME
;
1600 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1601 !refname_is_safe(refname
)) {
1606 * dwim_ref() uses REF_ISBROKEN to distinguish between
1607 * missing refs and refs that were present but invalid,
1608 * to complain about the latter to stderr.
1610 * We don't know whether the ref exists, so don't set
1626 strbuf_reset(sb_path
);
1627 strbuf_git_path(sb_path
, "%s", refname
);
1628 path
= sb_path
->buf
;
1631 * We might have to loop back here to avoid a race
1632 * condition: first we lstat() the file, then we try
1633 * to read it as a link or as a file. But if somebody
1634 * changes the type of the file (file <-> directory
1635 * <-> symlink) between the lstat() and reading, then
1636 * we don't want to report that as an error but rather
1637 * try again starting with the lstat().
1640 if (lstat(path
, &st
) < 0) {
1641 if (errno
!= ENOENT
)
1643 if (resolve_missing_loose_ref(refname
, resolve_flags
,
1649 *flags
|= REF_ISBROKEN
;
1654 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1655 if (S_ISLNK(st
.st_mode
)) {
1656 strbuf_reset(sb_contents
);
1657 if (strbuf_readlink(sb_contents
, path
, 0) < 0) {
1658 if (errno
== ENOENT
|| errno
== EINVAL
)
1659 /* inconsistent with lstat; retry */
1664 if (starts_with(sb_contents
->buf
, "refs/") &&
1665 !check_refname_format(sb_contents
->buf
, 0)) {
1666 strbuf_swap(sb_refname
, sb_contents
);
1667 refname
= sb_refname
->buf
;
1669 *flags
|= REF_ISSYMREF
;
1670 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1678 /* Is it a directory? */
1679 if (S_ISDIR(st
.st_mode
)) {
1685 * Anything else, just open it and try to use it as
1688 fd
= open(path
, O_RDONLY
);
1690 if (errno
== ENOENT
)
1691 /* inconsistent with lstat; retry */
1696 strbuf_reset(sb_contents
);
1697 if (strbuf_read(sb_contents
, fd
, 256) < 0) {
1698 int save_errno
= errno
;
1704 strbuf_rtrim(sb_contents
);
1707 * Is it a symbolic ref?
1709 if (!starts_with(sb_contents
->buf
, "ref:")) {
1711 * Please note that FETCH_HEAD has a second
1712 * line containing other data.
1714 if (get_sha1_hex(sb_contents
->buf
, sha1
) ||
1715 (sb_contents
->buf
[40] != '\0' && !isspace(sb_contents
->buf
[40]))) {
1717 *flags
|= REF_ISBROKEN
;
1724 *flags
|= REF_ISBROKEN
;
1729 *flags
|= REF_ISSYMREF
;
1730 buf
= sb_contents
->buf
+ 4;
1731 while (isspace(*buf
))
1733 strbuf_reset(sb_refname
);
1734 strbuf_addstr(sb_refname
, buf
);
1735 refname
= sb_refname
->buf
;
1736 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1740 if (check_refname_format(buf
, REFNAME_ALLOW_ONELEVEL
)) {
1742 *flags
|= REF_ISBROKEN
;
1744 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1745 !refname_is_safe(buf
)) {
1754 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1755 unsigned char *sha1
, int *flags
)
1757 static struct strbuf sb_refname
= STRBUF_INIT
;
1758 struct strbuf sb_contents
= STRBUF_INIT
;
1759 struct strbuf sb_path
= STRBUF_INIT
;
1762 ret
= resolve_ref_1(refname
, resolve_flags
, sha1
, flags
,
1763 &sb_refname
, &sb_path
, &sb_contents
);
1764 strbuf_release(&sb_path
);
1765 strbuf_release(&sb_contents
);
1769 char *resolve_refdup(const char *refname
, int resolve_flags
,
1770 unsigned char *sha1
, int *flags
)
1772 return xstrdup_or_null(resolve_ref_unsafe(refname
, resolve_flags
,
1776 /* The argument to filter_refs */
1778 const char *pattern
;
1783 int read_ref_full(const char *refname
, int resolve_flags
, unsigned char *sha1
, int *flags
)
1785 if (resolve_ref_unsafe(refname
, resolve_flags
, sha1
, flags
))
1790 int read_ref(const char *refname
, unsigned char *sha1
)
1792 return read_ref_full(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1795 int ref_exists(const char *refname
)
1797 unsigned char sha1
[20];
1798 return !!resolve_ref_unsafe(refname
, RESOLVE_REF_READING
, sha1
, NULL
);
1801 static int filter_refs(const char *refname
, const struct object_id
*oid
,
1802 int flags
, void *data
)
1804 struct ref_filter
*filter
= (struct ref_filter
*)data
;
1806 if (wildmatch(filter
->pattern
, refname
, 0, NULL
))
1808 return filter
->fn(refname
, oid
, flags
, filter
->cb_data
);
1812 /* object was peeled successfully: */
1816 * object cannot be peeled because the named object (or an
1817 * object referred to by a tag in the peel chain), does not
1822 /* object cannot be peeled because it is not a tag: */
1825 /* ref_entry contains no peeled value because it is a symref: */
1826 PEEL_IS_SYMREF
= -3,
1829 * ref_entry cannot be peeled because it is broken (i.e., the
1830 * symbolic reference cannot even be resolved to an object
1837 * Peel the named object; i.e., if the object is a tag, resolve the
1838 * tag recursively until a non-tag is found. If successful, store the
1839 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1840 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1841 * and leave sha1 unchanged.
1843 static enum peel_status
peel_object(const unsigned char *name
, unsigned char *sha1
)
1845 struct object
*o
= lookup_unknown_object(name
);
1847 if (o
->type
== OBJ_NONE
) {
1848 int type
= sha1_object_info(name
, NULL
);
1849 if (type
< 0 || !object_as_type(o
, type
, 0))
1850 return PEEL_INVALID
;
1853 if (o
->type
!= OBJ_TAG
)
1854 return PEEL_NON_TAG
;
1856 o
= deref_tag_noverify(o
);
1858 return PEEL_INVALID
;
1860 hashcpy(sha1
, o
->sha1
);
1865 * Peel the entry (if possible) and return its new peel_status. If
1866 * repeel is true, re-peel the entry even if there is an old peeled
1867 * value that is already stored in it.
1869 * It is OK to call this function with a packed reference entry that
1870 * might be stale and might even refer to an object that has since
1871 * been garbage-collected. In such a case, if the entry has
1872 * REF_KNOWS_PEELED then leave the status unchanged and return
1873 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1875 static enum peel_status
peel_entry(struct ref_entry
*entry
, int repeel
)
1877 enum peel_status status
;
1879 if (entry
->flag
& REF_KNOWS_PEELED
) {
1881 entry
->flag
&= ~REF_KNOWS_PEELED
;
1882 oidclr(&entry
->u
.value
.peeled
);
1884 return is_null_oid(&entry
->u
.value
.peeled
) ?
1885 PEEL_NON_TAG
: PEEL_PEELED
;
1888 if (entry
->flag
& REF_ISBROKEN
)
1890 if (entry
->flag
& REF_ISSYMREF
)
1891 return PEEL_IS_SYMREF
;
1893 status
= peel_object(entry
->u
.value
.oid
.hash
, entry
->u
.value
.peeled
.hash
);
1894 if (status
== PEEL_PEELED
|| status
== PEEL_NON_TAG
)
1895 entry
->flag
|= REF_KNOWS_PEELED
;
1899 int peel_ref(const char *refname
, unsigned char *sha1
)
1902 unsigned char base
[20];
1904 if (current_ref
&& (current_ref
->name
== refname
1905 || !strcmp(current_ref
->name
, refname
))) {
1906 if (peel_entry(current_ref
, 0))
1908 hashcpy(sha1
, current_ref
->u
.value
.peeled
.hash
);
1912 if (read_ref_full(refname
, RESOLVE_REF_READING
, base
, &flag
))
1916 * If the reference is packed, read its ref_entry from the
1917 * cache in the hope that we already know its peeled value.
1918 * We only try this optimization on packed references because
1919 * (a) forcing the filling of the loose reference cache could
1920 * be expensive and (b) loose references anyway usually do not
1921 * have REF_KNOWS_PEELED.
1923 if (flag
& REF_ISPACKED
) {
1924 struct ref_entry
*r
= get_packed_ref(refname
);
1926 if (peel_entry(r
, 0))
1928 hashcpy(sha1
, r
->u
.value
.peeled
.hash
);
1933 return peel_object(base
, sha1
);
1936 struct warn_if_dangling_data
{
1938 const char *refname
;
1939 const struct string_list
*refnames
;
1940 const char *msg_fmt
;
1943 static int warn_if_dangling_symref(const char *refname
, const struct object_id
*oid
,
1944 int flags
, void *cb_data
)
1946 struct warn_if_dangling_data
*d
= cb_data
;
1947 const char *resolves_to
;
1948 struct object_id junk
;
1950 if (!(flags
& REF_ISSYMREF
))
1953 resolves_to
= resolve_ref_unsafe(refname
, 0, junk
.hash
, NULL
);
1956 ? strcmp(resolves_to
, d
->refname
)
1957 : !string_list_has_string(d
->refnames
, resolves_to
))) {
1961 fprintf(d
->fp
, d
->msg_fmt
, refname
);
1966 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
1968 struct warn_if_dangling_data data
;
1971 data
.refname
= refname
;
1972 data
.refnames
= NULL
;
1973 data
.msg_fmt
= msg_fmt
;
1974 for_each_rawref(warn_if_dangling_symref
, &data
);
1977 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
1979 struct warn_if_dangling_data data
;
1982 data
.refname
= NULL
;
1983 data
.refnames
= refnames
;
1984 data
.msg_fmt
= msg_fmt
;
1985 for_each_rawref(warn_if_dangling_symref
, &data
);
1989 * Call fn for each reference in the specified ref_cache, omitting
1990 * references not in the containing_dir of base. fn is called for all
1991 * references, including broken ones. If fn ever returns a non-zero
1992 * value, stop the iteration and return that value; otherwise, return
1995 static int do_for_each_entry(struct ref_cache
*refs
, const char *base
,
1996 each_ref_entry_fn fn
, void *cb_data
)
1998 struct packed_ref_cache
*packed_ref_cache
;
1999 struct ref_dir
*loose_dir
;
2000 struct ref_dir
*packed_dir
;
2004 * We must make sure that all loose refs are read before accessing the
2005 * packed-refs file; this avoids a race condition in which loose refs
2006 * are migrated to the packed-refs file by a simultaneous process, but
2007 * our in-memory view is from before the migration. get_packed_ref_cache()
2008 * takes care of making sure our view is up to date with what is on
2011 loose_dir
= get_loose_refs(refs
);
2012 if (base
&& *base
) {
2013 loose_dir
= find_containing_dir(loose_dir
, base
, 0);
2016 prime_ref_dir(loose_dir
);
2018 packed_ref_cache
= get_packed_ref_cache(refs
);
2019 acquire_packed_ref_cache(packed_ref_cache
);
2020 packed_dir
= get_packed_ref_dir(packed_ref_cache
);
2021 if (base
&& *base
) {
2022 packed_dir
= find_containing_dir(packed_dir
, base
, 0);
2025 if (packed_dir
&& loose_dir
) {
2026 sort_ref_dir(packed_dir
);
2027 sort_ref_dir(loose_dir
);
2028 retval
= do_for_each_entry_in_dirs(
2029 packed_dir
, loose_dir
, fn
, cb_data
);
2030 } else if (packed_dir
) {
2031 sort_ref_dir(packed_dir
);
2032 retval
= do_for_each_entry_in_dir(
2033 packed_dir
, 0, fn
, cb_data
);
2034 } else if (loose_dir
) {
2035 sort_ref_dir(loose_dir
);
2036 retval
= do_for_each_entry_in_dir(
2037 loose_dir
, 0, fn
, cb_data
);
2040 release_packed_ref_cache(packed_ref_cache
);
2045 * Call fn for each reference in the specified ref_cache for which the
2046 * refname begins with base. If trim is non-zero, then trim that many
2047 * characters off the beginning of each refname before passing the
2048 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2049 * broken references in the iteration. If fn ever returns a non-zero
2050 * value, stop the iteration and return that value; otherwise, return
2053 static int do_for_each_ref(struct ref_cache
*refs
, const char *base
,
2054 each_ref_fn fn
, int trim
, int flags
, void *cb_data
)
2056 struct ref_entry_cb data
;
2061 data
.cb_data
= cb_data
;
2063 if (ref_paranoia
< 0)
2064 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 0);
2066 data
.flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
2068 return do_for_each_entry(refs
, base
, do_one_ref
, &data
);
2071 static int do_head_ref(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2073 struct object_id oid
;
2077 if (resolve_gitlink_ref(submodule
, "HEAD", oid
.hash
) == 0)
2078 return fn("HEAD", &oid
, 0, cb_data
);
2083 if (!read_ref_full("HEAD", RESOLVE_REF_READING
, oid
.hash
, &flag
))
2084 return fn("HEAD", &oid
, flag
, cb_data
);
2089 int head_ref(each_ref_fn fn
, void *cb_data
)
2091 return do_head_ref(NULL
, fn
, cb_data
);
2094 int head_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2096 return do_head_ref(submodule
, fn
, cb_data
);
2099 int for_each_ref(each_ref_fn fn
, void *cb_data
)
2101 return do_for_each_ref(&ref_cache
, "", fn
, 0, 0, cb_data
);
2104 int for_each_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2106 return do_for_each_ref(get_ref_cache(submodule
), "", fn
, 0, 0, cb_data
);
2109 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
2111 return do_for_each_ref(&ref_cache
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
2114 int for_each_ref_in_submodule(const char *submodule
, const char *prefix
,
2115 each_ref_fn fn
, void *cb_data
)
2117 return do_for_each_ref(get_ref_cache(submodule
), prefix
, fn
, strlen(prefix
), 0, cb_data
);
2120 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
2122 return for_each_ref_in("refs/tags/", fn
, cb_data
);
2125 int for_each_tag_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2127 return for_each_ref_in_submodule(submodule
, "refs/tags/", fn
, cb_data
);
2130 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
2132 return for_each_ref_in("refs/heads/", fn
, cb_data
);
2135 int for_each_branch_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2137 return for_each_ref_in_submodule(submodule
, "refs/heads/", fn
, cb_data
);
2140 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
2142 return for_each_ref_in("refs/remotes/", fn
, cb_data
);
2145 int for_each_remote_ref_submodule(const char *submodule
, each_ref_fn fn
, void *cb_data
)
2147 return for_each_ref_in_submodule(submodule
, "refs/remotes/", fn
, cb_data
);
2150 int for_each_replace_ref(each_ref_fn fn
, void *cb_data
)
2152 return do_for_each_ref(&ref_cache
, git_replace_ref_base
, fn
,
2153 strlen(git_replace_ref_base
), 0, cb_data
);
2156 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
2158 struct strbuf buf
= STRBUF_INIT
;
2160 struct object_id oid
;
2163 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
2164 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, oid
.hash
, &flag
))
2165 ret
= fn(buf
.buf
, &oid
, flag
, cb_data
);
2166 strbuf_release(&buf
);
2171 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
2173 struct strbuf buf
= STRBUF_INIT
;
2175 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
2176 ret
= do_for_each_ref(&ref_cache
, buf
.buf
, fn
, 0, 0, cb_data
);
2177 strbuf_release(&buf
);
2181 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
2182 const char *prefix
, void *cb_data
)
2184 struct strbuf real_pattern
= STRBUF_INIT
;
2185 struct ref_filter filter
;
2188 if (!prefix
&& !starts_with(pattern
, "refs/"))
2189 strbuf_addstr(&real_pattern
, "refs/");
2191 strbuf_addstr(&real_pattern
, prefix
);
2192 strbuf_addstr(&real_pattern
, pattern
);
2194 if (!has_glob_specials(pattern
)) {
2195 /* Append implied '/' '*' if not present. */
2196 if (real_pattern
.buf
[real_pattern
.len
- 1] != '/')
2197 strbuf_addch(&real_pattern
, '/');
2198 /* No need to check for '*', there is none. */
2199 strbuf_addch(&real_pattern
, '*');
2202 filter
.pattern
= real_pattern
.buf
;
2204 filter
.cb_data
= cb_data
;
2205 ret
= for_each_ref(filter_refs
, &filter
);
2207 strbuf_release(&real_pattern
);
2211 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
2213 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
2216 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
2218 return do_for_each_ref(&ref_cache
, "", fn
, 0,
2219 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
2222 const char *prettify_refname(const char *name
)
2225 starts_with(name
, "refs/heads/") ? 11 :
2226 starts_with(name
, "refs/tags/") ? 10 :
2227 starts_with(name
, "refs/remotes/") ? 13 :
2231 static const char *ref_rev_parse_rules
[] = {
2236 "refs/remotes/%.*s",
2237 "refs/remotes/%.*s/HEAD",
2241 int refname_match(const char *abbrev_name
, const char *full_name
)
2244 const int abbrev_name_len
= strlen(abbrev_name
);
2246 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2247 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
))) {
2255 static void unlock_ref(struct ref_lock
*lock
)
2257 /* Do not free lock->lk -- atexit() still looks at them */
2259 rollback_lock_file(lock
->lk
);
2260 free(lock
->ref_name
);
2261 free(lock
->orig_ref_name
);
2266 * Verify that the reference locked by lock has the value old_sha1.
2267 * Fail if the reference doesn't exist and mustexist is set. Return 0
2268 * on success. On error, write an error message to err, set errno, and
2269 * return a negative value.
2271 static int verify_lock(struct ref_lock
*lock
,
2272 const unsigned char *old_sha1
, int mustexist
,
2277 if (read_ref_full(lock
->ref_name
,
2278 mustexist
? RESOLVE_REF_READING
: 0,
2279 lock
->old_oid
.hash
, NULL
)) {
2280 int save_errno
= errno
;
2281 strbuf_addf(err
, "can't verify ref %s", lock
->ref_name
);
2285 if (hashcmp(lock
->old_oid
.hash
, old_sha1
)) {
2286 strbuf_addf(err
, "ref %s is at %s but expected %s",
2288 sha1_to_hex(lock
->old_oid
.hash
),
2289 sha1_to_hex(old_sha1
));
2296 static int remove_empty_directories(struct strbuf
*path
)
2299 * we want to create a file but there is a directory there;
2300 * if that is an empty directory (or a directory that contains
2301 * only empty directories), remove them.
2303 return remove_dir_recursively(path
, REMOVE_DIR_EMPTY_ONLY
);
2307 * *string and *len will only be substituted, and *string returned (for
2308 * later free()ing) if the string passed in is a magic short-hand form
2311 static char *substitute_branch_name(const char **string
, int *len
)
2313 struct strbuf buf
= STRBUF_INIT
;
2314 int ret
= interpret_branch_name(*string
, *len
, &buf
);
2318 *string
= strbuf_detach(&buf
, &size
);
2320 return (char *)*string
;
2326 int dwim_ref(const char *str
, int len
, unsigned char *sha1
, char **ref
)
2328 char *last_branch
= substitute_branch_name(&str
, &len
);
2333 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2334 char fullref
[PATH_MAX
];
2335 unsigned char sha1_from_ref
[20];
2336 unsigned char *this_result
;
2339 this_result
= refs_found
? sha1_from_ref
: sha1
;
2340 mksnpath(fullref
, sizeof(fullref
), *p
, len
, str
);
2341 r
= resolve_ref_unsafe(fullref
, RESOLVE_REF_READING
,
2342 this_result
, &flag
);
2346 if (!warn_ambiguous_refs
)
2348 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
, "HEAD")) {
2349 warning("ignoring dangling symref %s.", fullref
);
2350 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
, '/')) {
2351 warning("ignoring broken ref %s.", fullref
);
2358 int dwim_log(const char *str
, int len
, unsigned char *sha1
, char **log
)
2360 char *last_branch
= substitute_branch_name(&str
, &len
);
2365 for (p
= ref_rev_parse_rules
; *p
; p
++) {
2366 unsigned char hash
[20];
2367 char path
[PATH_MAX
];
2368 const char *ref
, *it
;
2370 mksnpath(path
, sizeof(path
), *p
, len
, str
);
2371 ref
= resolve_ref_unsafe(path
, RESOLVE_REF_READING
,
2375 if (reflog_exists(path
))
2377 else if (strcmp(ref
, path
) && reflog_exists(ref
))
2381 if (!logs_found
++) {
2383 hashcpy(sha1
, hash
);
2385 if (!warn_ambiguous_refs
)
2393 * Locks a ref returning the lock on success and NULL on failure.
2394 * On failure errno is set to something meaningful.
2396 static struct ref_lock
*lock_ref_sha1_basic(const char *refname
,
2397 const unsigned char *old_sha1
,
2398 const struct string_list
*extras
,
2399 const struct string_list
*skip
,
2400 unsigned int flags
, int *type_p
,
2403 struct strbuf ref_file
= STRBUF_INIT
;
2404 struct strbuf orig_ref_file
= STRBUF_INIT
;
2405 const char *orig_refname
= refname
;
2406 struct ref_lock
*lock
;
2409 int mustexist
= (old_sha1
&& !is_null_sha1(old_sha1
));
2410 int resolve_flags
= 0;
2411 int attempts_remaining
= 3;
2415 lock
= xcalloc(1, sizeof(struct ref_lock
));
2418 resolve_flags
|= RESOLVE_REF_READING
;
2419 if (flags
& REF_DELETING
) {
2420 resolve_flags
|= RESOLVE_REF_ALLOW_BAD_NAME
;
2421 if (flags
& REF_NODEREF
)
2422 resolve_flags
|= RESOLVE_REF_NO_RECURSE
;
2425 refname
= resolve_ref_unsafe(refname
, resolve_flags
,
2426 lock
->old_oid
.hash
, &type
);
2427 if (!refname
&& errno
== EISDIR
) {
2429 * we are trying to lock foo but we used to
2430 * have foo/bar which now does not exist;
2431 * it is normal for the empty directory 'foo'
2434 strbuf_git_path(&orig_ref_file
, "%s", orig_refname
);
2435 if (remove_empty_directories(&orig_ref_file
)) {
2437 if (!verify_refname_available(orig_refname
, extras
, skip
,
2438 get_loose_refs(&ref_cache
), err
))
2439 strbuf_addf(err
, "there are still refs under '%s'",
2443 refname
= resolve_ref_unsafe(orig_refname
, resolve_flags
,
2444 lock
->old_oid
.hash
, &type
);
2450 if (last_errno
!= ENOTDIR
||
2451 !verify_refname_available(orig_refname
, extras
, skip
,
2452 get_loose_refs(&ref_cache
), err
))
2453 strbuf_addf(err
, "unable to resolve reference %s: %s",
2454 orig_refname
, strerror(last_errno
));
2459 * If the ref did not exist and we are creating it, make sure
2460 * there is no existing packed ref whose name begins with our
2461 * refname, nor a packed ref whose name is a proper prefix of
2464 if (is_null_oid(&lock
->old_oid
) &&
2465 verify_refname_available(refname
, extras
, skip
,
2466 get_packed_refs(&ref_cache
), err
)) {
2467 last_errno
= ENOTDIR
;
2471 lock
->lk
= xcalloc(1, sizeof(struct lock_file
));
2474 if (flags
& REF_NODEREF
) {
2475 refname
= orig_refname
;
2476 lflags
|= LOCK_NO_DEREF
;
2478 lock
->ref_name
= xstrdup(refname
);
2479 lock
->orig_ref_name
= xstrdup(orig_refname
);
2480 strbuf_git_path(&ref_file
, "%s", refname
);
2483 switch (safe_create_leading_directories_const(ref_file
.buf
)) {
2485 break; /* success */
2487 if (--attempts_remaining
> 0)
2492 strbuf_addf(err
, "unable to create directory for %s",
2497 if (hold_lock_file_for_update(lock
->lk
, ref_file
.buf
, lflags
) < 0) {
2499 if (errno
== ENOENT
&& --attempts_remaining
> 0)
2501 * Maybe somebody just deleted one of the
2502 * directories leading to ref_file. Try
2507 unable_to_lock_message(ref_file
.buf
, errno
, err
);
2511 if (old_sha1
&& verify_lock(lock
, old_sha1
, mustexist
, err
)) {
2522 strbuf_release(&ref_file
);
2523 strbuf_release(&orig_ref_file
);
2529 * Write an entry to the packed-refs file for the specified refname.
2530 * If peeled is non-NULL, write it as the entry's peeled value.
2532 static void write_packed_entry(FILE *fh
, char *refname
, unsigned char *sha1
,
2533 unsigned char *peeled
)
2535 fprintf_or_die(fh
, "%s %s\n", sha1_to_hex(sha1
), refname
);
2537 fprintf_or_die(fh
, "^%s\n", sha1_to_hex(peeled
));
2541 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2543 static int write_packed_entry_fn(struct ref_entry
*entry
, void *cb_data
)
2545 enum peel_status peel_status
= peel_entry(entry
, 0);
2547 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2548 error("internal error: %s is not a valid packed reference!",
2550 write_packed_entry(cb_data
, entry
->name
, entry
->u
.value
.oid
.hash
,
2551 peel_status
== PEEL_PEELED
?
2552 entry
->u
.value
.peeled
.hash
: NULL
);
2557 * Lock the packed-refs file for writing. Flags is passed to
2558 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2559 * errno appropriately and return a nonzero value.
2561 static int lock_packed_refs(int flags
)
2563 static int timeout_configured
= 0;
2564 static int timeout_value
= 1000;
2566 struct packed_ref_cache
*packed_ref_cache
;
2568 if (!timeout_configured
) {
2569 git_config_get_int("core.packedrefstimeout", &timeout_value
);
2570 timeout_configured
= 1;
2573 if (hold_lock_file_for_update_timeout(
2574 &packlock
, git_path("packed-refs"),
2575 flags
, timeout_value
) < 0)
2578 * Get the current packed-refs while holding the lock. If the
2579 * packed-refs file has been modified since we last read it,
2580 * this will automatically invalidate the cache and re-read
2581 * the packed-refs file.
2583 packed_ref_cache
= get_packed_ref_cache(&ref_cache
);
2584 packed_ref_cache
->lock
= &packlock
;
2585 /* Increment the reference count to prevent it from being freed: */
2586 acquire_packed_ref_cache(packed_ref_cache
);
2591 * Write the current version of the packed refs cache from memory to
2592 * disk. The packed-refs file must already be locked for writing (see
2593 * lock_packed_refs()). Return zero on success. On errors, set errno
2594 * and return a nonzero value
2596 static int commit_packed_refs(void)
2598 struct packed_ref_cache
*packed_ref_cache
=
2599 get_packed_ref_cache(&ref_cache
);
2604 if (!packed_ref_cache
->lock
)
2605 die("internal error: packed-refs not locked");
2607 out
= fdopen_lock_file(packed_ref_cache
->lock
, "w");
2609 die_errno("unable to fdopen packed-refs descriptor");
2611 fprintf_or_die(out
, "%s", PACKED_REFS_HEADER
);
2612 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache
),
2613 0, write_packed_entry_fn
, out
);
2615 if (commit_lock_file(packed_ref_cache
->lock
)) {
2619 packed_ref_cache
->lock
= NULL
;
2620 release_packed_ref_cache(packed_ref_cache
);
2626 * Rollback the lockfile for the packed-refs file, and discard the
2627 * in-memory packed reference cache. (The packed-refs file will be
2628 * read anew if it is needed again after this function is called.)
2630 static void rollback_packed_refs(void)
2632 struct packed_ref_cache
*packed_ref_cache
=
2633 get_packed_ref_cache(&ref_cache
);
2635 if (!packed_ref_cache
->lock
)
2636 die("internal error: packed-refs not locked");
2637 rollback_lock_file(packed_ref_cache
->lock
);
2638 packed_ref_cache
->lock
= NULL
;
2639 release_packed_ref_cache(packed_ref_cache
);
2640 clear_packed_ref_cache(&ref_cache
);
2643 struct ref_to_prune
{
2644 struct ref_to_prune
*next
;
2645 unsigned char sha1
[20];
2646 char name
[FLEX_ARRAY
];
2649 struct pack_refs_cb_data
{
2651 struct ref_dir
*packed_refs
;
2652 struct ref_to_prune
*ref_to_prune
;
2656 * An each_ref_entry_fn that is run over loose references only. If
2657 * the loose reference can be packed, add an entry in the packed ref
2658 * cache. If the reference should be pruned, also add it to
2659 * ref_to_prune in the pack_refs_cb_data.
2661 static int pack_if_possible_fn(struct ref_entry
*entry
, void *cb_data
)
2663 struct pack_refs_cb_data
*cb
= cb_data
;
2664 enum peel_status peel_status
;
2665 struct ref_entry
*packed_entry
;
2666 int is_tag_ref
= starts_with(entry
->name
, "refs/tags/");
2668 /* ALWAYS pack tags */
2669 if (!(cb
->flags
& PACK_REFS_ALL
) && !is_tag_ref
)
2672 /* Do not pack symbolic or broken refs: */
2673 if ((entry
->flag
& REF_ISSYMREF
) || !ref_resolves_to_object(entry
))
2676 /* Add a packed ref cache entry equivalent to the loose entry. */
2677 peel_status
= peel_entry(entry
, 1);
2678 if (peel_status
!= PEEL_PEELED
&& peel_status
!= PEEL_NON_TAG
)
2679 die("internal error peeling reference %s (%s)",
2680 entry
->name
, oid_to_hex(&entry
->u
.value
.oid
));
2681 packed_entry
= find_ref(cb
->packed_refs
, entry
->name
);
2683 /* Overwrite existing packed entry with info from loose entry */
2684 packed_entry
->flag
= REF_ISPACKED
| REF_KNOWS_PEELED
;
2685 oidcpy(&packed_entry
->u
.value
.oid
, &entry
->u
.value
.oid
);
2687 packed_entry
= create_ref_entry(entry
->name
, entry
->u
.value
.oid
.hash
,
2688 REF_ISPACKED
| REF_KNOWS_PEELED
, 0);
2689 add_ref(cb
->packed_refs
, packed_entry
);
2691 oidcpy(&packed_entry
->u
.value
.peeled
, &entry
->u
.value
.peeled
);
2693 /* Schedule the loose reference for pruning if requested. */
2694 if ((cb
->flags
& PACK_REFS_PRUNE
)) {
2695 int namelen
= strlen(entry
->name
) + 1;
2696 struct ref_to_prune
*n
= xcalloc(1, sizeof(*n
) + namelen
);
2697 hashcpy(n
->sha1
, entry
->u
.value
.oid
.hash
);
2698 strcpy(n
->name
, entry
->name
);
2699 n
->next
= cb
->ref_to_prune
;
2700 cb
->ref_to_prune
= n
;
2706 * Remove empty parents, but spare refs/ and immediate subdirs.
2707 * Note: munges *name.
2709 static void try_remove_empty_parents(char *name
)
2714 for (i
= 0; i
< 2; i
++) { /* refs/{heads,tags,...}/ */
2715 while (*p
&& *p
!= '/')
2717 /* tolerate duplicate slashes; see check_refname_format() */
2721 for (q
= p
; *q
; q
++)
2724 while (q
> p
&& *q
!= '/')
2726 while (q
> p
&& *(q
-1) == '/')
2731 if (rmdir(git_path("%s", name
)))
2736 /* make sure nobody touched the ref, and unlink */
2737 static void prune_ref(struct ref_to_prune
*r
)
2739 struct ref_transaction
*transaction
;
2740 struct strbuf err
= STRBUF_INIT
;
2742 if (check_refname_format(r
->name
, 0))
2745 transaction
= ref_transaction_begin(&err
);
2747 ref_transaction_delete(transaction
, r
->name
, r
->sha1
,
2748 REF_ISPRUNING
, NULL
, &err
) ||
2749 ref_transaction_commit(transaction
, &err
)) {
2750 ref_transaction_free(transaction
);
2751 error("%s", err
.buf
);
2752 strbuf_release(&err
);
2755 ref_transaction_free(transaction
);
2756 strbuf_release(&err
);
2757 try_remove_empty_parents(r
->name
);
2760 static void prune_refs(struct ref_to_prune
*r
)
2768 int pack_refs(unsigned int flags
)
2770 struct pack_refs_cb_data cbdata
;
2772 memset(&cbdata
, 0, sizeof(cbdata
));
2773 cbdata
.flags
= flags
;
2775 lock_packed_refs(LOCK_DIE_ON_ERROR
);
2776 cbdata
.packed_refs
= get_packed_refs(&ref_cache
);
2778 do_for_each_entry_in_dir(get_loose_refs(&ref_cache
), 0,
2779 pack_if_possible_fn
, &cbdata
);
2781 if (commit_packed_refs())
2782 die_errno("unable to overwrite old ref-pack file");
2784 prune_refs(cbdata
.ref_to_prune
);
2789 * Rewrite the packed-refs file, omitting any refs listed in
2790 * 'refnames'. On error, leave packed-refs unchanged, write an error
2791 * message to 'err', and return a nonzero value.
2793 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2795 static int repack_without_refs(struct string_list
*refnames
, struct strbuf
*err
)
2797 struct ref_dir
*packed
;
2798 struct string_list_item
*refname
;
2799 int ret
, needs_repacking
= 0, removed
= 0;
2803 /* Look for a packed ref */
2804 for_each_string_list_item(refname
, refnames
) {
2805 if (get_packed_ref(refname
->string
)) {
2806 needs_repacking
= 1;
2811 /* Avoid locking if we have nothing to do */
2812 if (!needs_repacking
)
2813 return 0; /* no refname exists in packed refs */
2815 if (lock_packed_refs(0)) {
2816 unable_to_lock_message(git_path("packed-refs"), errno
, err
);
2819 packed
= get_packed_refs(&ref_cache
);
2821 /* Remove refnames from the cache */
2822 for_each_string_list_item(refname
, refnames
)
2823 if (remove_entry(packed
, refname
->string
) != -1)
2827 * All packed entries disappeared while we were
2828 * acquiring the lock.
2830 rollback_packed_refs();
2834 /* Write what remains */
2835 ret
= commit_packed_refs();
2837 strbuf_addf(err
, "unable to overwrite old ref-pack file: %s",
2842 static int delete_ref_loose(struct ref_lock
*lock
, int flag
, struct strbuf
*err
)
2846 if (!(flag
& REF_ISPACKED
) || flag
& REF_ISSYMREF
) {
2848 * loose. The loose file name is the same as the
2849 * lockfile name, minus ".lock":
2851 char *loose_filename
= get_locked_file_path(lock
->lk
);
2852 int res
= unlink_or_msg(loose_filename
, err
);
2853 free(loose_filename
);
2860 static int is_per_worktree_ref(const char *refname
)
2862 return !strcmp(refname
, "HEAD");
2865 static int is_pseudoref_syntax(const char *refname
)
2869 for (c
= refname
; *c
; c
++) {
2870 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
2877 enum ref_type
ref_type(const char *refname
)
2879 if (is_per_worktree_ref(refname
))
2880 return REF_TYPE_PER_WORKTREE
;
2881 if (is_pseudoref_syntax(refname
))
2882 return REF_TYPE_PSEUDOREF
;
2883 return REF_TYPE_NORMAL
;
2886 static int write_pseudoref(const char *pseudoref
, const unsigned char *sha1
,
2887 const unsigned char *old_sha1
, struct strbuf
*err
)
2889 const char *filename
;
2891 static struct lock_file lock
;
2892 struct strbuf buf
= STRBUF_INIT
;
2895 strbuf_addf(&buf
, "%s\n", sha1_to_hex(sha1
));
2897 filename
= git_path("%s", pseudoref
);
2898 fd
= hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
2900 strbuf_addf(err
, "Could not open '%s' for writing: %s",
2901 filename
, strerror(errno
));
2906 unsigned char actual_old_sha1
[20];
2908 if (read_ref(pseudoref
, actual_old_sha1
))
2909 die("could not read ref '%s'", pseudoref
);
2910 if (hashcmp(actual_old_sha1
, old_sha1
)) {
2911 strbuf_addf(err
, "Unexpected sha1 when writing %s", pseudoref
);
2912 rollback_lock_file(&lock
);
2917 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
) {
2918 strbuf_addf(err
, "Could not write to '%s'", filename
);
2919 rollback_lock_file(&lock
);
2923 commit_lock_file(&lock
);
2926 strbuf_release(&buf
);
2930 static int delete_pseudoref(const char *pseudoref
, const unsigned char *old_sha1
)
2932 static struct lock_file lock
;
2933 const char *filename
;
2935 filename
= git_path("%s", pseudoref
);
2937 if (old_sha1
&& !is_null_sha1(old_sha1
)) {
2939 unsigned char actual_old_sha1
[20];
2941 fd
= hold_lock_file_for_update(&lock
, filename
,
2944 die_errno(_("Could not open '%s' for writing"), filename
);
2945 if (read_ref(pseudoref
, actual_old_sha1
))
2946 die("could not read ref '%s'", pseudoref
);
2947 if (hashcmp(actual_old_sha1
, old_sha1
)) {
2948 warning("Unexpected sha1 when deleting %s", pseudoref
);
2949 rollback_lock_file(&lock
);
2954 rollback_lock_file(&lock
);
2962 int delete_ref(const char *refname
, const unsigned char *old_sha1
,
2965 struct ref_transaction
*transaction
;
2966 struct strbuf err
= STRBUF_INIT
;
2968 if (ref_type(refname
) == REF_TYPE_PSEUDOREF
)
2969 return delete_pseudoref(refname
, old_sha1
);
2971 transaction
= ref_transaction_begin(&err
);
2973 ref_transaction_delete(transaction
, refname
, old_sha1
,
2974 flags
, NULL
, &err
) ||
2975 ref_transaction_commit(transaction
, &err
)) {
2976 error("%s", err
.buf
);
2977 ref_transaction_free(transaction
);
2978 strbuf_release(&err
);
2981 ref_transaction_free(transaction
);
2982 strbuf_release(&err
);
2986 int delete_refs(struct string_list
*refnames
)
2988 struct strbuf err
= STRBUF_INIT
;
2994 result
= repack_without_refs(refnames
, &err
);
2997 * If we failed to rewrite the packed-refs file, then
2998 * it is unsafe to try to remove loose refs, because
2999 * doing so might expose an obsolete packed value for
3000 * a reference that might even point at an object that
3001 * has been garbage collected.
3003 if (refnames
->nr
== 1)
3004 error(_("could not delete reference %s: %s"),
3005 refnames
->items
[0].string
, err
.buf
);
3007 error(_("could not delete references: %s"), err
.buf
);
3012 for (i
= 0; i
< refnames
->nr
; i
++) {
3013 const char *refname
= refnames
->items
[i
].string
;
3015 if (delete_ref(refname
, NULL
, 0))
3016 result
|= error(_("could not remove reference %s"), refname
);
3020 strbuf_release(&err
);
3025 * People using contrib's git-new-workdir have .git/logs/refs ->
3026 * /some/other/path/.git/logs/refs, and that may live on another device.
3028 * IOW, to avoid cross device rename errors, the temporary renamed log must
3029 * live into logs/refs.
3031 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
3033 static int rename_tmp_log(const char *newrefname
)
3035 int attempts_remaining
= 4;
3036 struct strbuf path
= STRBUF_INIT
;
3040 strbuf_reset(&path
);
3041 strbuf_git_path(&path
, "logs/%s", newrefname
);
3042 switch (safe_create_leading_directories_const(path
.buf
)) {
3044 break; /* success */
3046 if (--attempts_remaining
> 0)
3050 error("unable to create directory for %s", newrefname
);
3054 if (rename(git_path(TMP_RENAMED_LOG
), path
.buf
)) {
3055 if ((errno
==EISDIR
|| errno
==ENOTDIR
) && --attempts_remaining
> 0) {
3057 * rename(a, b) when b is an existing
3058 * directory ought to result in ISDIR, but
3059 * Solaris 5.8 gives ENOTDIR. Sheesh.
3061 if (remove_empty_directories(&path
)) {
3062 error("Directory not empty: logs/%s", newrefname
);
3066 } else if (errno
== ENOENT
&& --attempts_remaining
> 0) {
3068 * Maybe another process just deleted one of
3069 * the directories in the path to newrefname.
3070 * Try again from the beginning.
3074 error("unable to move logfile "TMP_RENAMED_LOG
" to logs/%s: %s",
3075 newrefname
, strerror(errno
));
3081 strbuf_release(&path
);
3085 static int rename_ref_available(const char *oldname
, const char *newname
)
3087 struct string_list skip
= STRING_LIST_INIT_NODUP
;
3088 struct strbuf err
= STRBUF_INIT
;
3091 string_list_insert(&skip
, oldname
);
3092 ret
= !verify_refname_available(newname
, NULL
, &skip
,
3093 get_packed_refs(&ref_cache
), &err
)
3094 && !verify_refname_available(newname
, NULL
, &skip
,
3095 get_loose_refs(&ref_cache
), &err
);
3097 error("%s", err
.buf
);
3099 string_list_clear(&skip
, 0);
3100 strbuf_release(&err
);
3104 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3105 const unsigned char *sha1
, struct strbuf
*err
);
3106 static int commit_ref_update(struct ref_lock
*lock
,
3107 const unsigned char *sha1
, const char *logmsg
,
3108 int flags
, struct strbuf
*err
);
3110 int rename_ref(const char *oldrefname
, const char *newrefname
, const char *logmsg
)
3112 unsigned char sha1
[20], orig_sha1
[20];
3113 int flag
= 0, logmoved
= 0;
3114 struct ref_lock
*lock
;
3115 struct stat loginfo
;
3116 int log
= !lstat(git_path("logs/%s", oldrefname
), &loginfo
);
3117 const char *symref
= NULL
;
3118 struct strbuf err
= STRBUF_INIT
;
3120 if (log
&& S_ISLNK(loginfo
.st_mode
))
3121 return error("reflog for %s is a symlink", oldrefname
);
3123 symref
= resolve_ref_unsafe(oldrefname
, RESOLVE_REF_READING
,
3125 if (flag
& REF_ISSYMREF
)
3126 return error("refname %s is a symbolic ref, renaming it is not supported",
3129 return error("refname %s not found", oldrefname
);
3131 if (!rename_ref_available(oldrefname
, newrefname
))
3134 if (log
&& rename(git_path("logs/%s", oldrefname
), git_path(TMP_RENAMED_LOG
)))
3135 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG
": %s",
3136 oldrefname
, strerror(errno
));
3138 if (delete_ref(oldrefname
, orig_sha1
, REF_NODEREF
)) {
3139 error("unable to delete old %s", oldrefname
);
3143 if (!read_ref_full(newrefname
, RESOLVE_REF_READING
, sha1
, NULL
) &&
3144 delete_ref(newrefname
, sha1
, REF_NODEREF
)) {
3145 if (errno
==EISDIR
) {
3146 struct strbuf path
= STRBUF_INIT
;
3149 strbuf_git_path(&path
, "%s", newrefname
);
3150 result
= remove_empty_directories(&path
);
3151 strbuf_release(&path
);
3154 error("Directory not empty: %s", newrefname
);
3158 error("unable to delete existing %s", newrefname
);
3163 if (log
&& rename_tmp_log(newrefname
))
3168 lock
= lock_ref_sha1_basic(newrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
3170 error("unable to rename '%s' to '%s': %s", oldrefname
, newrefname
, err
.buf
);
3171 strbuf_release(&err
);
3174 hashcpy(lock
->old_oid
.hash
, orig_sha1
);
3176 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
3177 commit_ref_update(lock
, orig_sha1
, logmsg
, 0, &err
)) {
3178 error("unable to write current sha1 into %s: %s", newrefname
, err
.buf
);
3179 strbuf_release(&err
);
3186 lock
= lock_ref_sha1_basic(oldrefname
, NULL
, NULL
, NULL
, 0, NULL
, &err
);
3188 error("unable to lock %s for rollback: %s", oldrefname
, err
.buf
);
3189 strbuf_release(&err
);
3193 flag
= log_all_ref_updates
;
3194 log_all_ref_updates
= 0;
3195 if (write_ref_to_lockfile(lock
, orig_sha1
, &err
) ||
3196 commit_ref_update(lock
, orig_sha1
, NULL
, 0, &err
)) {
3197 error("unable to write current sha1 into %s: %s", oldrefname
, err
.buf
);
3198 strbuf_release(&err
);
3200 log_all_ref_updates
= flag
;
3203 if (logmoved
&& rename(git_path("logs/%s", newrefname
), git_path("logs/%s", oldrefname
)))
3204 error("unable to restore logfile %s from %s: %s",
3205 oldrefname
, newrefname
, strerror(errno
));
3206 if (!logmoved
&& log
&&
3207 rename(git_path(TMP_RENAMED_LOG
), git_path("logs/%s", oldrefname
)))
3208 error("unable to restore logfile %s from "TMP_RENAMED_LOG
": %s",
3209 oldrefname
, strerror(errno
));
3214 static int close_ref(struct ref_lock
*lock
)
3216 if (close_lock_file(lock
->lk
))
3221 static int commit_ref(struct ref_lock
*lock
)
3223 if (commit_lock_file(lock
->lk
))
3229 * copy the reflog message msg to buf, which has been allocated sufficiently
3230 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3231 * because reflog file is one line per entry.
3233 static int copy_msg(char *buf
, const char *msg
)
3240 while ((c
= *msg
++)) {
3241 if (wasspace
&& isspace(c
))
3243 wasspace
= isspace(c
);
3248 while (buf
< cp
&& isspace(cp
[-1]))
3254 static int should_autocreate_reflog(const char *refname
)
3256 if (!log_all_ref_updates
)
3258 return starts_with(refname
, "refs/heads/") ||
3259 starts_with(refname
, "refs/remotes/") ||
3260 starts_with(refname
, "refs/notes/") ||
3261 !strcmp(refname
, "HEAD");
3265 * Create a reflog for a ref. If force_create = 0, the reflog will
3266 * only be created for certain refs (those for which
3267 * should_autocreate_reflog returns non-zero. Otherwise, create it
3268 * regardless of the ref name. Fill in *err and return -1 on failure.
3270 static int log_ref_setup(const char *refname
, struct strbuf
*logfile
, struct strbuf
*err
, int force_create
)
3272 int logfd
, oflags
= O_APPEND
| O_WRONLY
;
3274 strbuf_git_path(logfile
, "logs/%s", refname
);
3275 if (force_create
|| should_autocreate_reflog(refname
)) {
3276 if (safe_create_leading_directories(logfile
->buf
) < 0) {
3277 strbuf_addf(err
, "unable to create directory for %s: "
3278 "%s", logfile
->buf
, strerror(errno
));
3284 logfd
= open(logfile
->buf
, oflags
, 0666);
3286 if (!(oflags
& O_CREAT
) && (errno
== ENOENT
|| errno
== EISDIR
))
3289 if (errno
== EISDIR
) {
3290 if (remove_empty_directories(logfile
)) {
3291 strbuf_addf(err
, "There are still logs under "
3292 "'%s'", logfile
->buf
);
3295 logfd
= open(logfile
->buf
, oflags
, 0666);
3299 strbuf_addf(err
, "unable to append to %s: %s",
3300 logfile
->buf
, strerror(errno
));
3305 adjust_shared_perm(logfile
->buf
);
3311 int safe_create_reflog(const char *refname
, int force_create
, struct strbuf
*err
)
3314 struct strbuf sb
= STRBUF_INIT
;
3316 ret
= log_ref_setup(refname
, &sb
, err
, force_create
);
3317 strbuf_release(&sb
);
3321 static int log_ref_write_fd(int fd
, const unsigned char *old_sha1
,
3322 const unsigned char *new_sha1
,
3323 const char *committer
, const char *msg
)
3325 int msglen
, written
;
3326 unsigned maxlen
, len
;
3329 msglen
= msg
? strlen(msg
) : 0;
3330 maxlen
= strlen(committer
) + msglen
+ 100;
3331 logrec
= xmalloc(maxlen
);
3332 len
= xsnprintf(logrec
, maxlen
, "%s %s %s\n",
3333 sha1_to_hex(old_sha1
),
3334 sha1_to_hex(new_sha1
),
3337 len
+= copy_msg(logrec
+ len
- 1, msg
) - 1;
3339 written
= len
<= maxlen
? write_in_full(fd
, logrec
, len
) : -1;
3347 static int log_ref_write_1(const char *refname
, const unsigned char *old_sha1
,
3348 const unsigned char *new_sha1
, const char *msg
,
3349 struct strbuf
*logfile
, int flags
,
3352 int logfd
, result
, oflags
= O_APPEND
| O_WRONLY
;
3354 if (log_all_ref_updates
< 0)
3355 log_all_ref_updates
= !is_bare_repository();
3357 result
= log_ref_setup(refname
, logfile
, err
, flags
& REF_FORCE_CREATE_REFLOG
);
3362 logfd
= open(logfile
->buf
, oflags
);
3365 result
= log_ref_write_fd(logfd
, old_sha1
, new_sha1
,
3366 git_committer_info(0), msg
);
3368 strbuf_addf(err
, "unable to append to %s: %s", logfile
->buf
,
3374 strbuf_addf(err
, "unable to append to %s: %s", logfile
->buf
,
3381 static int log_ref_write(const char *refname
, const unsigned char *old_sha1
,
3382 const unsigned char *new_sha1
, const char *msg
,
3383 int flags
, struct strbuf
*err
)
3385 struct strbuf sb
= STRBUF_INIT
;
3386 int ret
= log_ref_write_1(refname
, old_sha1
, new_sha1
, msg
, &sb
, flags
,
3388 strbuf_release(&sb
);
3392 int is_branch(const char *refname
)
3394 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
3398 * Write sha1 into the open lockfile, then close the lockfile. On
3399 * errors, rollback the lockfile, fill in *err and
3402 static int write_ref_to_lockfile(struct ref_lock
*lock
,
3403 const unsigned char *sha1
, struct strbuf
*err
)
3405 static char term
= '\n';
3409 o
= parse_object(sha1
);
3412 "Trying to write ref %s with nonexistent object %s",
3413 lock
->ref_name
, sha1_to_hex(sha1
));
3417 if (o
->type
!= OBJ_COMMIT
&& is_branch(lock
->ref_name
)) {
3419 "Trying to write non-commit object %s to branch %s",
3420 sha1_to_hex(sha1
), lock
->ref_name
);
3424 fd
= get_lock_file_fd(lock
->lk
);
3425 if (write_in_full(fd
, sha1_to_hex(sha1
), 40) != 40 ||
3426 write_in_full(fd
, &term
, 1) != 1 ||
3427 close_ref(lock
) < 0) {
3429 "Couldn't write %s", get_lock_file_path(lock
->lk
));
3437 * Commit a change to a loose reference that has already been written
3438 * to the loose reference lockfile. Also update the reflogs if
3439 * necessary, using the specified lockmsg (which can be NULL).
3441 static int commit_ref_update(struct ref_lock
*lock
,
3442 const unsigned char *sha1
, const char *logmsg
,
3443 int flags
, struct strbuf
*err
)
3445 clear_loose_ref_cache(&ref_cache
);
3446 if (log_ref_write(lock
->ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, flags
, err
) < 0 ||
3447 (strcmp(lock
->ref_name
, lock
->orig_ref_name
) &&
3448 log_ref_write(lock
->orig_ref_name
, lock
->old_oid
.hash
, sha1
, logmsg
, flags
, err
) < 0)) {
3449 char *old_msg
= strbuf_detach(err
, NULL
);
3450 strbuf_addf(err
, "Cannot update the ref '%s': %s",
3451 lock
->ref_name
, old_msg
);
3456 if (strcmp(lock
->orig_ref_name
, "HEAD") != 0) {
3458 * Special hack: If a branch is updated directly and HEAD
3459 * points to it (may happen on the remote side of a push
3460 * for example) then logically the HEAD reflog should be
3462 * A generic solution implies reverse symref information,
3463 * but finding all symrefs pointing to the given branch
3464 * would be rather costly for this rare event (the direct
3465 * update of a branch) to be worth it. So let's cheat and
3466 * check with HEAD only which should cover 99% of all usage
3467 * scenarios (even 100% of the default ones).
3469 unsigned char head_sha1
[20];
3471 const char *head_ref
;
3472 head_ref
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
3473 head_sha1
, &head_flag
);
3474 if (head_ref
&& (head_flag
& REF_ISSYMREF
) &&
3475 !strcmp(head_ref
, lock
->ref_name
)) {
3476 struct strbuf log_err
= STRBUF_INIT
;
3477 if (log_ref_write("HEAD", lock
->old_oid
.hash
, sha1
,
3478 logmsg
, 0, &log_err
)) {
3479 error("%s", log_err
.buf
);
3480 strbuf_release(&log_err
);
3484 if (commit_ref(lock
)) {
3485 error("Couldn't set %s", lock
->ref_name
);
3494 int create_symref(const char *ref_target
, const char *refs_heads_master
,
3497 char *lockpath
= NULL
;
3499 int fd
, len
, written
;
3500 char *git_HEAD
= git_pathdup("%s", ref_target
);
3501 unsigned char old_sha1
[20], new_sha1
[20];
3502 struct strbuf err
= STRBUF_INIT
;
3504 if (logmsg
&& read_ref(ref_target
, old_sha1
))
3507 if (safe_create_leading_directories(git_HEAD
) < 0)
3508 return error("unable to create directory for %s", git_HEAD
);
3510 #ifndef NO_SYMLINK_HEAD
3511 if (prefer_symlink_refs
) {
3513 if (!symlink(refs_heads_master
, git_HEAD
))
3515 fprintf(stderr
, "no symlink - falling back to symbolic ref\n");
3519 len
= snprintf(ref
, sizeof(ref
), "ref: %s\n", refs_heads_master
);
3520 if (sizeof(ref
) <= len
) {
3521 error("refname too long: %s", refs_heads_master
);
3522 goto error_free_return
;
3524 lockpath
= mkpathdup("%s.lock", git_HEAD
);
3525 fd
= open(lockpath
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
3527 error("Unable to open %s for writing", lockpath
);
3528 goto error_free_return
;
3530 written
= write_in_full(fd
, ref
, len
);
3531 if (close(fd
) != 0 || written
!= len
) {
3532 error("Unable to write to %s", lockpath
);
3533 goto error_unlink_return
;
3535 if (rename(lockpath
, git_HEAD
) < 0) {
3536 error("Unable to create %s", git_HEAD
);
3537 goto error_unlink_return
;
3539 if (adjust_shared_perm(git_HEAD
)) {
3540 error("Unable to fix permissions on %s", lockpath
);
3541 error_unlink_return
:
3542 unlink_or_warn(lockpath
);
3550 #ifndef NO_SYMLINK_HEAD
3553 if (logmsg
&& !read_ref(refs_heads_master
, new_sha1
) &&
3554 log_ref_write(ref_target
, old_sha1
, new_sha1
, logmsg
, 0, &err
)) {
3555 error("%s", err
.buf
);
3556 strbuf_release(&err
);
3563 struct read_ref_at_cb
{
3564 const char *refname
;
3565 unsigned long at_time
;
3568 unsigned char *sha1
;
3571 unsigned char osha1
[20];
3572 unsigned char nsha1
[20];
3576 unsigned long *cutoff_time
;
3581 static int read_ref_at_ent(unsigned char *osha1
, unsigned char *nsha1
,
3582 const char *email
, unsigned long timestamp
, int tz
,
3583 const char *message
, void *cb_data
)
3585 struct read_ref_at_cb
*cb
= cb_data
;
3589 cb
->date
= timestamp
;
3591 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
3593 *cb
->msg
= xstrdup(message
);
3594 if (cb
->cutoff_time
)
3595 *cb
->cutoff_time
= timestamp
;
3597 *cb
->cutoff_tz
= tz
;
3599 *cb
->cutoff_cnt
= cb
->reccnt
- 1;
3601 * we have not yet updated cb->[n|o]sha1 so they still
3602 * hold the values for the previous record.
3604 if (!is_null_sha1(cb
->osha1
)) {
3605 hashcpy(cb
->sha1
, nsha1
);
3606 if (hashcmp(cb
->osha1
, nsha1
))
3607 warning("Log for ref %s has gap after %s.",
3608 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_MODE(RFC2822
)));
3610 else if (cb
->date
== cb
->at_time
)
3611 hashcpy(cb
->sha1
, nsha1
);
3612 else if (hashcmp(nsha1
, cb
->sha1
))
3613 warning("Log for ref %s unexpectedly ended on %s.",
3614 cb
->refname
, show_date(cb
->date
, cb
->tz
,
3615 DATE_MODE(RFC2822
)));
3616 hashcpy(cb
->osha1
, osha1
);
3617 hashcpy(cb
->nsha1
, nsha1
);
3621 hashcpy(cb
->osha1
, osha1
);
3622 hashcpy(cb
->nsha1
, nsha1
);
3628 static int read_ref_at_ent_oldest(unsigned char *osha1
, unsigned char *nsha1
,
3629 const char *email
, unsigned long timestamp
,
3630 int tz
, const char *message
, void *cb_data
)
3632 struct read_ref_at_cb
*cb
= cb_data
;
3635 *cb
->msg
= xstrdup(message
);
3636 if (cb
->cutoff_time
)
3637 *cb
->cutoff_time
= timestamp
;
3639 *cb
->cutoff_tz
= tz
;
3641 *cb
->cutoff_cnt
= cb
->reccnt
;
3642 hashcpy(cb
->sha1
, osha1
);
3643 if (is_null_sha1(cb
->sha1
))
3644 hashcpy(cb
->sha1
, nsha1
);
3645 /* We just want the first entry */
3649 int read_ref_at(const char *refname
, unsigned int flags
, unsigned long at_time
, int cnt
,
3650 unsigned char *sha1
, char **msg
,
3651 unsigned long *cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
3653 struct read_ref_at_cb cb
;
3655 memset(&cb
, 0, sizeof(cb
));
3656 cb
.refname
= refname
;
3657 cb
.at_time
= at_time
;
3660 cb
.cutoff_time
= cutoff_time
;
3661 cb
.cutoff_tz
= cutoff_tz
;
3662 cb
.cutoff_cnt
= cutoff_cnt
;
3665 for_each_reflog_ent_reverse(refname
, read_ref_at_ent
, &cb
);
3668 if (flags
& GET_SHA1_QUIETLY
)
3671 die("Log for %s is empty.", refname
);
3676 for_each_reflog_ent(refname
, read_ref_at_ent_oldest
, &cb
);
3681 int reflog_exists(const char *refname
)
3685 return !lstat(git_path("logs/%s", refname
), &st
) &&
3686 S_ISREG(st
.st_mode
);
3689 int delete_reflog(const char *refname
)
3691 return remove_path(git_path("logs/%s", refname
));
3694 static int show_one_reflog_ent(struct strbuf
*sb
, each_reflog_ent_fn fn
, void *cb_data
)
3696 unsigned char osha1
[20], nsha1
[20];
3697 char *email_end
, *message
;
3698 unsigned long timestamp
;
3701 /* old SP new SP name <email> SP time TAB msg LF */
3702 if (sb
->len
< 83 || sb
->buf
[sb
->len
- 1] != '\n' ||
3703 get_sha1_hex(sb
->buf
, osha1
) || sb
->buf
[40] != ' ' ||
3704 get_sha1_hex(sb
->buf
+ 41, nsha1
) || sb
->buf
[81] != ' ' ||
3705 !(email_end
= strchr(sb
->buf
+ 82, '>')) ||
3706 email_end
[1] != ' ' ||
3707 !(timestamp
= strtoul(email_end
+ 2, &message
, 10)) ||
3708 !message
|| message
[0] != ' ' ||
3709 (message
[1] != '+' && message
[1] != '-') ||
3710 !isdigit(message
[2]) || !isdigit(message
[3]) ||
3711 !isdigit(message
[4]) || !isdigit(message
[5]))
3712 return 0; /* corrupt? */
3713 email_end
[1] = '\0';
3714 tz
= strtol(message
+ 1, NULL
, 10);
3715 if (message
[6] != '\t')
3719 return fn(osha1
, nsha1
, sb
->buf
+ 82, timestamp
, tz
, message
, cb_data
);
3722 static char *find_beginning_of_line(char *bob
, char *scan
)
3724 while (bob
< scan
&& *(--scan
) != '\n')
3725 ; /* keep scanning backwards */
3727 * Return either beginning of the buffer, or LF at the end of
3728 * the previous line.
3733 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3735 struct strbuf sb
= STRBUF_INIT
;
3738 int ret
= 0, at_tail
= 1;
3740 logfp
= fopen(git_path("logs/%s", refname
), "r");
3744 /* Jump to the end */
3745 if (fseek(logfp
, 0, SEEK_END
) < 0)
3746 return error("cannot seek back reflog for %s: %s",
3747 refname
, strerror(errno
));
3749 while (!ret
&& 0 < pos
) {
3755 /* Fill next block from the end */
3756 cnt
= (sizeof(buf
) < pos
) ? sizeof(buf
) : pos
;
3757 if (fseek(logfp
, pos
- cnt
, SEEK_SET
))
3758 return error("cannot seek back reflog for %s: %s",
3759 refname
, strerror(errno
));
3760 nread
= fread(buf
, cnt
, 1, logfp
);
3762 return error("cannot read %d bytes from reflog for %s: %s",
3763 cnt
, refname
, strerror(errno
));
3766 scanp
= endp
= buf
+ cnt
;
3767 if (at_tail
&& scanp
[-1] == '\n')
3768 /* Looking at the final LF at the end of the file */
3772 while (buf
< scanp
) {
3774 * terminating LF of the previous line, or the beginning
3779 bp
= find_beginning_of_line(buf
, scanp
);
3783 * The newline is the end of the previous line,
3784 * so we know we have complete line starting
3785 * at (bp + 1). Prefix it onto any prior data
3786 * we collected for the line and process it.
3788 strbuf_splice(&sb
, 0, 0, bp
+ 1, endp
- (bp
+ 1));
3791 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3797 * We are at the start of the buffer, and the
3798 * start of the file; there is no previous
3799 * line, and we have everything for this one.
3800 * Process it, and we can end the loop.
3802 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3803 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3810 * We are at the start of the buffer, and there
3811 * is more file to read backwards. Which means
3812 * we are in the middle of a line. Note that we
3813 * may get here even if *bp was a newline; that
3814 * just means we are at the exact end of the
3815 * previous line, rather than some spot in the
3818 * Save away what we have to be combined with
3819 * the data from the next read.
3821 strbuf_splice(&sb
, 0, 0, buf
, endp
- buf
);
3828 die("BUG: reverse reflog parser had leftover data");
3831 strbuf_release(&sb
);
3835 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
, void *cb_data
)
3838 struct strbuf sb
= STRBUF_INIT
;
3841 logfp
= fopen(git_path("logs/%s", refname
), "r");
3845 while (!ret
&& !strbuf_getwholeline(&sb
, logfp
, '\n'))
3846 ret
= show_one_reflog_ent(&sb
, fn
, cb_data
);
3848 strbuf_release(&sb
);
3852 * Call fn for each reflog in the namespace indicated by name. name
3853 * must be empty or end with '/'. Name will be used as a scratch
3854 * space, but its contents will be restored before return.
3856 static int do_for_each_reflog(struct strbuf
*name
, each_ref_fn fn
, void *cb_data
)
3858 DIR *d
= opendir(git_path("logs/%s", name
->buf
));
3861 int oldlen
= name
->len
;
3864 return name
->len
? errno
: 0;
3866 while ((de
= readdir(d
)) != NULL
) {
3869 if (de
->d_name
[0] == '.')
3871 if (ends_with(de
->d_name
, ".lock"))
3873 strbuf_addstr(name
, de
->d_name
);
3874 if (stat(git_path("logs/%s", name
->buf
), &st
) < 0) {
3875 ; /* silently ignore */
3877 if (S_ISDIR(st
.st_mode
)) {
3878 strbuf_addch(name
, '/');
3879 retval
= do_for_each_reflog(name
, fn
, cb_data
);
3881 struct object_id oid
;
3883 if (read_ref_full(name
->buf
, 0, oid
.hash
, NULL
))
3884 retval
= error("bad ref for %s", name
->buf
);
3886 retval
= fn(name
->buf
, &oid
, 0, cb_data
);
3891 strbuf_setlen(name
, oldlen
);
3897 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
3901 strbuf_init(&name
, PATH_MAX
);
3902 retval
= do_for_each_reflog(&name
, fn
, cb_data
);
3903 strbuf_release(&name
);
3908 * Information needed for a single ref update. Set new_sha1 to the new
3909 * value or to null_sha1 to delete the ref. To check the old value
3910 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3911 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3912 * not exist before update.
3916 * If (flags & REF_HAVE_NEW), set the reference to this value:
3918 unsigned char new_sha1
[20];
3920 * If (flags & REF_HAVE_OLD), check that the reference
3921 * previously had this value:
3923 unsigned char old_sha1
[20];
3925 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3926 * REF_DELETING, and REF_ISPRUNING:
3929 struct ref_lock
*lock
;
3932 const char refname
[FLEX_ARRAY
];
3936 * Transaction states.
3937 * OPEN: The transaction is in a valid state and can accept new updates.
3938 * An OPEN transaction can be committed.
3939 * CLOSED: A closed transaction is no longer active and no other operations
3940 * than free can be used on it in this state.
3941 * A transaction can either become closed by successfully committing
3942 * an active transaction or if there is a failure while building
3943 * the transaction thus rendering it failed/inactive.
3945 enum ref_transaction_state
{
3946 REF_TRANSACTION_OPEN
= 0,
3947 REF_TRANSACTION_CLOSED
= 1
3951 * Data structure for holding a reference transaction, which can
3952 * consist of checks and updates to multiple references, carried out
3953 * as atomically as possible. This structure is opaque to callers.
3955 struct ref_transaction
{
3956 struct ref_update
**updates
;
3959 enum ref_transaction_state state
;
3962 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
3966 return xcalloc(1, sizeof(struct ref_transaction
));
3969 void ref_transaction_free(struct ref_transaction
*transaction
)
3976 for (i
= 0; i
< transaction
->nr
; i
++) {
3977 free(transaction
->updates
[i
]->msg
);
3978 free(transaction
->updates
[i
]);
3980 free(transaction
->updates
);
3984 static struct ref_update
*add_update(struct ref_transaction
*transaction
,
3985 const char *refname
)
3987 size_t len
= strlen(refname
);
3988 struct ref_update
*update
= xcalloc(1, sizeof(*update
) + len
+ 1);
3990 strcpy((char *)update
->refname
, refname
);
3991 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
3992 transaction
->updates
[transaction
->nr
++] = update
;
3996 int ref_transaction_update(struct ref_transaction
*transaction
,
3997 const char *refname
,
3998 const unsigned char *new_sha1
,
3999 const unsigned char *old_sha1
,
4000 unsigned int flags
, const char *msg
,
4003 struct ref_update
*update
;
4007 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
4008 die("BUG: update called for transaction that is not open");
4010 if (new_sha1
&& !is_null_sha1(new_sha1
) &&
4011 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
4012 strbuf_addf(err
, "refusing to update ref with bad name %s",
4017 update
= add_update(transaction
, refname
);
4019 hashcpy(update
->new_sha1
, new_sha1
);
4020 flags
|= REF_HAVE_NEW
;
4023 hashcpy(update
->old_sha1
, old_sha1
);
4024 flags
|= REF_HAVE_OLD
;
4026 update
->flags
= flags
;
4028 update
->msg
= xstrdup(msg
);
4032 int ref_transaction_create(struct ref_transaction
*transaction
,
4033 const char *refname
,
4034 const unsigned char *new_sha1
,
4035 unsigned int flags
, const char *msg
,
4038 if (!new_sha1
|| is_null_sha1(new_sha1
))
4039 die("BUG: create called without valid new_sha1");
4040 return ref_transaction_update(transaction
, refname
, new_sha1
,
4041 null_sha1
, flags
, msg
, err
);
4044 int ref_transaction_delete(struct ref_transaction
*transaction
,
4045 const char *refname
,
4046 const unsigned char *old_sha1
,
4047 unsigned int flags
, const char *msg
,
4050 if (old_sha1
&& is_null_sha1(old_sha1
))
4051 die("BUG: delete called with old_sha1 set to zeros");
4052 return ref_transaction_update(transaction
, refname
,
4053 null_sha1
, old_sha1
,
4057 int ref_transaction_verify(struct ref_transaction
*transaction
,
4058 const char *refname
,
4059 const unsigned char *old_sha1
,
4064 die("BUG: verify called with old_sha1 set to NULL");
4065 return ref_transaction_update(transaction
, refname
,
4070 int update_ref(const char *msg
, const char *refname
,
4071 const unsigned char *new_sha1
, const unsigned char *old_sha1
,
4072 unsigned int flags
, enum action_on_err onerr
)
4074 struct ref_transaction
*t
= NULL
;
4075 struct strbuf err
= STRBUF_INIT
;
4078 if (ref_type(refname
) == REF_TYPE_PSEUDOREF
) {
4079 ret
= write_pseudoref(refname
, new_sha1
, old_sha1
, &err
);
4081 t
= ref_transaction_begin(&err
);
4083 ref_transaction_update(t
, refname
, new_sha1
, old_sha1
,
4084 flags
, msg
, &err
) ||
4085 ref_transaction_commit(t
, &err
)) {
4087 ref_transaction_free(t
);
4091 const char *str
= "update_ref failed for ref '%s': %s";
4094 case UPDATE_REFS_MSG_ON_ERR
:
4095 error(str
, refname
, err
.buf
);
4097 case UPDATE_REFS_DIE_ON_ERR
:
4098 die(str
, refname
, err
.buf
);
4100 case UPDATE_REFS_QUIET_ON_ERR
:
4103 strbuf_release(&err
);
4106 strbuf_release(&err
);
4108 ref_transaction_free(t
);
4112 static int ref_update_reject_duplicates(struct string_list
*refnames
,
4115 int i
, n
= refnames
->nr
;
4119 for (i
= 1; i
< n
; i
++)
4120 if (!strcmp(refnames
->items
[i
- 1].string
, refnames
->items
[i
].string
)) {
4122 "Multiple updates for ref '%s' not allowed.",
4123 refnames
->items
[i
].string
);
4129 int ref_transaction_commit(struct ref_transaction
*transaction
,
4133 int n
= transaction
->nr
;
4134 struct ref_update
**updates
= transaction
->updates
;
4135 struct string_list refs_to_delete
= STRING_LIST_INIT_NODUP
;
4136 struct string_list_item
*ref_to_delete
;
4137 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
4141 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
4142 die("BUG: commit called for transaction that is not open");
4145 transaction
->state
= REF_TRANSACTION_CLOSED
;
4149 /* Fail if a refname appears more than once in the transaction: */
4150 for (i
= 0; i
< n
; i
++)
4151 string_list_append(&affected_refnames
, updates
[i
]->refname
);
4152 string_list_sort(&affected_refnames
);
4153 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
4154 ret
= TRANSACTION_GENERIC_ERROR
;
4159 * Acquire all locks, verify old values if provided, check
4160 * that new values are valid, and write new values to the
4161 * lockfiles, ready to be activated. Only keep one lockfile
4162 * open at a time to avoid running out of file descriptors.
4164 for (i
= 0; i
< n
; i
++) {
4165 struct ref_update
*update
= updates
[i
];
4167 if ((update
->flags
& REF_HAVE_NEW
) &&
4168 is_null_sha1(update
->new_sha1
))
4169 update
->flags
|= REF_DELETING
;
4170 update
->lock
= lock_ref_sha1_basic(
4172 ((update
->flags
& REF_HAVE_OLD
) ?
4173 update
->old_sha1
: NULL
),
4174 &affected_refnames
, NULL
,
4178 if (!update
->lock
) {
4181 ret
= (errno
== ENOTDIR
)
4182 ? TRANSACTION_NAME_CONFLICT
4183 : TRANSACTION_GENERIC_ERROR
;
4184 reason
= strbuf_detach(err
, NULL
);
4185 strbuf_addf(err
, "cannot lock ref '%s': %s",
4186 update
->refname
, reason
);
4190 if ((update
->flags
& REF_HAVE_NEW
) &&
4191 !(update
->flags
& REF_DELETING
)) {
4192 int overwriting_symref
= ((update
->type
& REF_ISSYMREF
) &&
4193 (update
->flags
& REF_NODEREF
));
4195 if (!overwriting_symref
&&
4196 !hashcmp(update
->lock
->old_oid
.hash
, update
->new_sha1
)) {
4198 * The reference already has the desired
4199 * value, so we don't need to write it.
4201 } else if (write_ref_to_lockfile(update
->lock
,
4204 char *write_err
= strbuf_detach(err
, NULL
);
4207 * The lock was freed upon failure of
4208 * write_ref_to_lockfile():
4210 update
->lock
= NULL
;
4212 "cannot update the ref '%s': %s",
4213 update
->refname
, write_err
);
4215 ret
= TRANSACTION_GENERIC_ERROR
;
4218 update
->flags
|= REF_NEEDS_COMMIT
;
4221 if (!(update
->flags
& REF_NEEDS_COMMIT
)) {
4223 * We didn't have to write anything to the lockfile.
4224 * Close it to free up the file descriptor:
4226 if (close_ref(update
->lock
)) {
4227 strbuf_addf(err
, "Couldn't close %s.lock",
4234 /* Perform updates first so live commits remain referenced */
4235 for (i
= 0; i
< n
; i
++) {
4236 struct ref_update
*update
= updates
[i
];
4238 if (update
->flags
& REF_NEEDS_COMMIT
) {
4239 if (commit_ref_update(update
->lock
,
4240 update
->new_sha1
, update
->msg
,
4241 update
->flags
, err
)) {
4242 /* freed by commit_ref_update(): */
4243 update
->lock
= NULL
;
4244 ret
= TRANSACTION_GENERIC_ERROR
;
4247 /* freed by commit_ref_update(): */
4248 update
->lock
= NULL
;
4253 /* Perform deletes now that updates are safely completed */
4254 for (i
= 0; i
< n
; i
++) {
4255 struct ref_update
*update
= updates
[i
];
4257 if (update
->flags
& REF_DELETING
) {
4258 if (delete_ref_loose(update
->lock
, update
->type
, err
)) {
4259 ret
= TRANSACTION_GENERIC_ERROR
;
4263 if (!(update
->flags
& REF_ISPRUNING
))
4264 string_list_append(&refs_to_delete
,
4265 update
->lock
->ref_name
);
4269 if (repack_without_refs(&refs_to_delete
, err
)) {
4270 ret
= TRANSACTION_GENERIC_ERROR
;
4273 for_each_string_list_item(ref_to_delete
, &refs_to_delete
)
4274 unlink_or_warn(git_path("logs/%s", ref_to_delete
->string
));
4275 clear_loose_ref_cache(&ref_cache
);
4278 transaction
->state
= REF_TRANSACTION_CLOSED
;
4280 for (i
= 0; i
< n
; i
++)
4281 if (updates
[i
]->lock
)
4282 unlock_ref(updates
[i
]->lock
);
4283 string_list_clear(&refs_to_delete
, 0);
4284 string_list_clear(&affected_refnames
, 0);
4288 static int ref_present(const char *refname
,
4289 const struct object_id
*oid
, int flags
, void *cb_data
)
4291 struct string_list
*affected_refnames
= cb_data
;
4293 return string_list_has_string(affected_refnames
, refname
);
4296 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
4299 struct ref_dir
*loose_refs
= get_loose_refs(&ref_cache
);
4300 struct ref_dir
*packed_refs
= get_packed_refs(&ref_cache
);
4302 int n
= transaction
->nr
;
4303 struct ref_update
**updates
= transaction
->updates
;
4304 struct string_list affected_refnames
= STRING_LIST_INIT_NODUP
;
4308 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
4309 die("BUG: commit called for transaction that is not open");
4311 /* Fail if a refname appears more than once in the transaction: */
4312 for (i
= 0; i
< n
; i
++)
4313 string_list_append(&affected_refnames
, updates
[i
]->refname
);
4314 string_list_sort(&affected_refnames
);
4315 if (ref_update_reject_duplicates(&affected_refnames
, err
)) {
4316 ret
= TRANSACTION_GENERIC_ERROR
;
4321 * It's really undefined to call this function in an active
4322 * repository or when there are existing references: we are
4323 * only locking and changing packed-refs, so (1) any
4324 * simultaneous processes might try to change a reference at
4325 * the same time we do, and (2) any existing loose versions of
4326 * the references that we are setting would have precedence
4327 * over our values. But some remote helpers create the remote
4328 * "HEAD" and "master" branches before calling this function,
4329 * so here we really only check that none of the references
4330 * that we are creating already exists.
4332 if (for_each_rawref(ref_present
, &affected_refnames
))
4333 die("BUG: initial ref transaction called with existing refs");
4335 for (i
= 0; i
< n
; i
++) {
4336 struct ref_update
*update
= updates
[i
];
4338 if ((update
->flags
& REF_HAVE_OLD
) &&
4339 !is_null_sha1(update
->old_sha1
))
4340 die("BUG: initial ref transaction with old_sha1 set");
4341 if (verify_refname_available(update
->refname
,
4342 &affected_refnames
, NULL
,
4344 verify_refname_available(update
->refname
,
4345 &affected_refnames
, NULL
,
4346 packed_refs
, err
)) {
4347 ret
= TRANSACTION_NAME_CONFLICT
;
4352 if (lock_packed_refs(0)) {
4353 strbuf_addf(err
, "unable to lock packed-refs file: %s",
4355 ret
= TRANSACTION_GENERIC_ERROR
;
4359 for (i
= 0; i
< n
; i
++) {
4360 struct ref_update
*update
= updates
[i
];
4362 if ((update
->flags
& REF_HAVE_NEW
) &&
4363 !is_null_sha1(update
->new_sha1
))
4364 add_packed_ref(update
->refname
, update
->new_sha1
);
4367 if (commit_packed_refs()) {
4368 strbuf_addf(err
, "unable to commit packed-refs file: %s",
4370 ret
= TRANSACTION_GENERIC_ERROR
;
4375 transaction
->state
= REF_TRANSACTION_CLOSED
;
4376 string_list_clear(&affected_refnames
, 0);
4380 char *shorten_unambiguous_ref(const char *refname
, int strict
)
4383 static char **scanf_fmts
;
4384 static int nr_rules
;
4389 * Pre-generate scanf formats from ref_rev_parse_rules[].
4390 * Generate a format suitable for scanf from a
4391 * ref_rev_parse_rules rule by interpolating "%s" at the
4392 * location of the "%.*s".
4394 size_t total_len
= 0;
4397 /* the rule list is NULL terminated, count them first */
4398 for (nr_rules
= 0; ref_rev_parse_rules
[nr_rules
]; nr_rules
++)
4399 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4400 total_len
+= strlen(ref_rev_parse_rules
[nr_rules
]) - 2 + 1;
4402 scanf_fmts
= xmalloc(nr_rules
* sizeof(char *) + total_len
);
4405 for (i
= 0; i
< nr_rules
; i
++) {
4406 assert(offset
< total_len
);
4407 scanf_fmts
[i
] = (char *)&scanf_fmts
[nr_rules
] + offset
;
4408 offset
+= snprintf(scanf_fmts
[i
], total_len
- offset
,
4409 ref_rev_parse_rules
[i
], 2, "%s") + 1;
4413 /* bail out if there are no rules */
4415 return xstrdup(refname
);
4417 /* buffer for scanf result, at most refname must fit */
4418 short_name
= xstrdup(refname
);
4420 /* skip first rule, it will always match */
4421 for (i
= nr_rules
- 1; i
> 0 ; --i
) {
4423 int rules_to_fail
= i
;
4426 if (1 != sscanf(refname
, scanf_fmts
[i
], short_name
))
4429 short_name_len
= strlen(short_name
);
4432 * in strict mode, all (except the matched one) rules
4433 * must fail to resolve to a valid non-ambiguous ref
4436 rules_to_fail
= nr_rules
;
4439 * check if the short name resolves to a valid ref,
4440 * but use only rules prior to the matched one
4442 for (j
= 0; j
< rules_to_fail
; j
++) {
4443 const char *rule
= ref_rev_parse_rules
[j
];
4444 char refname
[PATH_MAX
];
4446 /* skip matched rule */
4451 * the short name is ambiguous, if it resolves
4452 * (with this previous rule) to a valid ref
4453 * read_ref() returns 0 on success
4455 mksnpath(refname
, sizeof(refname
),
4456 rule
, short_name_len
, short_name
);
4457 if (ref_exists(refname
))
4462 * short name is non-ambiguous if all previous rules
4463 * haven't resolved to a valid ref
4465 if (j
== rules_to_fail
)
4470 return xstrdup(refname
);
4473 static struct string_list
*hide_refs
;
4475 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
)
4477 if (!strcmp("transfer.hiderefs", var
) ||
4478 /* NEEDSWORK: use parse_config_key() once both are merged */
4479 (starts_with(var
, section
) && var
[strlen(section
)] == '.' &&
4480 !strcmp(var
+ strlen(section
), ".hiderefs"))) {
4485 return config_error_nonbool(var
);
4486 ref
= xstrdup(value
);
4488 while (len
&& ref
[len
- 1] == '/')
4491 hide_refs
= xcalloc(1, sizeof(*hide_refs
));
4492 hide_refs
->strdup_strings
= 1;
4494 string_list_append(hide_refs
, ref
);
4499 int ref_is_hidden(const char *refname
)
4505 for (i
= hide_refs
->nr
- 1; i
>= 0; i
--) {
4506 const char *match
= hide_refs
->items
[i
].string
;
4510 if (*match
== '!') {
4515 if (!starts_with(refname
, match
))
4517 len
= strlen(match
);
4518 if (!refname
[len
] || refname
[len
] == '/')
4524 struct expire_reflog_cb
{
4526 reflog_expiry_should_prune_fn
*should_prune_fn
;
4529 unsigned char last_kept_sha1
[20];
4532 static int expire_reflog_ent(unsigned char *osha1
, unsigned char *nsha1
,
4533 const char *email
, unsigned long timestamp
, int tz
,
4534 const char *message
, void *cb_data
)
4536 struct expire_reflog_cb
*cb
= cb_data
;
4537 struct expire_reflog_policy_cb
*policy_cb
= cb
->policy_cb
;
4539 if (cb
->flags
& EXPIRE_REFLOGS_REWRITE
)
4540 osha1
= cb
->last_kept_sha1
;
4542 if ((*cb
->should_prune_fn
)(osha1
, nsha1
, email
, timestamp
, tz
,
4543 message
, policy_cb
)) {
4545 printf("would prune %s", message
);
4546 else if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4547 printf("prune %s", message
);
4550 fprintf(cb
->newlog
, "%s %s %s %lu %+05d\t%s",
4551 sha1_to_hex(osha1
), sha1_to_hex(nsha1
),
4552 email
, timestamp
, tz
, message
);
4553 hashcpy(cb
->last_kept_sha1
, nsha1
);
4555 if (cb
->flags
& EXPIRE_REFLOGS_VERBOSE
)
4556 printf("keep %s", message
);
4561 int reflog_expire(const char *refname
, const unsigned char *sha1
,
4563 reflog_expiry_prepare_fn prepare_fn
,
4564 reflog_expiry_should_prune_fn should_prune_fn
,
4565 reflog_expiry_cleanup_fn cleanup_fn
,
4566 void *policy_cb_data
)
4568 static struct lock_file reflog_lock
;
4569 struct expire_reflog_cb cb
;
4570 struct ref_lock
*lock
;
4574 struct strbuf err
= STRBUF_INIT
;
4576 memset(&cb
, 0, sizeof(cb
));
4578 cb
.policy_cb
= policy_cb_data
;
4579 cb
.should_prune_fn
= should_prune_fn
;
4582 * The reflog file is locked by holding the lock on the
4583 * reference itself, plus we might need to update the
4584 * reference if --updateref was specified:
4586 lock
= lock_ref_sha1_basic(refname
, sha1
, NULL
, NULL
, 0, &type
, &err
);
4588 error("cannot lock ref '%s': %s", refname
, err
.buf
);
4589 strbuf_release(&err
);
4592 if (!reflog_exists(refname
)) {
4597 log_file
= git_pathdup("logs/%s", refname
);
4598 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4600 * Even though holding $GIT_DIR/logs/$reflog.lock has
4601 * no locking implications, we use the lock_file
4602 * machinery here anyway because it does a lot of the
4603 * work we need, including cleaning up if the program
4604 * exits unexpectedly.
4606 if (hold_lock_file_for_update(&reflog_lock
, log_file
, 0) < 0) {
4607 struct strbuf err
= STRBUF_INIT
;
4608 unable_to_lock_message(log_file
, errno
, &err
);
4609 error("%s", err
.buf
);
4610 strbuf_release(&err
);
4613 cb
.newlog
= fdopen_lock_file(&reflog_lock
, "w");
4615 error("cannot fdopen %s (%s)",
4616 get_lock_file_path(&reflog_lock
), strerror(errno
));
4621 (*prepare_fn
)(refname
, sha1
, cb
.policy_cb
);
4622 for_each_reflog_ent(refname
, expire_reflog_ent
, &cb
);
4623 (*cleanup_fn
)(cb
.policy_cb
);
4625 if (!(flags
& EXPIRE_REFLOGS_DRY_RUN
)) {
4627 * It doesn't make sense to adjust a reference pointed
4628 * to by a symbolic ref based on expiring entries in
4629 * the symbolic reference's reflog. Nor can we update
4630 * a reference if there are no remaining reflog
4633 int update
= (flags
& EXPIRE_REFLOGS_UPDATE_REF
) &&
4634 !(type
& REF_ISSYMREF
) &&
4635 !is_null_sha1(cb
.last_kept_sha1
);
4637 if (close_lock_file(&reflog_lock
)) {
4638 status
|= error("couldn't write %s: %s", log_file
,
4640 } else if (update
&&
4641 (write_in_full(get_lock_file_fd(lock
->lk
),
4642 sha1_to_hex(cb
.last_kept_sha1
), 40) != 40 ||
4643 write_str_in_full(get_lock_file_fd(lock
->lk
), "\n") != 1 ||
4644 close_ref(lock
) < 0)) {
4645 status
|= error("couldn't write %s",
4646 get_lock_file_path(lock
->lk
));
4647 rollback_lock_file(&reflog_lock
);
4648 } else if (commit_lock_file(&reflog_lock
)) {
4649 status
|= error("unable to commit reflog '%s' (%s)",
4650 log_file
, strerror(errno
));
4651 } else if (update
&& commit_ref(lock
)) {
4652 status
|= error("couldn't set %s", lock
->ref_name
);
4660 rollback_lock_file(&reflog_lock
);