7 #include "string-list.h"
13 unsigned char old_sha1[20];
18 * How to handle various characters in refnames:
19 * 0: An acceptable character for refs
21 * 2: ., look for a preceding . to reject .. in refs
22 * 3: {, look for a preceding @ to reject @{ in refs
23 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
25 static unsigned char refname_disposition[256] = {
26 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
37 * Used as a flag to ref_transaction_delete when a loose ref is being
40 #define REF_ISPRUNING 0x0100
42 * Try to read one refname component from the front of refname.
43 * Return the length of the component found, or -1 if the component is
44 * not legal. It is legal if it is something reasonable to have under
45 * ".git/refs/"; We do not like it if:
47 * - any path component of it begins with ".", or
48 * - it has double dots "..", or
49 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
50 * - it ends with a "/".
51 * - it ends with ".lock"
52 * - it contains a "\" (backslash)
54 static int check_refname_component(const char *refname, int flags)
59 for (cp = refname; ; cp++) {
61 unsigned char disp = refname_disposition[ch];
67 return -1; /* Refname contains "..". */
71 return -1; /* Refname contains "@{". */
80 return 0; /* Component has zero length. */
81 if (refname[0] == '.')
82 return -1; /* Component starts with '.'. */
83 if (cp - refname >= LOCK_SUFFIX_LEN &&
84 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
85 return -1; /* Refname ends with ".lock". */
89 int check_refname_format(const char *refname, int flags)
91 int component_len, component_count = 0;
93 if (!strcmp(refname, "@"))
94 /* Refname is a single character '@'. */
98 /* We are at the start of a path component. */
99 component_len = check_refname_component(refname, flags);
100 if (component_len <= 0) {
101 if ((flags & REFNAME_REFSPEC_PATTERN) &&
103 (refname[1] == '\0' || refname[1] == '/')) {
104 /* Accept one wildcard as a full refname component. */
105 flags &= ~REFNAME_REFSPEC_PATTERN;
112 if (refname[component_len] == '\0')
114 /* Skip to next component. */
115 refname += component_len + 1;
118 if (refname[component_len - 1] == '.')
119 return -1; /* Refname ends with '.'. */
120 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
121 return -1; /* Refname has only one component. */
128 * Information used (along with the information in ref_entry) to
129 * describe a single cached reference. This data structure only
130 * occurs embedded in a union in struct ref_entry, and only when
131 * (ref_entry->flag & REF_DIR) is zero.
135 * The name of the object to which this reference resolves
136 * (which may be a tag object). If REF_ISBROKEN, this is
137 * null. If REF_ISSYMREF, then this is the name of the object
138 * referred to by the last reference in the symlink chain.
140 unsigned char sha1[20];
143 * If REF_KNOWS_PEELED, then this field holds the peeled value
144 * of this reference, or null if the reference is known not to
145 * be peelable. See the documentation for peel_ref() for an
146 * exact definition of "peelable".
148 unsigned char peeled[20];
154 * Information used (along with the information in ref_entry) to
155 * describe a level in the hierarchy of references. This data
156 * structure only occurs embedded in a union in struct ref_entry, and
157 * only when (ref_entry.flag & REF_DIR) is set. In that case,
158 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
159 * in the directory have already been read:
161 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
162 * or packed references, already read.
164 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
165 * references that hasn't been read yet (nor has any of its
168 * Entries within a directory are stored within a growable array of
169 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
170 * sorted are sorted by their component name in strcmp() order and the
171 * remaining entries are unsorted.
173 * Loose references are read lazily, one directory at a time. When a
174 * directory of loose references is read, then all of the references
175 * in that directory are stored, and REF_INCOMPLETE stubs are created
176 * for any subdirectories, but the subdirectories themselves are not
177 * read. The reading is triggered by get_ref_dir().
183 * Entries with index 0 <= i < sorted are sorted by name. New
184 * entries are appended to the list unsorted, and are sorted
185 * only when required; thus we avoid the need to sort the list
186 * after the addition of every reference.
190 /* A pointer to the ref_cache that contains this ref_dir. */
191 struct ref_cache *ref_cache;
193 struct ref_entry **entries;
197 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
198 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
199 * public values; see refs.h.
203 * The field ref_entry->u.value.peeled of this value entry contains
204 * the correct peeled value for the reference, which might be
205 * null_sha1 if the reference is not a tag or if it is broken.
207 #define REF_KNOWS_PEELED 0x10
209 /* ref_entry represents a directory of references */
213 * Entry has not yet been read from disk (used only for REF_DIR
214 * entries representing loose references)
216 #define REF_INCOMPLETE 0x40
219 * A ref_entry represents either a reference or a "subdirectory" of
222 * Each directory in the reference namespace is represented by a
223 * ref_entry with (flags & REF_DIR) set and containing a subdir member
224 * that holds the entries in that directory that have been read so
225 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
226 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
227 * used for loose reference directories.
229 * References are represented by a ref_entry with (flags & REF_DIR)
230 * unset and a value member that describes the reference's value. The
231 * flag member is at the ref_entry level, but it is also needed to
232 * interpret the contents of the value field (in other words, a
233 * ref_value object is not very much use without the enclosing
236 * Reference names cannot end with slash and directories' names are
237 * always stored with a trailing slash (except for the top-level
238 * directory, which is always denoted by ""). This has two nice
239 * consequences: (1) when the entries in each subdir are sorted
240 * lexicographically by name (as they usually are), the references in
241 * a whole tree can be generated in lexicographic order by traversing
242 * the tree in left-to-right, depth-first order; (2) the names of
243 * references and subdirectories cannot conflict, and therefore the
244 * presence of an empty subdirectory does not block the creation of a
245 * similarly-named reference. (The fact that reference names with the
246 * same leading components can conflict *with each other* is a
247 * separate issue that is regulated by is_refname_available().)
249 * Please note that the name field contains the fully-qualified
250 * reference (or subdirectory) name. Space could be saved by only
251 * storing the relative names. But that would require the full names
252 * to be generated on the fly when iterating in do_for_each_ref(), and
253 * would break callback functions, who have always been able to assume
254 * that the name strings that they are passed will not be freed during
258 unsigned char flag; /* ISSYMREF? ISPACKED? */
260 struct ref_value value; /* if not (flags&REF_DIR) */
261 struct ref_dir subdir; /* if (flags&REF_DIR) */
264 * The full name of the reference (e.g., "refs/heads/master")
265 * or the full name of the directory with a trailing slash
266 * (e.g., "refs/heads/"):
268 char name[FLEX_ARRAY];
271 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
273 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
276 assert(entry->flag & REF_DIR);
277 dir = &entry->u.subdir;
278 if (entry->flag & REF_INCOMPLETE) {
279 read_loose_refs(entry->name, dir);
280 entry->flag &= ~REF_INCOMPLETE;
286 * Check if a refname is safe.
287 * For refs that start with "refs/" we consider it safe as long they do
288 * not try to resolve to outside of refs/.
290 * For all other refs we only consider them safe iff they only contain
291 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
294 static int refname_is_safe(const char *refname)
296 if (starts_with(refname, "refs/")) {
300 buf = xmalloc(strlen(refname) + 1);
302 * Does the refname try to escape refs/?
303 * For example: refs/foo/../bar is safe but refs/foo/../../bar
306 result = !normalize_path_copy(buf, refname + strlen("refs/"));
311 if (!isupper(*refname) && *refname != '_')
318 static struct ref_entry *create_ref_entry(const char *refname,
319 const unsigned char *sha1, int flag,
323 struct ref_entry *ref;
326 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
327 die("Reference has invalid format: '%s'", refname);
328 if (!check_name && !refname_is_safe(refname))
329 die("Reference has invalid name: '%s'", refname);
330 len = strlen(refname) + 1;
331 ref = xmalloc(sizeof(struct ref_entry) + len);
332 hashcpy(ref->u.value.sha1, sha1);
333 hashclr(ref->u.value.peeled);
334 memcpy(ref->name, refname, len);
339 static void clear_ref_dir(struct ref_dir *dir);
341 static void free_ref_entry(struct ref_entry *entry)
343 if (entry->flag & REF_DIR) {
345 * Do not use get_ref_dir() here, as that might
346 * trigger the reading of loose refs.
348 clear_ref_dir(&entry->u.subdir);
354 * Add a ref_entry to the end of dir (unsorted). Entry is always
355 * stored directly in dir; no recursion into subdirectories is
358 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
360 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
361 dir->entries[dir->nr++] = entry;
362 /* optimize for the case that entries are added in order */
364 (dir->nr == dir->sorted + 1 &&
365 strcmp(dir->entries[dir->nr - 2]->name,
366 dir->entries[dir->nr - 1]->name) < 0))
367 dir->sorted = dir->nr;
371 * Clear and free all entries in dir, recursively.
373 static void clear_ref_dir(struct ref_dir *dir)
376 for (i = 0; i < dir->nr; i++)
377 free_ref_entry(dir->entries[i]);
379 dir->sorted = dir->nr = dir->alloc = 0;
384 * Create a struct ref_entry object for the specified dirname.
385 * dirname is the name of the directory with a trailing slash (e.g.,
386 * "refs/heads/") or "" for the top-level directory.
388 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
389 const char *dirname, size_t len,
392 struct ref_entry *direntry;
393 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
394 memcpy(direntry->name, dirname, len);
395 direntry->name[len] = '\0';
396 direntry->u.subdir.ref_cache = ref_cache;
397 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
401 static int ref_entry_cmp(const void *a, const void *b)
403 struct ref_entry *one = *(struct ref_entry **)a;
404 struct ref_entry *two = *(struct ref_entry **)b;
405 return strcmp(one->name, two->name);
408 static void sort_ref_dir(struct ref_dir *dir);
410 struct string_slice {
415 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
417 const struct string_slice *key = key_;
418 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
419 int cmp = strncmp(key->str, ent->name, key->len);
422 return '\0' - (unsigned char)ent->name[key->len];
426 * Return the index of the entry with the given refname from the
427 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
428 * no such entry is found. dir must already be complete.
430 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
432 struct ref_entry **r;
433 struct string_slice key;
435 if (refname == NULL || !dir->nr)
441 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
442 ref_entry_cmp_sslice);
447 return r - dir->entries;
451 * Search for a directory entry directly within dir (without
452 * recursing). Sort dir if necessary. subdirname must be a directory
453 * name (i.e., end in '/'). If mkdir is set, then create the
454 * directory if it is missing; otherwise, return NULL if the desired
455 * directory cannot be found. dir must already be complete.
457 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
458 const char *subdirname, size_t len,
461 int entry_index = search_ref_dir(dir, subdirname, len);
462 struct ref_entry *entry;
463 if (entry_index == -1) {
467 * Since dir is complete, the absence of a subdir
468 * means that the subdir really doesn't exist;
469 * therefore, create an empty record for it but mark
470 * the record complete.
472 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
473 add_entry_to_dir(dir, entry);
475 entry = dir->entries[entry_index];
477 return get_ref_dir(entry);
481 * If refname is a reference name, find the ref_dir within the dir
482 * tree that should hold refname. If refname is a directory name
483 * (i.e., ends in '/'), then return that ref_dir itself. dir must
484 * represent the top-level directory and must already be complete.
485 * Sort ref_dirs and recurse into subdirectories as necessary. If
486 * mkdir is set, then create any missing directories; otherwise,
487 * return NULL if the desired directory cannot be found.
489 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
490 const char *refname, int mkdir)
493 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
494 size_t dirnamelen = slash - refname + 1;
495 struct ref_dir *subdir;
496 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
508 * Find the value entry with the given name in dir, sorting ref_dirs
509 * and recursing into subdirectories as necessary. If the name is not
510 * found or it corresponds to a directory entry, return NULL.
512 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
515 struct ref_entry *entry;
516 dir = find_containing_dir(dir, refname, 0);
519 entry_index = search_ref_dir(dir, refname, strlen(refname));
520 if (entry_index == -1)
522 entry = dir->entries[entry_index];
523 return (entry->flag & REF_DIR) ? NULL : entry;
527 * Remove the entry with the given name from dir, recursing into
528 * subdirectories as necessary. If refname is the name of a directory
529 * (i.e., ends with '/'), then remove the directory and its contents.
530 * If the removal was successful, return the number of entries
531 * remaining in the directory entry that contained the deleted entry.
532 * If the name was not found, return -1. Please note that this
533 * function only deletes the entry from the cache; it does not delete
534 * it from the filesystem or ensure that other cache entries (which
535 * might be symbolic references to the removed entry) are updated.
536 * Nor does it remove any containing dir entries that might be made
537 * empty by the removal. dir must represent the top-level directory
538 * and must already be complete.
540 static int remove_entry(struct ref_dir *dir, const char *refname)
542 int refname_len = strlen(refname);
544 struct ref_entry *entry;
545 int is_dir = refname[refname_len - 1] == '/';
548 * refname represents a reference directory. Remove
549 * the trailing slash; otherwise we will get the
550 * directory *representing* refname rather than the
551 * one *containing* it.
553 char *dirname = xmemdupz(refname, refname_len - 1);
554 dir = find_containing_dir(dir, dirname, 0);
557 dir = find_containing_dir(dir, refname, 0);
561 entry_index = search_ref_dir(dir, refname, refname_len);
562 if (entry_index == -1)
564 entry = dir->entries[entry_index];
566 memmove(&dir->entries[entry_index],
567 &dir->entries[entry_index + 1],
568 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
571 if (dir->sorted > entry_index)
573 free_ref_entry(entry);
578 * Add a ref_entry to the ref_dir (unsorted), recursing into
579 * subdirectories as necessary. dir must represent the top-level
580 * directory. Return 0 on success.
582 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
584 dir = find_containing_dir(dir, ref->name, 1);
587 add_entry_to_dir(dir, ref);
592 * Emit a warning and return true iff ref1 and ref2 have the same name
593 * and the same sha1. Die if they have the same name but different
596 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
598 if (strcmp(ref1->name, ref2->name))
601 /* Duplicate name; make sure that they don't conflict: */
603 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
604 /* This is impossible by construction */
605 die("Reference directory conflict: %s", ref1->name);
607 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
608 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
610 warning("Duplicated ref: %s", ref1->name);
615 * Sort the entries in dir non-recursively (if they are not already
616 * sorted) and remove any duplicate entries.
618 static void sort_ref_dir(struct ref_dir *dir)
621 struct ref_entry *last = NULL;
624 * This check also prevents passing a zero-length array to qsort(),
625 * which is a problem on some platforms.
627 if (dir->sorted == dir->nr)
630 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
632 /* Remove any duplicates: */
633 for (i = 0, j = 0; j < dir->nr; j++) {
634 struct ref_entry *entry = dir->entries[j];
635 if (last && is_dup_ref(last, entry))
636 free_ref_entry(entry);
638 last = dir->entries[i++] = entry;
640 dir->sorted = dir->nr = i;
643 /* Include broken references in a do_for_each_ref*() iteration: */
644 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
647 * Return true iff the reference described by entry can be resolved to
648 * an object in the database. Emit a warning if the referred-to
649 * object does not exist.
651 static int ref_resolves_to_object(struct ref_entry *entry)
653 if (entry->flag & REF_ISBROKEN)
655 if (!has_sha1_file(entry->u.value.sha1)) {
656 error("%s does not point to a valid object!", entry->name);
663 * current_ref is a performance hack: when iterating over references
664 * using the for_each_ref*() functions, current_ref is set to the
665 * current reference's entry before calling the callback function. If
666 * the callback function calls peel_ref(), then peel_ref() first
667 * checks whether the reference to be peeled is the current reference
668 * (it usually is) and if so, returns that reference's peeled version
669 * if it is available. This avoids a refname lookup in a common case.
671 static struct ref_entry *current_ref;
673 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
675 struct ref_entry_cb {
684 * Handle one reference in a do_for_each_ref*()-style iteration,
685 * calling an each_ref_fn for each entry.
687 static int do_one_ref(struct ref_entry *entry, void *cb_data)
689 struct ref_entry_cb *data = cb_data;
690 struct ref_entry *old_current_ref;
693 if (!starts_with(entry->name, data->base))
696 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
697 !ref_resolves_to_object(entry))
700 /* Store the old value, in case this is a recursive call: */
701 old_current_ref = current_ref;
703 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
704 entry->flag, data->cb_data);
705 current_ref = old_current_ref;
710 * Call fn for each reference in dir that has index in the range
711 * offset <= index < dir->nr. Recurse into subdirectories that are in
712 * that index range, sorting them before iterating. This function
713 * does not sort dir itself; it should be sorted beforehand. fn is
714 * called for all references, including broken ones.
716 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
717 each_ref_entry_fn fn, void *cb_data)
720 assert(dir->sorted == dir->nr);
721 for (i = offset; i < dir->nr; i++) {
722 struct ref_entry *entry = dir->entries[i];
724 if (entry->flag & REF_DIR) {
725 struct ref_dir *subdir = get_ref_dir(entry);
726 sort_ref_dir(subdir);
727 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
729 retval = fn(entry, cb_data);
738 * Call fn for each reference in the union of dir1 and dir2, in order
739 * by refname. Recurse into subdirectories. If a value entry appears
740 * in both dir1 and dir2, then only process the version that is in
741 * dir2. The input dirs must already be sorted, but subdirs will be
742 * sorted as needed. fn is called for all references, including
745 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
746 struct ref_dir *dir2,
747 each_ref_entry_fn fn, void *cb_data)
752 assert(dir1->sorted == dir1->nr);
753 assert(dir2->sorted == dir2->nr);
755 struct ref_entry *e1, *e2;
757 if (i1 == dir1->nr) {
758 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
760 if (i2 == dir2->nr) {
761 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
763 e1 = dir1->entries[i1];
764 e2 = dir2->entries[i2];
765 cmp = strcmp(e1->name, e2->name);
767 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
768 /* Both are directories; descend them in parallel. */
769 struct ref_dir *subdir1 = get_ref_dir(e1);
770 struct ref_dir *subdir2 = get_ref_dir(e2);
771 sort_ref_dir(subdir1);
772 sort_ref_dir(subdir2);
773 retval = do_for_each_entry_in_dirs(
774 subdir1, subdir2, fn, cb_data);
777 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
778 /* Both are references; ignore the one from dir1. */
779 retval = fn(e2, cb_data);
783 die("conflict between reference and directory: %s",
795 if (e->flag & REF_DIR) {
796 struct ref_dir *subdir = get_ref_dir(e);
797 sort_ref_dir(subdir);
798 retval = do_for_each_entry_in_dir(
799 subdir, 0, fn, cb_data);
801 retval = fn(e, cb_data);
810 * Load all of the refs from the dir into our in-memory cache. The hard work
811 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
812 * through all of the sub-directories. We do not even need to care about
813 * sorting, as traversal order does not matter to us.
815 static void prime_ref_dir(struct ref_dir *dir)
818 for (i = 0; i < dir->nr; i++) {
819 struct ref_entry *entry = dir->entries[i];
820 if (entry->flag & REF_DIR)
821 prime_ref_dir(get_ref_dir(entry));
825 static int entry_matches(struct ref_entry *entry, const struct string_list *list)
827 return list && string_list_has_string(list, entry->name);
830 struct nonmatching_ref_data {
831 const struct string_list *skip;
832 struct ref_entry *found;
835 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
837 struct nonmatching_ref_data *data = vdata;
839 if (entry_matches(entry, data->skip))
846 static void report_refname_conflict(struct ref_entry *entry,
849 error("'%s' exists; cannot create '%s'", entry->name, refname);
853 * Return true iff a reference named refname could be created without
854 * conflicting with the name of an existing reference in dir. If
855 * skip is non-NULL, ignore potential conflicts with refs in skip
856 * (e.g., because they are scheduled for deletion in the same
859 * Two reference names conflict if one of them exactly matches the
860 * leading components of the other; e.g., "foo/bar" conflicts with
861 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
864 * skip must be sorted.
866 static int is_refname_available(const char *refname,
867 const struct string_list *skip,
875 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
877 * We are still at a leading dir of the refname; we are
878 * looking for a conflict with a leaf entry.
880 * If we find one, we still must make sure it is
883 pos = search_ref_dir(dir, refname, slash - refname);
885 struct ref_entry *entry = dir->entries[pos];
886 if (entry_matches(entry, skip))
888 report_refname_conflict(entry, refname);
894 * Otherwise, we can try to continue our search with
895 * the next component; if we come up empty, we know
896 * there is nothing under this whole prefix.
898 pos = search_ref_dir(dir, refname, slash + 1 - refname);
902 dir = get_ref_dir(dir->entries[pos]);
906 * We are at the leaf of our refname; we want to
907 * make sure there are no directories which match it.
909 len = strlen(refname);
910 dirname = xmallocz(len + 1);
911 sprintf(dirname, "%s/", refname);
912 pos = search_ref_dir(dir, dirname, len + 1);
917 * We found a directory named "refname". It is a
918 * problem iff it contains any ref that is not
921 struct ref_entry *entry = dir->entries[pos];
922 struct ref_dir *dir = get_ref_dir(entry);
923 struct nonmatching_ref_data data;
927 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data))
930 report_refname_conflict(data.found, refname);
935 * There is no point in searching for another leaf
936 * node which matches it; such an entry would be the
937 * ref we are looking for, not a conflict.
942 struct packed_ref_cache {
943 struct ref_entry *root;
946 * Count of references to the data structure in this instance,
947 * including the pointer from ref_cache::packed if any. The
948 * data will not be freed as long as the reference count is
951 unsigned int referrers;
954 * Iff the packed-refs file associated with this instance is
955 * currently locked for writing, this points at the associated
956 * lock (which is owned by somebody else). The referrer count
957 * is also incremented when the file is locked and decremented
958 * when it is unlocked.
960 struct lock_file *lock;
962 /* The metadata from when this packed-refs cache was read */
963 struct stat_validity validity;
967 * Future: need to be in "struct repository"
968 * when doing a full libification.
970 static struct ref_cache {
971 struct ref_cache *next;
972 struct ref_entry *loose;
973 struct packed_ref_cache *packed;
975 * The submodule name, or "" for the main repo. We allocate
976 * length 1 rather than FLEX_ARRAY so that the main ref_cache
977 * is initialized correctly.
980 } ref_cache, *submodule_ref_caches;
982 /* Lock used for the main packed-refs file: */
983 static struct lock_file packlock;
986 * Increment the reference count of *packed_refs.
988 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
990 packed_refs->referrers++;
994 * Decrease the reference count of *packed_refs. If it goes to zero,
995 * free *packed_refs and return true; otherwise return false.
997 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
999 if (!--packed_refs->referrers) {
1000 free_ref_entry(packed_refs->root);
1001 stat_validity_clear(&packed_refs->validity);
1009 static void clear_packed_ref_cache(struct ref_cache *refs)
1012 struct packed_ref_cache *packed_refs = refs->packed;
1014 if (packed_refs->lock)
1015 die("internal error: packed-ref cache cleared while locked");
1016 refs->packed = NULL;
1017 release_packed_ref_cache(packed_refs);
1021 static void clear_loose_ref_cache(struct ref_cache *refs)
1024 free_ref_entry(refs->loose);
1029 static struct ref_cache *create_ref_cache(const char *submodule)
1032 struct ref_cache *refs;
1035 len = strlen(submodule) + 1;
1036 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1037 memcpy(refs->name, submodule, len);
1042 * Return a pointer to a ref_cache for the specified submodule. For
1043 * the main repository, use submodule==NULL. The returned structure
1044 * will be allocated and initialized but not necessarily populated; it
1045 * should not be freed.
1047 static struct ref_cache *get_ref_cache(const char *submodule)
1049 struct ref_cache *refs;
1051 if (!submodule || !*submodule)
1054 for (refs = submodule_ref_caches; refs; refs = refs->next)
1055 if (!strcmp(submodule, refs->name))
1058 refs = create_ref_cache(submodule);
1059 refs->next = submodule_ref_caches;
1060 submodule_ref_caches = refs;
1064 /* The length of a peeled reference line in packed-refs, including EOL: */
1065 #define PEELED_LINE_LENGTH 42
1068 * The packed-refs header line that we write out. Perhaps other
1069 * traits will be added later. The trailing space is required.
1071 static const char PACKED_REFS_HEADER[] =
1072 "# pack-refs with: peeled fully-peeled \n";
1075 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1076 * Return a pointer to the refname within the line (null-terminated),
1077 * or NULL if there was a problem.
1079 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1084 * 42: the answer to everything.
1086 * In this case, it happens to be the answer to
1087 * 40 (length of sha1 hex representation)
1088 * +1 (space in between hex and name)
1089 * +1 (newline at the end of the line)
1091 if (line->len <= 42)
1094 if (get_sha1_hex(line->buf, sha1) < 0)
1096 if (!isspace(line->buf[40]))
1099 ref = line->buf + 41;
1103 if (line->buf[line->len - 1] != '\n')
1105 line->buf[--line->len] = 0;
1111 * Read f, which is a packed-refs file, into dir.
1113 * A comment line of the form "# pack-refs with: " may contain zero or
1114 * more traits. We interpret the traits as follows:
1118 * Probably no references are peeled. But if the file contains a
1119 * peeled value for a reference, we will use it.
1123 * References under "refs/tags/", if they *can* be peeled, *are*
1124 * peeled in this file. References outside of "refs/tags/" are
1125 * probably not peeled even if they could have been, but if we find
1126 * a peeled value for such a reference we will use it.
1130 * All references in the file that can be peeled are peeled.
1131 * Inversely (and this is more important), any references in the
1132 * file for which no peeled value is recorded is not peelable. This
1133 * trait should typically be written alongside "peeled" for
1134 * compatibility with older clients, but we do not require it
1135 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1137 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1139 struct ref_entry *last = NULL;
1140 struct strbuf line = STRBUF_INIT;
1141 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1143 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1144 unsigned char sha1[20];
1145 const char *refname;
1148 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1149 if (strstr(traits, " fully-peeled "))
1150 peeled = PEELED_FULLY;
1151 else if (strstr(traits, " peeled "))
1152 peeled = PEELED_TAGS;
1153 /* perhaps other traits later as well */
1157 refname = parse_ref_line(&line, sha1);
1159 int flag = REF_ISPACKED;
1161 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1163 flag |= REF_BAD_NAME | REF_ISBROKEN;
1165 last = create_ref_entry(refname, sha1, flag, 0);
1166 if (peeled == PEELED_FULLY ||
1167 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1168 last->flag |= REF_KNOWS_PEELED;
1173 line.buf[0] == '^' &&
1174 line.len == PEELED_LINE_LENGTH &&
1175 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1176 !get_sha1_hex(line.buf + 1, sha1)) {
1177 hashcpy(last->u.value.peeled, sha1);
1179 * Regardless of what the file header said,
1180 * we definitely know the value of *this*
1183 last->flag |= REF_KNOWS_PEELED;
1187 strbuf_release(&line);
1191 * Get the packed_ref_cache for the specified ref_cache, creating it
1194 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1196 const char *packed_refs_file;
1199 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1201 packed_refs_file = git_path("packed-refs");
1204 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1205 clear_packed_ref_cache(refs);
1207 if (!refs->packed) {
1210 refs->packed = xcalloc(1, sizeof(*refs->packed));
1211 acquire_packed_ref_cache(refs->packed);
1212 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1213 f = fopen(packed_refs_file, "r");
1215 stat_validity_update(&refs->packed->validity, fileno(f));
1216 read_packed_refs(f, get_ref_dir(refs->packed->root));
1220 return refs->packed;
1223 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1225 return get_ref_dir(packed_ref_cache->root);
1228 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1230 return get_packed_ref_dir(get_packed_ref_cache(refs));
1233 void add_packed_ref(const char *refname, const unsigned char *sha1)
1235 struct packed_ref_cache *packed_ref_cache =
1236 get_packed_ref_cache(&ref_cache);
1238 if (!packed_ref_cache->lock)
1239 die("internal error: packed refs not locked");
1240 add_ref(get_packed_ref_dir(packed_ref_cache),
1241 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1245 * Read the loose references from the namespace dirname into dir
1246 * (without recursing). dirname must end with '/'. dir must be the
1247 * directory entry corresponding to dirname.
1249 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1251 struct ref_cache *refs = dir->ref_cache;
1255 int dirnamelen = strlen(dirname);
1256 struct strbuf refname;
1259 path = git_path_submodule(refs->name, "%s", dirname);
1261 path = git_path("%s", dirname);
1267 strbuf_init(&refname, dirnamelen + 257);
1268 strbuf_add(&refname, dirname, dirnamelen);
1270 while ((de = readdir(d)) != NULL) {
1271 unsigned char sha1[20];
1276 if (de->d_name[0] == '.')
1278 if (ends_with(de->d_name, ".lock"))
1280 strbuf_addstr(&refname, de->d_name);
1281 refdir = *refs->name
1282 ? git_path_submodule(refs->name, "%s", refname.buf)
1283 : git_path("%s", refname.buf);
1284 if (stat(refdir, &st) < 0) {
1285 ; /* silently ignore */
1286 } else if (S_ISDIR(st.st_mode)) {
1287 strbuf_addch(&refname, '/');
1288 add_entry_to_dir(dir,
1289 create_dir_entry(refs, refname.buf,
1295 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1297 flag |= REF_ISBROKEN;
1299 } else if (read_ref_full(refname.buf,
1300 RESOLVE_REF_READING,
1303 flag |= REF_ISBROKEN;
1305 if (check_refname_format(refname.buf,
1306 REFNAME_ALLOW_ONELEVEL)) {
1308 flag |= REF_BAD_NAME | REF_ISBROKEN;
1310 add_entry_to_dir(dir,
1311 create_ref_entry(refname.buf, sha1, flag, 0));
1313 strbuf_setlen(&refname, dirnamelen);
1315 strbuf_release(&refname);
1319 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1323 * Mark the top-level directory complete because we
1324 * are about to read the only subdirectory that can
1327 refs->loose = create_dir_entry(refs, "", 0, 0);
1329 * Create an incomplete entry for "refs/":
1331 add_entry_to_dir(get_ref_dir(refs->loose),
1332 create_dir_entry(refs, "refs/", 5, 1));
1334 return get_ref_dir(refs->loose);
1337 /* We allow "recursive" symbolic refs. Only within reason, though */
1339 #define MAXREFLEN (1024)
1342 * Called by resolve_gitlink_ref_recursive() after it failed to read
1343 * from the loose refs in ref_cache refs. Find <refname> in the
1344 * packed-refs file for the submodule.
1346 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1347 const char *refname, unsigned char *sha1)
1349 struct ref_entry *ref;
1350 struct ref_dir *dir = get_packed_refs(refs);
1352 ref = find_ref(dir, refname);
1356 hashcpy(sha1, ref->u.value.sha1);
1360 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1361 const char *refname, unsigned char *sha1,
1365 char buffer[128], *p;
1368 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1371 ? git_path_submodule(refs->name, "%s", refname)
1372 : git_path("%s", refname);
1373 fd = open(path, O_RDONLY);
1375 return resolve_gitlink_packed_ref(refs, refname, sha1);
1377 len = read(fd, buffer, sizeof(buffer)-1);
1381 while (len && isspace(buffer[len-1]))
1385 /* Was it a detached head or an old-fashioned symlink? */
1386 if (!get_sha1_hex(buffer, sha1))
1390 if (strncmp(buffer, "ref:", 4))
1396 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1399 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1401 int len = strlen(path), retval;
1403 struct ref_cache *refs;
1405 while (len && path[len-1] == '/')
1409 submodule = xstrndup(path, len);
1410 refs = get_ref_cache(submodule);
1413 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1418 * Return the ref_entry for the given refname from the packed
1419 * references. If it does not exist, return NULL.
1421 static struct ref_entry *get_packed_ref(const char *refname)
1423 return find_ref(get_packed_refs(&ref_cache), refname);
1427 * A loose ref file doesn't exist; check for a packed ref. The
1428 * options are forwarded from resolve_safe_unsafe().
1430 static int resolve_missing_loose_ref(const char *refname,
1432 unsigned char *sha1,
1435 struct ref_entry *entry;
1438 * The loose reference file does not exist; check for a packed
1441 entry = get_packed_ref(refname);
1443 hashcpy(sha1, entry->u.value.sha1);
1445 *flags |= REF_ISPACKED;
1448 /* The reference is not a packed reference, either. */
1449 if (resolve_flags & RESOLVE_REF_READING) {
1458 /* This function needs to return a meaningful errno on failure */
1459 const char *resolve_ref_unsafe(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1461 int depth = MAXDEPTH;
1464 static char refname_buffer[256];
1470 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1472 *flags |= REF_BAD_NAME;
1474 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1475 !refname_is_safe(refname)) {
1480 * dwim_ref() uses REF_ISBROKEN to distinguish between
1481 * missing refs and refs that were present but invalid,
1482 * to complain about the latter to stderr.
1484 * We don't know whether the ref exists, so don't set
1490 char path[PATH_MAX];
1500 git_snpath(path, sizeof(path), "%s", refname);
1503 * We might have to loop back here to avoid a race
1504 * condition: first we lstat() the file, then we try
1505 * to read it as a link or as a file. But if somebody
1506 * changes the type of the file (file <-> directory
1507 * <-> symlink) between the lstat() and reading, then
1508 * we don't want to report that as an error but rather
1509 * try again starting with the lstat().
1512 if (lstat(path, &st) < 0) {
1513 if (errno != ENOENT)
1515 if (resolve_missing_loose_ref(refname, resolve_flags,
1521 *flags |= REF_ISBROKEN;
1526 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1527 if (S_ISLNK(st.st_mode)) {
1528 len = readlink(path, buffer, sizeof(buffer)-1);
1530 if (errno == ENOENT || errno == EINVAL)
1531 /* inconsistent with lstat; retry */
1537 if (starts_with(buffer, "refs/") &&
1538 !check_refname_format(buffer, 0)) {
1539 strcpy(refname_buffer, buffer);
1540 refname = refname_buffer;
1542 *flags |= REF_ISSYMREF;
1543 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1551 /* Is it a directory? */
1552 if (S_ISDIR(st.st_mode)) {
1558 * Anything else, just open it and try to use it as
1561 fd = open(path, O_RDONLY);
1563 if (errno == ENOENT)
1564 /* inconsistent with lstat; retry */
1569 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1571 int save_errno = errno;
1577 while (len && isspace(buffer[len-1]))
1582 * Is it a symbolic ref?
1584 if (!starts_with(buffer, "ref:")) {
1586 * Please note that FETCH_HEAD has a second
1587 * line containing other data.
1589 if (get_sha1_hex(buffer, sha1) ||
1590 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1592 *flags |= REF_ISBROKEN;
1599 *flags |= REF_ISBROKEN;
1604 *flags |= REF_ISSYMREF;
1606 while (isspace(*buf))
1608 refname = strcpy(refname_buffer, buf);
1609 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1613 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1615 *flags |= REF_ISBROKEN;
1617 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1618 !refname_is_safe(buf)) {
1627 char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)
1629 const char *ret = resolve_ref_unsafe(ref, resolve_flags, sha1, flags);
1630 return ret ? xstrdup(ret) : NULL;
1633 /* The argument to filter_refs */
1635 const char *pattern;
1640 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1642 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1647 int read_ref(const char *refname, unsigned char *sha1)
1649 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1652 int ref_exists(const char *refname)
1654 unsigned char sha1[20];
1655 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1658 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1661 struct ref_filter *filter = (struct ref_filter *)data;
1662 if (wildmatch(filter->pattern, refname, 0, NULL))
1664 return filter->fn(refname, sha1, flags, filter->cb_data);
1668 /* object was peeled successfully: */
1672 * object cannot be peeled because the named object (or an
1673 * object referred to by a tag in the peel chain), does not
1678 /* object cannot be peeled because it is not a tag: */
1681 /* ref_entry contains no peeled value because it is a symref: */
1682 PEEL_IS_SYMREF = -3,
1685 * ref_entry cannot be peeled because it is broken (i.e., the
1686 * symbolic reference cannot even be resolved to an object
1693 * Peel the named object; i.e., if the object is a tag, resolve the
1694 * tag recursively until a non-tag is found. If successful, store the
1695 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1696 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1697 * and leave sha1 unchanged.
1699 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1701 struct object *o = lookup_unknown_object(name);
1703 if (o->type == OBJ_NONE) {
1704 int type = sha1_object_info(name, NULL);
1705 if (type < 0 || !object_as_type(o, type, 0))
1706 return PEEL_INVALID;
1709 if (o->type != OBJ_TAG)
1710 return PEEL_NON_TAG;
1712 o = deref_tag_noverify(o);
1714 return PEEL_INVALID;
1716 hashcpy(sha1, o->sha1);
1721 * Peel the entry (if possible) and return its new peel_status. If
1722 * repeel is true, re-peel the entry even if there is an old peeled
1723 * value that is already stored in it.
1725 * It is OK to call this function with a packed reference entry that
1726 * might be stale and might even refer to an object that has since
1727 * been garbage-collected. In such a case, if the entry has
1728 * REF_KNOWS_PEELED then leave the status unchanged and return
1729 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1731 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1733 enum peel_status status;
1735 if (entry->flag & REF_KNOWS_PEELED) {
1737 entry->flag &= ~REF_KNOWS_PEELED;
1738 hashclr(entry->u.value.peeled);
1740 return is_null_sha1(entry->u.value.peeled) ?
1741 PEEL_NON_TAG : PEEL_PEELED;
1744 if (entry->flag & REF_ISBROKEN)
1746 if (entry->flag & REF_ISSYMREF)
1747 return PEEL_IS_SYMREF;
1749 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1750 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1751 entry->flag |= REF_KNOWS_PEELED;
1755 int peel_ref(const char *refname, unsigned char *sha1)
1758 unsigned char base[20];
1760 if (current_ref && (current_ref->name == refname
1761 || !strcmp(current_ref->name, refname))) {
1762 if (peel_entry(current_ref, 0))
1764 hashcpy(sha1, current_ref->u.value.peeled);
1768 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1772 * If the reference is packed, read its ref_entry from the
1773 * cache in the hope that we already know its peeled value.
1774 * We only try this optimization on packed references because
1775 * (a) forcing the filling of the loose reference cache could
1776 * be expensive and (b) loose references anyway usually do not
1777 * have REF_KNOWS_PEELED.
1779 if (flag & REF_ISPACKED) {
1780 struct ref_entry *r = get_packed_ref(refname);
1782 if (peel_entry(r, 0))
1784 hashcpy(sha1, r->u.value.peeled);
1789 return peel_object(base, sha1);
1792 struct warn_if_dangling_data {
1794 const char *refname;
1795 const struct string_list *refnames;
1796 const char *msg_fmt;
1799 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1800 int flags, void *cb_data)
1802 struct warn_if_dangling_data *d = cb_data;
1803 const char *resolves_to;
1804 unsigned char junk[20];
1806 if (!(flags & REF_ISSYMREF))
1809 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
1812 ? strcmp(resolves_to, d->refname)
1813 : !string_list_has_string(d->refnames, resolves_to))) {
1817 fprintf(d->fp, d->msg_fmt, refname);
1822 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1824 struct warn_if_dangling_data data;
1827 data.refname = refname;
1828 data.refnames = NULL;
1829 data.msg_fmt = msg_fmt;
1830 for_each_rawref(warn_if_dangling_symref, &data);
1833 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1835 struct warn_if_dangling_data data;
1838 data.refname = NULL;
1839 data.refnames = refnames;
1840 data.msg_fmt = msg_fmt;
1841 for_each_rawref(warn_if_dangling_symref, &data);
1845 * Call fn for each reference in the specified ref_cache, omitting
1846 * references not in the containing_dir of base. fn is called for all
1847 * references, including broken ones. If fn ever returns a non-zero
1848 * value, stop the iteration and return that value; otherwise, return
1851 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1852 each_ref_entry_fn fn, void *cb_data)
1854 struct packed_ref_cache *packed_ref_cache;
1855 struct ref_dir *loose_dir;
1856 struct ref_dir *packed_dir;
1860 * We must make sure that all loose refs are read before accessing the
1861 * packed-refs file; this avoids a race condition in which loose refs
1862 * are migrated to the packed-refs file by a simultaneous process, but
1863 * our in-memory view is from before the migration. get_packed_ref_cache()
1864 * takes care of making sure our view is up to date with what is on
1867 loose_dir = get_loose_refs(refs);
1868 if (base && *base) {
1869 loose_dir = find_containing_dir(loose_dir, base, 0);
1872 prime_ref_dir(loose_dir);
1874 packed_ref_cache = get_packed_ref_cache(refs);
1875 acquire_packed_ref_cache(packed_ref_cache);
1876 packed_dir = get_packed_ref_dir(packed_ref_cache);
1877 if (base && *base) {
1878 packed_dir = find_containing_dir(packed_dir, base, 0);
1881 if (packed_dir && loose_dir) {
1882 sort_ref_dir(packed_dir);
1883 sort_ref_dir(loose_dir);
1884 retval = do_for_each_entry_in_dirs(
1885 packed_dir, loose_dir, fn, cb_data);
1886 } else if (packed_dir) {
1887 sort_ref_dir(packed_dir);
1888 retval = do_for_each_entry_in_dir(
1889 packed_dir, 0, fn, cb_data);
1890 } else if (loose_dir) {
1891 sort_ref_dir(loose_dir);
1892 retval = do_for_each_entry_in_dir(
1893 loose_dir, 0, fn, cb_data);
1896 release_packed_ref_cache(packed_ref_cache);
1901 * Call fn for each reference in the specified ref_cache for which the
1902 * refname begins with base. If trim is non-zero, then trim that many
1903 * characters off the beginning of each refname before passing the
1904 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1905 * broken references in the iteration. If fn ever returns a non-zero
1906 * value, stop the iteration and return that value; otherwise, return
1909 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1910 each_ref_fn fn, int trim, int flags, void *cb_data)
1912 struct ref_entry_cb data;
1917 data.cb_data = cb_data;
1919 return do_for_each_entry(refs, base, do_one_ref, &data);
1922 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1924 unsigned char sha1[20];
1928 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1929 return fn("HEAD", sha1, 0, cb_data);
1934 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
1935 return fn("HEAD", sha1, flag, cb_data);
1940 int head_ref(each_ref_fn fn, void *cb_data)
1942 return do_head_ref(NULL, fn, cb_data);
1945 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1947 return do_head_ref(submodule, fn, cb_data);
1950 int for_each_ref(each_ref_fn fn, void *cb_data)
1952 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1955 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1957 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1960 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1962 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1965 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1966 each_ref_fn fn, void *cb_data)
1968 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1971 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1973 return for_each_ref_in("refs/tags/", fn, cb_data);
1976 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1978 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1981 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1983 return for_each_ref_in("refs/heads/", fn, cb_data);
1986 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1988 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1991 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1993 return for_each_ref_in("refs/remotes/", fn, cb_data);
1996 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1998 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2001 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2003 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
2006 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2008 struct strbuf buf = STRBUF_INIT;
2010 unsigned char sha1[20];
2013 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2014 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
2015 ret = fn(buf.buf, sha1, flag, cb_data);
2016 strbuf_release(&buf);
2021 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2023 struct strbuf buf = STRBUF_INIT;
2025 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2026 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2027 strbuf_release(&buf);
2031 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2032 const char *prefix, void *cb_data)
2034 struct strbuf real_pattern = STRBUF_INIT;
2035 struct ref_filter filter;
2038 if (!prefix && !starts_with(pattern, "refs/"))
2039 strbuf_addstr(&real_pattern, "refs/");
2041 strbuf_addstr(&real_pattern, prefix);
2042 strbuf_addstr(&real_pattern, pattern);
2044 if (!has_glob_specials(pattern)) {
2045 /* Append implied '/' '*' if not present. */
2046 if (real_pattern.buf[real_pattern.len - 1] != '/')
2047 strbuf_addch(&real_pattern, '/');
2048 /* No need to check for '*', there is none. */
2049 strbuf_addch(&real_pattern, '*');
2052 filter.pattern = real_pattern.buf;
2054 filter.cb_data = cb_data;
2055 ret = for_each_ref(filter_refs, &filter);
2057 strbuf_release(&real_pattern);
2061 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2063 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2066 int for_each_rawref(each_ref_fn fn, void *cb_data)
2068 return do_for_each_ref(&ref_cache, "", fn, 0,
2069 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2072 const char *prettify_refname(const char *name)
2075 starts_with(name, "refs/heads/") ? 11 :
2076 starts_with(name, "refs/tags/") ? 10 :
2077 starts_with(name, "refs/remotes/") ? 13 :
2081 static const char *ref_rev_parse_rules[] = {
2086 "refs/remotes/%.*s",
2087 "refs/remotes/%.*s/HEAD",
2091 int refname_match(const char *abbrev_name, const char *full_name)
2094 const int abbrev_name_len = strlen(abbrev_name);
2096 for (p = ref_rev_parse_rules; *p; p++) {
2097 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2105 static void unlock_ref(struct ref_lock *lock)
2107 /* Do not free lock->lk -- atexit() still looks at them */
2109 rollback_lock_file(lock->lk);
2110 free(lock->ref_name);
2111 free(lock->orig_ref_name);
2115 /* This function should make sure errno is meaningful on error */
2116 static struct ref_lock *verify_lock(struct ref_lock *lock,
2117 const unsigned char *old_sha1, int mustexist)
2119 if (read_ref_full(lock->ref_name,
2120 mustexist ? RESOLVE_REF_READING : 0,
2121 lock->old_sha1, NULL)) {
2122 int save_errno = errno;
2123 error("Can't verify ref %s", lock->ref_name);
2128 if (hashcmp(lock->old_sha1, old_sha1)) {
2129 error("Ref %s is at %s but expected %s", lock->ref_name,
2130 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2138 static int remove_empty_directories(const char *file)
2140 /* we want to create a file but there is a directory there;
2141 * if that is an empty directory (or a directory that contains
2142 * only empty directories), remove them.
2145 int result, save_errno;
2147 strbuf_init(&path, 20);
2148 strbuf_addstr(&path, file);
2150 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2153 strbuf_release(&path);
2160 * *string and *len will only be substituted, and *string returned (for
2161 * later free()ing) if the string passed in is a magic short-hand form
2164 static char *substitute_branch_name(const char **string, int *len)
2166 struct strbuf buf = STRBUF_INIT;
2167 int ret = interpret_branch_name(*string, *len, &buf);
2171 *string = strbuf_detach(&buf, &size);
2173 return (char *)*string;
2179 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2181 char *last_branch = substitute_branch_name(&str, &len);
2186 for (p = ref_rev_parse_rules; *p; p++) {
2187 char fullref[PATH_MAX];
2188 unsigned char sha1_from_ref[20];
2189 unsigned char *this_result;
2192 this_result = refs_found ? sha1_from_ref : sha1;
2193 mksnpath(fullref, sizeof(fullref), *p, len, str);
2194 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2195 this_result, &flag);
2199 if (!warn_ambiguous_refs)
2201 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2202 warning("ignoring dangling symref %s.", fullref);
2203 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2204 warning("ignoring broken ref %s.", fullref);
2211 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2213 char *last_branch = substitute_branch_name(&str, &len);
2218 for (p = ref_rev_parse_rules; *p; p++) {
2219 unsigned char hash[20];
2220 char path[PATH_MAX];
2221 const char *ref, *it;
2223 mksnpath(path, sizeof(path), *p, len, str);
2224 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2228 if (reflog_exists(path))
2230 else if (strcmp(ref, path) && reflog_exists(ref))
2234 if (!logs_found++) {
2236 hashcpy(sha1, hash);
2238 if (!warn_ambiguous_refs)
2246 * Locks a ref returning the lock on success and NULL on failure.
2247 * On failure errno is set to something meaningful.
2249 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2250 const unsigned char *old_sha1,
2251 const struct string_list *skip,
2252 int flags, int *type_p)
2255 const char *orig_refname = refname;
2256 struct ref_lock *lock;
2259 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2260 int resolve_flags = 0;
2261 int attempts_remaining = 3;
2263 lock = xcalloc(1, sizeof(struct ref_lock));
2267 resolve_flags |= RESOLVE_REF_READING;
2268 if (flags & REF_DELETING) {
2269 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2270 if (flags & REF_NODEREF)
2271 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2274 refname = resolve_ref_unsafe(refname, resolve_flags,
2275 lock->old_sha1, &type);
2276 if (!refname && errno == EISDIR) {
2277 /* we are trying to lock foo but we used to
2278 * have foo/bar which now does not exist;
2279 * it is normal for the empty directory 'foo'
2282 ref_file = git_path("%s", orig_refname);
2283 if (remove_empty_directories(ref_file)) {
2285 error("there are still refs under '%s'", orig_refname);
2288 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2289 lock->old_sha1, &type);
2295 error("unable to resolve reference %s: %s",
2296 orig_refname, strerror(errno));
2300 * If the ref did not exist and we are creating it, make sure
2301 * there is no existing packed ref whose name begins with our
2302 * refname, nor a packed ref whose name is a proper prefix of
2305 if (is_null_sha1(lock->old_sha1) &&
2306 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {
2307 last_errno = ENOTDIR;
2311 lock->lk = xcalloc(1, sizeof(struct lock_file));
2314 if (flags & REF_NODEREF) {
2315 refname = orig_refname;
2316 lflags |= LOCK_NO_DEREF;
2318 lock->ref_name = xstrdup(refname);
2319 lock->orig_ref_name = xstrdup(orig_refname);
2320 ref_file = git_path("%s", refname);
2323 switch (safe_create_leading_directories(ref_file)) {
2325 break; /* success */
2327 if (--attempts_remaining > 0)
2332 error("unable to create directory for %s", ref_file);
2336 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2337 if (lock->lock_fd < 0) {
2339 if (errno == ENOENT && --attempts_remaining > 0)
2341 * Maybe somebody just deleted one of the
2342 * directories leading to ref_file. Try
2347 struct strbuf err = STRBUF_INIT;
2348 unable_to_lock_message(ref_file, errno, &err);
2349 error("%s", err.buf);
2350 strbuf_release(&err);
2354 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2363 * Write an entry to the packed-refs file for the specified refname.
2364 * If peeled is non-NULL, write it as the entry's peeled value.
2366 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2367 unsigned char *peeled)
2369 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2371 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2375 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2377 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2379 enum peel_status peel_status = peel_entry(entry, 0);
2381 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2382 error("internal error: %s is not a valid packed reference!",
2384 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
2385 peel_status == PEEL_PEELED ?
2386 entry->u.value.peeled : NULL);
2390 /* This should return a meaningful errno on failure */
2391 int lock_packed_refs(int flags)
2393 struct packed_ref_cache *packed_ref_cache;
2395 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2398 * Get the current packed-refs while holding the lock. If the
2399 * packed-refs file has been modified since we last read it,
2400 * this will automatically invalidate the cache and re-read
2401 * the packed-refs file.
2403 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2404 packed_ref_cache->lock = &packlock;
2405 /* Increment the reference count to prevent it from being freed: */
2406 acquire_packed_ref_cache(packed_ref_cache);
2411 * Commit the packed refs changes.
2412 * On error we must make sure that errno contains a meaningful value.
2414 int commit_packed_refs(void)
2416 struct packed_ref_cache *packed_ref_cache =
2417 get_packed_ref_cache(&ref_cache);
2422 if (!packed_ref_cache->lock)
2423 die("internal error: packed-refs not locked");
2425 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2427 die_errno("unable to fdopen packed-refs descriptor");
2429 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2430 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2431 0, write_packed_entry_fn, out);
2433 if (commit_lock_file(packed_ref_cache->lock)) {
2437 packed_ref_cache->lock = NULL;
2438 release_packed_ref_cache(packed_ref_cache);
2443 void rollback_packed_refs(void)
2445 struct packed_ref_cache *packed_ref_cache =
2446 get_packed_ref_cache(&ref_cache);
2448 if (!packed_ref_cache->lock)
2449 die("internal error: packed-refs not locked");
2450 rollback_lock_file(packed_ref_cache->lock);
2451 packed_ref_cache->lock = NULL;
2452 release_packed_ref_cache(packed_ref_cache);
2453 clear_packed_ref_cache(&ref_cache);
2456 struct ref_to_prune {
2457 struct ref_to_prune *next;
2458 unsigned char sha1[20];
2459 char name[FLEX_ARRAY];
2462 struct pack_refs_cb_data {
2464 struct ref_dir *packed_refs;
2465 struct ref_to_prune *ref_to_prune;
2469 * An each_ref_entry_fn that is run over loose references only. If
2470 * the loose reference can be packed, add an entry in the packed ref
2471 * cache. If the reference should be pruned, also add it to
2472 * ref_to_prune in the pack_refs_cb_data.
2474 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2476 struct pack_refs_cb_data *cb = cb_data;
2477 enum peel_status peel_status;
2478 struct ref_entry *packed_entry;
2479 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2481 /* ALWAYS pack tags */
2482 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2485 /* Do not pack symbolic or broken refs: */
2486 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2489 /* Add a packed ref cache entry equivalent to the loose entry. */
2490 peel_status = peel_entry(entry, 1);
2491 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2492 die("internal error peeling reference %s (%s)",
2493 entry->name, sha1_to_hex(entry->u.value.sha1));
2494 packed_entry = find_ref(cb->packed_refs, entry->name);
2496 /* Overwrite existing packed entry with info from loose entry */
2497 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2498 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2500 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2501 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2502 add_ref(cb->packed_refs, packed_entry);
2504 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2506 /* Schedule the loose reference for pruning if requested. */
2507 if ((cb->flags & PACK_REFS_PRUNE)) {
2508 int namelen = strlen(entry->name) + 1;
2509 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2510 hashcpy(n->sha1, entry->u.value.sha1);
2511 strcpy(n->name, entry->name);
2512 n->next = cb->ref_to_prune;
2513 cb->ref_to_prune = n;
2519 * Remove empty parents, but spare refs/ and immediate subdirs.
2520 * Note: munges *name.
2522 static void try_remove_empty_parents(char *name)
2527 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2528 while (*p && *p != '/')
2530 /* tolerate duplicate slashes; see check_refname_format() */
2534 for (q = p; *q; q++)
2537 while (q > p && *q != '/')
2539 while (q > p && *(q-1) == '/')
2544 if (rmdir(git_path("%s", name)))
2549 /* make sure nobody touched the ref, and unlink */
2550 static void prune_ref(struct ref_to_prune *r)
2552 struct ref_transaction *transaction;
2553 struct strbuf err = STRBUF_INIT;
2555 if (check_refname_format(r->name, 0))
2558 transaction = ref_transaction_begin(&err);
2560 ref_transaction_delete(transaction, r->name, r->sha1,
2561 REF_ISPRUNING, 1, NULL, &err) ||
2562 ref_transaction_commit(transaction, &err)) {
2563 ref_transaction_free(transaction);
2564 error("%s", err.buf);
2565 strbuf_release(&err);
2568 ref_transaction_free(transaction);
2569 strbuf_release(&err);
2570 try_remove_empty_parents(r->name);
2573 static void prune_refs(struct ref_to_prune *r)
2581 int pack_refs(unsigned int flags)
2583 struct pack_refs_cb_data cbdata;
2585 memset(&cbdata, 0, sizeof(cbdata));
2586 cbdata.flags = flags;
2588 lock_packed_refs(LOCK_DIE_ON_ERROR);
2589 cbdata.packed_refs = get_packed_refs(&ref_cache);
2591 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2592 pack_if_possible_fn, &cbdata);
2594 if (commit_packed_refs())
2595 die_errno("unable to overwrite old ref-pack file");
2597 prune_refs(cbdata.ref_to_prune);
2602 * If entry is no longer needed in packed-refs, add it to the string
2603 * list pointed to by cb_data. Reasons for deleting entries:
2605 * - Entry is broken.
2606 * - Entry is overridden by a loose ref.
2607 * - Entry does not point at a valid object.
2609 * In the first and third cases, also emit an error message because these
2610 * are indications of repository corruption.
2612 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2614 struct string_list *refs_to_delete = cb_data;
2616 if (entry->flag & REF_ISBROKEN) {
2617 /* This shouldn't happen to packed refs. */
2618 error("%s is broken!", entry->name);
2619 string_list_append(refs_to_delete, entry->name);
2622 if (!has_sha1_file(entry->u.value.sha1)) {
2623 unsigned char sha1[20];
2626 if (read_ref_full(entry->name, 0, sha1, &flags))
2627 /* We should at least have found the packed ref. */
2628 die("Internal error");
2629 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2631 * This packed reference is overridden by a
2632 * loose reference, so it is OK that its value
2633 * is no longer valid; for example, it might
2634 * refer to an object that has been garbage
2635 * collected. For this purpose we don't even
2636 * care whether the loose reference itself is
2637 * invalid, broken, symbolic, etc. Silently
2638 * remove the packed reference.
2640 string_list_append(refs_to_delete, entry->name);
2644 * There is no overriding loose reference, so the fact
2645 * that this reference doesn't refer to a valid object
2646 * indicates some kind of repository corruption.
2647 * Report the problem, then omit the reference from
2650 error("%s does not point to a valid object!", entry->name);
2651 string_list_append(refs_to_delete, entry->name);
2658 int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2660 struct ref_dir *packed;
2661 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2662 struct string_list_item *refname, *ref_to_delete;
2663 int ret, needs_repacking = 0, removed = 0;
2667 /* Look for a packed ref */
2668 for_each_string_list_item(refname, refnames) {
2669 if (get_packed_ref(refname->string)) {
2670 needs_repacking = 1;
2675 /* Avoid locking if we have nothing to do */
2676 if (!needs_repacking)
2677 return 0; /* no refname exists in packed refs */
2679 if (lock_packed_refs(0)) {
2680 unable_to_lock_message(git_path("packed-refs"), errno, err);
2683 packed = get_packed_refs(&ref_cache);
2685 /* Remove refnames from the cache */
2686 for_each_string_list_item(refname, refnames)
2687 if (remove_entry(packed, refname->string) != -1)
2691 * All packed entries disappeared while we were
2692 * acquiring the lock.
2694 rollback_packed_refs();
2698 /* Remove any other accumulated cruft */
2699 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2700 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2701 if (remove_entry(packed, ref_to_delete->string) == -1)
2702 die("internal error");
2705 /* Write what remains */
2706 ret = commit_packed_refs();
2708 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2713 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2717 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2719 * loose. The loose file name is the same as the
2720 * lockfile name, minus ".lock":
2722 char *loose_filename = get_locked_file_path(lock->lk);
2723 int res = unlink_or_msg(loose_filename, err);
2724 free(loose_filename);
2731 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2733 struct ref_transaction *transaction;
2734 struct strbuf err = STRBUF_INIT;
2736 transaction = ref_transaction_begin(&err);
2738 ref_transaction_delete(transaction, refname, sha1, delopt,
2739 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2740 ref_transaction_commit(transaction, &err)) {
2741 error("%s", err.buf);
2742 ref_transaction_free(transaction);
2743 strbuf_release(&err);
2746 ref_transaction_free(transaction);
2747 strbuf_release(&err);
2752 * People using contrib's git-new-workdir have .git/logs/refs ->
2753 * /some/other/path/.git/logs/refs, and that may live on another device.
2755 * IOW, to avoid cross device rename errors, the temporary renamed log must
2756 * live into logs/refs.
2758 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2760 static int rename_tmp_log(const char *newrefname)
2762 int attempts_remaining = 4;
2765 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2767 break; /* success */
2769 if (--attempts_remaining > 0)
2773 error("unable to create directory for %s", newrefname);
2777 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2778 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2780 * rename(a, b) when b is an existing
2781 * directory ought to result in ISDIR, but
2782 * Solaris 5.8 gives ENOTDIR. Sheesh.
2784 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2785 error("Directory not empty: logs/%s", newrefname);
2789 } else if (errno == ENOENT && --attempts_remaining > 0) {
2791 * Maybe another process just deleted one of
2792 * the directories in the path to newrefname.
2793 * Try again from the beginning.
2797 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2798 newrefname, strerror(errno));
2805 static int rename_ref_available(const char *oldname, const char *newname)
2807 struct string_list skip = STRING_LIST_INIT_NODUP;
2810 string_list_insert(&skip, oldname);
2811 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))
2812 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));
2813 string_list_clear(&skip, 0);
2817 static int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1,
2818 const char *logmsg);
2820 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2822 unsigned char sha1[20], orig_sha1[20];
2823 int flag = 0, logmoved = 0;
2824 struct ref_lock *lock;
2825 struct stat loginfo;
2826 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2827 const char *symref = NULL;
2829 if (log && S_ISLNK(loginfo.st_mode))
2830 return error("reflog for %s is a symlink", oldrefname);
2832 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2834 if (flag & REF_ISSYMREF)
2835 return error("refname %s is a symbolic ref, renaming it is not supported",
2838 return error("refname %s not found", oldrefname);
2840 if (!rename_ref_available(oldrefname, newrefname))
2843 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2844 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2845 oldrefname, strerror(errno));
2847 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2848 error("unable to delete old %s", oldrefname);
2852 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2853 delete_ref(newrefname, sha1, REF_NODEREF)) {
2854 if (errno==EISDIR) {
2855 if (remove_empty_directories(git_path("%s", newrefname))) {
2856 error("Directory not empty: %s", newrefname);
2860 error("unable to delete existing %s", newrefname);
2865 if (log && rename_tmp_log(newrefname))
2870 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);
2872 error("unable to lock %s for update", newrefname);
2875 hashcpy(lock->old_sha1, orig_sha1);
2876 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
2877 error("unable to write current sha1 into %s", newrefname);
2884 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);
2886 error("unable to lock %s for rollback", oldrefname);
2890 flag = log_all_ref_updates;
2891 log_all_ref_updates = 0;
2892 if (write_ref_sha1(lock, orig_sha1, NULL))
2893 error("unable to write current sha1 into %s", oldrefname);
2894 log_all_ref_updates = flag;
2897 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2898 error("unable to restore logfile %s from %s: %s",
2899 oldrefname, newrefname, strerror(errno));
2900 if (!logmoved && log &&
2901 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2902 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2903 oldrefname, strerror(errno));
2908 static int close_ref(struct ref_lock *lock)
2910 if (close_lock_file(lock->lk))
2916 static int commit_ref(struct ref_lock *lock)
2918 if (commit_lock_file(lock->lk))
2925 * copy the reflog message msg to buf, which has been allocated sufficiently
2926 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2927 * because reflog file is one line per entry.
2929 static int copy_msg(char *buf, const char *msg)
2936 while ((c = *msg++)) {
2937 if (wasspace && isspace(c))
2939 wasspace = isspace(c);
2944 while (buf < cp && isspace(cp[-1]))
2950 /* This function must set a meaningful errno on failure */
2951 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2953 int logfd, oflags = O_APPEND | O_WRONLY;
2955 git_snpath(logfile, bufsize, "logs/%s", refname);
2956 if (log_all_ref_updates &&
2957 (starts_with(refname, "refs/heads/") ||
2958 starts_with(refname, "refs/remotes/") ||
2959 starts_with(refname, "refs/notes/") ||
2960 !strcmp(refname, "HEAD"))) {
2961 if (safe_create_leading_directories(logfile) < 0) {
2962 int save_errno = errno;
2963 error("unable to create directory for %s", logfile);
2970 logfd = open(logfile, oflags, 0666);
2972 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2975 if (errno == EISDIR) {
2976 if (remove_empty_directories(logfile)) {
2977 int save_errno = errno;
2978 error("There are still logs under '%s'",
2983 logfd = open(logfile, oflags, 0666);
2987 int save_errno = errno;
2988 error("Unable to append to %s: %s", logfile,
2995 adjust_shared_perm(logfile);
3000 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3001 const unsigned char *new_sha1,
3002 const char *committer, const char *msg)
3004 int msglen, written;
3005 unsigned maxlen, len;
3008 msglen = msg ? strlen(msg) : 0;
3009 maxlen = strlen(committer) + msglen + 100;
3010 logrec = xmalloc(maxlen);
3011 len = sprintf(logrec, "%s %s %s\n",
3012 sha1_to_hex(old_sha1),
3013 sha1_to_hex(new_sha1),
3016 len += copy_msg(logrec + len - 1, msg) - 1;
3018 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3026 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3027 const unsigned char *new_sha1, const char *msg)
3029 int logfd, result, oflags = O_APPEND | O_WRONLY;
3030 char log_file[PATH_MAX];
3032 if (log_all_ref_updates < 0)
3033 log_all_ref_updates = !is_bare_repository();
3035 result = log_ref_setup(refname, log_file, sizeof(log_file));
3039 logfd = open(log_file, oflags);
3042 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3043 git_committer_info(0), msg);
3045 int save_errno = errno;
3047 error("Unable to append to %s", log_file);
3052 int save_errno = errno;
3053 error("Unable to append to %s", log_file);
3060 int is_branch(const char *refname)
3062 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3066 * Write sha1 into the ref specified by the lock. Make sure that errno
3069 static int write_ref_sha1(struct ref_lock *lock,
3070 const unsigned char *sha1, const char *logmsg)
3072 static char term = '\n';
3075 o = parse_object(sha1);
3077 error("Trying to write ref %s with nonexistent object %s",
3078 lock->ref_name, sha1_to_hex(sha1));
3083 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3084 error("Trying to write non-commit object %s to branch %s",
3085 sha1_to_hex(sha1), lock->ref_name);
3090 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
3091 write_in_full(lock->lock_fd, &term, 1) != 1 ||
3092 close_ref(lock) < 0) {
3093 int save_errno = errno;
3094 error("Couldn't write %s", lock->lk->filename.buf);
3099 clear_loose_ref_cache(&ref_cache);
3100 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3101 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3102 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
3106 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3108 * Special hack: If a branch is updated directly and HEAD
3109 * points to it (may happen on the remote side of a push
3110 * for example) then logically the HEAD reflog should be
3112 * A generic solution implies reverse symref information,
3113 * but finding all symrefs pointing to the given branch
3114 * would be rather costly for this rare event (the direct
3115 * update of a branch) to be worth it. So let's cheat and
3116 * check with HEAD only which should cover 99% of all usage
3117 * scenarios (even 100% of the default ones).
3119 unsigned char head_sha1[20];
3121 const char *head_ref;
3122 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3123 head_sha1, &head_flag);
3124 if (head_ref && (head_flag & REF_ISSYMREF) &&
3125 !strcmp(head_ref, lock->ref_name))
3126 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3128 if (commit_ref(lock)) {
3129 error("Couldn't set %s", lock->ref_name);
3137 int create_symref(const char *ref_target, const char *refs_heads_master,
3140 const char *lockpath;
3142 int fd, len, written;
3143 char *git_HEAD = git_pathdup("%s", ref_target);
3144 unsigned char old_sha1[20], new_sha1[20];
3146 if (logmsg && read_ref(ref_target, old_sha1))
3149 if (safe_create_leading_directories(git_HEAD) < 0)
3150 return error("unable to create directory for %s", git_HEAD);
3152 #ifndef NO_SYMLINK_HEAD
3153 if (prefer_symlink_refs) {
3155 if (!symlink(refs_heads_master, git_HEAD))
3157 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3161 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3162 if (sizeof(ref) <= len) {
3163 error("refname too long: %s", refs_heads_master);
3164 goto error_free_return;
3166 lockpath = mkpath("%s.lock", git_HEAD);
3167 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3169 error("Unable to open %s for writing", lockpath);
3170 goto error_free_return;
3172 written = write_in_full(fd, ref, len);
3173 if (close(fd) != 0 || written != len) {
3174 error("Unable to write to %s", lockpath);
3175 goto error_unlink_return;
3177 if (rename(lockpath, git_HEAD) < 0) {
3178 error("Unable to create %s", git_HEAD);
3179 goto error_unlink_return;
3181 if (adjust_shared_perm(git_HEAD)) {
3182 error("Unable to fix permissions on %s", lockpath);
3183 error_unlink_return:
3184 unlink_or_warn(lockpath);
3190 #ifndef NO_SYMLINK_HEAD
3193 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3194 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3200 struct read_ref_at_cb {
3201 const char *refname;
3202 unsigned long at_time;
3205 unsigned char *sha1;
3208 unsigned char osha1[20];
3209 unsigned char nsha1[20];
3213 unsigned long *cutoff_time;
3218 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3219 const char *email, unsigned long timestamp, int tz,
3220 const char *message, void *cb_data)
3222 struct read_ref_at_cb *cb = cb_data;
3226 cb->date = timestamp;
3228 if (timestamp <= cb->at_time || cb->cnt == 0) {
3230 *cb->msg = xstrdup(message);
3231 if (cb->cutoff_time)
3232 *cb->cutoff_time = timestamp;
3234 *cb->cutoff_tz = tz;
3236 *cb->cutoff_cnt = cb->reccnt - 1;
3238 * we have not yet updated cb->[n|o]sha1 so they still
3239 * hold the values for the previous record.
3241 if (!is_null_sha1(cb->osha1)) {
3242 hashcpy(cb->sha1, nsha1);
3243 if (hashcmp(cb->osha1, nsha1))
3244 warning("Log for ref %s has gap after %s.",
3245 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3247 else if (cb->date == cb->at_time)
3248 hashcpy(cb->sha1, nsha1);
3249 else if (hashcmp(nsha1, cb->sha1))
3250 warning("Log for ref %s unexpectedly ended on %s.",
3251 cb->refname, show_date(cb->date, cb->tz,
3253 hashcpy(cb->osha1, osha1);
3254 hashcpy(cb->nsha1, nsha1);
3258 hashcpy(cb->osha1, osha1);
3259 hashcpy(cb->nsha1, nsha1);
3265 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3266 const char *email, unsigned long timestamp,
3267 int tz, const char *message, void *cb_data)
3269 struct read_ref_at_cb *cb = cb_data;
3272 *cb->msg = xstrdup(message);
3273 if (cb->cutoff_time)
3274 *cb->cutoff_time = timestamp;
3276 *cb->cutoff_tz = tz;
3278 *cb->cutoff_cnt = cb->reccnt;
3279 hashcpy(cb->sha1, osha1);
3280 if (is_null_sha1(cb->sha1))
3281 hashcpy(cb->sha1, nsha1);
3282 /* We just want the first entry */
3286 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3287 unsigned char *sha1, char **msg,
3288 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3290 struct read_ref_at_cb cb;
3292 memset(&cb, 0, sizeof(cb));
3293 cb.refname = refname;
3294 cb.at_time = at_time;
3297 cb.cutoff_time = cutoff_time;
3298 cb.cutoff_tz = cutoff_tz;
3299 cb.cutoff_cnt = cutoff_cnt;
3302 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3305 if (flags & GET_SHA1_QUIETLY)
3308 die("Log for %s is empty.", refname);
3313 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3318 int reflog_exists(const char *refname)
3322 return !lstat(git_path("logs/%s", refname), &st) &&
3323 S_ISREG(st.st_mode);
3326 int delete_reflog(const char *refname)
3328 return remove_path(git_path("logs/%s", refname));
3331 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3333 unsigned char osha1[20], nsha1[20];
3334 char *email_end, *message;
3335 unsigned long timestamp;
3338 /* old SP new SP name <email> SP time TAB msg LF */
3339 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3340 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3341 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3342 !(email_end = strchr(sb->buf + 82, '>')) ||
3343 email_end[1] != ' ' ||
3344 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3345 !message || message[0] != ' ' ||
3346 (message[1] != '+' && message[1] != '-') ||
3347 !isdigit(message[2]) || !isdigit(message[3]) ||
3348 !isdigit(message[4]) || !isdigit(message[5]))
3349 return 0; /* corrupt? */
3350 email_end[1] = '\0';
3351 tz = strtol(message + 1, NULL, 10);
3352 if (message[6] != '\t')
3356 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3359 static char *find_beginning_of_line(char *bob, char *scan)
3361 while (bob < scan && *(--scan) != '\n')
3362 ; /* keep scanning backwards */
3364 * Return either beginning of the buffer, or LF at the end of
3365 * the previous line.
3370 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3372 struct strbuf sb = STRBUF_INIT;
3375 int ret = 0, at_tail = 1;
3377 logfp = fopen(git_path("logs/%s", refname), "r");
3381 /* Jump to the end */
3382 if (fseek(logfp, 0, SEEK_END) < 0)
3383 return error("cannot seek back reflog for %s: %s",
3384 refname, strerror(errno));
3386 while (!ret && 0 < pos) {
3392 /* Fill next block from the end */
3393 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3394 if (fseek(logfp, pos - cnt, SEEK_SET))
3395 return error("cannot seek back reflog for %s: %s",
3396 refname, strerror(errno));
3397 nread = fread(buf, cnt, 1, logfp);
3399 return error("cannot read %d bytes from reflog for %s: %s",
3400 cnt, refname, strerror(errno));
3403 scanp = endp = buf + cnt;
3404 if (at_tail && scanp[-1] == '\n')
3405 /* Looking at the final LF at the end of the file */
3409 while (buf < scanp) {
3411 * terminating LF of the previous line, or the beginning
3416 bp = find_beginning_of_line(buf, scanp);
3420 * The newline is the end of the previous line,
3421 * so we know we have complete line starting
3422 * at (bp + 1). Prefix it onto any prior data
3423 * we collected for the line and process it.
3425 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3428 ret = show_one_reflog_ent(&sb, fn, cb_data);
3434 * We are at the start of the buffer, and the
3435 * start of the file; there is no previous
3436 * line, and we have everything for this one.
3437 * Process it, and we can end the loop.
3439 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3440 ret = show_one_reflog_ent(&sb, fn, cb_data);
3447 * We are at the start of the buffer, and there
3448 * is more file to read backwards. Which means
3449 * we are in the middle of a line. Note that we
3450 * may get here even if *bp was a newline; that
3451 * just means we are at the exact end of the
3452 * previous line, rather than some spot in the
3455 * Save away what we have to be combined with
3456 * the data from the next read.
3458 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3465 die("BUG: reverse reflog parser had leftover data");
3468 strbuf_release(&sb);
3472 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3475 struct strbuf sb = STRBUF_INIT;
3478 logfp = fopen(git_path("logs/%s", refname), "r");
3482 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3483 ret = show_one_reflog_ent(&sb, fn, cb_data);
3485 strbuf_release(&sb);
3489 * Call fn for each reflog in the namespace indicated by name. name
3490 * must be empty or end with '/'. Name will be used as a scratch
3491 * space, but its contents will be restored before return.
3493 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3495 DIR *d = opendir(git_path("logs/%s", name->buf));
3498 int oldlen = name->len;
3501 return name->len ? errno : 0;
3503 while ((de = readdir(d)) != NULL) {
3506 if (de->d_name[0] == '.')
3508 if (ends_with(de->d_name, ".lock"))
3510 strbuf_addstr(name, de->d_name);
3511 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3512 ; /* silently ignore */
3514 if (S_ISDIR(st.st_mode)) {
3515 strbuf_addch(name, '/');
3516 retval = do_for_each_reflog(name, fn, cb_data);
3518 unsigned char sha1[20];
3519 if (read_ref_full(name->buf, 0, sha1, NULL))
3520 retval = error("bad ref for %s", name->buf);
3522 retval = fn(name->buf, sha1, 0, cb_data);
3527 strbuf_setlen(name, oldlen);
3533 int for_each_reflog(each_ref_fn fn, void *cb_data)
3537 strbuf_init(&name, PATH_MAX);
3538 retval = do_for_each_reflog(&name, fn, cb_data);
3539 strbuf_release(&name);
3544 * Information needed for a single ref update. Set new_sha1 to the
3545 * new value or to zero to delete the ref. To check the old value
3546 * while locking the ref, set have_old to 1 and set old_sha1 to the
3547 * value or to zero to ensure the ref does not exist before update.
3550 unsigned char new_sha1[20];
3551 unsigned char old_sha1[20];
3552 int flags; /* REF_NODEREF? */
3553 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3554 struct ref_lock *lock;
3557 const char refname[FLEX_ARRAY];
3561 * Transaction states.
3562 * OPEN: The transaction is in a valid state and can accept new updates.
3563 * An OPEN transaction can be committed.
3564 * CLOSED: A closed transaction is no longer active and no other operations
3565 * than free can be used on it in this state.
3566 * A transaction can either become closed by successfully committing
3567 * an active transaction or if there is a failure while building
3568 * the transaction thus rendering it failed/inactive.
3570 enum ref_transaction_state {
3571 REF_TRANSACTION_OPEN = 0,
3572 REF_TRANSACTION_CLOSED = 1
3576 * Data structure for holding a reference transaction, which can
3577 * consist of checks and updates to multiple references, carried out
3578 * as atomically as possible. This structure is opaque to callers.
3580 struct ref_transaction {
3581 struct ref_update **updates;
3584 enum ref_transaction_state state;
3587 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3591 return xcalloc(1, sizeof(struct ref_transaction));
3594 void ref_transaction_free(struct ref_transaction *transaction)
3601 for (i = 0; i < transaction->nr; i++) {
3602 free(transaction->updates[i]->msg);
3603 free(transaction->updates[i]);
3605 free(transaction->updates);
3609 static struct ref_update *add_update(struct ref_transaction *transaction,
3610 const char *refname)
3612 size_t len = strlen(refname);
3613 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3615 strcpy((char *)update->refname, refname);
3616 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3617 transaction->updates[transaction->nr++] = update;
3621 int ref_transaction_update(struct ref_transaction *transaction,
3622 const char *refname,
3623 const unsigned char *new_sha1,
3624 const unsigned char *old_sha1,
3625 int flags, int have_old, const char *msg,
3628 struct ref_update *update;
3632 if (transaction->state != REF_TRANSACTION_OPEN)
3633 die("BUG: update called for transaction that is not open");
3635 if (have_old && !old_sha1)
3636 die("BUG: have_old is true but old_sha1 is NULL");
3638 if (!is_null_sha1(new_sha1) &&
3639 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3640 strbuf_addf(err, "refusing to update ref with bad name %s",
3645 update = add_update(transaction, refname);
3646 hashcpy(update->new_sha1, new_sha1);
3647 update->flags = flags;
3648 update->have_old = have_old;
3650 hashcpy(update->old_sha1, old_sha1);
3652 update->msg = xstrdup(msg);
3656 int ref_transaction_create(struct ref_transaction *transaction,
3657 const char *refname,
3658 const unsigned char *new_sha1,
3659 int flags, const char *msg,
3662 return ref_transaction_update(transaction, refname, new_sha1,
3663 null_sha1, flags, 1, msg, err);
3666 int ref_transaction_delete(struct ref_transaction *transaction,
3667 const char *refname,
3668 const unsigned char *old_sha1,
3669 int flags, int have_old, const char *msg,
3672 return ref_transaction_update(transaction, refname, null_sha1,
3673 old_sha1, flags, have_old, msg, err);
3676 int update_ref(const char *action, const char *refname,
3677 const unsigned char *sha1, const unsigned char *oldval,
3678 int flags, enum action_on_err onerr)
3680 struct ref_transaction *t;
3681 struct strbuf err = STRBUF_INIT;
3683 t = ref_transaction_begin(&err);
3685 ref_transaction_update(t, refname, sha1, oldval, flags,
3686 !!oldval, action, &err) ||
3687 ref_transaction_commit(t, &err)) {
3688 const char *str = "update_ref failed for ref '%s': %s";
3690 ref_transaction_free(t);
3692 case UPDATE_REFS_MSG_ON_ERR:
3693 error(str, refname, err.buf);
3695 case UPDATE_REFS_DIE_ON_ERR:
3696 die(str, refname, err.buf);
3698 case UPDATE_REFS_QUIET_ON_ERR:
3701 strbuf_release(&err);
3704 strbuf_release(&err);
3705 ref_transaction_free(t);
3709 static int ref_update_compare(const void *r1, const void *r2)
3711 const struct ref_update * const *u1 = r1;
3712 const struct ref_update * const *u2 = r2;
3713 return strcmp((*u1)->refname, (*u2)->refname);
3716 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3723 for (i = 1; i < n; i++)
3724 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3726 "Multiple updates for ref '%s' not allowed.",
3727 updates[i]->refname);
3733 int ref_transaction_commit(struct ref_transaction *transaction,
3737 int n = transaction->nr;
3738 struct ref_update **updates = transaction->updates;
3739 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3740 struct string_list_item *ref_to_delete;
3744 if (transaction->state != REF_TRANSACTION_OPEN)
3745 die("BUG: commit called for transaction that is not open");
3748 transaction->state = REF_TRANSACTION_CLOSED;
3752 /* Copy, sort, and reject duplicate refs */
3753 qsort(updates, n, sizeof(*updates), ref_update_compare);
3754 if (ref_update_reject_duplicates(updates, n, err)) {
3755 ret = TRANSACTION_GENERIC_ERROR;
3759 /* Acquire all locks while verifying old values */
3760 for (i = 0; i < n; i++) {
3761 struct ref_update *update = updates[i];
3762 int flags = update->flags;
3764 if (is_null_sha1(update->new_sha1))
3765 flags |= REF_DELETING;
3766 update->lock = lock_ref_sha1_basic(update->refname,
3773 if (!update->lock) {
3774 ret = (errno == ENOTDIR)
3775 ? TRANSACTION_NAME_CONFLICT
3776 : TRANSACTION_GENERIC_ERROR;
3777 strbuf_addf(err, "Cannot lock the ref '%s'.",
3783 /* Perform updates first so live commits remain referenced */
3784 for (i = 0; i < n; i++) {
3785 struct ref_update *update = updates[i];
3787 if (!is_null_sha1(update->new_sha1)) {
3788 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3789 (update->flags & REF_NODEREF));
3791 if (!overwriting_symref
3792 && !hashcmp(update->lock->old_sha1, update->new_sha1)) {
3794 * The reference already has the desired
3795 * value, so we don't need to write it.
3797 unlock_ref(update->lock);
3798 update->lock = NULL;
3799 } else if (write_ref_sha1(update->lock, update->new_sha1,
3801 update->lock = NULL; /* freed by write_ref_sha1 */
3802 strbuf_addf(err, "Cannot update the ref '%s'.",
3804 ret = TRANSACTION_GENERIC_ERROR;
3807 /* freed by write_ref_sha1(): */
3808 update->lock = NULL;
3813 /* Perform deletes now that updates are safely completed */
3814 for (i = 0; i < n; i++) {
3815 struct ref_update *update = updates[i];
3818 if (delete_ref_loose(update->lock, update->type, err)) {
3819 ret = TRANSACTION_GENERIC_ERROR;
3823 if (!(update->flags & REF_ISPRUNING))
3824 string_list_append(&refs_to_delete,
3825 update->lock->ref_name);
3829 if (repack_without_refs(&refs_to_delete, err)) {
3830 ret = TRANSACTION_GENERIC_ERROR;
3833 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3834 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3835 clear_loose_ref_cache(&ref_cache);
3838 transaction->state = REF_TRANSACTION_CLOSED;
3840 for (i = 0; i < n; i++)
3841 if (updates[i]->lock)
3842 unlock_ref(updates[i]->lock);
3843 string_list_clear(&refs_to_delete, 0);
3847 char *shorten_unambiguous_ref(const char *refname, int strict)
3850 static char **scanf_fmts;
3851 static int nr_rules;
3856 * Pre-generate scanf formats from ref_rev_parse_rules[].
3857 * Generate a format suitable for scanf from a
3858 * ref_rev_parse_rules rule by interpolating "%s" at the
3859 * location of the "%.*s".
3861 size_t total_len = 0;
3864 /* the rule list is NULL terminated, count them first */
3865 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3866 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3867 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3869 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3872 for (i = 0; i < nr_rules; i++) {
3873 assert(offset < total_len);
3874 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3875 offset += snprintf(scanf_fmts[i], total_len - offset,
3876 ref_rev_parse_rules[i], 2, "%s") + 1;
3880 /* bail out if there are no rules */
3882 return xstrdup(refname);
3884 /* buffer for scanf result, at most refname must fit */
3885 short_name = xstrdup(refname);
3887 /* skip first rule, it will always match */
3888 for (i = nr_rules - 1; i > 0 ; --i) {
3890 int rules_to_fail = i;
3893 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3896 short_name_len = strlen(short_name);
3899 * in strict mode, all (except the matched one) rules
3900 * must fail to resolve to a valid non-ambiguous ref
3903 rules_to_fail = nr_rules;
3906 * check if the short name resolves to a valid ref,
3907 * but use only rules prior to the matched one
3909 for (j = 0; j < rules_to_fail; j++) {
3910 const char *rule = ref_rev_parse_rules[j];
3911 char refname[PATH_MAX];
3913 /* skip matched rule */
3918 * the short name is ambiguous, if it resolves
3919 * (with this previous rule) to a valid ref
3920 * read_ref() returns 0 on success
3922 mksnpath(refname, sizeof(refname),
3923 rule, short_name_len, short_name);
3924 if (ref_exists(refname))
3929 * short name is non-ambiguous if all previous rules
3930 * haven't resolved to a valid ref
3932 if (j == rules_to_fail)
3937 return xstrdup(refname);
3940 static struct string_list *hide_refs;
3942 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3944 if (!strcmp("transfer.hiderefs", var) ||
3945 /* NEEDSWORK: use parse_config_key() once both are merged */
3946 (starts_with(var, section) && var[strlen(section)] == '.' &&
3947 !strcmp(var + strlen(section), ".hiderefs"))) {
3952 return config_error_nonbool(var);
3953 ref = xstrdup(value);
3955 while (len && ref[len - 1] == '/')
3958 hide_refs = xcalloc(1, sizeof(*hide_refs));
3959 hide_refs->strdup_strings = 1;
3961 string_list_append(hide_refs, ref);
3966 int ref_is_hidden(const char *refname)
3968 struct string_list_item *item;
3972 for_each_string_list_item(item, hide_refs) {
3974 if (!starts_with(refname, item->string))
3976 len = strlen(item->string);
3977 if (!refname[len] || refname[len] == '/')
3983 struct expire_reflog_cb {
3985 reflog_expiry_should_prune_fn *should_prune_fn;
3988 unsigned char last_kept_sha1[20];
3991 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3992 const char *email, unsigned long timestamp, int tz,
3993 const char *message, void *cb_data)
3995 struct expire_reflog_cb *cb = cb_data;
3996 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3998 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3999 osha1 = cb->last_kept_sha1;
4001 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4002 message, policy_cb)) {
4004 printf("would prune %s", message);
4005 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4006 printf("prune %s", message);
4009 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4010 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4011 email, timestamp, tz, message);
4012 hashcpy(cb->last_kept_sha1, nsha1);
4014 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4015 printf("keep %s", message);
4020 int reflog_expire(const char *refname, const unsigned char *sha1,
4022 reflog_expiry_prepare_fn prepare_fn,
4023 reflog_expiry_should_prune_fn should_prune_fn,
4024 reflog_expiry_cleanup_fn cleanup_fn,
4025 void *policy_cb_data)
4027 static struct lock_file reflog_lock;
4028 struct expire_reflog_cb cb;
4029 struct ref_lock *lock;
4034 memset(&cb, 0, sizeof(cb));
4036 cb.policy_cb = policy_cb_data;
4037 cb.should_prune_fn = should_prune_fn;
4040 * The reflog file is locked by holding the lock on the
4041 * reference itself, plus we might need to update the
4042 * reference if --updateref was specified:
4044 lock = lock_ref_sha1_basic(refname, sha1, NULL, 0, &type);
4046 return error("cannot lock ref '%s'", refname);
4047 if (!reflog_exists(refname)) {
4052 log_file = git_pathdup("logs/%s", refname);
4053 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4055 * Even though holding $GIT_DIR/logs/$reflog.lock has
4056 * no locking implications, we use the lock_file
4057 * machinery here anyway because it does a lot of the
4058 * work we need, including cleaning up if the program
4059 * exits unexpectedly.
4061 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4062 struct strbuf err = STRBUF_INIT;
4063 unable_to_lock_message(log_file, errno, &err);
4064 error("%s", err.buf);
4065 strbuf_release(&err);
4068 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4070 error("cannot fdopen %s (%s)",
4071 reflog_lock.filename.buf, strerror(errno));
4076 (*prepare_fn)(refname, sha1, cb.policy_cb);
4077 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4078 (*cleanup_fn)(cb.policy_cb);
4080 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4082 * It doesn't make sense to adjust a reference pointed
4083 * to by a symbolic ref based on expiring entries in
4084 * the symbolic reference's reflog. Nor can we update
4085 * a reference if there are no remaining reflog
4088 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4089 !(type & REF_ISSYMREF) &&
4090 !is_null_sha1(cb.last_kept_sha1);
4092 if (close_lock_file(&reflog_lock)) {
4093 status |= error("couldn't write %s: %s", log_file,
4095 } else if (update &&
4096 (write_in_full(lock->lock_fd,
4097 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4098 write_str_in_full(lock->lock_fd, "\n") != 1 ||
4099 close_ref(lock) < 0)) {
4100 status |= error("couldn't write %s",
4101 lock->lk->filename.buf);
4102 rollback_lock_file(&reflog_lock);
4103 } else if (commit_lock_file(&reflog_lock)) {
4104 status |= error("unable to commit reflog '%s' (%s)",
4105 log_file, strerror(errno));
4106 } else if (update && commit_ref(lock)) {
4107 status |= error("couldn't set %s", lock->ref_name);
4115 rollback_lock_file(&reflog_lock);