7 #include "string-list.h"
13 struct object_id old_oid;
17 * How to handle various characters in refnames:
18 * 0: An acceptable character for refs
20 * 2: ., look for a preceding . to reject .. in refs
21 * 3: {, look for a preceding @ to reject @{ in refs
22 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
24 static unsigned char refname_disposition[256] = {
25 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
26 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
37 * refs (i.e., because the reference is about to be deleted anyway).
39 #define REF_DELETING 0x02
42 * Used as a flag in ref_update::flags when a loose ref is being
45 #define REF_ISPRUNING 0x04
48 * Used as a flag in ref_update::flags when the reference should be
49 * updated to new_sha1.
51 #define REF_HAVE_NEW 0x08
54 * Used as a flag in ref_update::flags when old_sha1 should be
57 #define REF_HAVE_OLD 0x10
60 * Used as a flag in ref_update::flags when the lockfile needs to be
63 #define REF_NEEDS_COMMIT 0x20
66 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a
67 * value to ref_update::flags
71 * Try to read one refname component from the front of refname.
72 * Return the length of the component found, or -1 if the component is
73 * not legal. It is legal if it is something reasonable to have under
74 * ".git/refs/"; We do not like it if:
76 * - any path component of it begins with ".", or
77 * - it has double dots "..", or
78 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
79 * - it ends with a "/".
80 * - it ends with ".lock"
81 * - it contains a "\" (backslash)
83 static int check_refname_component(const char *refname, int flags)
88 for (cp = refname; ; cp++) {
90 unsigned char disp = refname_disposition[ch];
96 return -1; /* Refname contains "..". */
100 return -1; /* Refname contains "@{". */
109 return 0; /* Component has zero length. */
110 if (refname[0] == '.')
111 return -1; /* Component starts with '.'. */
112 if (cp - refname >= LOCK_SUFFIX_LEN &&
113 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
114 return -1; /* Refname ends with ".lock". */
118 int check_refname_format(const char *refname, int flags)
120 int component_len, component_count = 0;
122 if (!strcmp(refname, "@"))
123 /* Refname is a single character '@'. */
127 /* We are at the start of a path component. */
128 component_len = check_refname_component(refname, flags);
129 if (component_len <= 0) {
130 if ((flags & REFNAME_REFSPEC_PATTERN) &&
132 (refname[1] == '\0' || refname[1] == '/')) {
133 /* Accept one wildcard as a full refname component. */
134 flags &= ~REFNAME_REFSPEC_PATTERN;
141 if (refname[component_len] == '\0')
143 /* Skip to next component. */
144 refname += component_len + 1;
147 if (refname[component_len - 1] == '.')
148 return -1; /* Refname ends with '.'. */
149 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
150 return -1; /* Refname has only one component. */
157 * Information used (along with the information in ref_entry) to
158 * describe a single cached reference. This data structure only
159 * occurs embedded in a union in struct ref_entry, and only when
160 * (ref_entry->flag & REF_DIR) is zero.
164 * The name of the object to which this reference resolves
165 * (which may be a tag object). If REF_ISBROKEN, this is
166 * null. If REF_ISSYMREF, then this is the name of the object
167 * referred to by the last reference in the symlink chain.
169 struct object_id oid;
172 * If REF_KNOWS_PEELED, then this field holds the peeled value
173 * of this reference, or null if the reference is known not to
174 * be peelable. See the documentation for peel_ref() for an
175 * exact definition of "peelable".
177 struct object_id peeled;
183 * Information used (along with the information in ref_entry) to
184 * describe a level in the hierarchy of references. This data
185 * structure only occurs embedded in a union in struct ref_entry, and
186 * only when (ref_entry.flag & REF_DIR) is set. In that case,
187 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
188 * in the directory have already been read:
190 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
191 * or packed references, already read.
193 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
194 * references that hasn't been read yet (nor has any of its
197 * Entries within a directory are stored within a growable array of
198 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
199 * sorted are sorted by their component name in strcmp() order and the
200 * remaining entries are unsorted.
202 * Loose references are read lazily, one directory at a time. When a
203 * directory of loose references is read, then all of the references
204 * in that directory are stored, and REF_INCOMPLETE stubs are created
205 * for any subdirectories, but the subdirectories themselves are not
206 * read. The reading is triggered by get_ref_dir().
212 * Entries with index 0 <= i < sorted are sorted by name. New
213 * entries are appended to the list unsorted, and are sorted
214 * only when required; thus we avoid the need to sort the list
215 * after the addition of every reference.
219 /* A pointer to the ref_cache that contains this ref_dir. */
220 struct ref_cache *ref_cache;
222 struct ref_entry **entries;
226 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
227 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
228 * public values; see refs.h.
232 * The field ref_entry->u.value.peeled of this value entry contains
233 * the correct peeled value for the reference, which might be
234 * null_sha1 if the reference is not a tag or if it is broken.
236 #define REF_KNOWS_PEELED 0x10
238 /* ref_entry represents a directory of references */
242 * Entry has not yet been read from disk (used only for REF_DIR
243 * entries representing loose references)
245 #define REF_INCOMPLETE 0x40
248 * A ref_entry represents either a reference or a "subdirectory" of
251 * Each directory in the reference namespace is represented by a
252 * ref_entry with (flags & REF_DIR) set and containing a subdir member
253 * that holds the entries in that directory that have been read so
254 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
255 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
256 * used for loose reference directories.
258 * References are represented by a ref_entry with (flags & REF_DIR)
259 * unset and a value member that describes the reference's value. The
260 * flag member is at the ref_entry level, but it is also needed to
261 * interpret the contents of the value field (in other words, a
262 * ref_value object is not very much use without the enclosing
265 * Reference names cannot end with slash and directories' names are
266 * always stored with a trailing slash (except for the top-level
267 * directory, which is always denoted by ""). This has two nice
268 * consequences: (1) when the entries in each subdir are sorted
269 * lexicographically by name (as they usually are), the references in
270 * a whole tree can be generated in lexicographic order by traversing
271 * the tree in left-to-right, depth-first order; (2) the names of
272 * references and subdirectories cannot conflict, and therefore the
273 * presence of an empty subdirectory does not block the creation of a
274 * similarly-named reference. (The fact that reference names with the
275 * same leading components can conflict *with each other* is a
276 * separate issue that is regulated by verify_refname_available().)
278 * Please note that the name field contains the fully-qualified
279 * reference (or subdirectory) name. Space could be saved by only
280 * storing the relative names. But that would require the full names
281 * to be generated on the fly when iterating in do_for_each_ref(), and
282 * would break callback functions, who have always been able to assume
283 * that the name strings that they are passed will not be freed during
287 unsigned char flag; /* ISSYMREF? ISPACKED? */
289 struct ref_value value; /* if not (flags&REF_DIR) */
290 struct ref_dir subdir; /* if (flags&REF_DIR) */
293 * The full name of the reference (e.g., "refs/heads/master")
294 * or the full name of the directory with a trailing slash
295 * (e.g., "refs/heads/"):
297 char name[FLEX_ARRAY];
300 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
302 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
305 assert(entry->flag & REF_DIR);
306 dir = &entry->u.subdir;
307 if (entry->flag & REF_INCOMPLETE) {
308 read_loose_refs(entry->name, dir);
309 entry->flag &= ~REF_INCOMPLETE;
315 * Check if a refname is safe.
316 * For refs that start with "refs/" we consider it safe as long they do
317 * not try to resolve to outside of refs/.
319 * For all other refs we only consider them safe iff they only contain
320 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
323 static int refname_is_safe(const char *refname)
325 if (starts_with(refname, "refs/")) {
329 buf = xmalloc(strlen(refname) + 1);
331 * Does the refname try to escape refs/?
332 * For example: refs/foo/../bar is safe but refs/foo/../../bar
335 result = !normalize_path_copy(buf, refname + strlen("refs/"));
340 if (!isupper(*refname) && *refname != '_')
347 static struct ref_entry *create_ref_entry(const char *refname,
348 const unsigned char *sha1, int flag,
352 struct ref_entry *ref;
355 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
356 die("Reference has invalid format: '%s'", refname);
357 len = strlen(refname) + 1;
358 ref = xmalloc(sizeof(struct ref_entry) + len);
359 hashcpy(ref->u.value.oid.hash, sha1);
360 oidclr(&ref->u.value.peeled);
361 memcpy(ref->name, refname, len);
366 static void clear_ref_dir(struct ref_dir *dir);
368 static void free_ref_entry(struct ref_entry *entry)
370 if (entry->flag & REF_DIR) {
372 * Do not use get_ref_dir() here, as that might
373 * trigger the reading of loose refs.
375 clear_ref_dir(&entry->u.subdir);
381 * Add a ref_entry to the end of dir (unsorted). Entry is always
382 * stored directly in dir; no recursion into subdirectories is
385 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
387 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
388 dir->entries[dir->nr++] = entry;
389 /* optimize for the case that entries are added in order */
391 (dir->nr == dir->sorted + 1 &&
392 strcmp(dir->entries[dir->nr - 2]->name,
393 dir->entries[dir->nr - 1]->name) < 0))
394 dir->sorted = dir->nr;
398 * Clear and free all entries in dir, recursively.
400 static void clear_ref_dir(struct ref_dir *dir)
403 for (i = 0; i < dir->nr; i++)
404 free_ref_entry(dir->entries[i]);
406 dir->sorted = dir->nr = dir->alloc = 0;
411 * Create a struct ref_entry object for the specified dirname.
412 * dirname is the name of the directory with a trailing slash (e.g.,
413 * "refs/heads/") or "" for the top-level directory.
415 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
416 const char *dirname, size_t len,
419 struct ref_entry *direntry;
420 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
421 memcpy(direntry->name, dirname, len);
422 direntry->name[len] = '\0';
423 direntry->u.subdir.ref_cache = ref_cache;
424 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
428 static int ref_entry_cmp(const void *a, const void *b)
430 struct ref_entry *one = *(struct ref_entry **)a;
431 struct ref_entry *two = *(struct ref_entry **)b;
432 return strcmp(one->name, two->name);
435 static void sort_ref_dir(struct ref_dir *dir);
437 struct string_slice {
442 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
444 const struct string_slice *key = key_;
445 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
446 int cmp = strncmp(key->str, ent->name, key->len);
449 return '\0' - (unsigned char)ent->name[key->len];
453 * Return the index of the entry with the given refname from the
454 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
455 * no such entry is found. dir must already be complete.
457 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
459 struct ref_entry **r;
460 struct string_slice key;
462 if (refname == NULL || !dir->nr)
468 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
469 ref_entry_cmp_sslice);
474 return r - dir->entries;
478 * Search for a directory entry directly within dir (without
479 * recursing). Sort dir if necessary. subdirname must be a directory
480 * name (i.e., end in '/'). If mkdir is set, then create the
481 * directory if it is missing; otherwise, return NULL if the desired
482 * directory cannot be found. dir must already be complete.
484 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
485 const char *subdirname, size_t len,
488 int entry_index = search_ref_dir(dir, subdirname, len);
489 struct ref_entry *entry;
490 if (entry_index == -1) {
494 * Since dir is complete, the absence of a subdir
495 * means that the subdir really doesn't exist;
496 * therefore, create an empty record for it but mark
497 * the record complete.
499 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
500 add_entry_to_dir(dir, entry);
502 entry = dir->entries[entry_index];
504 return get_ref_dir(entry);
508 * If refname is a reference name, find the ref_dir within the dir
509 * tree that should hold refname. If refname is a directory name
510 * (i.e., ends in '/'), then return that ref_dir itself. dir must
511 * represent the top-level directory and must already be complete.
512 * Sort ref_dirs and recurse into subdirectories as necessary. If
513 * mkdir is set, then create any missing directories; otherwise,
514 * return NULL if the desired directory cannot be found.
516 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
517 const char *refname, int mkdir)
520 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
521 size_t dirnamelen = slash - refname + 1;
522 struct ref_dir *subdir;
523 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
535 * Find the value entry with the given name in dir, sorting ref_dirs
536 * and recursing into subdirectories as necessary. If the name is not
537 * found or it corresponds to a directory entry, return NULL.
539 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
542 struct ref_entry *entry;
543 dir = find_containing_dir(dir, refname, 0);
546 entry_index = search_ref_dir(dir, refname, strlen(refname));
547 if (entry_index == -1)
549 entry = dir->entries[entry_index];
550 return (entry->flag & REF_DIR) ? NULL : entry;
554 * Remove the entry with the given name from dir, recursing into
555 * subdirectories as necessary. If refname is the name of a directory
556 * (i.e., ends with '/'), then remove the directory and its contents.
557 * If the removal was successful, return the number of entries
558 * remaining in the directory entry that contained the deleted entry.
559 * If the name was not found, return -1. Please note that this
560 * function only deletes the entry from the cache; it does not delete
561 * it from the filesystem or ensure that other cache entries (which
562 * might be symbolic references to the removed entry) are updated.
563 * Nor does it remove any containing dir entries that might be made
564 * empty by the removal. dir must represent the top-level directory
565 * and must already be complete.
567 static int remove_entry(struct ref_dir *dir, const char *refname)
569 int refname_len = strlen(refname);
571 struct ref_entry *entry;
572 int is_dir = refname[refname_len - 1] == '/';
575 * refname represents a reference directory. Remove
576 * the trailing slash; otherwise we will get the
577 * directory *representing* refname rather than the
578 * one *containing* it.
580 char *dirname = xmemdupz(refname, refname_len - 1);
581 dir = find_containing_dir(dir, dirname, 0);
584 dir = find_containing_dir(dir, refname, 0);
588 entry_index = search_ref_dir(dir, refname, refname_len);
589 if (entry_index == -1)
591 entry = dir->entries[entry_index];
593 memmove(&dir->entries[entry_index],
594 &dir->entries[entry_index + 1],
595 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
598 if (dir->sorted > entry_index)
600 free_ref_entry(entry);
605 * Add a ref_entry to the ref_dir (unsorted), recursing into
606 * subdirectories as necessary. dir must represent the top-level
607 * directory. Return 0 on success.
609 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
611 dir = find_containing_dir(dir, ref->name, 1);
614 add_entry_to_dir(dir, ref);
619 * Emit a warning and return true iff ref1 and ref2 have the same name
620 * and the same sha1. Die if they have the same name but different
623 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
625 if (strcmp(ref1->name, ref2->name))
628 /* Duplicate name; make sure that they don't conflict: */
630 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
631 /* This is impossible by construction */
632 die("Reference directory conflict: %s", ref1->name);
634 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
635 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
637 warning("Duplicated ref: %s", ref1->name);
642 * Sort the entries in dir non-recursively (if they are not already
643 * sorted) and remove any duplicate entries.
645 static void sort_ref_dir(struct ref_dir *dir)
648 struct ref_entry *last = NULL;
651 * This check also prevents passing a zero-length array to qsort(),
652 * which is a problem on some platforms.
654 if (dir->sorted == dir->nr)
657 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
659 /* Remove any duplicates: */
660 for (i = 0, j = 0; j < dir->nr; j++) {
661 struct ref_entry *entry = dir->entries[j];
662 if (last && is_dup_ref(last, entry))
663 free_ref_entry(entry);
665 last = dir->entries[i++] = entry;
667 dir->sorted = dir->nr = i;
670 /* Include broken references in a do_for_each_ref*() iteration: */
671 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
674 * Return true iff the reference described by entry can be resolved to
675 * an object in the database. Emit a warning if the referred-to
676 * object does not exist.
678 static int ref_resolves_to_object(struct ref_entry *entry)
680 if (entry->flag & REF_ISBROKEN)
682 if (!has_sha1_file(entry->u.value.oid.hash)) {
683 error("%s does not point to a valid object!", entry->name);
690 * current_ref is a performance hack: when iterating over references
691 * using the for_each_ref*() functions, current_ref is set to the
692 * current reference's entry before calling the callback function. If
693 * the callback function calls peel_ref(), then peel_ref() first
694 * checks whether the reference to be peeled is the current reference
695 * (it usually is) and if so, returns that reference's peeled version
696 * if it is available. This avoids a refname lookup in a common case.
698 static struct ref_entry *current_ref;
700 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
702 struct ref_entry_cb {
711 * Handle one reference in a do_for_each_ref*()-style iteration,
712 * calling an each_ref_fn for each entry.
714 static int do_one_ref(struct ref_entry *entry, void *cb_data)
716 struct ref_entry_cb *data = cb_data;
717 struct ref_entry *old_current_ref;
720 if (!starts_with(entry->name, data->base))
723 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
724 !ref_resolves_to_object(entry))
727 /* Store the old value, in case this is a recursive call: */
728 old_current_ref = current_ref;
730 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
731 entry->flag, data->cb_data);
732 current_ref = old_current_ref;
737 * Call fn for each reference in dir that has index in the range
738 * offset <= index < dir->nr. Recurse into subdirectories that are in
739 * that index range, sorting them before iterating. This function
740 * does not sort dir itself; it should be sorted beforehand. fn is
741 * called for all references, including broken ones.
743 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
744 each_ref_entry_fn fn, void *cb_data)
747 assert(dir->sorted == dir->nr);
748 for (i = offset; i < dir->nr; i++) {
749 struct ref_entry *entry = dir->entries[i];
751 if (entry->flag & REF_DIR) {
752 struct ref_dir *subdir = get_ref_dir(entry);
753 sort_ref_dir(subdir);
754 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
756 retval = fn(entry, cb_data);
765 * Call fn for each reference in the union of dir1 and dir2, in order
766 * by refname. Recurse into subdirectories. If a value entry appears
767 * in both dir1 and dir2, then only process the version that is in
768 * dir2. The input dirs must already be sorted, but subdirs will be
769 * sorted as needed. fn is called for all references, including
772 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
773 struct ref_dir *dir2,
774 each_ref_entry_fn fn, void *cb_data)
779 assert(dir1->sorted == dir1->nr);
780 assert(dir2->sorted == dir2->nr);
782 struct ref_entry *e1, *e2;
784 if (i1 == dir1->nr) {
785 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
787 if (i2 == dir2->nr) {
788 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
790 e1 = dir1->entries[i1];
791 e2 = dir2->entries[i2];
792 cmp = strcmp(e1->name, e2->name);
794 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
795 /* Both are directories; descend them in parallel. */
796 struct ref_dir *subdir1 = get_ref_dir(e1);
797 struct ref_dir *subdir2 = get_ref_dir(e2);
798 sort_ref_dir(subdir1);
799 sort_ref_dir(subdir2);
800 retval = do_for_each_entry_in_dirs(
801 subdir1, subdir2, fn, cb_data);
804 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
805 /* Both are references; ignore the one from dir1. */
806 retval = fn(e2, cb_data);
810 die("conflict between reference and directory: %s",
822 if (e->flag & REF_DIR) {
823 struct ref_dir *subdir = get_ref_dir(e);
824 sort_ref_dir(subdir);
825 retval = do_for_each_entry_in_dir(
826 subdir, 0, fn, cb_data);
828 retval = fn(e, cb_data);
837 * Load all of the refs from the dir into our in-memory cache. The hard work
838 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
839 * through all of the sub-directories. We do not even need to care about
840 * sorting, as traversal order does not matter to us.
842 static void prime_ref_dir(struct ref_dir *dir)
845 for (i = 0; i < dir->nr; i++) {
846 struct ref_entry *entry = dir->entries[i];
847 if (entry->flag & REF_DIR)
848 prime_ref_dir(get_ref_dir(entry));
852 struct nonmatching_ref_data {
853 const struct string_list *skip;
854 const char *conflicting_refname;
857 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
859 struct nonmatching_ref_data *data = vdata;
861 if (data->skip && string_list_has_string(data->skip, entry->name))
864 data->conflicting_refname = entry->name;
869 * Return 0 if a reference named refname could be created without
870 * conflicting with the name of an existing reference in dir.
871 * Otherwise, return a negative value and write an explanation to err.
872 * If extras is non-NULL, it is a list of additional refnames with
873 * which refname is not allowed to conflict. If skip is non-NULL,
874 * ignore potential conflicts with refs in skip (e.g., because they
875 * are scheduled for deletion in the same operation). Behavior is
876 * undefined if the same name is listed in both extras and skip.
878 * Two reference names conflict if one of them exactly matches the
879 * leading components of the other; e.g., "refs/foo/bar" conflicts
880 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
881 * "refs/foo/bar" or "refs/foo/barbados".
883 * extras and skip must be sorted.
885 static int verify_refname_available(const char *refname,
886 const struct string_list *extras,
887 const struct string_list *skip,
893 struct strbuf dirname = STRBUF_INIT;
897 * For the sake of comments in this function, suppose that
898 * refname is "refs/foo/bar".
903 strbuf_grow(&dirname, strlen(refname) + 1);
904 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
905 /* Expand dirname to the new prefix, not including the trailing slash: */
906 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
909 * We are still at a leading dir of the refname (e.g.,
910 * "refs/foo"; if there is a reference with that name,
911 * it is a conflict, *unless* it is in skip.
914 pos = search_ref_dir(dir, dirname.buf, dirname.len);
916 (!skip || !string_list_has_string(skip, dirname.buf))) {
918 * We found a reference whose name is
919 * a proper prefix of refname; e.g.,
920 * "refs/foo", and is not in skip.
922 strbuf_addf(err, "'%s' exists; cannot create '%s'",
923 dirname.buf, refname);
928 if (extras && string_list_has_string(extras, dirname.buf) &&
929 (!skip || !string_list_has_string(skip, dirname.buf))) {
930 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
931 refname, dirname.buf);
936 * Otherwise, we can try to continue our search with
937 * the next component. So try to look up the
938 * directory, e.g., "refs/foo/". If we come up empty,
939 * we know there is nothing under this whole prefix,
940 * but even in that case we still have to continue the
941 * search for conflicts with extras.
943 strbuf_addch(&dirname, '/');
945 pos = search_ref_dir(dir, dirname.buf, dirname.len);
948 * There was no directory "refs/foo/",
949 * so there is nothing under this
950 * whole prefix. So there is no need
951 * to continue looking for conflicting
952 * references. But we need to continue
953 * looking for conflicting extras.
957 dir = get_ref_dir(dir->entries[pos]);
963 * We are at the leaf of our refname (e.g., "refs/foo/bar").
964 * There is no point in searching for a reference with that
965 * name, because a refname isn't considered to conflict with
966 * itself. But we still need to check for references whose
967 * names are in the "refs/foo/bar/" namespace, because they
970 strbuf_addstr(&dirname, refname + dirname.len);
971 strbuf_addch(&dirname, '/');
974 pos = search_ref_dir(dir, dirname.buf, dirname.len);
978 * We found a directory named "$refname/"
979 * (e.g., "refs/foo/bar/"). It is a problem
980 * iff it contains any ref that is not in
983 struct nonmatching_ref_data data;
986 data.conflicting_refname = NULL;
987 dir = get_ref_dir(dir->entries[pos]);
989 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
990 strbuf_addf(err, "'%s' exists; cannot create '%s'",
991 data.conflicting_refname, refname);
999 * Check for entries in extras that start with
1000 * "$refname/". We do that by looking for the place
1001 * where "$refname/" would be inserted in extras. If
1002 * there is an entry at that position that starts with
1003 * "$refname/" and is not in skip, then we have a
1006 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1007 pos < extras->nr; pos++) {
1008 const char *extra_refname = extras->items[pos].string;
1010 if (!starts_with(extra_refname, dirname.buf))
1013 if (!skip || !string_list_has_string(skip, extra_refname)) {
1014 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1015 refname, extra_refname);
1021 /* No conflicts were found */
1025 strbuf_release(&dirname);
1029 struct packed_ref_cache {
1030 struct ref_entry *root;
1033 * Count of references to the data structure in this instance,
1034 * including the pointer from ref_cache::packed if any. The
1035 * data will not be freed as long as the reference count is
1038 unsigned int referrers;
1041 * Iff the packed-refs file associated with this instance is
1042 * currently locked for writing, this points at the associated
1043 * lock (which is owned by somebody else). The referrer count
1044 * is also incremented when the file is locked and decremented
1045 * when it is unlocked.
1047 struct lock_file *lock;
1049 /* The metadata from when this packed-refs cache was read */
1050 struct stat_validity validity;
1054 * Future: need to be in "struct repository"
1055 * when doing a full libification.
1057 static struct ref_cache {
1058 struct ref_cache *next;
1059 struct ref_entry *loose;
1060 struct packed_ref_cache *packed;
1062 * The submodule name, or "" for the main repo. We allocate
1063 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1064 * is initialized correctly.
1067 } ref_cache, *submodule_ref_caches;
1069 /* Lock used for the main packed-refs file: */
1070 static struct lock_file packlock;
1073 * Increment the reference count of *packed_refs.
1075 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1077 packed_refs->referrers++;
1081 * Decrease the reference count of *packed_refs. If it goes to zero,
1082 * free *packed_refs and return true; otherwise return false.
1084 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1086 if (!--packed_refs->referrers) {
1087 free_ref_entry(packed_refs->root);
1088 stat_validity_clear(&packed_refs->validity);
1096 static void clear_packed_ref_cache(struct ref_cache *refs)
1099 struct packed_ref_cache *packed_refs = refs->packed;
1101 if (packed_refs->lock)
1102 die("internal error: packed-ref cache cleared while locked");
1103 refs->packed = NULL;
1104 release_packed_ref_cache(packed_refs);
1108 static void clear_loose_ref_cache(struct ref_cache *refs)
1111 free_ref_entry(refs->loose);
1116 static struct ref_cache *create_ref_cache(const char *submodule)
1119 struct ref_cache *refs;
1122 len = strlen(submodule) + 1;
1123 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1124 memcpy(refs->name, submodule, len);
1129 * Return a pointer to a ref_cache for the specified submodule. For
1130 * the main repository, use submodule==NULL. The returned structure
1131 * will be allocated and initialized but not necessarily populated; it
1132 * should not be freed.
1134 static struct ref_cache *get_ref_cache(const char *submodule)
1136 struct ref_cache *refs;
1138 if (!submodule || !*submodule)
1141 for (refs = submodule_ref_caches; refs; refs = refs->next)
1142 if (!strcmp(submodule, refs->name))
1145 refs = create_ref_cache(submodule);
1146 refs->next = submodule_ref_caches;
1147 submodule_ref_caches = refs;
1151 /* The length of a peeled reference line in packed-refs, including EOL: */
1152 #define PEELED_LINE_LENGTH 42
1155 * The packed-refs header line that we write out. Perhaps other
1156 * traits will be added later. The trailing space is required.
1158 static const char PACKED_REFS_HEADER[] =
1159 "# pack-refs with: peeled fully-peeled \n";
1162 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1163 * Return a pointer to the refname within the line (null-terminated),
1164 * or NULL if there was a problem.
1166 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1171 * 42: the answer to everything.
1173 * In this case, it happens to be the answer to
1174 * 40 (length of sha1 hex representation)
1175 * +1 (space in between hex and name)
1176 * +1 (newline at the end of the line)
1178 if (line->len <= 42)
1181 if (get_sha1_hex(line->buf, sha1) < 0)
1183 if (!isspace(line->buf[40]))
1186 ref = line->buf + 41;
1190 if (line->buf[line->len - 1] != '\n')
1192 line->buf[--line->len] = 0;
1198 * Read f, which is a packed-refs file, into dir.
1200 * A comment line of the form "# pack-refs with: " may contain zero or
1201 * more traits. We interpret the traits as follows:
1205 * Probably no references are peeled. But if the file contains a
1206 * peeled value for a reference, we will use it.
1210 * References under "refs/tags/", if they *can* be peeled, *are*
1211 * peeled in this file. References outside of "refs/tags/" are
1212 * probably not peeled even if they could have been, but if we find
1213 * a peeled value for such a reference we will use it.
1217 * All references in the file that can be peeled are peeled.
1218 * Inversely (and this is more important), any references in the
1219 * file for which no peeled value is recorded is not peelable. This
1220 * trait should typically be written alongside "peeled" for
1221 * compatibility with older clients, but we do not require it
1222 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1224 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1226 struct ref_entry *last = NULL;
1227 struct strbuf line = STRBUF_INIT;
1228 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1230 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1231 unsigned char sha1[20];
1232 const char *refname;
1235 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1236 if (strstr(traits, " fully-peeled "))
1237 peeled = PEELED_FULLY;
1238 else if (strstr(traits, " peeled "))
1239 peeled = PEELED_TAGS;
1240 /* perhaps other traits later as well */
1244 refname = parse_ref_line(&line, sha1);
1246 int flag = REF_ISPACKED;
1248 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1249 if (!refname_is_safe(refname))
1250 die("packed refname is dangerous: %s", refname);
1252 flag |= REF_BAD_NAME | REF_ISBROKEN;
1254 last = create_ref_entry(refname, sha1, flag, 0);
1255 if (peeled == PEELED_FULLY ||
1256 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1257 last->flag |= REF_KNOWS_PEELED;
1262 line.buf[0] == '^' &&
1263 line.len == PEELED_LINE_LENGTH &&
1264 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1265 !get_sha1_hex(line.buf + 1, sha1)) {
1266 hashcpy(last->u.value.peeled.hash, sha1);
1268 * Regardless of what the file header said,
1269 * we definitely know the value of *this*
1272 last->flag |= REF_KNOWS_PEELED;
1276 strbuf_release(&line);
1280 * Get the packed_ref_cache for the specified ref_cache, creating it
1283 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1285 const char *packed_refs_file;
1288 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1290 packed_refs_file = git_path("packed-refs");
1293 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1294 clear_packed_ref_cache(refs);
1296 if (!refs->packed) {
1299 refs->packed = xcalloc(1, sizeof(*refs->packed));
1300 acquire_packed_ref_cache(refs->packed);
1301 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1302 f = fopen(packed_refs_file, "r");
1304 stat_validity_update(&refs->packed->validity, fileno(f));
1305 read_packed_refs(f, get_ref_dir(refs->packed->root));
1309 return refs->packed;
1312 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1314 return get_ref_dir(packed_ref_cache->root);
1317 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1319 return get_packed_ref_dir(get_packed_ref_cache(refs));
1323 * Add a reference to the in-memory packed reference cache. This may
1324 * only be called while the packed-refs file is locked (see
1325 * lock_packed_refs()). To actually write the packed-refs file, call
1326 * commit_packed_refs().
1328 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1330 struct packed_ref_cache *packed_ref_cache =
1331 get_packed_ref_cache(&ref_cache);
1333 if (!packed_ref_cache->lock)
1334 die("internal error: packed refs not locked");
1335 add_ref(get_packed_ref_dir(packed_ref_cache),
1336 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1340 * Read the loose references from the namespace dirname into dir
1341 * (without recursing). dirname must end with '/'. dir must be the
1342 * directory entry corresponding to dirname.
1344 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1346 struct ref_cache *refs = dir->ref_cache;
1350 int dirnamelen = strlen(dirname);
1351 struct strbuf refname;
1354 path = git_path_submodule(refs->name, "%s", dirname);
1356 path = git_path("%s", dirname);
1362 strbuf_init(&refname, dirnamelen + 257);
1363 strbuf_add(&refname, dirname, dirnamelen);
1365 while ((de = readdir(d)) != NULL) {
1366 unsigned char sha1[20];
1371 if (de->d_name[0] == '.')
1373 if (ends_with(de->d_name, ".lock"))
1375 strbuf_addstr(&refname, de->d_name);
1376 refdir = *refs->name
1377 ? git_path_submodule(refs->name, "%s", refname.buf)
1378 : git_path("%s", refname.buf);
1379 if (stat(refdir, &st) < 0) {
1380 ; /* silently ignore */
1381 } else if (S_ISDIR(st.st_mode)) {
1382 strbuf_addch(&refname, '/');
1383 add_entry_to_dir(dir,
1384 create_dir_entry(refs, refname.buf,
1392 read_ok = !resolve_gitlink_ref(refs->name,
1395 read_ok = !read_ref_full(refname.buf,
1396 RESOLVE_REF_READING,
1402 flag |= REF_ISBROKEN;
1403 } else if (is_null_sha1(sha1)) {
1405 * It is so astronomically unlikely
1406 * that NULL_SHA1 is the SHA-1 of an
1407 * actual object that we consider its
1408 * appearance in a loose reference
1409 * file to be repo corruption
1410 * (probably due to a software bug).
1412 flag |= REF_ISBROKEN;
1415 if (check_refname_format(refname.buf,
1416 REFNAME_ALLOW_ONELEVEL)) {
1417 if (!refname_is_safe(refname.buf))
1418 die("loose refname is dangerous: %s", refname.buf);
1420 flag |= REF_BAD_NAME | REF_ISBROKEN;
1422 add_entry_to_dir(dir,
1423 create_ref_entry(refname.buf, sha1, flag, 0));
1425 strbuf_setlen(&refname, dirnamelen);
1427 strbuf_release(&refname);
1431 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1435 * Mark the top-level directory complete because we
1436 * are about to read the only subdirectory that can
1439 refs->loose = create_dir_entry(refs, "", 0, 0);
1441 * Create an incomplete entry for "refs/":
1443 add_entry_to_dir(get_ref_dir(refs->loose),
1444 create_dir_entry(refs, "refs/", 5, 1));
1446 return get_ref_dir(refs->loose);
1449 /* We allow "recursive" symbolic refs. Only within reason, though */
1451 #define MAXREFLEN (1024)
1454 * Called by resolve_gitlink_ref_recursive() after it failed to read
1455 * from the loose refs in ref_cache refs. Find <refname> in the
1456 * packed-refs file for the submodule.
1458 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1459 const char *refname, unsigned char *sha1)
1461 struct ref_entry *ref;
1462 struct ref_dir *dir = get_packed_refs(refs);
1464 ref = find_ref(dir, refname);
1468 hashcpy(sha1, ref->u.value.oid.hash);
1472 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1473 const char *refname, unsigned char *sha1,
1477 char buffer[128], *p;
1480 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1483 ? git_path_submodule(refs->name, "%s", refname)
1484 : git_path("%s", refname);
1485 fd = open(path, O_RDONLY);
1487 return resolve_gitlink_packed_ref(refs, refname, sha1);
1489 len = read(fd, buffer, sizeof(buffer)-1);
1493 while (len && isspace(buffer[len-1]))
1497 /* Was it a detached head or an old-fashioned symlink? */
1498 if (!get_sha1_hex(buffer, sha1))
1502 if (strncmp(buffer, "ref:", 4))
1508 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1511 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1513 int len = strlen(path), retval;
1515 struct ref_cache *refs;
1517 while (len && path[len-1] == '/')
1521 submodule = xstrndup(path, len);
1522 refs = get_ref_cache(submodule);
1525 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1530 * Return the ref_entry for the given refname from the packed
1531 * references. If it does not exist, return NULL.
1533 static struct ref_entry *get_packed_ref(const char *refname)
1535 return find_ref(get_packed_refs(&ref_cache), refname);
1539 * A loose ref file doesn't exist; check for a packed ref. The
1540 * options are forwarded from resolve_safe_unsafe().
1542 static int resolve_missing_loose_ref(const char *refname,
1544 unsigned char *sha1,
1547 struct ref_entry *entry;
1550 * The loose reference file does not exist; check for a packed
1553 entry = get_packed_ref(refname);
1555 hashcpy(sha1, entry->u.value.oid.hash);
1557 *flags |= REF_ISPACKED;
1560 /* The reference is not a packed reference, either. */
1561 if (resolve_flags & RESOLVE_REF_READING) {
1570 /* This function needs to return a meaningful errno on failure */
1571 static const char *resolve_ref_unsafe_1(const char *refname,
1573 unsigned char *sha1,
1575 struct strbuf *sb_path)
1577 int depth = MAXDEPTH;
1580 static char refname_buffer[256];
1586 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1588 *flags |= REF_BAD_NAME;
1590 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1591 !refname_is_safe(refname)) {
1596 * dwim_ref() uses REF_ISBROKEN to distinguish between
1597 * missing refs and refs that were present but invalid,
1598 * to complain about the latter to stderr.
1600 * We don't know whether the ref exists, so don't set
1616 strbuf_reset(sb_path);
1617 strbuf_git_path(sb_path, "%s", refname);
1618 path = sb_path->buf;
1621 * We might have to loop back here to avoid a race
1622 * condition: first we lstat() the file, then we try
1623 * to read it as a link or as a file. But if somebody
1624 * changes the type of the file (file <-> directory
1625 * <-> symlink) between the lstat() and reading, then
1626 * we don't want to report that as an error but rather
1627 * try again starting with the lstat().
1630 if (lstat(path, &st) < 0) {
1631 if (errno != ENOENT)
1633 if (resolve_missing_loose_ref(refname, resolve_flags,
1639 *flags |= REF_ISBROKEN;
1644 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1645 if (S_ISLNK(st.st_mode)) {
1646 len = readlink(path, buffer, sizeof(buffer)-1);
1648 if (errno == ENOENT || errno == EINVAL)
1649 /* inconsistent with lstat; retry */
1655 if (starts_with(buffer, "refs/") &&
1656 !check_refname_format(buffer, 0)) {
1657 strcpy(refname_buffer, buffer);
1658 refname = refname_buffer;
1660 *flags |= REF_ISSYMREF;
1661 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1669 /* Is it a directory? */
1670 if (S_ISDIR(st.st_mode)) {
1676 * Anything else, just open it and try to use it as
1679 fd = open(path, O_RDONLY);
1681 if (errno == ENOENT)
1682 /* inconsistent with lstat; retry */
1687 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1689 int save_errno = errno;
1695 while (len && isspace(buffer[len-1]))
1700 * Is it a symbolic ref?
1702 if (!starts_with(buffer, "ref:")) {
1704 * Please note that FETCH_HEAD has a second
1705 * line containing other data.
1707 if (get_sha1_hex(buffer, sha1) ||
1708 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1710 *flags |= REF_ISBROKEN;
1717 *flags |= REF_ISBROKEN;
1722 *flags |= REF_ISSYMREF;
1724 while (isspace(*buf))
1726 refname = strcpy(refname_buffer, buf);
1727 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1731 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1733 *flags |= REF_ISBROKEN;
1735 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1736 !refname_is_safe(buf)) {
1745 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1746 unsigned char *sha1, int *flags)
1748 struct strbuf sb_path = STRBUF_INIT;
1749 const char *ret = resolve_ref_unsafe_1(refname, resolve_flags,
1750 sha1, flags, &sb_path);
1751 strbuf_release(&sb_path);
1755 char *resolve_refdup(const char *refname, int resolve_flags,
1756 unsigned char *sha1, int *flags)
1758 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1762 /* The argument to filter_refs */
1764 const char *pattern;
1769 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1771 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1776 int read_ref(const char *refname, unsigned char *sha1)
1778 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1781 int ref_exists(const char *refname)
1783 unsigned char sha1[20];
1784 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1787 static int filter_refs(const char *refname, const struct object_id *oid,
1788 int flags, void *data)
1790 struct ref_filter *filter = (struct ref_filter *)data;
1792 if (wildmatch(filter->pattern, refname, 0, NULL))
1794 return filter->fn(refname, oid, flags, filter->cb_data);
1798 /* object was peeled successfully: */
1802 * object cannot be peeled because the named object (or an
1803 * object referred to by a tag in the peel chain), does not
1808 /* object cannot be peeled because it is not a tag: */
1811 /* ref_entry contains no peeled value because it is a symref: */
1812 PEEL_IS_SYMREF = -3,
1815 * ref_entry cannot be peeled because it is broken (i.e., the
1816 * symbolic reference cannot even be resolved to an object
1823 * Peel the named object; i.e., if the object is a tag, resolve the
1824 * tag recursively until a non-tag is found. If successful, store the
1825 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1826 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1827 * and leave sha1 unchanged.
1829 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1831 struct object *o = lookup_unknown_object(name);
1833 if (o->type == OBJ_NONE) {
1834 int type = sha1_object_info(name, NULL);
1835 if (type < 0 || !object_as_type(o, type, 0))
1836 return PEEL_INVALID;
1839 if (o->type != OBJ_TAG)
1840 return PEEL_NON_TAG;
1842 o = deref_tag_noverify(o);
1844 return PEEL_INVALID;
1846 hashcpy(sha1, o->sha1);
1851 * Peel the entry (if possible) and return its new peel_status. If
1852 * repeel is true, re-peel the entry even if there is an old peeled
1853 * value that is already stored in it.
1855 * It is OK to call this function with a packed reference entry that
1856 * might be stale and might even refer to an object that has since
1857 * been garbage-collected. In such a case, if the entry has
1858 * REF_KNOWS_PEELED then leave the status unchanged and return
1859 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1861 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1863 enum peel_status status;
1865 if (entry->flag & REF_KNOWS_PEELED) {
1867 entry->flag &= ~REF_KNOWS_PEELED;
1868 oidclr(&entry->u.value.peeled);
1870 return is_null_oid(&entry->u.value.peeled) ?
1871 PEEL_NON_TAG : PEEL_PEELED;
1874 if (entry->flag & REF_ISBROKEN)
1876 if (entry->flag & REF_ISSYMREF)
1877 return PEEL_IS_SYMREF;
1879 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1880 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1881 entry->flag |= REF_KNOWS_PEELED;
1885 int peel_ref(const char *refname, unsigned char *sha1)
1888 unsigned char base[20];
1890 if (current_ref && (current_ref->name == refname
1891 || !strcmp(current_ref->name, refname))) {
1892 if (peel_entry(current_ref, 0))
1894 hashcpy(sha1, current_ref->u.value.peeled.hash);
1898 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1902 * If the reference is packed, read its ref_entry from the
1903 * cache in the hope that we already know its peeled value.
1904 * We only try this optimization on packed references because
1905 * (a) forcing the filling of the loose reference cache could
1906 * be expensive and (b) loose references anyway usually do not
1907 * have REF_KNOWS_PEELED.
1909 if (flag & REF_ISPACKED) {
1910 struct ref_entry *r = get_packed_ref(refname);
1912 if (peel_entry(r, 0))
1914 hashcpy(sha1, r->u.value.peeled.hash);
1919 return peel_object(base, sha1);
1922 struct warn_if_dangling_data {
1924 const char *refname;
1925 const struct string_list *refnames;
1926 const char *msg_fmt;
1929 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1930 int flags, void *cb_data)
1932 struct warn_if_dangling_data *d = cb_data;
1933 const char *resolves_to;
1934 struct object_id junk;
1936 if (!(flags & REF_ISSYMREF))
1939 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1942 ? strcmp(resolves_to, d->refname)
1943 : !string_list_has_string(d->refnames, resolves_to))) {
1947 fprintf(d->fp, d->msg_fmt, refname);
1952 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1954 struct warn_if_dangling_data data;
1957 data.refname = refname;
1958 data.refnames = NULL;
1959 data.msg_fmt = msg_fmt;
1960 for_each_rawref(warn_if_dangling_symref, &data);
1963 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1965 struct warn_if_dangling_data data;
1968 data.refname = NULL;
1969 data.refnames = refnames;
1970 data.msg_fmt = msg_fmt;
1971 for_each_rawref(warn_if_dangling_symref, &data);
1975 * Call fn for each reference in the specified ref_cache, omitting
1976 * references not in the containing_dir of base. fn is called for all
1977 * references, including broken ones. If fn ever returns a non-zero
1978 * value, stop the iteration and return that value; otherwise, return
1981 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1982 each_ref_entry_fn fn, void *cb_data)
1984 struct packed_ref_cache *packed_ref_cache;
1985 struct ref_dir *loose_dir;
1986 struct ref_dir *packed_dir;
1990 * We must make sure that all loose refs are read before accessing the
1991 * packed-refs file; this avoids a race condition in which loose refs
1992 * are migrated to the packed-refs file by a simultaneous process, but
1993 * our in-memory view is from before the migration. get_packed_ref_cache()
1994 * takes care of making sure our view is up to date with what is on
1997 loose_dir = get_loose_refs(refs);
1998 if (base && *base) {
1999 loose_dir = find_containing_dir(loose_dir, base, 0);
2002 prime_ref_dir(loose_dir);
2004 packed_ref_cache = get_packed_ref_cache(refs);
2005 acquire_packed_ref_cache(packed_ref_cache);
2006 packed_dir = get_packed_ref_dir(packed_ref_cache);
2007 if (base && *base) {
2008 packed_dir = find_containing_dir(packed_dir, base, 0);
2011 if (packed_dir && loose_dir) {
2012 sort_ref_dir(packed_dir);
2013 sort_ref_dir(loose_dir);
2014 retval = do_for_each_entry_in_dirs(
2015 packed_dir, loose_dir, fn, cb_data);
2016 } else if (packed_dir) {
2017 sort_ref_dir(packed_dir);
2018 retval = do_for_each_entry_in_dir(
2019 packed_dir, 0, fn, cb_data);
2020 } else if (loose_dir) {
2021 sort_ref_dir(loose_dir);
2022 retval = do_for_each_entry_in_dir(
2023 loose_dir, 0, fn, cb_data);
2026 release_packed_ref_cache(packed_ref_cache);
2031 * Call fn for each reference in the specified ref_cache for which the
2032 * refname begins with base. If trim is non-zero, then trim that many
2033 * characters off the beginning of each refname before passing the
2034 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2035 * broken references in the iteration. If fn ever returns a non-zero
2036 * value, stop the iteration and return that value; otherwise, return
2039 static int do_for_each_ref(struct ref_cache *refs, const char *base,
2040 each_ref_fn fn, int trim, int flags, void *cb_data)
2042 struct ref_entry_cb data;
2047 data.cb_data = cb_data;
2049 if (ref_paranoia < 0)
2050 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2052 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2054 return do_for_each_entry(refs, base, do_one_ref, &data);
2057 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2059 struct object_id oid;
2063 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2064 return fn("HEAD", &oid, 0, cb_data);
2069 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2070 return fn("HEAD", &oid, flag, cb_data);
2075 int head_ref(each_ref_fn fn, void *cb_data)
2077 return do_head_ref(NULL, fn, cb_data);
2080 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2082 return do_head_ref(submodule, fn, cb_data);
2085 int for_each_ref(each_ref_fn fn, void *cb_data)
2087 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2090 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2092 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2095 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2097 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2100 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2101 each_ref_fn fn, void *cb_data)
2103 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2106 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2108 return for_each_ref_in("refs/tags/", fn, cb_data);
2111 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2113 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2116 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2118 return for_each_ref_in("refs/heads/", fn, cb_data);
2121 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2123 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2126 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2128 return for_each_ref_in("refs/remotes/", fn, cb_data);
2131 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2133 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2136 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2138 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2139 strlen(git_replace_ref_base), 0, cb_data);
2142 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2144 struct strbuf buf = STRBUF_INIT;
2146 struct object_id oid;
2149 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2150 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2151 ret = fn(buf.buf, &oid, flag, cb_data);
2152 strbuf_release(&buf);
2157 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2159 struct strbuf buf = STRBUF_INIT;
2161 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2162 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2163 strbuf_release(&buf);
2167 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2168 const char *prefix, void *cb_data)
2170 struct strbuf real_pattern = STRBUF_INIT;
2171 struct ref_filter filter;
2174 if (!prefix && !starts_with(pattern, "refs/"))
2175 strbuf_addstr(&real_pattern, "refs/");
2177 strbuf_addstr(&real_pattern, prefix);
2178 strbuf_addstr(&real_pattern, pattern);
2180 if (!has_glob_specials(pattern)) {
2181 /* Append implied '/' '*' if not present. */
2182 if (real_pattern.buf[real_pattern.len - 1] != '/')
2183 strbuf_addch(&real_pattern, '/');
2184 /* No need to check for '*', there is none. */
2185 strbuf_addch(&real_pattern, '*');
2188 filter.pattern = real_pattern.buf;
2190 filter.cb_data = cb_data;
2191 ret = for_each_ref(filter_refs, &filter);
2193 strbuf_release(&real_pattern);
2197 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2199 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2202 int for_each_rawref(each_ref_fn fn, void *cb_data)
2204 return do_for_each_ref(&ref_cache, "", fn, 0,
2205 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2208 const char *prettify_refname(const char *name)
2211 starts_with(name, "refs/heads/") ? 11 :
2212 starts_with(name, "refs/tags/") ? 10 :
2213 starts_with(name, "refs/remotes/") ? 13 :
2217 static const char *ref_rev_parse_rules[] = {
2222 "refs/remotes/%.*s",
2223 "refs/remotes/%.*s/HEAD",
2227 int refname_match(const char *abbrev_name, const char *full_name)
2230 const int abbrev_name_len = strlen(abbrev_name);
2232 for (p = ref_rev_parse_rules; *p; p++) {
2233 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2241 static void unlock_ref(struct ref_lock *lock)
2243 /* Do not free lock->lk -- atexit() still looks at them */
2245 rollback_lock_file(lock->lk);
2246 free(lock->ref_name);
2247 free(lock->orig_ref_name);
2252 * Verify that the reference locked by lock has the value old_sha1.
2253 * Fail if the reference doesn't exist and mustexist is set. Return 0
2254 * on success. On error, write an error message to err, set errno, and
2255 * return a negative value.
2257 static int verify_lock(struct ref_lock *lock,
2258 const unsigned char *old_sha1, int mustexist,
2263 if (read_ref_full(lock->ref_name,
2264 mustexist ? RESOLVE_REF_READING : 0,
2265 lock->old_oid.hash, NULL)) {
2266 int save_errno = errno;
2267 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2271 if (hashcmp(lock->old_oid.hash, old_sha1)) {
2272 strbuf_addf(err, "ref %s is at %s but expected %s",
2274 sha1_to_hex(lock->old_oid.hash),
2275 sha1_to_hex(old_sha1));
2282 static int remove_empty_directories(const char *file)
2284 /* we want to create a file but there is a directory there;
2285 * if that is an empty directory (or a directory that contains
2286 * only empty directories), remove them.
2289 int result, save_errno;
2291 strbuf_init(&path, 20);
2292 strbuf_addstr(&path, file);
2294 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2297 strbuf_release(&path);
2304 * *string and *len will only be substituted, and *string returned (for
2305 * later free()ing) if the string passed in is a magic short-hand form
2308 static char *substitute_branch_name(const char **string, int *len)
2310 struct strbuf buf = STRBUF_INIT;
2311 int ret = interpret_branch_name(*string, *len, &buf);
2315 *string = strbuf_detach(&buf, &size);
2317 return (char *)*string;
2323 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2325 char *last_branch = substitute_branch_name(&str, &len);
2330 for (p = ref_rev_parse_rules; *p; p++) {
2331 char fullref[PATH_MAX];
2332 unsigned char sha1_from_ref[20];
2333 unsigned char *this_result;
2336 this_result = refs_found ? sha1_from_ref : sha1;
2337 mksnpath(fullref, sizeof(fullref), *p, len, str);
2338 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2339 this_result, &flag);
2343 if (!warn_ambiguous_refs)
2345 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2346 warning("ignoring dangling symref %s.", fullref);
2347 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2348 warning("ignoring broken ref %s.", fullref);
2355 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2357 char *last_branch = substitute_branch_name(&str, &len);
2362 for (p = ref_rev_parse_rules; *p; p++) {
2363 unsigned char hash[20];
2364 char path[PATH_MAX];
2365 const char *ref, *it;
2367 mksnpath(path, sizeof(path), *p, len, str);
2368 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2372 if (reflog_exists(path))
2374 else if (strcmp(ref, path) && reflog_exists(ref))
2378 if (!logs_found++) {
2380 hashcpy(sha1, hash);
2382 if (!warn_ambiguous_refs)
2390 * Locks a ref returning the lock on success and NULL on failure.
2391 * On failure errno is set to something meaningful.
2393 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2394 const unsigned char *old_sha1,
2395 const struct string_list *extras,
2396 const struct string_list *skip,
2397 unsigned int flags, int *type_p,
2400 const char *ref_file;
2401 const char *orig_refname = refname;
2402 struct ref_lock *lock;
2405 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2406 int resolve_flags = 0;
2407 int attempts_remaining = 3;
2411 lock = xcalloc(1, sizeof(struct ref_lock));
2414 resolve_flags |= RESOLVE_REF_READING;
2415 if (flags & REF_DELETING) {
2416 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2417 if (flags & REF_NODEREF)
2418 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2421 refname = resolve_ref_unsafe(refname, resolve_flags,
2422 lock->old_oid.hash, &type);
2423 if (!refname && errno == EISDIR) {
2424 /* we are trying to lock foo but we used to
2425 * have foo/bar which now does not exist;
2426 * it is normal for the empty directory 'foo'
2429 ref_file = git_path("%s", orig_refname);
2430 if (remove_empty_directories(ref_file)) {
2433 if (!verify_refname_available(orig_refname, extras, skip,
2434 get_loose_refs(&ref_cache), err))
2435 strbuf_addf(err, "there are still refs under '%s'",
2440 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2441 lock->old_oid.hash, &type);
2447 if (last_errno != ENOTDIR ||
2448 !verify_refname_available(orig_refname, extras, skip,
2449 get_loose_refs(&ref_cache), err))
2450 strbuf_addf(err, "unable to resolve reference %s: %s",
2451 orig_refname, strerror(last_errno));
2456 * If the ref did not exist and we are creating it, make sure
2457 * there is no existing packed ref whose name begins with our
2458 * refname, nor a packed ref whose name is a proper prefix of
2461 if (is_null_oid(&lock->old_oid) &&
2462 verify_refname_available(refname, extras, skip,
2463 get_packed_refs(&ref_cache), err)) {
2464 last_errno = ENOTDIR;
2468 lock->lk = xcalloc(1, sizeof(struct lock_file));
2471 if (flags & REF_NODEREF) {
2472 refname = orig_refname;
2473 lflags |= LOCK_NO_DEREF;
2475 lock->ref_name = xstrdup(refname);
2476 lock->orig_ref_name = xstrdup(orig_refname);
2477 ref_file = git_path("%s", refname);
2480 switch (safe_create_leading_directories_const(ref_file)) {
2482 break; /* success */
2484 if (--attempts_remaining > 0)
2489 strbuf_addf(err, "unable to create directory for %s", ref_file);
2493 if (hold_lock_file_for_update(lock->lk, ref_file, lflags) < 0) {
2495 if (errno == ENOENT && --attempts_remaining > 0)
2497 * Maybe somebody just deleted one of the
2498 * directories leading to ref_file. Try
2503 unable_to_lock_message(ref_file, errno, err);
2507 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2520 * Write an entry to the packed-refs file for the specified refname.
2521 * If peeled is non-NULL, write it as the entry's peeled value.
2523 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2524 unsigned char *peeled)
2526 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2528 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2532 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2534 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2536 enum peel_status peel_status = peel_entry(entry, 0);
2538 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2539 error("internal error: %s is not a valid packed reference!",
2541 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2542 peel_status == PEEL_PEELED ?
2543 entry->u.value.peeled.hash : NULL);
2548 * Lock the packed-refs file for writing. Flags is passed to
2549 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2550 * errno appropriately and return a nonzero value.
2552 static int lock_packed_refs(int flags)
2554 static int timeout_configured = 0;
2555 static int timeout_value = 1000;
2557 struct packed_ref_cache *packed_ref_cache;
2559 if (!timeout_configured) {
2560 git_config_get_int("core.packedrefstimeout", &timeout_value);
2561 timeout_configured = 1;
2564 if (hold_lock_file_for_update_timeout(
2565 &packlock, git_path("packed-refs"),
2566 flags, timeout_value) < 0)
2569 * Get the current packed-refs while holding the lock. If the
2570 * packed-refs file has been modified since we last read it,
2571 * this will automatically invalidate the cache and re-read
2572 * the packed-refs file.
2574 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2575 packed_ref_cache->lock = &packlock;
2576 /* Increment the reference count to prevent it from being freed: */
2577 acquire_packed_ref_cache(packed_ref_cache);
2582 * Write the current version of the packed refs cache from memory to
2583 * disk. The packed-refs file must already be locked for writing (see
2584 * lock_packed_refs()). Return zero on success. On errors, set errno
2585 * and return a nonzero value
2587 static int commit_packed_refs(void)
2589 struct packed_ref_cache *packed_ref_cache =
2590 get_packed_ref_cache(&ref_cache);
2595 if (!packed_ref_cache->lock)
2596 die("internal error: packed-refs not locked");
2598 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2600 die_errno("unable to fdopen packed-refs descriptor");
2602 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2603 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2604 0, write_packed_entry_fn, out);
2606 if (commit_lock_file(packed_ref_cache->lock)) {
2610 packed_ref_cache->lock = NULL;
2611 release_packed_ref_cache(packed_ref_cache);
2617 * Rollback the lockfile for the packed-refs file, and discard the
2618 * in-memory packed reference cache. (The packed-refs file will be
2619 * read anew if it is needed again after this function is called.)
2621 static void rollback_packed_refs(void)
2623 struct packed_ref_cache *packed_ref_cache =
2624 get_packed_ref_cache(&ref_cache);
2626 if (!packed_ref_cache->lock)
2627 die("internal error: packed-refs not locked");
2628 rollback_lock_file(packed_ref_cache->lock);
2629 packed_ref_cache->lock = NULL;
2630 release_packed_ref_cache(packed_ref_cache);
2631 clear_packed_ref_cache(&ref_cache);
2634 struct ref_to_prune {
2635 struct ref_to_prune *next;
2636 unsigned char sha1[20];
2637 char name[FLEX_ARRAY];
2640 struct pack_refs_cb_data {
2642 struct ref_dir *packed_refs;
2643 struct ref_to_prune *ref_to_prune;
2647 * An each_ref_entry_fn that is run over loose references only. If
2648 * the loose reference can be packed, add an entry in the packed ref
2649 * cache. If the reference should be pruned, also add it to
2650 * ref_to_prune in the pack_refs_cb_data.
2652 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2654 struct pack_refs_cb_data *cb = cb_data;
2655 enum peel_status peel_status;
2656 struct ref_entry *packed_entry;
2657 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2659 /* ALWAYS pack tags */
2660 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2663 /* Do not pack symbolic or broken refs: */
2664 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2667 /* Add a packed ref cache entry equivalent to the loose entry. */
2668 peel_status = peel_entry(entry, 1);
2669 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2670 die("internal error peeling reference %s (%s)",
2671 entry->name, oid_to_hex(&entry->u.value.oid));
2672 packed_entry = find_ref(cb->packed_refs, entry->name);
2674 /* Overwrite existing packed entry with info from loose entry */
2675 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2676 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2678 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2679 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2680 add_ref(cb->packed_refs, packed_entry);
2682 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2684 /* Schedule the loose reference for pruning if requested. */
2685 if ((cb->flags & PACK_REFS_PRUNE)) {
2686 int namelen = strlen(entry->name) + 1;
2687 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2688 hashcpy(n->sha1, entry->u.value.oid.hash);
2689 strcpy(n->name, entry->name);
2690 n->next = cb->ref_to_prune;
2691 cb->ref_to_prune = n;
2697 * Remove empty parents, but spare refs/ and immediate subdirs.
2698 * Note: munges *name.
2700 static void try_remove_empty_parents(char *name)
2705 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2706 while (*p && *p != '/')
2708 /* tolerate duplicate slashes; see check_refname_format() */
2712 for (q = p; *q; q++)
2715 while (q > p && *q != '/')
2717 while (q > p && *(q-1) == '/')
2722 if (rmdir(git_path("%s", name)))
2727 /* make sure nobody touched the ref, and unlink */
2728 static void prune_ref(struct ref_to_prune *r)
2730 struct ref_transaction *transaction;
2731 struct strbuf err = STRBUF_INIT;
2733 if (check_refname_format(r->name, 0))
2736 transaction = ref_transaction_begin(&err);
2738 ref_transaction_delete(transaction, r->name, r->sha1,
2739 REF_ISPRUNING, NULL, &err) ||
2740 ref_transaction_commit(transaction, &err)) {
2741 ref_transaction_free(transaction);
2742 error("%s", err.buf);
2743 strbuf_release(&err);
2746 ref_transaction_free(transaction);
2747 strbuf_release(&err);
2748 try_remove_empty_parents(r->name);
2751 static void prune_refs(struct ref_to_prune *r)
2759 int pack_refs(unsigned int flags)
2761 struct pack_refs_cb_data cbdata;
2763 memset(&cbdata, 0, sizeof(cbdata));
2764 cbdata.flags = flags;
2766 lock_packed_refs(LOCK_DIE_ON_ERROR);
2767 cbdata.packed_refs = get_packed_refs(&ref_cache);
2769 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2770 pack_if_possible_fn, &cbdata);
2772 if (commit_packed_refs())
2773 die_errno("unable to overwrite old ref-pack file");
2775 prune_refs(cbdata.ref_to_prune);
2780 * Rewrite the packed-refs file, omitting any refs listed in
2781 * 'refnames'. On error, leave packed-refs unchanged, write an error
2782 * message to 'err', and return a nonzero value.
2784 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2786 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2788 struct ref_dir *packed;
2789 struct string_list_item *refname;
2790 int ret, needs_repacking = 0, removed = 0;
2794 /* Look for a packed ref */
2795 for_each_string_list_item(refname, refnames) {
2796 if (get_packed_ref(refname->string)) {
2797 needs_repacking = 1;
2802 /* Avoid locking if we have nothing to do */
2803 if (!needs_repacking)
2804 return 0; /* no refname exists in packed refs */
2806 if (lock_packed_refs(0)) {
2807 unable_to_lock_message(git_path("packed-refs"), errno, err);
2810 packed = get_packed_refs(&ref_cache);
2812 /* Remove refnames from the cache */
2813 for_each_string_list_item(refname, refnames)
2814 if (remove_entry(packed, refname->string) != -1)
2818 * All packed entries disappeared while we were
2819 * acquiring the lock.
2821 rollback_packed_refs();
2825 /* Write what remains */
2826 ret = commit_packed_refs();
2828 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2833 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2837 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2839 * loose. The loose file name is the same as the
2840 * lockfile name, minus ".lock":
2842 char *loose_filename = get_locked_file_path(lock->lk);
2843 int res = unlink_or_msg(loose_filename, err);
2844 free(loose_filename);
2851 int delete_ref(const char *refname, const unsigned char *old_sha1,
2854 struct ref_transaction *transaction;
2855 struct strbuf err = STRBUF_INIT;
2857 transaction = ref_transaction_begin(&err);
2859 ref_transaction_delete(transaction, refname, old_sha1,
2860 flags, NULL, &err) ||
2861 ref_transaction_commit(transaction, &err)) {
2862 error("%s", err.buf);
2863 ref_transaction_free(transaction);
2864 strbuf_release(&err);
2867 ref_transaction_free(transaction);
2868 strbuf_release(&err);
2872 int delete_refs(struct string_list *refnames)
2874 struct strbuf err = STRBUF_INIT;
2880 result = repack_without_refs(refnames, &err);
2883 * If we failed to rewrite the packed-refs file, then
2884 * it is unsafe to try to remove loose refs, because
2885 * doing so might expose an obsolete packed value for
2886 * a reference that might even point at an object that
2887 * has been garbage collected.
2889 if (refnames->nr == 1)
2890 error(_("could not delete reference %s: %s"),
2891 refnames->items[0].string, err.buf);
2893 error(_("could not delete references: %s"), err.buf);
2898 for (i = 0; i < refnames->nr; i++) {
2899 const char *refname = refnames->items[i].string;
2901 if (delete_ref(refname, NULL, 0))
2902 result |= error(_("could not remove reference %s"), refname);
2906 strbuf_release(&err);
2911 * People using contrib's git-new-workdir have .git/logs/refs ->
2912 * /some/other/path/.git/logs/refs, and that may live on another device.
2914 * IOW, to avoid cross device rename errors, the temporary renamed log must
2915 * live into logs/refs.
2917 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2919 static int rename_tmp_log(const char *newrefname)
2921 int attempts_remaining = 4;
2924 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {
2926 break; /* success */
2928 if (--attempts_remaining > 0)
2932 error("unable to create directory for %s", newrefname);
2936 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2937 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2939 * rename(a, b) when b is an existing
2940 * directory ought to result in ISDIR, but
2941 * Solaris 5.8 gives ENOTDIR. Sheesh.
2943 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2944 error("Directory not empty: logs/%s", newrefname);
2948 } else if (errno == ENOENT && --attempts_remaining > 0) {
2950 * Maybe another process just deleted one of
2951 * the directories in the path to newrefname.
2952 * Try again from the beginning.
2956 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2957 newrefname, strerror(errno));
2964 static int rename_ref_available(const char *oldname, const char *newname)
2966 struct string_list skip = STRING_LIST_INIT_NODUP;
2967 struct strbuf err = STRBUF_INIT;
2970 string_list_insert(&skip, oldname);
2971 ret = !verify_refname_available(newname, NULL, &skip,
2972 get_packed_refs(&ref_cache), &err)
2973 && !verify_refname_available(newname, NULL, &skip,
2974 get_loose_refs(&ref_cache), &err);
2976 error("%s", err.buf);
2978 string_list_clear(&skip, 0);
2979 strbuf_release(&err);
2983 static int write_ref_to_lockfile(struct ref_lock *lock,
2984 const unsigned char *sha1, struct strbuf *err);
2985 static int commit_ref_update(struct ref_lock *lock,
2986 const unsigned char *sha1, const char *logmsg,
2987 int flags, struct strbuf *err);
2989 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2991 unsigned char sha1[20], orig_sha1[20];
2992 int flag = 0, logmoved = 0;
2993 struct ref_lock *lock;
2994 struct stat loginfo;
2995 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2996 const char *symref = NULL;
2997 struct strbuf err = STRBUF_INIT;
2999 if (log && S_ISLNK(loginfo.st_mode))
3000 return error("reflog for %s is a symlink", oldrefname);
3002 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
3004 if (flag & REF_ISSYMREF)
3005 return error("refname %s is a symbolic ref, renaming it is not supported",
3008 return error("refname %s not found", oldrefname);
3010 if (!rename_ref_available(oldrefname, newrefname))
3013 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3014 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3015 oldrefname, strerror(errno));
3017 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3018 error("unable to delete old %s", oldrefname);
3022 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3023 delete_ref(newrefname, sha1, REF_NODEREF)) {
3024 if (errno==EISDIR) {
3025 if (remove_empty_directories(git_path("%s", newrefname))) {
3026 error("Directory not empty: %s", newrefname);
3030 error("unable to delete existing %s", newrefname);
3035 if (log && rename_tmp_log(newrefname))
3040 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3042 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3043 strbuf_release(&err);
3046 hashcpy(lock->old_oid.hash, orig_sha1);
3048 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3049 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
3050 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
3051 strbuf_release(&err);
3058 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3060 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3061 strbuf_release(&err);
3065 flag = log_all_ref_updates;
3066 log_all_ref_updates = 0;
3067 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3068 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
3069 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
3070 strbuf_release(&err);
3072 log_all_ref_updates = flag;
3075 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3076 error("unable to restore logfile %s from %s: %s",
3077 oldrefname, newrefname, strerror(errno));
3078 if (!logmoved && log &&
3079 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3080 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3081 oldrefname, strerror(errno));
3086 static int close_ref(struct ref_lock *lock)
3088 if (close_lock_file(lock->lk))
3093 static int commit_ref(struct ref_lock *lock)
3095 if (commit_lock_file(lock->lk))
3101 * copy the reflog message msg to buf, which has been allocated sufficiently
3102 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3103 * because reflog file is one line per entry.
3105 static int copy_msg(char *buf, const char *msg)
3112 while ((c = *msg++)) {
3113 if (wasspace && isspace(c))
3115 wasspace = isspace(c);
3120 while (buf < cp && isspace(cp[-1]))
3126 static int should_autocreate_reflog(const char *refname)
3128 if (!log_all_ref_updates)
3130 return starts_with(refname, "refs/heads/") ||
3131 starts_with(refname, "refs/remotes/") ||
3132 starts_with(refname, "refs/notes/") ||
3133 !strcmp(refname, "HEAD");
3137 * Create a reflog for a ref. If force_create = 0, the reflog will
3138 * only be created for certain refs (those for which
3139 * should_autocreate_reflog returns non-zero. Otherwise, create it
3140 * regardless of the ref name. Fill in *err and return -1 on failure.
3142 static int log_ref_setup(const char *refname, struct strbuf *sb_logfile, struct strbuf *err, int force_create)
3144 int logfd, oflags = O_APPEND | O_WRONLY;
3147 strbuf_git_path(sb_logfile, "logs/%s", refname);
3148 logfile = sb_logfile->buf;
3149 /* make sure the rest of the function can't change "logfile" */
3151 if (force_create || should_autocreate_reflog(refname)) {
3152 if (safe_create_leading_directories(logfile) < 0) {
3153 strbuf_addf(err, "unable to create directory for %s: "
3154 "%s", logfile, strerror(errno));
3160 logfd = open(logfile, oflags, 0666);
3162 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3165 if (errno == EISDIR) {
3166 if (remove_empty_directories(logfile)) {
3167 strbuf_addf(err, "There are still logs under "
3171 logfd = open(logfile, oflags, 0666);
3175 strbuf_addf(err, "unable to append to %s: %s",
3176 logfile, strerror(errno));
3181 adjust_shared_perm(logfile);
3187 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
3190 struct strbuf sb = STRBUF_INIT;
3192 ret = log_ref_setup(refname, &sb, err, force_create);
3193 strbuf_release(&sb);
3197 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3198 const unsigned char *new_sha1,
3199 const char *committer, const char *msg)
3201 int msglen, written;
3202 unsigned maxlen, len;
3205 msglen = msg ? strlen(msg) : 0;
3206 maxlen = strlen(committer) + msglen + 100;
3207 logrec = xmalloc(maxlen);
3208 len = sprintf(logrec, "%s %s %s\n",
3209 sha1_to_hex(old_sha1),
3210 sha1_to_hex(new_sha1),
3213 len += copy_msg(logrec + len - 1, msg) - 1;
3215 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3223 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3224 const unsigned char *new_sha1, const char *msg,
3225 struct strbuf *sb_log_file, int flags,
3228 int logfd, result, oflags = O_APPEND | O_WRONLY;
3231 if (log_all_ref_updates < 0)
3232 log_all_ref_updates = !is_bare_repository();
3234 result = log_ref_setup(refname, sb_log_file, err, flags & REF_FORCE_CREATE_REFLOG);
3238 log_file = sb_log_file->buf;
3239 /* make sure the rest of the function can't change "log_file" */
3242 logfd = open(log_file, oflags);
3245 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3246 git_committer_info(0), msg);
3248 strbuf_addf(err, "unable to append to %s: %s", log_file,
3254 strbuf_addf(err, "unable to append to %s: %s", log_file,
3261 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3262 const unsigned char *new_sha1, const char *msg,
3263 int flags, struct strbuf *err)
3265 struct strbuf sb = STRBUF_INIT;
3266 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
3268 strbuf_release(&sb);
3272 int is_branch(const char *refname)
3274 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3278 * Write sha1 into the open lockfile, then close the lockfile. On
3279 * errors, rollback the lockfile, fill in *err and
3282 static int write_ref_to_lockfile(struct ref_lock *lock,
3283 const unsigned char *sha1, struct strbuf *err)
3285 static char term = '\n';
3288 o = parse_object(sha1);
3291 "Trying to write ref %s with nonexistent object %s",
3292 lock->ref_name, sha1_to_hex(sha1));
3296 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3298 "Trying to write non-commit object %s to branch %s",
3299 sha1_to_hex(sha1), lock->ref_name);
3303 if (write_in_full(lock->lk->fd, sha1_to_hex(sha1), 40) != 40 ||
3304 write_in_full(lock->lk->fd, &term, 1) != 1 ||
3305 close_ref(lock) < 0) {
3307 "Couldn't write %s", lock->lk->filename.buf);
3315 * Commit a change to a loose reference that has already been written
3316 * to the loose reference lockfile. Also update the reflogs if
3317 * necessary, using the specified lockmsg (which can be NULL).
3319 static int commit_ref_update(struct ref_lock *lock,
3320 const unsigned char *sha1, const char *logmsg,
3321 int flags, struct strbuf *err)
3323 clear_loose_ref_cache(&ref_cache);
3324 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
3325 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3326 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
3327 char *old_msg = strbuf_detach(err, NULL);
3328 strbuf_addf(err, "Cannot update the ref '%s': %s",
3329 lock->ref_name, old_msg);
3334 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3336 * Special hack: If a branch is updated directly and HEAD
3337 * points to it (may happen on the remote side of a push
3338 * for example) then logically the HEAD reflog should be
3340 * A generic solution implies reverse symref information,
3341 * but finding all symrefs pointing to the given branch
3342 * would be rather costly for this rare event (the direct
3343 * update of a branch) to be worth it. So let's cheat and
3344 * check with HEAD only which should cover 99% of all usage
3345 * scenarios (even 100% of the default ones).
3347 unsigned char head_sha1[20];
3349 const char *head_ref;
3350 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3351 head_sha1, &head_flag);
3352 if (head_ref && (head_flag & REF_ISSYMREF) &&
3353 !strcmp(head_ref, lock->ref_name)) {
3354 struct strbuf log_err = STRBUF_INIT;
3355 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
3356 logmsg, 0, &log_err)) {
3357 error("%s", log_err.buf);
3358 strbuf_release(&log_err);
3362 if (commit_ref(lock)) {
3363 error("Couldn't set %s", lock->ref_name);
3372 int create_symref(const char *ref_target, const char *refs_heads_master,
3375 const char *lockpath;
3377 int fd, len, written;
3378 char *git_HEAD = git_pathdup("%s", ref_target);
3379 unsigned char old_sha1[20], new_sha1[20];
3380 struct strbuf err = STRBUF_INIT;
3382 if (logmsg && read_ref(ref_target, old_sha1))
3385 if (safe_create_leading_directories(git_HEAD) < 0)
3386 return error("unable to create directory for %s", git_HEAD);
3388 #ifndef NO_SYMLINK_HEAD
3389 if (prefer_symlink_refs) {
3391 if (!symlink(refs_heads_master, git_HEAD))
3393 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3397 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3398 if (sizeof(ref) <= len) {
3399 error("refname too long: %s", refs_heads_master);
3400 goto error_free_return;
3402 lockpath = mkpath("%s.lock", git_HEAD);
3403 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3405 error("Unable to open %s for writing", lockpath);
3406 goto error_free_return;
3408 written = write_in_full(fd, ref, len);
3409 if (close(fd) != 0 || written != len) {
3410 error("Unable to write to %s", lockpath);
3411 goto error_unlink_return;
3413 if (rename(lockpath, git_HEAD) < 0) {
3414 error("Unable to create %s", git_HEAD);
3415 goto error_unlink_return;
3417 if (adjust_shared_perm(git_HEAD)) {
3418 error("Unable to fix permissions on %s", lockpath);
3419 error_unlink_return:
3420 unlink_or_warn(lockpath);
3426 #ifndef NO_SYMLINK_HEAD
3429 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
3430 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
3431 error("%s", err.buf);
3432 strbuf_release(&err);
3439 struct read_ref_at_cb {
3440 const char *refname;
3441 unsigned long at_time;
3444 unsigned char *sha1;
3447 unsigned char osha1[20];
3448 unsigned char nsha1[20];
3452 unsigned long *cutoff_time;
3457 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3458 const char *email, unsigned long timestamp, int tz,
3459 const char *message, void *cb_data)
3461 struct read_ref_at_cb *cb = cb_data;
3465 cb->date = timestamp;
3467 if (timestamp <= cb->at_time || cb->cnt == 0) {
3469 *cb->msg = xstrdup(message);
3470 if (cb->cutoff_time)
3471 *cb->cutoff_time = timestamp;
3473 *cb->cutoff_tz = tz;
3475 *cb->cutoff_cnt = cb->reccnt - 1;
3477 * we have not yet updated cb->[n|o]sha1 so they still
3478 * hold the values for the previous record.
3480 if (!is_null_sha1(cb->osha1)) {
3481 hashcpy(cb->sha1, nsha1);
3482 if (hashcmp(cb->osha1, nsha1))
3483 warning("Log for ref %s has gap after %s.",
3484 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
3486 else if (cb->date == cb->at_time)
3487 hashcpy(cb->sha1, nsha1);
3488 else if (hashcmp(nsha1, cb->sha1))
3489 warning("Log for ref %s unexpectedly ended on %s.",
3490 cb->refname, show_date(cb->date, cb->tz,
3491 DATE_MODE(RFC2822)));
3492 hashcpy(cb->osha1, osha1);
3493 hashcpy(cb->nsha1, nsha1);
3497 hashcpy(cb->osha1, osha1);
3498 hashcpy(cb->nsha1, nsha1);
3504 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3505 const char *email, unsigned long timestamp,
3506 int tz, const char *message, void *cb_data)
3508 struct read_ref_at_cb *cb = cb_data;
3511 *cb->msg = xstrdup(message);
3512 if (cb->cutoff_time)
3513 *cb->cutoff_time = timestamp;
3515 *cb->cutoff_tz = tz;
3517 *cb->cutoff_cnt = cb->reccnt;
3518 hashcpy(cb->sha1, osha1);
3519 if (is_null_sha1(cb->sha1))
3520 hashcpy(cb->sha1, nsha1);
3521 /* We just want the first entry */
3525 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3526 unsigned char *sha1, char **msg,
3527 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3529 struct read_ref_at_cb cb;
3531 memset(&cb, 0, sizeof(cb));
3532 cb.refname = refname;
3533 cb.at_time = at_time;
3536 cb.cutoff_time = cutoff_time;
3537 cb.cutoff_tz = cutoff_tz;
3538 cb.cutoff_cnt = cutoff_cnt;
3541 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3544 if (flags & GET_SHA1_QUIETLY)
3547 die("Log for %s is empty.", refname);
3552 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3557 int reflog_exists(const char *refname)
3561 return !lstat(git_path("logs/%s", refname), &st) &&
3562 S_ISREG(st.st_mode);
3565 int delete_reflog(const char *refname)
3567 return remove_path(git_path("logs/%s", refname));
3570 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3572 unsigned char osha1[20], nsha1[20];
3573 char *email_end, *message;
3574 unsigned long timestamp;
3577 /* old SP new SP name <email> SP time TAB msg LF */
3578 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3579 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3580 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3581 !(email_end = strchr(sb->buf + 82, '>')) ||
3582 email_end[1] != ' ' ||
3583 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3584 !message || message[0] != ' ' ||
3585 (message[1] != '+' && message[1] != '-') ||
3586 !isdigit(message[2]) || !isdigit(message[3]) ||
3587 !isdigit(message[4]) || !isdigit(message[5]))
3588 return 0; /* corrupt? */
3589 email_end[1] = '\0';
3590 tz = strtol(message + 1, NULL, 10);
3591 if (message[6] != '\t')
3595 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3598 static char *find_beginning_of_line(char *bob, char *scan)
3600 while (bob < scan && *(--scan) != '\n')
3601 ; /* keep scanning backwards */
3603 * Return either beginning of the buffer, or LF at the end of
3604 * the previous line.
3609 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3611 struct strbuf sb = STRBUF_INIT;
3614 int ret = 0, at_tail = 1;
3616 logfp = fopen(git_path("logs/%s", refname), "r");
3620 /* Jump to the end */
3621 if (fseek(logfp, 0, SEEK_END) < 0)
3622 return error("cannot seek back reflog for %s: %s",
3623 refname, strerror(errno));
3625 while (!ret && 0 < pos) {
3631 /* Fill next block from the end */
3632 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3633 if (fseek(logfp, pos - cnt, SEEK_SET))
3634 return error("cannot seek back reflog for %s: %s",
3635 refname, strerror(errno));
3636 nread = fread(buf, cnt, 1, logfp);
3638 return error("cannot read %d bytes from reflog for %s: %s",
3639 cnt, refname, strerror(errno));
3642 scanp = endp = buf + cnt;
3643 if (at_tail && scanp[-1] == '\n')
3644 /* Looking at the final LF at the end of the file */
3648 while (buf < scanp) {
3650 * terminating LF of the previous line, or the beginning
3655 bp = find_beginning_of_line(buf, scanp);
3659 * The newline is the end of the previous line,
3660 * so we know we have complete line starting
3661 * at (bp + 1). Prefix it onto any prior data
3662 * we collected for the line and process it.
3664 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3667 ret = show_one_reflog_ent(&sb, fn, cb_data);
3673 * We are at the start of the buffer, and the
3674 * start of the file; there is no previous
3675 * line, and we have everything for this one.
3676 * Process it, and we can end the loop.
3678 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3679 ret = show_one_reflog_ent(&sb, fn, cb_data);
3686 * We are at the start of the buffer, and there
3687 * is more file to read backwards. Which means
3688 * we are in the middle of a line. Note that we
3689 * may get here even if *bp was a newline; that
3690 * just means we are at the exact end of the
3691 * previous line, rather than some spot in the
3694 * Save away what we have to be combined with
3695 * the data from the next read.
3697 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3704 die("BUG: reverse reflog parser had leftover data");
3707 strbuf_release(&sb);
3711 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3714 struct strbuf sb = STRBUF_INIT;
3717 logfp = fopen(git_path("logs/%s", refname), "r");
3721 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3722 ret = show_one_reflog_ent(&sb, fn, cb_data);
3724 strbuf_release(&sb);
3728 * Call fn for each reflog in the namespace indicated by name. name
3729 * must be empty or end with '/'. Name will be used as a scratch
3730 * space, but its contents will be restored before return.
3732 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3734 DIR *d = opendir(git_path("logs/%s", name->buf));
3737 int oldlen = name->len;
3740 return name->len ? errno : 0;
3742 while ((de = readdir(d)) != NULL) {
3745 if (de->d_name[0] == '.')
3747 if (ends_with(de->d_name, ".lock"))
3749 strbuf_addstr(name, de->d_name);
3750 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3751 ; /* silently ignore */
3753 if (S_ISDIR(st.st_mode)) {
3754 strbuf_addch(name, '/');
3755 retval = do_for_each_reflog(name, fn, cb_data);
3757 struct object_id oid;
3759 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3760 retval = error("bad ref for %s", name->buf);
3762 retval = fn(name->buf, &oid, 0, cb_data);
3767 strbuf_setlen(name, oldlen);
3773 int for_each_reflog(each_ref_fn fn, void *cb_data)
3777 strbuf_init(&name, PATH_MAX);
3778 retval = do_for_each_reflog(&name, fn, cb_data);
3779 strbuf_release(&name);
3784 * Information needed for a single ref update. Set new_sha1 to the new
3785 * value or to null_sha1 to delete the ref. To check the old value
3786 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3787 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3788 * not exist before update.
3792 * If (flags & REF_HAVE_NEW), set the reference to this value:
3794 unsigned char new_sha1[20];
3796 * If (flags & REF_HAVE_OLD), check that the reference
3797 * previously had this value:
3799 unsigned char old_sha1[20];
3801 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3802 * REF_DELETING, and REF_ISPRUNING:
3805 struct ref_lock *lock;
3808 const char refname[FLEX_ARRAY];
3812 * Transaction states.
3813 * OPEN: The transaction is in a valid state and can accept new updates.
3814 * An OPEN transaction can be committed.
3815 * CLOSED: A closed transaction is no longer active and no other operations
3816 * than free can be used on it in this state.
3817 * A transaction can either become closed by successfully committing
3818 * an active transaction or if there is a failure while building
3819 * the transaction thus rendering it failed/inactive.
3821 enum ref_transaction_state {
3822 REF_TRANSACTION_OPEN = 0,
3823 REF_TRANSACTION_CLOSED = 1
3827 * Data structure for holding a reference transaction, which can
3828 * consist of checks and updates to multiple references, carried out
3829 * as atomically as possible. This structure is opaque to callers.
3831 struct ref_transaction {
3832 struct ref_update **updates;
3835 enum ref_transaction_state state;
3838 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3842 return xcalloc(1, sizeof(struct ref_transaction));
3845 void ref_transaction_free(struct ref_transaction *transaction)
3852 for (i = 0; i < transaction->nr; i++) {
3853 free(transaction->updates[i]->msg);
3854 free(transaction->updates[i]);
3856 free(transaction->updates);
3860 static struct ref_update *add_update(struct ref_transaction *transaction,
3861 const char *refname)
3863 size_t len = strlen(refname);
3864 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3866 strcpy((char *)update->refname, refname);
3867 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3868 transaction->updates[transaction->nr++] = update;
3872 int ref_transaction_update(struct ref_transaction *transaction,
3873 const char *refname,
3874 const unsigned char *new_sha1,
3875 const unsigned char *old_sha1,
3876 unsigned int flags, const char *msg,
3879 struct ref_update *update;
3883 if (transaction->state != REF_TRANSACTION_OPEN)
3884 die("BUG: update called for transaction that is not open");
3886 if (new_sha1 && !is_null_sha1(new_sha1) &&
3887 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3888 strbuf_addf(err, "refusing to update ref with bad name %s",
3893 update = add_update(transaction, refname);
3895 hashcpy(update->new_sha1, new_sha1);
3896 flags |= REF_HAVE_NEW;
3899 hashcpy(update->old_sha1, old_sha1);
3900 flags |= REF_HAVE_OLD;
3902 update->flags = flags;
3904 update->msg = xstrdup(msg);
3908 int ref_transaction_create(struct ref_transaction *transaction,
3909 const char *refname,
3910 const unsigned char *new_sha1,
3911 unsigned int flags, const char *msg,
3914 if (!new_sha1 || is_null_sha1(new_sha1))
3915 die("BUG: create called without valid new_sha1");
3916 return ref_transaction_update(transaction, refname, new_sha1,
3917 null_sha1, flags, msg, err);
3920 int ref_transaction_delete(struct ref_transaction *transaction,
3921 const char *refname,
3922 const unsigned char *old_sha1,
3923 unsigned int flags, const char *msg,
3926 if (old_sha1 && is_null_sha1(old_sha1))
3927 die("BUG: delete called with old_sha1 set to zeros");
3928 return ref_transaction_update(transaction, refname,
3929 null_sha1, old_sha1,
3933 int ref_transaction_verify(struct ref_transaction *transaction,
3934 const char *refname,
3935 const unsigned char *old_sha1,
3940 die("BUG: verify called with old_sha1 set to NULL");
3941 return ref_transaction_update(transaction, refname,
3946 int update_ref(const char *msg, const char *refname,
3947 const unsigned char *new_sha1, const unsigned char *old_sha1,
3948 unsigned int flags, enum action_on_err onerr)
3950 struct ref_transaction *t;
3951 struct strbuf err = STRBUF_INIT;
3953 t = ref_transaction_begin(&err);
3955 ref_transaction_update(t, refname, new_sha1, old_sha1,
3956 flags, msg, &err) ||
3957 ref_transaction_commit(t, &err)) {
3958 const char *str = "update_ref failed for ref '%s': %s";
3960 ref_transaction_free(t);
3962 case UPDATE_REFS_MSG_ON_ERR:
3963 error(str, refname, err.buf);
3965 case UPDATE_REFS_DIE_ON_ERR:
3966 die(str, refname, err.buf);
3968 case UPDATE_REFS_QUIET_ON_ERR:
3971 strbuf_release(&err);
3974 strbuf_release(&err);
3975 ref_transaction_free(t);
3979 static int ref_update_reject_duplicates(struct string_list *refnames,
3982 int i, n = refnames->nr;
3986 for (i = 1; i < n; i++)
3987 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3989 "Multiple updates for ref '%s' not allowed.",
3990 refnames->items[i].string);
3996 int ref_transaction_commit(struct ref_transaction *transaction,
4000 int n = transaction->nr;
4001 struct ref_update **updates = transaction->updates;
4002 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
4003 struct string_list_item *ref_to_delete;
4004 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4008 if (transaction->state != REF_TRANSACTION_OPEN)
4009 die("BUG: commit called for transaction that is not open");
4012 transaction->state = REF_TRANSACTION_CLOSED;
4016 /* Fail if a refname appears more than once in the transaction: */
4017 for (i = 0; i < n; i++)
4018 string_list_append(&affected_refnames, updates[i]->refname);
4019 string_list_sort(&affected_refnames);
4020 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4021 ret = TRANSACTION_GENERIC_ERROR;
4026 * Acquire all locks, verify old values if provided, check
4027 * that new values are valid, and write new values to the
4028 * lockfiles, ready to be activated. Only keep one lockfile
4029 * open at a time to avoid running out of file descriptors.
4031 for (i = 0; i < n; i++) {
4032 struct ref_update *update = updates[i];
4034 if ((update->flags & REF_HAVE_NEW) &&
4035 is_null_sha1(update->new_sha1))
4036 update->flags |= REF_DELETING;
4037 update->lock = lock_ref_sha1_basic(
4039 ((update->flags & REF_HAVE_OLD) ?
4040 update->old_sha1 : NULL),
4041 &affected_refnames, NULL,
4045 if (!update->lock) {
4048 ret = (errno == ENOTDIR)
4049 ? TRANSACTION_NAME_CONFLICT
4050 : TRANSACTION_GENERIC_ERROR;
4051 reason = strbuf_detach(err, NULL);
4052 strbuf_addf(err, "cannot lock ref '%s': %s",
4053 update->refname, reason);
4057 if ((update->flags & REF_HAVE_NEW) &&
4058 !(update->flags & REF_DELETING)) {
4059 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4060 (update->flags & REF_NODEREF));
4062 if (!overwriting_symref &&
4063 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4065 * The reference already has the desired
4066 * value, so we don't need to write it.
4068 } else if (write_ref_to_lockfile(update->lock,
4071 char *write_err = strbuf_detach(err, NULL);
4074 * The lock was freed upon failure of
4075 * write_ref_to_lockfile():
4077 update->lock = NULL;
4079 "cannot update the ref '%s': %s",
4080 update->refname, write_err);
4082 ret = TRANSACTION_GENERIC_ERROR;
4085 update->flags |= REF_NEEDS_COMMIT;
4088 if (!(update->flags & REF_NEEDS_COMMIT)) {
4090 * We didn't have to write anything to the lockfile.
4091 * Close it to free up the file descriptor:
4093 if (close_ref(update->lock)) {
4094 strbuf_addf(err, "Couldn't close %s.lock",
4101 /* Perform updates first so live commits remain referenced */
4102 for (i = 0; i < n; i++) {
4103 struct ref_update *update = updates[i];
4105 if (update->flags & REF_NEEDS_COMMIT) {
4106 if (commit_ref_update(update->lock,
4107 update->new_sha1, update->msg,
4108 update->flags, err)) {
4109 /* freed by commit_ref_update(): */
4110 update->lock = NULL;
4111 ret = TRANSACTION_GENERIC_ERROR;
4114 /* freed by commit_ref_update(): */
4115 update->lock = NULL;
4120 /* Perform deletes now that updates are safely completed */
4121 for (i = 0; i < n; i++) {
4122 struct ref_update *update = updates[i];
4124 if (update->flags & REF_DELETING) {
4125 if (delete_ref_loose(update->lock, update->type, err)) {
4126 ret = TRANSACTION_GENERIC_ERROR;
4130 if (!(update->flags & REF_ISPRUNING))
4131 string_list_append(&refs_to_delete,
4132 update->lock->ref_name);
4136 if (repack_without_refs(&refs_to_delete, err)) {
4137 ret = TRANSACTION_GENERIC_ERROR;
4140 for_each_string_list_item(ref_to_delete, &refs_to_delete)
4141 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4142 clear_loose_ref_cache(&ref_cache);
4145 transaction->state = REF_TRANSACTION_CLOSED;
4147 for (i = 0; i < n; i++)
4148 if (updates[i]->lock)
4149 unlock_ref(updates[i]->lock);
4150 string_list_clear(&refs_to_delete, 0);
4151 string_list_clear(&affected_refnames, 0);
4155 static int ref_present(const char *refname,
4156 const struct object_id *oid, int flags, void *cb_data)
4158 struct string_list *affected_refnames = cb_data;
4160 return string_list_has_string(affected_refnames, refname);
4163 int initial_ref_transaction_commit(struct ref_transaction *transaction,
4166 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
4167 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
4169 int n = transaction->nr;
4170 struct ref_update **updates = transaction->updates;
4171 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4175 if (transaction->state != REF_TRANSACTION_OPEN)
4176 die("BUG: commit called for transaction that is not open");
4178 /* Fail if a refname appears more than once in the transaction: */
4179 for (i = 0; i < n; i++)
4180 string_list_append(&affected_refnames, updates[i]->refname);
4181 string_list_sort(&affected_refnames);
4182 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4183 ret = TRANSACTION_GENERIC_ERROR;
4188 * It's really undefined to call this function in an active
4189 * repository or when there are existing references: we are
4190 * only locking and changing packed-refs, so (1) any
4191 * simultaneous processes might try to change a reference at
4192 * the same time we do, and (2) any existing loose versions of
4193 * the references that we are setting would have precedence
4194 * over our values. But some remote helpers create the remote
4195 * "HEAD" and "master" branches before calling this function,
4196 * so here we really only check that none of the references
4197 * that we are creating already exists.
4199 if (for_each_rawref(ref_present, &affected_refnames))
4200 die("BUG: initial ref transaction called with existing refs");
4202 for (i = 0; i < n; i++) {
4203 struct ref_update *update = updates[i];
4205 if ((update->flags & REF_HAVE_OLD) &&
4206 !is_null_sha1(update->old_sha1))
4207 die("BUG: initial ref transaction with old_sha1 set");
4208 if (verify_refname_available(update->refname,
4209 &affected_refnames, NULL,
4211 verify_refname_available(update->refname,
4212 &affected_refnames, NULL,
4213 packed_refs, err)) {
4214 ret = TRANSACTION_NAME_CONFLICT;
4219 if (lock_packed_refs(0)) {
4220 strbuf_addf(err, "unable to lock packed-refs file: %s",
4222 ret = TRANSACTION_GENERIC_ERROR;
4226 for (i = 0; i < n; i++) {
4227 struct ref_update *update = updates[i];
4229 if ((update->flags & REF_HAVE_NEW) &&
4230 !is_null_sha1(update->new_sha1))
4231 add_packed_ref(update->refname, update->new_sha1);
4234 if (commit_packed_refs()) {
4235 strbuf_addf(err, "unable to commit packed-refs file: %s",
4237 ret = TRANSACTION_GENERIC_ERROR;
4242 transaction->state = REF_TRANSACTION_CLOSED;
4243 string_list_clear(&affected_refnames, 0);
4247 char *shorten_unambiguous_ref(const char *refname, int strict)
4250 static char **scanf_fmts;
4251 static int nr_rules;
4256 * Pre-generate scanf formats from ref_rev_parse_rules[].
4257 * Generate a format suitable for scanf from a
4258 * ref_rev_parse_rules rule by interpolating "%s" at the
4259 * location of the "%.*s".
4261 size_t total_len = 0;
4264 /* the rule list is NULL terminated, count them first */
4265 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4266 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4267 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4269 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4272 for (i = 0; i < nr_rules; i++) {
4273 assert(offset < total_len);
4274 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4275 offset += snprintf(scanf_fmts[i], total_len - offset,
4276 ref_rev_parse_rules[i], 2, "%s") + 1;
4280 /* bail out if there are no rules */
4282 return xstrdup(refname);
4284 /* buffer for scanf result, at most refname must fit */
4285 short_name = xstrdup(refname);
4287 /* skip first rule, it will always match */
4288 for (i = nr_rules - 1; i > 0 ; --i) {
4290 int rules_to_fail = i;
4293 if (1 != sscanf(refname, scanf_fmts[i], short_name))
4296 short_name_len = strlen(short_name);
4299 * in strict mode, all (except the matched one) rules
4300 * must fail to resolve to a valid non-ambiguous ref
4303 rules_to_fail = nr_rules;
4306 * check if the short name resolves to a valid ref,
4307 * but use only rules prior to the matched one
4309 for (j = 0; j < rules_to_fail; j++) {
4310 const char *rule = ref_rev_parse_rules[j];
4311 char refname[PATH_MAX];
4313 /* skip matched rule */
4318 * the short name is ambiguous, if it resolves
4319 * (with this previous rule) to a valid ref
4320 * read_ref() returns 0 on success
4322 mksnpath(refname, sizeof(refname),
4323 rule, short_name_len, short_name);
4324 if (ref_exists(refname))
4329 * short name is non-ambiguous if all previous rules
4330 * haven't resolved to a valid ref
4332 if (j == rules_to_fail)
4337 return xstrdup(refname);
4340 static struct string_list *hide_refs;
4342 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4344 if (!strcmp("transfer.hiderefs", var) ||
4345 /* NEEDSWORK: use parse_config_key() once both are merged */
4346 (starts_with(var, section) && var[strlen(section)] == '.' &&
4347 !strcmp(var + strlen(section), ".hiderefs"))) {
4352 return config_error_nonbool(var);
4353 ref = xstrdup(value);
4355 while (len && ref[len - 1] == '/')
4358 hide_refs = xcalloc(1, sizeof(*hide_refs));
4359 hide_refs->strdup_strings = 1;
4361 string_list_append(hide_refs, ref);
4366 int ref_is_hidden(const char *refname)
4368 struct string_list_item *item;
4372 for_each_string_list_item(item, hide_refs) {
4374 if (!starts_with(refname, item->string))
4376 len = strlen(item->string);
4377 if (!refname[len] || refname[len] == '/')
4383 struct expire_reflog_cb {
4385 reflog_expiry_should_prune_fn *should_prune_fn;
4388 unsigned char last_kept_sha1[20];
4391 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4392 const char *email, unsigned long timestamp, int tz,
4393 const char *message, void *cb_data)
4395 struct expire_reflog_cb *cb = cb_data;
4396 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4398 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4399 osha1 = cb->last_kept_sha1;
4401 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4402 message, policy_cb)) {
4404 printf("would prune %s", message);
4405 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4406 printf("prune %s", message);
4409 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4410 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4411 email, timestamp, tz, message);
4412 hashcpy(cb->last_kept_sha1, nsha1);
4414 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4415 printf("keep %s", message);
4420 int reflog_expire(const char *refname, const unsigned char *sha1,
4422 reflog_expiry_prepare_fn prepare_fn,
4423 reflog_expiry_should_prune_fn should_prune_fn,
4424 reflog_expiry_cleanup_fn cleanup_fn,
4425 void *policy_cb_data)
4427 static struct lock_file reflog_lock;
4428 struct expire_reflog_cb cb;
4429 struct ref_lock *lock;
4433 struct strbuf err = STRBUF_INIT;
4435 memset(&cb, 0, sizeof(cb));
4437 cb.policy_cb = policy_cb_data;
4438 cb.should_prune_fn = should_prune_fn;
4441 * The reflog file is locked by holding the lock on the
4442 * reference itself, plus we might need to update the
4443 * reference if --updateref was specified:
4445 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4447 error("cannot lock ref '%s': %s", refname, err.buf);
4448 strbuf_release(&err);
4451 if (!reflog_exists(refname)) {
4456 log_file = git_pathdup("logs/%s", refname);
4457 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4459 * Even though holding $GIT_DIR/logs/$reflog.lock has
4460 * no locking implications, we use the lock_file
4461 * machinery here anyway because it does a lot of the
4462 * work we need, including cleaning up if the program
4463 * exits unexpectedly.
4465 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4466 struct strbuf err = STRBUF_INIT;
4467 unable_to_lock_message(log_file, errno, &err);
4468 error("%s", err.buf);
4469 strbuf_release(&err);
4472 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4474 error("cannot fdopen %s (%s)",
4475 reflog_lock.filename.buf, strerror(errno));
4480 (*prepare_fn)(refname, sha1, cb.policy_cb);
4481 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4482 (*cleanup_fn)(cb.policy_cb);
4484 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4486 * It doesn't make sense to adjust a reference pointed
4487 * to by a symbolic ref based on expiring entries in
4488 * the symbolic reference's reflog. Nor can we update
4489 * a reference if there are no remaining reflog
4492 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4493 !(type & REF_ISSYMREF) &&
4494 !is_null_sha1(cb.last_kept_sha1);
4496 if (close_lock_file(&reflog_lock)) {
4497 status |= error("couldn't write %s: %s", log_file,
4499 } else if (update &&
4500 (write_in_full(lock->lk->fd,
4501 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4502 write_str_in_full(lock->lk->fd, "\n") != 1 ||
4503 close_ref(lock) < 0)) {
4504 status |= error("couldn't write %s",
4505 lock->lk->filename.buf);
4506 rollback_lock_file(&reflog_lock);
4507 } else if (commit_lock_file(&reflog_lock)) {
4508 status |= error("unable to commit reflog '%s' (%s)",
4509 log_file, strerror(errno));
4510 } else if (update && commit_ref(lock)) {
4511 status |= error("couldn't set %s", lock->ref_name);
4519 rollback_lock_file(&reflog_lock);