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);
307 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
308 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
309 const char *dirname, size_t len,
311 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
313 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
316 assert(entry->flag & REF_DIR);
317 dir = &entry->u.subdir;
318 if (entry->flag & REF_INCOMPLETE) {
319 read_loose_refs(entry->name, dir);
322 * Manually add refs/bisect, which, being
323 * per-worktree, might not appear in the directory
324 * listing for refs/ in the main repo.
326 if (!strcmp(entry->name, "refs/")) {
327 int pos = search_ref_dir(dir, "refs/bisect/", 12);
329 struct ref_entry *child_entry;
330 child_entry = create_dir_entry(dir->ref_cache,
333 add_entry_to_dir(dir, child_entry);
334 read_loose_refs("refs/bisect",
335 &child_entry->u.subdir);
338 entry->flag &= ~REF_INCOMPLETE;
344 * Check if a refname is safe.
345 * For refs that start with "refs/" we consider it safe as long they do
346 * not try to resolve to outside of refs/.
348 * For all other refs we only consider them safe iff they only contain
349 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
352 static int refname_is_safe(const char *refname)
354 if (starts_with(refname, "refs/")) {
358 buf = xmalloc(strlen(refname) + 1);
360 * Does the refname try to escape refs/?
361 * For example: refs/foo/../bar is safe but refs/foo/../../bar
364 result = !normalize_path_copy(buf, refname + strlen("refs/"));
369 if (!isupper(*refname) && *refname != '_')
376 static struct ref_entry *create_ref_entry(const char *refname,
377 const unsigned char *sha1, int flag,
381 struct ref_entry *ref;
384 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
385 die("Reference has invalid format: '%s'", refname);
386 len = strlen(refname) + 1;
387 ref = xmalloc(sizeof(struct ref_entry) + len);
388 hashcpy(ref->u.value.oid.hash, sha1);
389 oidclr(&ref->u.value.peeled);
390 memcpy(ref->name, refname, len);
395 static void clear_ref_dir(struct ref_dir *dir);
397 static void free_ref_entry(struct ref_entry *entry)
399 if (entry->flag & REF_DIR) {
401 * Do not use get_ref_dir() here, as that might
402 * trigger the reading of loose refs.
404 clear_ref_dir(&entry->u.subdir);
410 * Add a ref_entry to the end of dir (unsorted). Entry is always
411 * stored directly in dir; no recursion into subdirectories is
414 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
416 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
417 dir->entries[dir->nr++] = entry;
418 /* optimize for the case that entries are added in order */
420 (dir->nr == dir->sorted + 1 &&
421 strcmp(dir->entries[dir->nr - 2]->name,
422 dir->entries[dir->nr - 1]->name) < 0))
423 dir->sorted = dir->nr;
427 * Clear and free all entries in dir, recursively.
429 static void clear_ref_dir(struct ref_dir *dir)
432 for (i = 0; i < dir->nr; i++)
433 free_ref_entry(dir->entries[i]);
435 dir->sorted = dir->nr = dir->alloc = 0;
440 * Create a struct ref_entry object for the specified dirname.
441 * dirname is the name of the directory with a trailing slash (e.g.,
442 * "refs/heads/") or "" for the top-level directory.
444 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
445 const char *dirname, size_t len,
448 struct ref_entry *direntry;
449 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
450 memcpy(direntry->name, dirname, len);
451 direntry->name[len] = '\0';
452 direntry->u.subdir.ref_cache = ref_cache;
453 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
457 static int ref_entry_cmp(const void *a, const void *b)
459 struct ref_entry *one = *(struct ref_entry **)a;
460 struct ref_entry *two = *(struct ref_entry **)b;
461 return strcmp(one->name, two->name);
464 static void sort_ref_dir(struct ref_dir *dir);
466 struct string_slice {
471 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
473 const struct string_slice *key = key_;
474 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
475 int cmp = strncmp(key->str, ent->name, key->len);
478 return '\0' - (unsigned char)ent->name[key->len];
482 * Return the index of the entry with the given refname from the
483 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
484 * no such entry is found. dir must already be complete.
486 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
488 struct ref_entry **r;
489 struct string_slice key;
491 if (refname == NULL || !dir->nr)
497 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
498 ref_entry_cmp_sslice);
503 return r - dir->entries;
507 * Search for a directory entry directly within dir (without
508 * recursing). Sort dir if necessary. subdirname must be a directory
509 * name (i.e., end in '/'). If mkdir is set, then create the
510 * directory if it is missing; otherwise, return NULL if the desired
511 * directory cannot be found. dir must already be complete.
513 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
514 const char *subdirname, size_t len,
517 int entry_index = search_ref_dir(dir, subdirname, len);
518 struct ref_entry *entry;
519 if (entry_index == -1) {
523 * Since dir is complete, the absence of a subdir
524 * means that the subdir really doesn't exist;
525 * therefore, create an empty record for it but mark
526 * the record complete.
528 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
529 add_entry_to_dir(dir, entry);
531 entry = dir->entries[entry_index];
533 return get_ref_dir(entry);
537 * If refname is a reference name, find the ref_dir within the dir
538 * tree that should hold refname. If refname is a directory name
539 * (i.e., ends in '/'), then return that ref_dir itself. dir must
540 * represent the top-level directory and must already be complete.
541 * Sort ref_dirs and recurse into subdirectories as necessary. If
542 * mkdir is set, then create any missing directories; otherwise,
543 * return NULL if the desired directory cannot be found.
545 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
546 const char *refname, int mkdir)
549 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
550 size_t dirnamelen = slash - refname + 1;
551 struct ref_dir *subdir;
552 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
564 * Find the value entry with the given name in dir, sorting ref_dirs
565 * and recursing into subdirectories as necessary. If the name is not
566 * found or it corresponds to a directory entry, return NULL.
568 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
571 struct ref_entry *entry;
572 dir = find_containing_dir(dir, refname, 0);
575 entry_index = search_ref_dir(dir, refname, strlen(refname));
576 if (entry_index == -1)
578 entry = dir->entries[entry_index];
579 return (entry->flag & REF_DIR) ? NULL : entry;
583 * Remove the entry with the given name from dir, recursing into
584 * subdirectories as necessary. If refname is the name of a directory
585 * (i.e., ends with '/'), then remove the directory and its contents.
586 * If the removal was successful, return the number of entries
587 * remaining in the directory entry that contained the deleted entry.
588 * If the name was not found, return -1. Please note that this
589 * function only deletes the entry from the cache; it does not delete
590 * it from the filesystem or ensure that other cache entries (which
591 * might be symbolic references to the removed entry) are updated.
592 * Nor does it remove any containing dir entries that might be made
593 * empty by the removal. dir must represent the top-level directory
594 * and must already be complete.
596 static int remove_entry(struct ref_dir *dir, const char *refname)
598 int refname_len = strlen(refname);
600 struct ref_entry *entry;
601 int is_dir = refname[refname_len - 1] == '/';
604 * refname represents a reference directory. Remove
605 * the trailing slash; otherwise we will get the
606 * directory *representing* refname rather than the
607 * one *containing* it.
609 char *dirname = xmemdupz(refname, refname_len - 1);
610 dir = find_containing_dir(dir, dirname, 0);
613 dir = find_containing_dir(dir, refname, 0);
617 entry_index = search_ref_dir(dir, refname, refname_len);
618 if (entry_index == -1)
620 entry = dir->entries[entry_index];
622 memmove(&dir->entries[entry_index],
623 &dir->entries[entry_index + 1],
624 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
627 if (dir->sorted > entry_index)
629 free_ref_entry(entry);
634 * Add a ref_entry to the ref_dir (unsorted), recursing into
635 * subdirectories as necessary. dir must represent the top-level
636 * directory. Return 0 on success.
638 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
640 dir = find_containing_dir(dir, ref->name, 1);
643 add_entry_to_dir(dir, ref);
648 * Emit a warning and return true iff ref1 and ref2 have the same name
649 * and the same sha1. Die if they have the same name but different
652 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
654 if (strcmp(ref1->name, ref2->name))
657 /* Duplicate name; make sure that they don't conflict: */
659 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
660 /* This is impossible by construction */
661 die("Reference directory conflict: %s", ref1->name);
663 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
664 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
666 warning("Duplicated ref: %s", ref1->name);
671 * Sort the entries in dir non-recursively (if they are not already
672 * sorted) and remove any duplicate entries.
674 static void sort_ref_dir(struct ref_dir *dir)
677 struct ref_entry *last = NULL;
680 * This check also prevents passing a zero-length array to qsort(),
681 * which is a problem on some platforms.
683 if (dir->sorted == dir->nr)
686 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
688 /* Remove any duplicates: */
689 for (i = 0, j = 0; j < dir->nr; j++) {
690 struct ref_entry *entry = dir->entries[j];
691 if (last && is_dup_ref(last, entry))
692 free_ref_entry(entry);
694 last = dir->entries[i++] = entry;
696 dir->sorted = dir->nr = i;
699 /* Include broken references in a do_for_each_ref*() iteration: */
700 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
703 * Return true iff the reference described by entry can be resolved to
704 * an object in the database. Emit a warning if the referred-to
705 * object does not exist.
707 static int ref_resolves_to_object(struct ref_entry *entry)
709 if (entry->flag & REF_ISBROKEN)
711 if (!has_sha1_file(entry->u.value.oid.hash)) {
712 error("%s does not point to a valid object!", entry->name);
719 * current_ref is a performance hack: when iterating over references
720 * using the for_each_ref*() functions, current_ref is set to the
721 * current reference's entry before calling the callback function. If
722 * the callback function calls peel_ref(), then peel_ref() first
723 * checks whether the reference to be peeled is the current reference
724 * (it usually is) and if so, returns that reference's peeled version
725 * if it is available. This avoids a refname lookup in a common case.
727 static struct ref_entry *current_ref;
729 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
731 struct ref_entry_cb {
740 * Handle one reference in a do_for_each_ref*()-style iteration,
741 * calling an each_ref_fn for each entry.
743 static int do_one_ref(struct ref_entry *entry, void *cb_data)
745 struct ref_entry_cb *data = cb_data;
746 struct ref_entry *old_current_ref;
749 if (!starts_with(entry->name, data->base))
752 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
753 !ref_resolves_to_object(entry))
756 /* Store the old value, in case this is a recursive call: */
757 old_current_ref = current_ref;
759 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
760 entry->flag, data->cb_data);
761 current_ref = old_current_ref;
766 * Call fn for each reference in dir that has index in the range
767 * offset <= index < dir->nr. Recurse into subdirectories that are in
768 * that index range, sorting them before iterating. This function
769 * does not sort dir itself; it should be sorted beforehand. fn is
770 * called for all references, including broken ones.
772 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
773 each_ref_entry_fn fn, void *cb_data)
776 assert(dir->sorted == dir->nr);
777 for (i = offset; i < dir->nr; i++) {
778 struct ref_entry *entry = dir->entries[i];
780 if (entry->flag & REF_DIR) {
781 struct ref_dir *subdir = get_ref_dir(entry);
782 sort_ref_dir(subdir);
783 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
785 retval = fn(entry, cb_data);
794 * Call fn for each reference in the union of dir1 and dir2, in order
795 * by refname. Recurse into subdirectories. If a value entry appears
796 * in both dir1 and dir2, then only process the version that is in
797 * dir2. The input dirs must already be sorted, but subdirs will be
798 * sorted as needed. fn is called for all references, including
801 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
802 struct ref_dir *dir2,
803 each_ref_entry_fn fn, void *cb_data)
808 assert(dir1->sorted == dir1->nr);
809 assert(dir2->sorted == dir2->nr);
811 struct ref_entry *e1, *e2;
813 if (i1 == dir1->nr) {
814 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
816 if (i2 == dir2->nr) {
817 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
819 e1 = dir1->entries[i1];
820 e2 = dir2->entries[i2];
821 cmp = strcmp(e1->name, e2->name);
823 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
824 /* Both are directories; descend them in parallel. */
825 struct ref_dir *subdir1 = get_ref_dir(e1);
826 struct ref_dir *subdir2 = get_ref_dir(e2);
827 sort_ref_dir(subdir1);
828 sort_ref_dir(subdir2);
829 retval = do_for_each_entry_in_dirs(
830 subdir1, subdir2, fn, cb_data);
833 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
834 /* Both are references; ignore the one from dir1. */
835 retval = fn(e2, cb_data);
839 die("conflict between reference and directory: %s",
851 if (e->flag & REF_DIR) {
852 struct ref_dir *subdir = get_ref_dir(e);
853 sort_ref_dir(subdir);
854 retval = do_for_each_entry_in_dir(
855 subdir, 0, fn, cb_data);
857 retval = fn(e, cb_data);
866 * Load all of the refs from the dir into our in-memory cache. The hard work
867 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
868 * through all of the sub-directories. We do not even need to care about
869 * sorting, as traversal order does not matter to us.
871 static void prime_ref_dir(struct ref_dir *dir)
874 for (i = 0; i < dir->nr; i++) {
875 struct ref_entry *entry = dir->entries[i];
876 if (entry->flag & REF_DIR)
877 prime_ref_dir(get_ref_dir(entry));
881 struct nonmatching_ref_data {
882 const struct string_list *skip;
883 const char *conflicting_refname;
886 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
888 struct nonmatching_ref_data *data = vdata;
890 if (data->skip && string_list_has_string(data->skip, entry->name))
893 data->conflicting_refname = entry->name;
898 * Return 0 if a reference named refname could be created without
899 * conflicting with the name of an existing reference in dir.
900 * See verify_refname_available for more information.
902 static int verify_refname_available_dir(const char *refname,
903 const struct string_list *extras,
904 const struct string_list *skip,
910 struct strbuf dirname = STRBUF_INIT;
914 * For the sake of comments in this function, suppose that
915 * refname is "refs/foo/bar".
920 strbuf_grow(&dirname, strlen(refname) + 1);
921 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
922 /* Expand dirname to the new prefix, not including the trailing slash: */
923 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
926 * We are still at a leading dir of the refname (e.g.,
927 * "refs/foo"; if there is a reference with that name,
928 * it is a conflict, *unless* it is in skip.
931 pos = search_ref_dir(dir, dirname.buf, dirname.len);
933 (!skip || !string_list_has_string(skip, dirname.buf))) {
935 * We found a reference whose name is
936 * a proper prefix of refname; e.g.,
937 * "refs/foo", and is not in skip.
939 strbuf_addf(err, "'%s' exists; cannot create '%s'",
940 dirname.buf, refname);
945 if (extras && string_list_has_string(extras, dirname.buf) &&
946 (!skip || !string_list_has_string(skip, dirname.buf))) {
947 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
948 refname, dirname.buf);
953 * Otherwise, we can try to continue our search with
954 * the next component. So try to look up the
955 * directory, e.g., "refs/foo/". If we come up empty,
956 * we know there is nothing under this whole prefix,
957 * but even in that case we still have to continue the
958 * search for conflicts with extras.
960 strbuf_addch(&dirname, '/');
962 pos = search_ref_dir(dir, dirname.buf, dirname.len);
965 * There was no directory "refs/foo/",
966 * so there is nothing under this
967 * whole prefix. So there is no need
968 * to continue looking for conflicting
969 * references. But we need to continue
970 * looking for conflicting extras.
974 dir = get_ref_dir(dir->entries[pos]);
980 * We are at the leaf of our refname (e.g., "refs/foo/bar").
981 * There is no point in searching for a reference with that
982 * name, because a refname isn't considered to conflict with
983 * itself. But we still need to check for references whose
984 * names are in the "refs/foo/bar/" namespace, because they
987 strbuf_addstr(&dirname, refname + dirname.len);
988 strbuf_addch(&dirname, '/');
991 pos = search_ref_dir(dir, dirname.buf, dirname.len);
995 * We found a directory named "$refname/"
996 * (e.g., "refs/foo/bar/"). It is a problem
997 * iff it contains any ref that is not in
1000 struct nonmatching_ref_data data;
1003 data.conflicting_refname = NULL;
1004 dir = get_ref_dir(dir->entries[pos]);
1006 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
1007 strbuf_addf(err, "'%s' exists; cannot create '%s'",
1008 data.conflicting_refname, refname);
1016 * Check for entries in extras that start with
1017 * "$refname/". We do that by looking for the place
1018 * where "$refname/" would be inserted in extras. If
1019 * there is an entry at that position that starts with
1020 * "$refname/" and is not in skip, then we have a
1023 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1024 pos < extras->nr; pos++) {
1025 const char *extra_refname = extras->items[pos].string;
1027 if (!starts_with(extra_refname, dirname.buf))
1030 if (!skip || !string_list_has_string(skip, extra_refname)) {
1031 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1032 refname, extra_refname);
1038 /* No conflicts were found */
1042 strbuf_release(&dirname);
1046 struct packed_ref_cache {
1047 struct ref_entry *root;
1050 * Count of references to the data structure in this instance,
1051 * including the pointer from ref_cache::packed if any. The
1052 * data will not be freed as long as the reference count is
1055 unsigned int referrers;
1058 * Iff the packed-refs file associated with this instance is
1059 * currently locked for writing, this points at the associated
1060 * lock (which is owned by somebody else). The referrer count
1061 * is also incremented when the file is locked and decremented
1062 * when it is unlocked.
1064 struct lock_file *lock;
1066 /* The metadata from when this packed-refs cache was read */
1067 struct stat_validity validity;
1071 * Future: need to be in "struct repository"
1072 * when doing a full libification.
1074 static struct ref_cache {
1075 struct ref_cache *next;
1076 struct ref_entry *loose;
1077 struct packed_ref_cache *packed;
1079 * The submodule name, or "" for the main repo. We allocate
1080 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1081 * is initialized correctly.
1084 } ref_cache, *submodule_ref_caches;
1086 /* Lock used for the main packed-refs file: */
1087 static struct lock_file packlock;
1090 * Increment the reference count of *packed_refs.
1092 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1094 packed_refs->referrers++;
1098 * Decrease the reference count of *packed_refs. If it goes to zero,
1099 * free *packed_refs and return true; otherwise return false.
1101 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1103 if (!--packed_refs->referrers) {
1104 free_ref_entry(packed_refs->root);
1105 stat_validity_clear(&packed_refs->validity);
1113 static void clear_packed_ref_cache(struct ref_cache *refs)
1116 struct packed_ref_cache *packed_refs = refs->packed;
1118 if (packed_refs->lock)
1119 die("internal error: packed-ref cache cleared while locked");
1120 refs->packed = NULL;
1121 release_packed_ref_cache(packed_refs);
1125 static void clear_loose_ref_cache(struct ref_cache *refs)
1128 free_ref_entry(refs->loose);
1133 static struct ref_cache *create_ref_cache(const char *submodule)
1136 struct ref_cache *refs;
1139 len = strlen(submodule) + 1;
1140 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1141 memcpy(refs->name, submodule, len);
1146 * Return a pointer to a ref_cache for the specified submodule. For
1147 * the main repository, use submodule==NULL. The returned structure
1148 * will be allocated and initialized but not necessarily populated; it
1149 * should not be freed.
1151 static struct ref_cache *get_ref_cache(const char *submodule)
1153 struct ref_cache *refs;
1155 if (!submodule || !*submodule)
1158 for (refs = submodule_ref_caches; refs; refs = refs->next)
1159 if (!strcmp(submodule, refs->name))
1162 refs = create_ref_cache(submodule);
1163 refs->next = submodule_ref_caches;
1164 submodule_ref_caches = refs;
1168 /* The length of a peeled reference line in packed-refs, including EOL: */
1169 #define PEELED_LINE_LENGTH 42
1172 * The packed-refs header line that we write out. Perhaps other
1173 * traits will be added later. The trailing space is required.
1175 static const char PACKED_REFS_HEADER[] =
1176 "# pack-refs with: peeled fully-peeled \n";
1179 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1180 * Return a pointer to the refname within the line (null-terminated),
1181 * or NULL if there was a problem.
1183 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1188 * 42: the answer to everything.
1190 * In this case, it happens to be the answer to
1191 * 40 (length of sha1 hex representation)
1192 * +1 (space in between hex and name)
1193 * +1 (newline at the end of the line)
1195 if (line->len <= 42)
1198 if (get_sha1_hex(line->buf, sha1) < 0)
1200 if (!isspace(line->buf[40]))
1203 ref = line->buf + 41;
1207 if (line->buf[line->len - 1] != '\n')
1209 line->buf[--line->len] = 0;
1215 * Read f, which is a packed-refs file, into dir.
1217 * A comment line of the form "# pack-refs with: " may contain zero or
1218 * more traits. We interpret the traits as follows:
1222 * Probably no references are peeled. But if the file contains a
1223 * peeled value for a reference, we will use it.
1227 * References under "refs/tags/", if they *can* be peeled, *are*
1228 * peeled in this file. References outside of "refs/tags/" are
1229 * probably not peeled even if they could have been, but if we find
1230 * a peeled value for such a reference we will use it.
1234 * All references in the file that can be peeled are peeled.
1235 * Inversely (and this is more important), any references in the
1236 * file for which no peeled value is recorded is not peelable. This
1237 * trait should typically be written alongside "peeled" for
1238 * compatibility with older clients, but we do not require it
1239 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1241 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1243 struct ref_entry *last = NULL;
1244 struct strbuf line = STRBUF_INIT;
1245 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1247 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1248 unsigned char sha1[20];
1249 const char *refname;
1252 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1253 if (strstr(traits, " fully-peeled "))
1254 peeled = PEELED_FULLY;
1255 else if (strstr(traits, " peeled "))
1256 peeled = PEELED_TAGS;
1257 /* perhaps other traits later as well */
1261 refname = parse_ref_line(&line, sha1);
1263 int flag = REF_ISPACKED;
1265 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1266 if (!refname_is_safe(refname))
1267 die("packed refname is dangerous: %s", refname);
1269 flag |= REF_BAD_NAME | REF_ISBROKEN;
1271 last = create_ref_entry(refname, sha1, flag, 0);
1272 if (peeled == PEELED_FULLY ||
1273 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1274 last->flag |= REF_KNOWS_PEELED;
1279 line.buf[0] == '^' &&
1280 line.len == PEELED_LINE_LENGTH &&
1281 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1282 !get_sha1_hex(line.buf + 1, sha1)) {
1283 hashcpy(last->u.value.peeled.hash, sha1);
1285 * Regardless of what the file header said,
1286 * we definitely know the value of *this*
1289 last->flag |= REF_KNOWS_PEELED;
1293 strbuf_release(&line);
1297 * Get the packed_ref_cache for the specified ref_cache, creating it
1300 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1302 char *packed_refs_file;
1305 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1307 packed_refs_file = git_pathdup("packed-refs");
1310 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1311 clear_packed_ref_cache(refs);
1313 if (!refs->packed) {
1316 refs->packed = xcalloc(1, sizeof(*refs->packed));
1317 acquire_packed_ref_cache(refs->packed);
1318 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1319 f = fopen(packed_refs_file, "r");
1321 stat_validity_update(&refs->packed->validity, fileno(f));
1322 read_packed_refs(f, get_ref_dir(refs->packed->root));
1326 free(packed_refs_file);
1327 return refs->packed;
1330 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1332 return get_ref_dir(packed_ref_cache->root);
1335 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1337 return get_packed_ref_dir(get_packed_ref_cache(refs));
1341 * Add a reference to the in-memory packed reference cache. This may
1342 * only be called while the packed-refs file is locked (see
1343 * lock_packed_refs()). To actually write the packed-refs file, call
1344 * commit_packed_refs().
1346 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1348 struct packed_ref_cache *packed_ref_cache =
1349 get_packed_ref_cache(&ref_cache);
1351 if (!packed_ref_cache->lock)
1352 die("internal error: packed refs not locked");
1353 add_ref(get_packed_ref_dir(packed_ref_cache),
1354 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1358 * Read the loose references from the namespace dirname into dir
1359 * (without recursing). dirname must end with '/'. dir must be the
1360 * directory entry corresponding to dirname.
1362 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1364 struct ref_cache *refs = dir->ref_cache;
1367 int dirnamelen = strlen(dirname);
1368 struct strbuf refname;
1369 struct strbuf path = STRBUF_INIT;
1370 size_t path_baselen;
1373 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1375 strbuf_git_path(&path, "%s", dirname);
1376 path_baselen = path.len;
1378 d = opendir(path.buf);
1380 strbuf_release(&path);
1384 strbuf_init(&refname, dirnamelen + 257);
1385 strbuf_add(&refname, dirname, dirnamelen);
1387 while ((de = readdir(d)) != NULL) {
1388 unsigned char sha1[20];
1392 if (de->d_name[0] == '.')
1394 if (ends_with(de->d_name, ".lock"))
1396 strbuf_addstr(&refname, de->d_name);
1397 strbuf_addstr(&path, de->d_name);
1398 if (stat(path.buf, &st) < 0) {
1399 ; /* silently ignore */
1400 } else if (S_ISDIR(st.st_mode)) {
1401 strbuf_addch(&refname, '/');
1402 add_entry_to_dir(dir,
1403 create_dir_entry(refs, refname.buf,
1411 read_ok = !resolve_gitlink_ref(refs->name,
1414 read_ok = !read_ref_full(refname.buf,
1415 RESOLVE_REF_READING,
1421 flag |= REF_ISBROKEN;
1422 } else if (is_null_sha1(sha1)) {
1424 * It is so astronomically unlikely
1425 * that NULL_SHA1 is the SHA-1 of an
1426 * actual object that we consider its
1427 * appearance in a loose reference
1428 * file to be repo corruption
1429 * (probably due to a software bug).
1431 flag |= REF_ISBROKEN;
1434 if (check_refname_format(refname.buf,
1435 REFNAME_ALLOW_ONELEVEL)) {
1436 if (!refname_is_safe(refname.buf))
1437 die("loose refname is dangerous: %s", refname.buf);
1439 flag |= REF_BAD_NAME | REF_ISBROKEN;
1441 add_entry_to_dir(dir,
1442 create_ref_entry(refname.buf, sha1, flag, 0));
1444 strbuf_setlen(&refname, dirnamelen);
1445 strbuf_setlen(&path, path_baselen);
1447 strbuf_release(&refname);
1448 strbuf_release(&path);
1452 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1456 * Mark the top-level directory complete because we
1457 * are about to read the only subdirectory that can
1460 refs->loose = create_dir_entry(refs, "", 0, 0);
1462 * Create an incomplete entry for "refs/":
1464 add_entry_to_dir(get_ref_dir(refs->loose),
1465 create_dir_entry(refs, "refs/", 5, 1));
1467 return get_ref_dir(refs->loose);
1470 /* We allow "recursive" symbolic refs. Only within reason, though */
1472 #define MAXREFLEN (1024)
1475 * Called by resolve_gitlink_ref_recursive() after it failed to read
1476 * from the loose refs in ref_cache refs. Find <refname> in the
1477 * packed-refs file for the submodule.
1479 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1480 const char *refname, unsigned char *sha1)
1482 struct ref_entry *ref;
1483 struct ref_dir *dir = get_packed_refs(refs);
1485 ref = find_ref(dir, refname);
1489 hashcpy(sha1, ref->u.value.oid.hash);
1493 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1494 const char *refname, unsigned char *sha1,
1498 char buffer[128], *p;
1501 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1504 ? git_pathdup_submodule(refs->name, "%s", refname)
1505 : git_pathdup("%s", refname);
1506 fd = open(path, O_RDONLY);
1509 return resolve_gitlink_packed_ref(refs, refname, sha1);
1511 len = read(fd, buffer, sizeof(buffer)-1);
1515 while (len && isspace(buffer[len-1]))
1519 /* Was it a detached head or an old-fashioned symlink? */
1520 if (!get_sha1_hex(buffer, sha1))
1524 if (strncmp(buffer, "ref:", 4))
1530 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1533 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1535 int len = strlen(path), retval;
1537 struct ref_cache *refs;
1539 while (len && path[len-1] == '/')
1543 submodule = xstrndup(path, len);
1544 refs = get_ref_cache(submodule);
1547 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1552 * Return the ref_entry for the given refname from the packed
1553 * references. If it does not exist, return NULL.
1555 static struct ref_entry *get_packed_ref(const char *refname)
1557 return find_ref(get_packed_refs(&ref_cache), refname);
1561 * A loose ref file doesn't exist; check for a packed ref. The
1562 * options are forwarded from resolve_safe_unsafe().
1564 static int resolve_missing_loose_ref(const char *refname,
1566 unsigned char *sha1,
1569 struct ref_entry *entry;
1572 * The loose reference file does not exist; check for a packed
1575 entry = get_packed_ref(refname);
1577 hashcpy(sha1, entry->u.value.oid.hash);
1579 *flags |= REF_ISPACKED;
1582 /* The reference is not a packed reference, either. */
1583 if (resolve_flags & RESOLVE_REF_READING) {
1592 /* This function needs to return a meaningful errno on failure */
1593 static const char *resolve_ref_1(const char *refname,
1595 unsigned char *sha1,
1597 struct strbuf *sb_refname,
1598 struct strbuf *sb_path,
1599 struct strbuf *sb_contents)
1601 int depth = MAXDEPTH;
1607 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1609 *flags |= REF_BAD_NAME;
1611 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1612 !refname_is_safe(refname)) {
1617 * dwim_ref() uses REF_ISBROKEN to distinguish between
1618 * missing refs and refs that were present but invalid,
1619 * to complain about the latter to stderr.
1621 * We don't know whether the ref exists, so don't set
1637 strbuf_reset(sb_path);
1638 strbuf_git_path(sb_path, "%s", refname);
1639 path = sb_path->buf;
1642 * We might have to loop back here to avoid a race
1643 * condition: first we lstat() the file, then we try
1644 * to read it as a link or as a file. But if somebody
1645 * changes the type of the file (file <-> directory
1646 * <-> symlink) between the lstat() and reading, then
1647 * we don't want to report that as an error but rather
1648 * try again starting with the lstat().
1651 if (lstat(path, &st) < 0) {
1652 if (errno != ENOENT)
1654 if (resolve_missing_loose_ref(refname, resolve_flags,
1660 *flags |= REF_ISBROKEN;
1665 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1666 if (S_ISLNK(st.st_mode)) {
1667 strbuf_reset(sb_contents);
1668 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1669 if (errno == ENOENT || errno == EINVAL)
1670 /* inconsistent with lstat; retry */
1675 if (starts_with(sb_contents->buf, "refs/") &&
1676 !check_refname_format(sb_contents->buf, 0)) {
1677 strbuf_swap(sb_refname, sb_contents);
1678 refname = sb_refname->buf;
1680 *flags |= REF_ISSYMREF;
1681 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1689 /* Is it a directory? */
1690 if (S_ISDIR(st.st_mode)) {
1696 * Anything else, just open it and try to use it as
1699 fd = open(path, O_RDONLY);
1701 if (errno == ENOENT)
1702 /* inconsistent with lstat; retry */
1707 strbuf_reset(sb_contents);
1708 if (strbuf_read(sb_contents, fd, 256) < 0) {
1709 int save_errno = errno;
1715 strbuf_rtrim(sb_contents);
1718 * Is it a symbolic ref?
1720 if (!starts_with(sb_contents->buf, "ref:")) {
1722 * Please note that FETCH_HEAD has a second
1723 * line containing other data.
1725 if (get_sha1_hex(sb_contents->buf, sha1) ||
1726 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1728 *flags |= REF_ISBROKEN;
1735 *flags |= REF_ISBROKEN;
1740 *flags |= REF_ISSYMREF;
1741 buf = sb_contents->buf + 4;
1742 while (isspace(*buf))
1744 strbuf_reset(sb_refname);
1745 strbuf_addstr(sb_refname, buf);
1746 refname = sb_refname->buf;
1747 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1751 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1753 *flags |= REF_ISBROKEN;
1755 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1756 !refname_is_safe(buf)) {
1765 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1766 unsigned char *sha1, int *flags)
1768 static struct strbuf sb_refname = STRBUF_INIT;
1769 struct strbuf sb_contents = STRBUF_INIT;
1770 struct strbuf sb_path = STRBUF_INIT;
1773 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1774 &sb_refname, &sb_path, &sb_contents);
1775 strbuf_release(&sb_path);
1776 strbuf_release(&sb_contents);
1780 char *resolve_refdup(const char *refname, int resolve_flags,
1781 unsigned char *sha1, int *flags)
1783 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1787 /* The argument to filter_refs */
1789 const char *pattern;
1794 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1796 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1801 int read_ref(const char *refname, unsigned char *sha1)
1803 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1806 int ref_exists(const char *refname)
1808 unsigned char sha1[20];
1809 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1812 static int filter_refs(const char *refname, const struct object_id *oid,
1813 int flags, void *data)
1815 struct ref_filter *filter = (struct ref_filter *)data;
1817 if (wildmatch(filter->pattern, refname, 0, NULL))
1819 return filter->fn(refname, oid, flags, filter->cb_data);
1823 /* object was peeled successfully: */
1827 * object cannot be peeled because the named object (or an
1828 * object referred to by a tag in the peel chain), does not
1833 /* object cannot be peeled because it is not a tag: */
1836 /* ref_entry contains no peeled value because it is a symref: */
1837 PEEL_IS_SYMREF = -3,
1840 * ref_entry cannot be peeled because it is broken (i.e., the
1841 * symbolic reference cannot even be resolved to an object
1848 * Peel the named object; i.e., if the object is a tag, resolve the
1849 * tag recursively until a non-tag is found. If successful, store the
1850 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1851 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1852 * and leave sha1 unchanged.
1854 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1856 struct object *o = lookup_unknown_object(name);
1858 if (o->type == OBJ_NONE) {
1859 int type = sha1_object_info(name, NULL);
1860 if (type < 0 || !object_as_type(o, type, 0))
1861 return PEEL_INVALID;
1864 if (o->type != OBJ_TAG)
1865 return PEEL_NON_TAG;
1867 o = deref_tag_noverify(o);
1869 return PEEL_INVALID;
1871 hashcpy(sha1, o->sha1);
1876 * Peel the entry (if possible) and return its new peel_status. If
1877 * repeel is true, re-peel the entry even if there is an old peeled
1878 * value that is already stored in it.
1880 * It is OK to call this function with a packed reference entry that
1881 * might be stale and might even refer to an object that has since
1882 * been garbage-collected. In such a case, if the entry has
1883 * REF_KNOWS_PEELED then leave the status unchanged and return
1884 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1886 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1888 enum peel_status status;
1890 if (entry->flag & REF_KNOWS_PEELED) {
1892 entry->flag &= ~REF_KNOWS_PEELED;
1893 oidclr(&entry->u.value.peeled);
1895 return is_null_oid(&entry->u.value.peeled) ?
1896 PEEL_NON_TAG : PEEL_PEELED;
1899 if (entry->flag & REF_ISBROKEN)
1901 if (entry->flag & REF_ISSYMREF)
1902 return PEEL_IS_SYMREF;
1904 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1905 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1906 entry->flag |= REF_KNOWS_PEELED;
1910 int peel_ref(const char *refname, unsigned char *sha1)
1913 unsigned char base[20];
1915 if (current_ref && (current_ref->name == refname
1916 || !strcmp(current_ref->name, refname))) {
1917 if (peel_entry(current_ref, 0))
1919 hashcpy(sha1, current_ref->u.value.peeled.hash);
1923 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1927 * If the reference is packed, read its ref_entry from the
1928 * cache in the hope that we already know its peeled value.
1929 * We only try this optimization on packed references because
1930 * (a) forcing the filling of the loose reference cache could
1931 * be expensive and (b) loose references anyway usually do not
1932 * have REF_KNOWS_PEELED.
1934 if (flag & REF_ISPACKED) {
1935 struct ref_entry *r = get_packed_ref(refname);
1937 if (peel_entry(r, 0))
1939 hashcpy(sha1, r->u.value.peeled.hash);
1944 return peel_object(base, sha1);
1947 struct warn_if_dangling_data {
1949 const char *refname;
1950 const struct string_list *refnames;
1951 const char *msg_fmt;
1954 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1955 int flags, void *cb_data)
1957 struct warn_if_dangling_data *d = cb_data;
1958 const char *resolves_to;
1959 struct object_id junk;
1961 if (!(flags & REF_ISSYMREF))
1964 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1967 ? strcmp(resolves_to, d->refname)
1968 : !string_list_has_string(d->refnames, resolves_to))) {
1972 fprintf(d->fp, d->msg_fmt, refname);
1977 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1979 struct warn_if_dangling_data data;
1982 data.refname = refname;
1983 data.refnames = NULL;
1984 data.msg_fmt = msg_fmt;
1985 for_each_rawref(warn_if_dangling_symref, &data);
1988 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1990 struct warn_if_dangling_data data;
1993 data.refname = NULL;
1994 data.refnames = refnames;
1995 data.msg_fmt = msg_fmt;
1996 for_each_rawref(warn_if_dangling_symref, &data);
2000 * Call fn for each reference in the specified ref_cache, omitting
2001 * references not in the containing_dir of base. fn is called for all
2002 * references, including broken ones. If fn ever returns a non-zero
2003 * value, stop the iteration and return that value; otherwise, return
2006 static int do_for_each_entry(struct ref_cache *refs, const char *base,
2007 each_ref_entry_fn fn, void *cb_data)
2009 struct packed_ref_cache *packed_ref_cache;
2010 struct ref_dir *loose_dir;
2011 struct ref_dir *packed_dir;
2015 * We must make sure that all loose refs are read before accessing the
2016 * packed-refs file; this avoids a race condition in which loose refs
2017 * are migrated to the packed-refs file by a simultaneous process, but
2018 * our in-memory view is from before the migration. get_packed_ref_cache()
2019 * takes care of making sure our view is up to date with what is on
2022 loose_dir = get_loose_refs(refs);
2023 if (base && *base) {
2024 loose_dir = find_containing_dir(loose_dir, base, 0);
2027 prime_ref_dir(loose_dir);
2029 packed_ref_cache = get_packed_ref_cache(refs);
2030 acquire_packed_ref_cache(packed_ref_cache);
2031 packed_dir = get_packed_ref_dir(packed_ref_cache);
2032 if (base && *base) {
2033 packed_dir = find_containing_dir(packed_dir, base, 0);
2036 if (packed_dir && loose_dir) {
2037 sort_ref_dir(packed_dir);
2038 sort_ref_dir(loose_dir);
2039 retval = do_for_each_entry_in_dirs(
2040 packed_dir, loose_dir, fn, cb_data);
2041 } else if (packed_dir) {
2042 sort_ref_dir(packed_dir);
2043 retval = do_for_each_entry_in_dir(
2044 packed_dir, 0, fn, cb_data);
2045 } else if (loose_dir) {
2046 sort_ref_dir(loose_dir);
2047 retval = do_for_each_entry_in_dir(
2048 loose_dir, 0, fn, cb_data);
2051 release_packed_ref_cache(packed_ref_cache);
2056 * Call fn for each reference in the specified ref_cache for which the
2057 * refname begins with base. If trim is non-zero, then trim that many
2058 * characters off the beginning of each refname before passing the
2059 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2060 * broken references in the iteration. If fn ever returns a non-zero
2061 * value, stop the iteration and return that value; otherwise, return
2064 static int do_for_each_ref(struct ref_cache *refs, const char *base,
2065 each_ref_fn fn, int trim, int flags, void *cb_data)
2067 struct ref_entry_cb data;
2072 data.cb_data = cb_data;
2074 if (ref_paranoia < 0)
2075 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2077 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2079 return do_for_each_entry(refs, base, do_one_ref, &data);
2082 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2084 struct object_id oid;
2088 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2089 return fn("HEAD", &oid, 0, cb_data);
2094 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2095 return fn("HEAD", &oid, flag, cb_data);
2100 int head_ref(each_ref_fn fn, void *cb_data)
2102 return do_head_ref(NULL, fn, cb_data);
2105 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2107 return do_head_ref(submodule, fn, cb_data);
2110 int for_each_ref(each_ref_fn fn, void *cb_data)
2112 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2115 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2117 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2120 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2122 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2125 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
2127 unsigned int flag = 0;
2130 flag = DO_FOR_EACH_INCLUDE_BROKEN;
2131 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
2134 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2135 each_ref_fn fn, void *cb_data)
2137 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2140 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2142 return for_each_ref_in("refs/tags/", fn, cb_data);
2145 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2147 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2150 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2152 return for_each_ref_in("refs/heads/", fn, cb_data);
2155 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2157 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2160 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2162 return for_each_ref_in("refs/remotes/", fn, cb_data);
2165 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2167 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2170 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2172 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2173 strlen(git_replace_ref_base), 0, cb_data);
2176 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2178 struct strbuf buf = STRBUF_INIT;
2180 struct object_id oid;
2183 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2184 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2185 ret = fn(buf.buf, &oid, flag, cb_data);
2186 strbuf_release(&buf);
2191 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2193 struct strbuf buf = STRBUF_INIT;
2195 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2196 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2197 strbuf_release(&buf);
2201 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2202 const char *prefix, void *cb_data)
2204 struct strbuf real_pattern = STRBUF_INIT;
2205 struct ref_filter filter;
2208 if (!prefix && !starts_with(pattern, "refs/"))
2209 strbuf_addstr(&real_pattern, "refs/");
2211 strbuf_addstr(&real_pattern, prefix);
2212 strbuf_addstr(&real_pattern, pattern);
2214 if (!has_glob_specials(pattern)) {
2215 /* Append implied '/' '*' if not present. */
2216 strbuf_complete(&real_pattern, '/');
2217 /* No need to check for '*', there is none. */
2218 strbuf_addch(&real_pattern, '*');
2221 filter.pattern = real_pattern.buf;
2223 filter.cb_data = cb_data;
2224 ret = for_each_ref(filter_refs, &filter);
2226 strbuf_release(&real_pattern);
2230 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2232 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2235 int for_each_rawref(each_ref_fn fn, void *cb_data)
2237 return do_for_each_ref(&ref_cache, "", fn, 0,
2238 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2241 const char *prettify_refname(const char *name)
2244 starts_with(name, "refs/heads/") ? 11 :
2245 starts_with(name, "refs/tags/") ? 10 :
2246 starts_with(name, "refs/remotes/") ? 13 :
2250 static const char *ref_rev_parse_rules[] = {
2255 "refs/remotes/%.*s",
2256 "refs/remotes/%.*s/HEAD",
2260 int refname_match(const char *abbrev_name, const char *full_name)
2263 const int abbrev_name_len = strlen(abbrev_name);
2265 for (p = ref_rev_parse_rules; *p; p++) {
2266 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2274 static void unlock_ref(struct ref_lock *lock)
2276 /* Do not free lock->lk -- atexit() still looks at them */
2278 rollback_lock_file(lock->lk);
2279 free(lock->ref_name);
2280 free(lock->orig_ref_name);
2285 * Verify that the reference locked by lock has the value old_sha1.
2286 * Fail if the reference doesn't exist and mustexist is set. Return 0
2287 * on success. On error, write an error message to err, set errno, and
2288 * return a negative value.
2290 static int verify_lock(struct ref_lock *lock,
2291 const unsigned char *old_sha1, int mustexist,
2296 if (read_ref_full(lock->ref_name,
2297 mustexist ? RESOLVE_REF_READING : 0,
2298 lock->old_oid.hash, NULL)) {
2299 int save_errno = errno;
2300 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2304 if (hashcmp(lock->old_oid.hash, old_sha1)) {
2305 strbuf_addf(err, "ref %s is at %s but expected %s",
2307 sha1_to_hex(lock->old_oid.hash),
2308 sha1_to_hex(old_sha1));
2315 static int remove_empty_directories(struct strbuf *path)
2318 * we want to create a file but there is a directory there;
2319 * if that is an empty directory (or a directory that contains
2320 * only empty directories), remove them.
2322 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
2326 * *string and *len will only be substituted, and *string returned (for
2327 * later free()ing) if the string passed in is a magic short-hand form
2330 static char *substitute_branch_name(const char **string, int *len)
2332 struct strbuf buf = STRBUF_INIT;
2333 int ret = interpret_branch_name(*string, *len, &buf);
2337 *string = strbuf_detach(&buf, &size);
2339 return (char *)*string;
2345 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2347 char *last_branch = substitute_branch_name(&str, &len);
2352 for (p = ref_rev_parse_rules; *p; p++) {
2353 char fullref[PATH_MAX];
2354 unsigned char sha1_from_ref[20];
2355 unsigned char *this_result;
2358 this_result = refs_found ? sha1_from_ref : sha1;
2359 mksnpath(fullref, sizeof(fullref), *p, len, str);
2360 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2361 this_result, &flag);
2365 if (!warn_ambiguous_refs)
2367 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2368 warning("ignoring dangling symref %s.", fullref);
2369 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2370 warning("ignoring broken ref %s.", fullref);
2377 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2379 char *last_branch = substitute_branch_name(&str, &len);
2384 for (p = ref_rev_parse_rules; *p; p++) {
2385 unsigned char hash[20];
2386 char path[PATH_MAX];
2387 const char *ref, *it;
2389 mksnpath(path, sizeof(path), *p, len, str);
2390 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2394 if (reflog_exists(path))
2396 else if (strcmp(ref, path) && reflog_exists(ref))
2400 if (!logs_found++) {
2402 hashcpy(sha1, hash);
2404 if (!warn_ambiguous_refs)
2412 * Locks a ref returning the lock on success and NULL on failure.
2413 * On failure errno is set to something meaningful.
2415 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2416 const unsigned char *old_sha1,
2417 const struct string_list *extras,
2418 const struct string_list *skip,
2419 unsigned int flags, int *type_p,
2422 struct strbuf ref_file = STRBUF_INIT;
2423 struct strbuf orig_ref_file = STRBUF_INIT;
2424 const char *orig_refname = refname;
2425 struct ref_lock *lock;
2428 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2429 int resolve_flags = 0;
2430 int attempts_remaining = 3;
2434 lock = xcalloc(1, sizeof(struct ref_lock));
2437 resolve_flags |= RESOLVE_REF_READING;
2438 if (flags & REF_DELETING) {
2439 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2440 if (flags & REF_NODEREF)
2441 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2444 refname = resolve_ref_unsafe(refname, resolve_flags,
2445 lock->old_oid.hash, &type);
2446 if (!refname && errno == EISDIR) {
2448 * we are trying to lock foo but we used to
2449 * have foo/bar which now does not exist;
2450 * it is normal for the empty directory 'foo'
2453 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
2454 if (remove_empty_directories(&orig_ref_file)) {
2456 if (!verify_refname_available_dir(orig_refname, extras, skip,
2457 get_loose_refs(&ref_cache), err))
2458 strbuf_addf(err, "there are still refs under '%s'",
2462 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2463 lock->old_oid.hash, &type);
2469 if (last_errno != ENOTDIR ||
2470 !verify_refname_available_dir(orig_refname, extras, skip,
2471 get_loose_refs(&ref_cache), err))
2472 strbuf_addf(err, "unable to resolve reference %s: %s",
2473 orig_refname, strerror(last_errno));
2478 * If the ref did not exist and we are creating it, make sure
2479 * there is no existing packed ref whose name begins with our
2480 * refname, nor a packed ref whose name is a proper prefix of
2483 if (is_null_oid(&lock->old_oid) &&
2484 verify_refname_available_dir(refname, extras, skip,
2485 get_packed_refs(&ref_cache), err)) {
2486 last_errno = ENOTDIR;
2490 lock->lk = xcalloc(1, sizeof(struct lock_file));
2493 if (flags & REF_NODEREF) {
2494 refname = orig_refname;
2495 lflags |= LOCK_NO_DEREF;
2497 lock->ref_name = xstrdup(refname);
2498 lock->orig_ref_name = xstrdup(orig_refname);
2499 strbuf_git_path(&ref_file, "%s", refname);
2502 switch (safe_create_leading_directories_const(ref_file.buf)) {
2504 break; /* success */
2506 if (--attempts_remaining > 0)
2511 strbuf_addf(err, "unable to create directory for %s",
2516 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
2518 if (errno == ENOENT && --attempts_remaining > 0)
2520 * Maybe somebody just deleted one of the
2521 * directories leading to ref_file. Try
2526 unable_to_lock_message(ref_file.buf, errno, err);
2530 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2541 strbuf_release(&ref_file);
2542 strbuf_release(&orig_ref_file);
2548 * Write an entry to the packed-refs file for the specified refname.
2549 * If peeled is non-NULL, write it as the entry's peeled value.
2551 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2552 unsigned char *peeled)
2554 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2556 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2560 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2562 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2564 enum peel_status peel_status = peel_entry(entry, 0);
2566 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2567 error("internal error: %s is not a valid packed reference!",
2569 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2570 peel_status == PEEL_PEELED ?
2571 entry->u.value.peeled.hash : NULL);
2576 * Lock the packed-refs file for writing. Flags is passed to
2577 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2578 * errno appropriately and return a nonzero value.
2580 static int lock_packed_refs(int flags)
2582 static int timeout_configured = 0;
2583 static int timeout_value = 1000;
2585 struct packed_ref_cache *packed_ref_cache;
2587 if (!timeout_configured) {
2588 git_config_get_int("core.packedrefstimeout", &timeout_value);
2589 timeout_configured = 1;
2592 if (hold_lock_file_for_update_timeout(
2593 &packlock, git_path("packed-refs"),
2594 flags, timeout_value) < 0)
2597 * Get the current packed-refs while holding the lock. If the
2598 * packed-refs file has been modified since we last read it,
2599 * this will automatically invalidate the cache and re-read
2600 * the packed-refs file.
2602 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2603 packed_ref_cache->lock = &packlock;
2604 /* Increment the reference count to prevent it from being freed: */
2605 acquire_packed_ref_cache(packed_ref_cache);
2610 * Write the current version of the packed refs cache from memory to
2611 * disk. The packed-refs file must already be locked for writing (see
2612 * lock_packed_refs()). Return zero on success. On errors, set errno
2613 * and return a nonzero value
2615 static int commit_packed_refs(void)
2617 struct packed_ref_cache *packed_ref_cache =
2618 get_packed_ref_cache(&ref_cache);
2623 if (!packed_ref_cache->lock)
2624 die("internal error: packed-refs not locked");
2626 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2628 die_errno("unable to fdopen packed-refs descriptor");
2630 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2631 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2632 0, write_packed_entry_fn, out);
2634 if (commit_lock_file(packed_ref_cache->lock)) {
2638 packed_ref_cache->lock = NULL;
2639 release_packed_ref_cache(packed_ref_cache);
2645 * Rollback the lockfile for the packed-refs file, and discard the
2646 * in-memory packed reference cache. (The packed-refs file will be
2647 * read anew if it is needed again after this function is called.)
2649 static void rollback_packed_refs(void)
2651 struct packed_ref_cache *packed_ref_cache =
2652 get_packed_ref_cache(&ref_cache);
2654 if (!packed_ref_cache->lock)
2655 die("internal error: packed-refs not locked");
2656 rollback_lock_file(packed_ref_cache->lock);
2657 packed_ref_cache->lock = NULL;
2658 release_packed_ref_cache(packed_ref_cache);
2659 clear_packed_ref_cache(&ref_cache);
2662 struct ref_to_prune {
2663 struct ref_to_prune *next;
2664 unsigned char sha1[20];
2665 char name[FLEX_ARRAY];
2668 struct pack_refs_cb_data {
2670 struct ref_dir *packed_refs;
2671 struct ref_to_prune *ref_to_prune;
2674 static int is_per_worktree_ref(const char *refname);
2677 * An each_ref_entry_fn that is run over loose references only. If
2678 * the loose reference can be packed, add an entry in the packed ref
2679 * cache. If the reference should be pruned, also add it to
2680 * ref_to_prune in the pack_refs_cb_data.
2682 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2684 struct pack_refs_cb_data *cb = cb_data;
2685 enum peel_status peel_status;
2686 struct ref_entry *packed_entry;
2687 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2689 /* Do not pack per-worktree refs: */
2690 if (is_per_worktree_ref(entry->name))
2693 /* ALWAYS pack tags */
2694 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2697 /* Do not pack symbolic or broken refs: */
2698 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2701 /* Add a packed ref cache entry equivalent to the loose entry. */
2702 peel_status = peel_entry(entry, 1);
2703 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2704 die("internal error peeling reference %s (%s)",
2705 entry->name, oid_to_hex(&entry->u.value.oid));
2706 packed_entry = find_ref(cb->packed_refs, entry->name);
2708 /* Overwrite existing packed entry with info from loose entry */
2709 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2710 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2712 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2713 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2714 add_ref(cb->packed_refs, packed_entry);
2716 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2718 /* Schedule the loose reference for pruning if requested. */
2719 if ((cb->flags & PACK_REFS_PRUNE)) {
2720 int namelen = strlen(entry->name) + 1;
2721 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2722 hashcpy(n->sha1, entry->u.value.oid.hash);
2723 memcpy(n->name, entry->name, namelen); /* includes NUL */
2724 n->next = cb->ref_to_prune;
2725 cb->ref_to_prune = n;
2731 * Remove empty parents, but spare refs/ and immediate subdirs.
2732 * Note: munges *name.
2734 static void try_remove_empty_parents(char *name)
2739 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2740 while (*p && *p != '/')
2742 /* tolerate duplicate slashes; see check_refname_format() */
2746 for (q = p; *q; q++)
2749 while (q > p && *q != '/')
2751 while (q > p && *(q-1) == '/')
2756 if (rmdir(git_path("%s", name)))
2761 /* make sure nobody touched the ref, and unlink */
2762 static void prune_ref(struct ref_to_prune *r)
2764 struct ref_transaction *transaction;
2765 struct strbuf err = STRBUF_INIT;
2767 if (check_refname_format(r->name, 0))
2770 transaction = ref_transaction_begin(&err);
2772 ref_transaction_delete(transaction, r->name, r->sha1,
2773 REF_ISPRUNING, NULL, &err) ||
2774 ref_transaction_commit(transaction, &err)) {
2775 ref_transaction_free(transaction);
2776 error("%s", err.buf);
2777 strbuf_release(&err);
2780 ref_transaction_free(transaction);
2781 strbuf_release(&err);
2782 try_remove_empty_parents(r->name);
2785 static void prune_refs(struct ref_to_prune *r)
2793 int pack_refs(unsigned int flags)
2795 struct pack_refs_cb_data cbdata;
2797 memset(&cbdata, 0, sizeof(cbdata));
2798 cbdata.flags = flags;
2800 lock_packed_refs(LOCK_DIE_ON_ERROR);
2801 cbdata.packed_refs = get_packed_refs(&ref_cache);
2803 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2804 pack_if_possible_fn, &cbdata);
2806 if (commit_packed_refs())
2807 die_errno("unable to overwrite old ref-pack file");
2809 prune_refs(cbdata.ref_to_prune);
2814 * Rewrite the packed-refs file, omitting any refs listed in
2815 * 'refnames'. On error, leave packed-refs unchanged, write an error
2816 * message to 'err', and return a nonzero value.
2818 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2820 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2822 struct ref_dir *packed;
2823 struct string_list_item *refname;
2824 int ret, needs_repacking = 0, removed = 0;
2828 /* Look for a packed ref */
2829 for_each_string_list_item(refname, refnames) {
2830 if (get_packed_ref(refname->string)) {
2831 needs_repacking = 1;
2836 /* Avoid locking if we have nothing to do */
2837 if (!needs_repacking)
2838 return 0; /* no refname exists in packed refs */
2840 if (lock_packed_refs(0)) {
2841 unable_to_lock_message(git_path("packed-refs"), errno, err);
2844 packed = get_packed_refs(&ref_cache);
2846 /* Remove refnames from the cache */
2847 for_each_string_list_item(refname, refnames)
2848 if (remove_entry(packed, refname->string) != -1)
2852 * All packed entries disappeared while we were
2853 * acquiring the lock.
2855 rollback_packed_refs();
2859 /* Write what remains */
2860 ret = commit_packed_refs();
2862 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2867 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2871 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2873 * loose. The loose file name is the same as the
2874 * lockfile name, minus ".lock":
2876 char *loose_filename = get_locked_file_path(lock->lk);
2877 int res = unlink_or_msg(loose_filename, err);
2878 free(loose_filename);
2885 static int is_per_worktree_ref(const char *refname)
2887 return !strcmp(refname, "HEAD") ||
2888 starts_with(refname, "refs/bisect/");
2891 static int is_pseudoref_syntax(const char *refname)
2895 for (c = refname; *c; c++) {
2896 if (!isupper(*c) && *c != '-' && *c != '_')
2903 enum ref_type ref_type(const char *refname)
2905 if (is_per_worktree_ref(refname))
2906 return REF_TYPE_PER_WORKTREE;
2907 if (is_pseudoref_syntax(refname))
2908 return REF_TYPE_PSEUDOREF;
2909 return REF_TYPE_NORMAL;
2912 static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
2913 const unsigned char *old_sha1, struct strbuf *err)
2915 const char *filename;
2917 static struct lock_file lock;
2918 struct strbuf buf = STRBUF_INIT;
2921 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
2923 filename = git_path("%s", pseudoref);
2924 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
2926 strbuf_addf(err, "Could not open '%s' for writing: %s",
2927 filename, strerror(errno));
2932 unsigned char actual_old_sha1[20];
2934 if (read_ref(pseudoref, actual_old_sha1))
2935 die("could not read ref '%s'", pseudoref);
2936 if (hashcmp(actual_old_sha1, old_sha1)) {
2937 strbuf_addf(err, "Unexpected sha1 when writing %s", pseudoref);
2938 rollback_lock_file(&lock);
2943 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
2944 strbuf_addf(err, "Could not write to '%s'", filename);
2945 rollback_lock_file(&lock);
2949 commit_lock_file(&lock);
2952 strbuf_release(&buf);
2956 static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
2958 static struct lock_file lock;
2959 const char *filename;
2961 filename = git_path("%s", pseudoref);
2963 if (old_sha1 && !is_null_sha1(old_sha1)) {
2965 unsigned char actual_old_sha1[20];
2967 fd = hold_lock_file_for_update(&lock, filename,
2970 die_errno(_("Could not open '%s' for writing"), filename);
2971 if (read_ref(pseudoref, actual_old_sha1))
2972 die("could not read ref '%s'", pseudoref);
2973 if (hashcmp(actual_old_sha1, old_sha1)) {
2974 warning("Unexpected sha1 when deleting %s", pseudoref);
2975 rollback_lock_file(&lock);
2980 rollback_lock_file(&lock);
2988 int delete_ref(const char *refname, const unsigned char *old_sha1,
2991 struct ref_transaction *transaction;
2992 struct strbuf err = STRBUF_INIT;
2994 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
2995 return delete_pseudoref(refname, old_sha1);
2997 transaction = ref_transaction_begin(&err);
2999 ref_transaction_delete(transaction, refname, old_sha1,
3000 flags, NULL, &err) ||
3001 ref_transaction_commit(transaction, &err)) {
3002 error("%s", err.buf);
3003 ref_transaction_free(transaction);
3004 strbuf_release(&err);
3007 ref_transaction_free(transaction);
3008 strbuf_release(&err);
3012 int delete_refs(struct string_list *refnames)
3014 struct strbuf err = STRBUF_INIT;
3020 result = repack_without_refs(refnames, &err);
3023 * If we failed to rewrite the packed-refs file, then
3024 * it is unsafe to try to remove loose refs, because
3025 * doing so might expose an obsolete packed value for
3026 * a reference that might even point at an object that
3027 * has been garbage collected.
3029 if (refnames->nr == 1)
3030 error(_("could not delete reference %s: %s"),
3031 refnames->items[0].string, err.buf);
3033 error(_("could not delete references: %s"), err.buf);
3038 for (i = 0; i < refnames->nr; i++) {
3039 const char *refname = refnames->items[i].string;
3041 if (delete_ref(refname, NULL, 0))
3042 result |= error(_("could not remove reference %s"), refname);
3046 strbuf_release(&err);
3051 * People using contrib's git-new-workdir have .git/logs/refs ->
3052 * /some/other/path/.git/logs/refs, and that may live on another device.
3054 * IOW, to avoid cross device rename errors, the temporary renamed log must
3055 * live into logs/refs.
3057 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
3059 static int rename_tmp_log(const char *newrefname)
3061 int attempts_remaining = 4;
3062 struct strbuf path = STRBUF_INIT;
3066 strbuf_reset(&path);
3067 strbuf_git_path(&path, "logs/%s", newrefname);
3068 switch (safe_create_leading_directories_const(path.buf)) {
3070 break; /* success */
3072 if (--attempts_remaining > 0)
3076 error("unable to create directory for %s", newrefname);
3080 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
3081 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
3083 * rename(a, b) when b is an existing
3084 * directory ought to result in ISDIR, but
3085 * Solaris 5.8 gives ENOTDIR. Sheesh.
3087 if (remove_empty_directories(&path)) {
3088 error("Directory not empty: logs/%s", newrefname);
3092 } else if (errno == ENOENT && --attempts_remaining > 0) {
3094 * Maybe another process just deleted one of
3095 * the directories in the path to newrefname.
3096 * Try again from the beginning.
3100 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
3101 newrefname, strerror(errno));
3107 strbuf_release(&path);
3112 * Return 0 if a reference named refname could be created without
3113 * conflicting with the name of an existing reference. Otherwise,
3114 * return a negative value and write an explanation to err. If extras
3115 * is non-NULL, it is a list of additional refnames with which refname
3116 * is not allowed to conflict. If skip is non-NULL, ignore potential
3117 * conflicts with refs in skip (e.g., because they are scheduled for
3118 * deletion in the same operation). Behavior is undefined if the same
3119 * name is listed in both extras and skip.
3121 * Two reference names conflict if one of them exactly matches the
3122 * leading components of the other; e.g., "foo/bar" conflicts with
3123 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
3126 * extras and skip must be sorted.
3128 static int verify_refname_available(const char *newname,
3129 struct string_list *extras,
3130 struct string_list *skip,
3133 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
3134 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
3136 if (verify_refname_available_dir(newname, extras, skip,
3137 packed_refs, err) ||
3138 verify_refname_available_dir(newname, extras, skip,
3145 static int rename_ref_available(const char *oldname, const char *newname)
3147 struct string_list skip = STRING_LIST_INIT_NODUP;
3148 struct strbuf err = STRBUF_INIT;
3151 string_list_insert(&skip, oldname);
3152 ret = !verify_refname_available(newname, NULL, &skip, &err);
3154 error("%s", err.buf);
3156 string_list_clear(&skip, 0);
3157 strbuf_release(&err);
3161 static int write_ref_to_lockfile(struct ref_lock *lock,
3162 const unsigned char *sha1, struct strbuf *err);
3163 static int commit_ref_update(struct ref_lock *lock,
3164 const unsigned char *sha1, const char *logmsg,
3165 int flags, struct strbuf *err);
3167 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
3169 unsigned char sha1[20], orig_sha1[20];
3170 int flag = 0, logmoved = 0;
3171 struct ref_lock *lock;
3172 struct stat loginfo;
3173 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
3174 const char *symref = NULL;
3175 struct strbuf err = STRBUF_INIT;
3177 if (log && S_ISLNK(loginfo.st_mode))
3178 return error("reflog for %s is a symlink", oldrefname);
3180 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
3182 if (flag & REF_ISSYMREF)
3183 return error("refname %s is a symbolic ref, renaming it is not supported",
3186 return error("refname %s not found", oldrefname);
3188 if (!rename_ref_available(oldrefname, newrefname))
3191 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3192 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3193 oldrefname, strerror(errno));
3195 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3196 error("unable to delete old %s", oldrefname);
3200 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3201 delete_ref(newrefname, sha1, REF_NODEREF)) {
3202 if (errno==EISDIR) {
3203 struct strbuf path = STRBUF_INIT;
3206 strbuf_git_path(&path, "%s", newrefname);
3207 result = remove_empty_directories(&path);
3208 strbuf_release(&path);
3211 error("Directory not empty: %s", newrefname);
3215 error("unable to delete existing %s", newrefname);
3220 if (log && rename_tmp_log(newrefname))
3225 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3227 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3228 strbuf_release(&err);
3231 hashcpy(lock->old_oid.hash, orig_sha1);
3233 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3234 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
3235 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
3236 strbuf_release(&err);
3243 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3245 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3246 strbuf_release(&err);
3250 flag = log_all_ref_updates;
3251 log_all_ref_updates = 0;
3252 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3253 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
3254 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
3255 strbuf_release(&err);
3257 log_all_ref_updates = flag;
3260 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3261 error("unable to restore logfile %s from %s: %s",
3262 oldrefname, newrefname, strerror(errno));
3263 if (!logmoved && log &&
3264 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3265 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3266 oldrefname, strerror(errno));
3271 static int close_ref(struct ref_lock *lock)
3273 if (close_lock_file(lock->lk))
3278 static int commit_ref(struct ref_lock *lock)
3280 if (commit_lock_file(lock->lk))
3286 * copy the reflog message msg to buf, which has been allocated sufficiently
3287 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3288 * because reflog file is one line per entry.
3290 static int copy_reflog_msg(char *buf, const char *msg)
3297 while ((c = *msg++)) {
3298 if (wasspace && isspace(c))
3300 wasspace = isspace(c);
3305 while (buf < cp && isspace(cp[-1]))
3311 static int should_autocreate_reflog(const char *refname)
3313 if (!log_all_ref_updates)
3315 return starts_with(refname, "refs/heads/") ||
3316 starts_with(refname, "refs/remotes/") ||
3317 starts_with(refname, "refs/notes/") ||
3318 !strcmp(refname, "HEAD");
3322 * Create a reflog for a ref. If force_create = 0, the reflog will
3323 * only be created for certain refs (those for which
3324 * should_autocreate_reflog returns non-zero. Otherwise, create it
3325 * regardless of the ref name. Fill in *err and return -1 on failure.
3327 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
3329 int logfd, oflags = O_APPEND | O_WRONLY;
3331 strbuf_git_path(logfile, "logs/%s", refname);
3332 if (force_create || should_autocreate_reflog(refname)) {
3333 if (safe_create_leading_directories(logfile->buf) < 0) {
3334 strbuf_addf(err, "unable to create directory for %s: "
3335 "%s", logfile->buf, strerror(errno));
3341 logfd = open(logfile->buf, oflags, 0666);
3343 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3346 if (errno == EISDIR) {
3347 if (remove_empty_directories(logfile)) {
3348 strbuf_addf(err, "There are still logs under "
3349 "'%s'", logfile->buf);
3352 logfd = open(logfile->buf, oflags, 0666);
3356 strbuf_addf(err, "unable to append to %s: %s",
3357 logfile->buf, strerror(errno));
3362 adjust_shared_perm(logfile->buf);
3368 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
3371 struct strbuf sb = STRBUF_INIT;
3373 ret = log_ref_setup(refname, &sb, err, force_create);
3374 strbuf_release(&sb);
3378 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3379 const unsigned char *new_sha1,
3380 const char *committer, const char *msg)
3382 int msglen, written;
3383 unsigned maxlen, len;
3386 msglen = msg ? strlen(msg) : 0;
3387 maxlen = strlen(committer) + msglen + 100;
3388 logrec = xmalloc(maxlen);
3389 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
3390 sha1_to_hex(old_sha1),
3391 sha1_to_hex(new_sha1),
3394 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
3396 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3404 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3405 const unsigned char *new_sha1, const char *msg,
3406 struct strbuf *logfile, int flags,
3409 int logfd, result, oflags = O_APPEND | O_WRONLY;
3411 if (log_all_ref_updates < 0)
3412 log_all_ref_updates = !is_bare_repository();
3414 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
3419 logfd = open(logfile->buf, oflags);
3422 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3423 git_committer_info(0), msg);
3425 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3431 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3438 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3439 const unsigned char *new_sha1, const char *msg,
3440 int flags, struct strbuf *err)
3442 struct strbuf sb = STRBUF_INIT;
3443 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
3445 strbuf_release(&sb);
3449 int is_branch(const char *refname)
3451 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3455 * Write sha1 into the open lockfile, then close the lockfile. On
3456 * errors, rollback the lockfile, fill in *err and
3459 static int write_ref_to_lockfile(struct ref_lock *lock,
3460 const unsigned char *sha1, struct strbuf *err)
3462 static char term = '\n';
3466 o = parse_object(sha1);
3469 "Trying to write ref %s with nonexistent object %s",
3470 lock->ref_name, sha1_to_hex(sha1));
3474 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3476 "Trying to write non-commit object %s to branch %s",
3477 sha1_to_hex(sha1), lock->ref_name);
3481 fd = get_lock_file_fd(lock->lk);
3482 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
3483 write_in_full(fd, &term, 1) != 1 ||
3484 close_ref(lock) < 0) {
3486 "Couldn't write %s", get_lock_file_path(lock->lk));
3494 * Commit a change to a loose reference that has already been written
3495 * to the loose reference lockfile. Also update the reflogs if
3496 * necessary, using the specified lockmsg (which can be NULL).
3498 static int commit_ref_update(struct ref_lock *lock,
3499 const unsigned char *sha1, const char *logmsg,
3500 int flags, struct strbuf *err)
3502 clear_loose_ref_cache(&ref_cache);
3503 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
3504 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3505 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
3506 char *old_msg = strbuf_detach(err, NULL);
3507 strbuf_addf(err, "Cannot update the ref '%s': %s",
3508 lock->ref_name, old_msg);
3513 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3515 * Special hack: If a branch is updated directly and HEAD
3516 * points to it (may happen on the remote side of a push
3517 * for example) then logically the HEAD reflog should be
3519 * A generic solution implies reverse symref information,
3520 * but finding all symrefs pointing to the given branch
3521 * would be rather costly for this rare event (the direct
3522 * update of a branch) to be worth it. So let's cheat and
3523 * check with HEAD only which should cover 99% of all usage
3524 * scenarios (even 100% of the default ones).
3526 unsigned char head_sha1[20];
3528 const char *head_ref;
3529 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3530 head_sha1, &head_flag);
3531 if (head_ref && (head_flag & REF_ISSYMREF) &&
3532 !strcmp(head_ref, lock->ref_name)) {
3533 struct strbuf log_err = STRBUF_INIT;
3534 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
3535 logmsg, 0, &log_err)) {
3536 error("%s", log_err.buf);
3537 strbuf_release(&log_err);
3541 if (commit_ref(lock)) {
3542 error("Couldn't set %s", lock->ref_name);
3551 int create_symref(const char *ref_target, const char *refs_heads_master,
3554 char *lockpath = NULL;
3556 int fd, len, written;
3557 char *git_HEAD = git_pathdup("%s", ref_target);
3558 unsigned char old_sha1[20], new_sha1[20];
3559 struct strbuf err = STRBUF_INIT;
3561 if (logmsg && read_ref(ref_target, old_sha1))
3564 if (safe_create_leading_directories(git_HEAD) < 0)
3565 return error("unable to create directory for %s", git_HEAD);
3567 #ifndef NO_SYMLINK_HEAD
3568 if (prefer_symlink_refs) {
3570 if (!symlink(refs_heads_master, git_HEAD))
3572 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3576 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3577 if (sizeof(ref) <= len) {
3578 error("refname too long: %s", refs_heads_master);
3579 goto error_free_return;
3581 lockpath = mkpathdup("%s.lock", git_HEAD);
3582 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3584 error("Unable to open %s for writing", lockpath);
3585 goto error_free_return;
3587 written = write_in_full(fd, ref, len);
3588 if (close(fd) != 0 || written != len) {
3589 error("Unable to write to %s", lockpath);
3590 goto error_unlink_return;
3592 if (rename(lockpath, git_HEAD) < 0) {
3593 error("Unable to create %s", git_HEAD);
3594 goto error_unlink_return;
3596 if (adjust_shared_perm(git_HEAD)) {
3597 error("Unable to fix permissions on %s", lockpath);
3598 error_unlink_return:
3599 unlink_or_warn(lockpath);
3607 #ifndef NO_SYMLINK_HEAD
3610 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
3611 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
3612 error("%s", err.buf);
3613 strbuf_release(&err);
3620 struct read_ref_at_cb {
3621 const char *refname;
3622 unsigned long at_time;
3625 unsigned char *sha1;
3628 unsigned char osha1[20];
3629 unsigned char nsha1[20];
3633 unsigned long *cutoff_time;
3638 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3639 const char *email, unsigned long timestamp, int tz,
3640 const char *message, void *cb_data)
3642 struct read_ref_at_cb *cb = cb_data;
3646 cb->date = timestamp;
3648 if (timestamp <= cb->at_time || cb->cnt == 0) {
3650 *cb->msg = xstrdup(message);
3651 if (cb->cutoff_time)
3652 *cb->cutoff_time = timestamp;
3654 *cb->cutoff_tz = tz;
3656 *cb->cutoff_cnt = cb->reccnt - 1;
3658 * we have not yet updated cb->[n|o]sha1 so they still
3659 * hold the values for the previous record.
3661 if (!is_null_sha1(cb->osha1)) {
3662 hashcpy(cb->sha1, nsha1);
3663 if (hashcmp(cb->osha1, nsha1))
3664 warning("Log for ref %s has gap after %s.",
3665 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
3667 else if (cb->date == cb->at_time)
3668 hashcpy(cb->sha1, nsha1);
3669 else if (hashcmp(nsha1, cb->sha1))
3670 warning("Log for ref %s unexpectedly ended on %s.",
3671 cb->refname, show_date(cb->date, cb->tz,
3672 DATE_MODE(RFC2822)));
3673 hashcpy(cb->osha1, osha1);
3674 hashcpy(cb->nsha1, nsha1);
3678 hashcpy(cb->osha1, osha1);
3679 hashcpy(cb->nsha1, nsha1);
3685 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3686 const char *email, unsigned long timestamp,
3687 int tz, const char *message, void *cb_data)
3689 struct read_ref_at_cb *cb = cb_data;
3692 *cb->msg = xstrdup(message);
3693 if (cb->cutoff_time)
3694 *cb->cutoff_time = timestamp;
3696 *cb->cutoff_tz = tz;
3698 *cb->cutoff_cnt = cb->reccnt;
3699 hashcpy(cb->sha1, osha1);
3700 if (is_null_sha1(cb->sha1))
3701 hashcpy(cb->sha1, nsha1);
3702 /* We just want the first entry */
3706 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3707 unsigned char *sha1, char **msg,
3708 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3710 struct read_ref_at_cb cb;
3712 memset(&cb, 0, sizeof(cb));
3713 cb.refname = refname;
3714 cb.at_time = at_time;
3717 cb.cutoff_time = cutoff_time;
3718 cb.cutoff_tz = cutoff_tz;
3719 cb.cutoff_cnt = cutoff_cnt;
3722 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3725 if (flags & GET_SHA1_QUIETLY)
3728 die("Log for %s is empty.", refname);
3733 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3738 int reflog_exists(const char *refname)
3742 return !lstat(git_path("logs/%s", refname), &st) &&
3743 S_ISREG(st.st_mode);
3746 int delete_reflog(const char *refname)
3748 return remove_path(git_path("logs/%s", refname));
3751 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3753 unsigned char osha1[20], nsha1[20];
3754 char *email_end, *message;
3755 unsigned long timestamp;
3758 /* old SP new SP name <email> SP time TAB msg LF */
3759 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3760 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3761 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3762 !(email_end = strchr(sb->buf + 82, '>')) ||
3763 email_end[1] != ' ' ||
3764 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3765 !message || message[0] != ' ' ||
3766 (message[1] != '+' && message[1] != '-') ||
3767 !isdigit(message[2]) || !isdigit(message[3]) ||
3768 !isdigit(message[4]) || !isdigit(message[5]))
3769 return 0; /* corrupt? */
3770 email_end[1] = '\0';
3771 tz = strtol(message + 1, NULL, 10);
3772 if (message[6] != '\t')
3776 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3779 static char *find_beginning_of_line(char *bob, char *scan)
3781 while (bob < scan && *(--scan) != '\n')
3782 ; /* keep scanning backwards */
3784 * Return either beginning of the buffer, or LF at the end of
3785 * the previous line.
3790 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3792 struct strbuf sb = STRBUF_INIT;
3795 int ret = 0, at_tail = 1;
3797 logfp = fopen(git_path("logs/%s", refname), "r");
3801 /* Jump to the end */
3802 if (fseek(logfp, 0, SEEK_END) < 0)
3803 return error("cannot seek back reflog for %s: %s",
3804 refname, strerror(errno));
3806 while (!ret && 0 < pos) {
3812 /* Fill next block from the end */
3813 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3814 if (fseek(logfp, pos - cnt, SEEK_SET))
3815 return error("cannot seek back reflog for %s: %s",
3816 refname, strerror(errno));
3817 nread = fread(buf, cnt, 1, logfp);
3819 return error("cannot read %d bytes from reflog for %s: %s",
3820 cnt, refname, strerror(errno));
3823 scanp = endp = buf + cnt;
3824 if (at_tail && scanp[-1] == '\n')
3825 /* Looking at the final LF at the end of the file */
3829 while (buf < scanp) {
3831 * terminating LF of the previous line, or the beginning
3836 bp = find_beginning_of_line(buf, scanp);
3840 * The newline is the end of the previous line,
3841 * so we know we have complete line starting
3842 * at (bp + 1). Prefix it onto any prior data
3843 * we collected for the line and process it.
3845 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3848 ret = show_one_reflog_ent(&sb, fn, cb_data);
3854 * We are at the start of the buffer, and the
3855 * start of the file; there is no previous
3856 * line, and we have everything for this one.
3857 * Process it, and we can end the loop.
3859 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3860 ret = show_one_reflog_ent(&sb, fn, cb_data);
3867 * We are at the start of the buffer, and there
3868 * is more file to read backwards. Which means
3869 * we are in the middle of a line. Note that we
3870 * may get here even if *bp was a newline; that
3871 * just means we are at the exact end of the
3872 * previous line, rather than some spot in the
3875 * Save away what we have to be combined with
3876 * the data from the next read.
3878 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3885 die("BUG: reverse reflog parser had leftover data");
3888 strbuf_release(&sb);
3892 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3895 struct strbuf sb = STRBUF_INIT;
3898 logfp = fopen(git_path("logs/%s", refname), "r");
3902 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3903 ret = show_one_reflog_ent(&sb, fn, cb_data);
3905 strbuf_release(&sb);
3909 * Call fn for each reflog in the namespace indicated by name. name
3910 * must be empty or end with '/'. Name will be used as a scratch
3911 * space, but its contents will be restored before return.
3913 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3915 DIR *d = opendir(git_path("logs/%s", name->buf));
3918 int oldlen = name->len;
3921 return name->len ? errno : 0;
3923 while ((de = readdir(d)) != NULL) {
3926 if (de->d_name[0] == '.')
3928 if (ends_with(de->d_name, ".lock"))
3930 strbuf_addstr(name, de->d_name);
3931 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3932 ; /* silently ignore */
3934 if (S_ISDIR(st.st_mode)) {
3935 strbuf_addch(name, '/');
3936 retval = do_for_each_reflog(name, fn, cb_data);
3938 struct object_id oid;
3940 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3941 retval = error("bad ref for %s", name->buf);
3943 retval = fn(name->buf, &oid, 0, cb_data);
3948 strbuf_setlen(name, oldlen);
3954 int for_each_reflog(each_ref_fn fn, void *cb_data)
3958 strbuf_init(&name, PATH_MAX);
3959 retval = do_for_each_reflog(&name, fn, cb_data);
3960 strbuf_release(&name);
3965 * Information needed for a single ref update. Set new_sha1 to the new
3966 * value or to null_sha1 to delete the ref. To check the old value
3967 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3968 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3969 * not exist before update.
3973 * If (flags & REF_HAVE_NEW), set the reference to this value:
3975 unsigned char new_sha1[20];
3977 * If (flags & REF_HAVE_OLD), check that the reference
3978 * previously had this value:
3980 unsigned char old_sha1[20];
3982 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3983 * REF_DELETING, and REF_ISPRUNING:
3986 struct ref_lock *lock;
3989 const char refname[FLEX_ARRAY];
3993 * Transaction states.
3994 * OPEN: The transaction is in a valid state and can accept new updates.
3995 * An OPEN transaction can be committed.
3996 * CLOSED: A closed transaction is no longer active and no other operations
3997 * than free can be used on it in this state.
3998 * A transaction can either become closed by successfully committing
3999 * an active transaction or if there is a failure while building
4000 * the transaction thus rendering it failed/inactive.
4002 enum ref_transaction_state {
4003 REF_TRANSACTION_OPEN = 0,
4004 REF_TRANSACTION_CLOSED = 1
4008 * Data structure for holding a reference transaction, which can
4009 * consist of checks and updates to multiple references, carried out
4010 * as atomically as possible. This structure is opaque to callers.
4012 struct ref_transaction {
4013 struct ref_update **updates;
4016 enum ref_transaction_state state;
4019 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
4023 return xcalloc(1, sizeof(struct ref_transaction));
4026 void ref_transaction_free(struct ref_transaction *transaction)
4033 for (i = 0; i < transaction->nr; i++) {
4034 free(transaction->updates[i]->msg);
4035 free(transaction->updates[i]);
4037 free(transaction->updates);
4041 static struct ref_update *add_update(struct ref_transaction *transaction,
4042 const char *refname)
4044 size_t len = strlen(refname) + 1;
4045 struct ref_update *update = xcalloc(1, sizeof(*update) + len);
4047 memcpy((char *)update->refname, refname, len); /* includes NUL */
4048 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
4049 transaction->updates[transaction->nr++] = update;
4053 int ref_transaction_update(struct ref_transaction *transaction,
4054 const char *refname,
4055 const unsigned char *new_sha1,
4056 const unsigned char *old_sha1,
4057 unsigned int flags, const char *msg,
4060 struct ref_update *update;
4064 if (transaction->state != REF_TRANSACTION_OPEN)
4065 die("BUG: update called for transaction that is not open");
4067 if (new_sha1 && !is_null_sha1(new_sha1) &&
4068 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
4069 strbuf_addf(err, "refusing to update ref with bad name %s",
4074 update = add_update(transaction, refname);
4076 hashcpy(update->new_sha1, new_sha1);
4077 flags |= REF_HAVE_NEW;
4080 hashcpy(update->old_sha1, old_sha1);
4081 flags |= REF_HAVE_OLD;
4083 update->flags = flags;
4085 update->msg = xstrdup(msg);
4089 int ref_transaction_create(struct ref_transaction *transaction,
4090 const char *refname,
4091 const unsigned char *new_sha1,
4092 unsigned int flags, const char *msg,
4095 if (!new_sha1 || is_null_sha1(new_sha1))
4096 die("BUG: create called without valid new_sha1");
4097 return ref_transaction_update(transaction, refname, new_sha1,
4098 null_sha1, flags, msg, err);
4101 int ref_transaction_delete(struct ref_transaction *transaction,
4102 const char *refname,
4103 const unsigned char *old_sha1,
4104 unsigned int flags, const char *msg,
4107 if (old_sha1 && is_null_sha1(old_sha1))
4108 die("BUG: delete called with old_sha1 set to zeros");
4109 return ref_transaction_update(transaction, refname,
4110 null_sha1, old_sha1,
4114 int ref_transaction_verify(struct ref_transaction *transaction,
4115 const char *refname,
4116 const unsigned char *old_sha1,
4121 die("BUG: verify called with old_sha1 set to NULL");
4122 return ref_transaction_update(transaction, refname,
4127 int update_ref(const char *msg, const char *refname,
4128 const unsigned char *new_sha1, const unsigned char *old_sha1,
4129 unsigned int flags, enum action_on_err onerr)
4131 struct ref_transaction *t = NULL;
4132 struct strbuf err = STRBUF_INIT;
4135 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
4136 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
4138 t = ref_transaction_begin(&err);
4140 ref_transaction_update(t, refname, new_sha1, old_sha1,
4141 flags, msg, &err) ||
4142 ref_transaction_commit(t, &err)) {
4144 ref_transaction_free(t);
4148 const char *str = "update_ref failed for ref '%s': %s";
4151 case UPDATE_REFS_MSG_ON_ERR:
4152 error(str, refname, err.buf);
4154 case UPDATE_REFS_DIE_ON_ERR:
4155 die(str, refname, err.buf);
4157 case UPDATE_REFS_QUIET_ON_ERR:
4160 strbuf_release(&err);
4163 strbuf_release(&err);
4165 ref_transaction_free(t);
4169 static int ref_update_reject_duplicates(struct string_list *refnames,
4172 int i, n = refnames->nr;
4176 for (i = 1; i < n; i++)
4177 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
4179 "Multiple updates for ref '%s' not allowed.",
4180 refnames->items[i].string);
4186 int ref_transaction_commit(struct ref_transaction *transaction,
4190 int n = transaction->nr;
4191 struct ref_update **updates = transaction->updates;
4192 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
4193 struct string_list_item *ref_to_delete;
4194 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4198 if (transaction->state != REF_TRANSACTION_OPEN)
4199 die("BUG: commit called for transaction that is not open");
4202 transaction->state = REF_TRANSACTION_CLOSED;
4206 /* Fail if a refname appears more than once in the transaction: */
4207 for (i = 0; i < n; i++)
4208 string_list_append(&affected_refnames, updates[i]->refname);
4209 string_list_sort(&affected_refnames);
4210 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4211 ret = TRANSACTION_GENERIC_ERROR;
4216 * Acquire all locks, verify old values if provided, check
4217 * that new values are valid, and write new values to the
4218 * lockfiles, ready to be activated. Only keep one lockfile
4219 * open at a time to avoid running out of file descriptors.
4221 for (i = 0; i < n; i++) {
4222 struct ref_update *update = updates[i];
4224 if ((update->flags & REF_HAVE_NEW) &&
4225 is_null_sha1(update->new_sha1))
4226 update->flags |= REF_DELETING;
4227 update->lock = lock_ref_sha1_basic(
4229 ((update->flags & REF_HAVE_OLD) ?
4230 update->old_sha1 : NULL),
4231 &affected_refnames, NULL,
4235 if (!update->lock) {
4238 ret = (errno == ENOTDIR)
4239 ? TRANSACTION_NAME_CONFLICT
4240 : TRANSACTION_GENERIC_ERROR;
4241 reason = strbuf_detach(err, NULL);
4242 strbuf_addf(err, "cannot lock ref '%s': %s",
4243 update->refname, reason);
4247 if ((update->flags & REF_HAVE_NEW) &&
4248 !(update->flags & REF_DELETING)) {
4249 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4250 (update->flags & REF_NODEREF));
4252 if (!overwriting_symref &&
4253 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4255 * The reference already has the desired
4256 * value, so we don't need to write it.
4258 } else if (write_ref_to_lockfile(update->lock,
4261 char *write_err = strbuf_detach(err, NULL);
4264 * The lock was freed upon failure of
4265 * write_ref_to_lockfile():
4267 update->lock = NULL;
4269 "cannot update the ref '%s': %s",
4270 update->refname, write_err);
4272 ret = TRANSACTION_GENERIC_ERROR;
4275 update->flags |= REF_NEEDS_COMMIT;
4278 if (!(update->flags & REF_NEEDS_COMMIT)) {
4280 * We didn't have to write anything to the lockfile.
4281 * Close it to free up the file descriptor:
4283 if (close_ref(update->lock)) {
4284 strbuf_addf(err, "Couldn't close %s.lock",
4291 /* Perform updates first so live commits remain referenced */
4292 for (i = 0; i < n; i++) {
4293 struct ref_update *update = updates[i];
4295 if (update->flags & REF_NEEDS_COMMIT) {
4296 if (commit_ref_update(update->lock,
4297 update->new_sha1, update->msg,
4298 update->flags, err)) {
4299 /* freed by commit_ref_update(): */
4300 update->lock = NULL;
4301 ret = TRANSACTION_GENERIC_ERROR;
4304 /* freed by commit_ref_update(): */
4305 update->lock = NULL;
4310 /* Perform deletes now that updates are safely completed */
4311 for (i = 0; i < n; i++) {
4312 struct ref_update *update = updates[i];
4314 if (update->flags & REF_DELETING) {
4315 if (delete_ref_loose(update->lock, update->type, err)) {
4316 ret = TRANSACTION_GENERIC_ERROR;
4320 if (!(update->flags & REF_ISPRUNING))
4321 string_list_append(&refs_to_delete,
4322 update->lock->ref_name);
4326 if (repack_without_refs(&refs_to_delete, err)) {
4327 ret = TRANSACTION_GENERIC_ERROR;
4330 for_each_string_list_item(ref_to_delete, &refs_to_delete)
4331 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4332 clear_loose_ref_cache(&ref_cache);
4335 transaction->state = REF_TRANSACTION_CLOSED;
4337 for (i = 0; i < n; i++)
4338 if (updates[i]->lock)
4339 unlock_ref(updates[i]->lock);
4340 string_list_clear(&refs_to_delete, 0);
4341 string_list_clear(&affected_refnames, 0);
4345 static int ref_present(const char *refname,
4346 const struct object_id *oid, int flags, void *cb_data)
4348 struct string_list *affected_refnames = cb_data;
4350 return string_list_has_string(affected_refnames, refname);
4353 int initial_ref_transaction_commit(struct ref_transaction *transaction,
4357 int n = transaction->nr;
4358 struct ref_update **updates = transaction->updates;
4359 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4363 if (transaction->state != REF_TRANSACTION_OPEN)
4364 die("BUG: commit called for transaction that is not open");
4366 /* Fail if a refname appears more than once in the transaction: */
4367 for (i = 0; i < n; i++)
4368 string_list_append(&affected_refnames, updates[i]->refname);
4369 string_list_sort(&affected_refnames);
4370 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4371 ret = TRANSACTION_GENERIC_ERROR;
4376 * It's really undefined to call this function in an active
4377 * repository or when there are existing references: we are
4378 * only locking and changing packed-refs, so (1) any
4379 * simultaneous processes might try to change a reference at
4380 * the same time we do, and (2) any existing loose versions of
4381 * the references that we are setting would have precedence
4382 * over our values. But some remote helpers create the remote
4383 * "HEAD" and "master" branches before calling this function,
4384 * so here we really only check that none of the references
4385 * that we are creating already exists.
4387 if (for_each_rawref(ref_present, &affected_refnames))
4388 die("BUG: initial ref transaction called with existing refs");
4390 for (i = 0; i < n; i++) {
4391 struct ref_update *update = updates[i];
4393 if ((update->flags & REF_HAVE_OLD) &&
4394 !is_null_sha1(update->old_sha1))
4395 die("BUG: initial ref transaction with old_sha1 set");
4396 if (verify_refname_available(update->refname,
4397 &affected_refnames, NULL,
4399 ret = TRANSACTION_NAME_CONFLICT;
4404 if (lock_packed_refs(0)) {
4405 strbuf_addf(err, "unable to lock packed-refs file: %s",
4407 ret = TRANSACTION_GENERIC_ERROR;
4411 for (i = 0; i < n; i++) {
4412 struct ref_update *update = updates[i];
4414 if ((update->flags & REF_HAVE_NEW) &&
4415 !is_null_sha1(update->new_sha1))
4416 add_packed_ref(update->refname, update->new_sha1);
4419 if (commit_packed_refs()) {
4420 strbuf_addf(err, "unable to commit packed-refs file: %s",
4422 ret = TRANSACTION_GENERIC_ERROR;
4427 transaction->state = REF_TRANSACTION_CLOSED;
4428 string_list_clear(&affected_refnames, 0);
4432 char *shorten_unambiguous_ref(const char *refname, int strict)
4435 static char **scanf_fmts;
4436 static int nr_rules;
4441 * Pre-generate scanf formats from ref_rev_parse_rules[].
4442 * Generate a format suitable for scanf from a
4443 * ref_rev_parse_rules rule by interpolating "%s" at the
4444 * location of the "%.*s".
4446 size_t total_len = 0;
4449 /* the rule list is NULL terminated, count them first */
4450 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4451 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4452 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4454 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4457 for (i = 0; i < nr_rules; i++) {
4458 assert(offset < total_len);
4459 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4460 offset += snprintf(scanf_fmts[i], total_len - offset,
4461 ref_rev_parse_rules[i], 2, "%s") + 1;
4465 /* bail out if there are no rules */
4467 return xstrdup(refname);
4469 /* buffer for scanf result, at most refname must fit */
4470 short_name = xstrdup(refname);
4472 /* skip first rule, it will always match */
4473 for (i = nr_rules - 1; i > 0 ; --i) {
4475 int rules_to_fail = i;
4478 if (1 != sscanf(refname, scanf_fmts[i], short_name))
4481 short_name_len = strlen(short_name);
4484 * in strict mode, all (except the matched one) rules
4485 * must fail to resolve to a valid non-ambiguous ref
4488 rules_to_fail = nr_rules;
4491 * check if the short name resolves to a valid ref,
4492 * but use only rules prior to the matched one
4494 for (j = 0; j < rules_to_fail; j++) {
4495 const char *rule = ref_rev_parse_rules[j];
4496 char refname[PATH_MAX];
4498 /* skip matched rule */
4503 * the short name is ambiguous, if it resolves
4504 * (with this previous rule) to a valid ref
4505 * read_ref() returns 0 on success
4507 mksnpath(refname, sizeof(refname),
4508 rule, short_name_len, short_name);
4509 if (ref_exists(refname))
4514 * short name is non-ambiguous if all previous rules
4515 * haven't resolved to a valid ref
4517 if (j == rules_to_fail)
4522 return xstrdup(refname);
4525 static struct string_list *hide_refs;
4527 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4529 if (!strcmp("transfer.hiderefs", var) ||
4530 /* NEEDSWORK: use parse_config_key() once both are merged */
4531 (starts_with(var, section) && var[strlen(section)] == '.' &&
4532 !strcmp(var + strlen(section), ".hiderefs"))) {
4537 return config_error_nonbool(var);
4538 ref = xstrdup(value);
4540 while (len && ref[len - 1] == '/')
4543 hide_refs = xcalloc(1, sizeof(*hide_refs));
4544 hide_refs->strdup_strings = 1;
4546 string_list_append(hide_refs, ref);
4551 int ref_is_hidden(const char *refname)
4557 for (i = hide_refs->nr - 1; i >= 0; i--) {
4558 const char *match = hide_refs->items[i].string;
4562 if (*match == '!') {
4567 if (!starts_with(refname, match))
4569 len = strlen(match);
4570 if (!refname[len] || refname[len] == '/')
4576 struct expire_reflog_cb {
4578 reflog_expiry_should_prune_fn *should_prune_fn;
4581 unsigned char last_kept_sha1[20];
4584 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4585 const char *email, unsigned long timestamp, int tz,
4586 const char *message, void *cb_data)
4588 struct expire_reflog_cb *cb = cb_data;
4589 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4591 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4592 osha1 = cb->last_kept_sha1;
4594 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4595 message, policy_cb)) {
4597 printf("would prune %s", message);
4598 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4599 printf("prune %s", message);
4602 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4603 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4604 email, timestamp, tz, message);
4605 hashcpy(cb->last_kept_sha1, nsha1);
4607 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4608 printf("keep %s", message);
4613 int reflog_expire(const char *refname, const unsigned char *sha1,
4615 reflog_expiry_prepare_fn prepare_fn,
4616 reflog_expiry_should_prune_fn should_prune_fn,
4617 reflog_expiry_cleanup_fn cleanup_fn,
4618 void *policy_cb_data)
4620 static struct lock_file reflog_lock;
4621 struct expire_reflog_cb cb;
4622 struct ref_lock *lock;
4626 struct strbuf err = STRBUF_INIT;
4628 memset(&cb, 0, sizeof(cb));
4630 cb.policy_cb = policy_cb_data;
4631 cb.should_prune_fn = should_prune_fn;
4634 * The reflog file is locked by holding the lock on the
4635 * reference itself, plus we might need to update the
4636 * reference if --updateref was specified:
4638 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4640 error("cannot lock ref '%s': %s", refname, err.buf);
4641 strbuf_release(&err);
4644 if (!reflog_exists(refname)) {
4649 log_file = git_pathdup("logs/%s", refname);
4650 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4652 * Even though holding $GIT_DIR/logs/$reflog.lock has
4653 * no locking implications, we use the lock_file
4654 * machinery here anyway because it does a lot of the
4655 * work we need, including cleaning up if the program
4656 * exits unexpectedly.
4658 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4659 struct strbuf err = STRBUF_INIT;
4660 unable_to_lock_message(log_file, errno, &err);
4661 error("%s", err.buf);
4662 strbuf_release(&err);
4665 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4667 error("cannot fdopen %s (%s)",
4668 get_lock_file_path(&reflog_lock), strerror(errno));
4673 (*prepare_fn)(refname, sha1, cb.policy_cb);
4674 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4675 (*cleanup_fn)(cb.policy_cb);
4677 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4679 * It doesn't make sense to adjust a reference pointed
4680 * to by a symbolic ref based on expiring entries in
4681 * the symbolic reference's reflog. Nor can we update
4682 * a reference if there are no remaining reflog
4685 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4686 !(type & REF_ISSYMREF) &&
4687 !is_null_sha1(cb.last_kept_sha1);
4689 if (close_lock_file(&reflog_lock)) {
4690 status |= error("couldn't write %s: %s", log_file,
4692 } else if (update &&
4693 (write_in_full(get_lock_file_fd(lock->lk),
4694 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4695 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
4696 close_ref(lock) < 0)) {
4697 status |= error("couldn't write %s",
4698 get_lock_file_path(lock->lk));
4699 rollback_lock_file(&reflog_lock);
4700 } else if (commit_lock_file(&reflog_lock)) {
4701 status |= error("unable to commit reflog '%s' (%s)",
4702 log_file, strerror(errno));
4703 } else if (update && commit_ref(lock)) {
4704 status |= error("couldn't set %s", lock->ref_name);
4712 rollback_lock_file(&reflog_lock);