refs.c: propagate any errno==ENOTDIR from _commit back to the callers
[git/jrn.git] / refs.c
blob69cbca5fdee44fec332cabc7f16ac24a3bc6be9a
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
6 #include "string-list.h"
8 /*
9 * How to handle various characters in refnames:
10 * 0: An acceptable character for refs
11 * 1: End-of-component
12 * 2: ., look for a preceding . to reject .. in refs
13 * 3: {, look for a preceding @ to reject @{ in refs
14 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
16 static unsigned char refname_disposition[256] = {
17 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
18 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
19 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
28 * Used as a flag to ref_transaction_delete when a loose ref is being
29 * pruned.
31 #define REF_ISPRUNING 0x0100
33 * Try to read one refname component from the front of refname.
34 * Return the length of the component found, or -1 if the component is
35 * not legal. It is legal if it is something reasonable to have under
36 * ".git/refs/"; We do not like it if:
38 * - any path component of it begins with ".", or
39 * - it has double dots "..", or
40 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
41 * - it ends with a "/".
42 * - it ends with ".lock"
43 * - it contains a "\" (backslash)
45 static int check_refname_component(const char *refname, int flags)
47 const char *cp;
48 char last = '\0';
50 for (cp = refname; ; cp++) {
51 int ch = *cp & 255;
52 unsigned char disp = refname_disposition[ch];
53 switch (disp) {
54 case 1:
55 goto out;
56 case 2:
57 if (last == '.')
58 return -1; /* Refname contains "..". */
59 break;
60 case 3:
61 if (last == '@')
62 return -1; /* Refname contains "@{". */
63 break;
64 case 4:
65 return -1;
67 last = ch;
69 out:
70 if (cp == refname)
71 return 0; /* Component has zero length. */
72 if (refname[0] == '.') {
73 if (!(flags & REFNAME_DOT_COMPONENT))
74 return -1; /* Component starts with '.'. */
76 * Even if leading dots are allowed, don't allow "."
77 * as a component (".." is prevented by a rule above).
79 if (refname[1] == '\0')
80 return -1; /* Component equals ".". */
82 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
83 return -1; /* Refname ends with ".lock". */
84 return cp - refname;
87 int check_refname_format(const char *refname, int flags)
89 int component_len, component_count = 0;
91 if (!strcmp(refname, "@"))
92 /* Refname is a single character '@'. */
93 return -1;
95 while (1) {
96 /* We are at the start of a path component. */
97 component_len = check_refname_component(refname, flags);
98 if (component_len <= 0) {
99 if ((flags & REFNAME_REFSPEC_PATTERN) &&
100 refname[0] == '*' &&
101 (refname[1] == '\0' || refname[1] == '/')) {
102 /* Accept one wildcard as a full refname component. */
103 flags &= ~REFNAME_REFSPEC_PATTERN;
104 component_len = 1;
105 } else {
106 return -1;
109 component_count++;
110 if (refname[component_len] == '\0')
111 break;
112 /* Skip to next component. */
113 refname += component_len + 1;
116 if (refname[component_len - 1] == '.')
117 return -1; /* Refname ends with '.'. */
118 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
119 return -1; /* Refname has only one component. */
120 return 0;
123 struct ref_entry;
126 * Information used (along with the information in ref_entry) to
127 * describe a single cached reference. This data structure only
128 * occurs embedded in a union in struct ref_entry, and only when
129 * (ref_entry->flag & REF_DIR) is zero.
131 struct ref_value {
133 * The name of the object to which this reference resolves
134 * (which may be a tag object). If REF_ISBROKEN, this is
135 * null. If REF_ISSYMREF, then this is the name of the object
136 * referred to by the last reference in the symlink chain.
138 unsigned char sha1[20];
141 * If REF_KNOWS_PEELED, then this field holds the peeled value
142 * of this reference, or null if the reference is known not to
143 * be peelable. See the documentation for peel_ref() for an
144 * exact definition of "peelable".
146 unsigned char peeled[20];
149 struct ref_cache;
152 * Information used (along with the information in ref_entry) to
153 * describe a level in the hierarchy of references. This data
154 * structure only occurs embedded in a union in struct ref_entry, and
155 * only when (ref_entry.flag & REF_DIR) is set. In that case,
156 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
157 * in the directory have already been read:
159 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
160 * or packed references, already read.
162 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
163 * references that hasn't been read yet (nor has any of its
164 * subdirectories).
166 * Entries within a directory are stored within a growable array of
167 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
168 * sorted are sorted by their component name in strcmp() order and the
169 * remaining entries are unsorted.
171 * Loose references are read lazily, one directory at a time. When a
172 * directory of loose references is read, then all of the references
173 * in that directory are stored, and REF_INCOMPLETE stubs are created
174 * for any subdirectories, but the subdirectories themselves are not
175 * read. The reading is triggered by get_ref_dir().
177 struct ref_dir {
178 int nr, alloc;
181 * Entries with index 0 <= i < sorted are sorted by name. New
182 * entries are appended to the list unsorted, and are sorted
183 * only when required; thus we avoid the need to sort the list
184 * after the addition of every reference.
186 int sorted;
188 /* A pointer to the ref_cache that contains this ref_dir. */
189 struct ref_cache *ref_cache;
191 struct ref_entry **entries;
195 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
196 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see
197 * refs.h.
201 * The field ref_entry->u.value.peeled of this value entry contains
202 * the correct peeled value for the reference, which might be
203 * null_sha1 if the reference is not a tag or if it is broken.
205 #define REF_KNOWS_PEELED 0x08
207 /* ref_entry represents a directory of references */
208 #define REF_DIR 0x10
211 * Entry has not yet been read from disk (used only for REF_DIR
212 * entries representing loose references)
214 #define REF_INCOMPLETE 0x20
217 * A ref_entry represents either a reference or a "subdirectory" of
218 * references.
220 * Each directory in the reference namespace is represented by a
221 * ref_entry with (flags & REF_DIR) set and containing a subdir member
222 * that holds the entries in that directory that have been read so
223 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
224 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
225 * used for loose reference directories.
227 * References are represented by a ref_entry with (flags & REF_DIR)
228 * unset and a value member that describes the reference's value. The
229 * flag member is at the ref_entry level, but it is also needed to
230 * interpret the contents of the value field (in other words, a
231 * ref_value object is not very much use without the enclosing
232 * ref_entry).
234 * Reference names cannot end with slash and directories' names are
235 * always stored with a trailing slash (except for the top-level
236 * directory, which is always denoted by ""). This has two nice
237 * consequences: (1) when the entries in each subdir are sorted
238 * lexicographically by name (as they usually are), the references in
239 * a whole tree can be generated in lexicographic order by traversing
240 * the tree in left-to-right, depth-first order; (2) the names of
241 * references and subdirectories cannot conflict, and therefore the
242 * presence of an empty subdirectory does not block the creation of a
243 * similarly-named reference. (The fact that reference names with the
244 * same leading components can conflict *with each other* is a
245 * separate issue that is regulated by is_refname_available().)
247 * Please note that the name field contains the fully-qualified
248 * reference (or subdirectory) name. Space could be saved by only
249 * storing the relative names. But that would require the full names
250 * to be generated on the fly when iterating in do_for_each_ref(), and
251 * would break callback functions, who have always been able to assume
252 * that the name strings that they are passed will not be freed during
253 * the iteration.
255 struct ref_entry {
256 unsigned char flag; /* ISSYMREF? ISPACKED? */
257 union {
258 struct ref_value value; /* if not (flags&REF_DIR) */
259 struct ref_dir subdir; /* if (flags&REF_DIR) */
260 } u;
262 * The full name of the reference (e.g., "refs/heads/master")
263 * or the full name of the directory with a trailing slash
264 * (e.g., "refs/heads/"):
266 char name[FLEX_ARRAY];
269 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
271 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
273 struct ref_dir *dir;
274 assert(entry->flag & REF_DIR);
275 dir = &entry->u.subdir;
276 if (entry->flag & REF_INCOMPLETE) {
277 read_loose_refs(entry->name, dir);
278 entry->flag &= ~REF_INCOMPLETE;
280 return dir;
283 static struct ref_entry *create_ref_entry(const char *refname,
284 const unsigned char *sha1, int flag,
285 int check_name)
287 int len;
288 struct ref_entry *ref;
290 if (check_name &&
291 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
292 die("Reference has invalid format: '%s'", refname);
293 len = strlen(refname) + 1;
294 ref = xmalloc(sizeof(struct ref_entry) + len);
295 hashcpy(ref->u.value.sha1, sha1);
296 hashclr(ref->u.value.peeled);
297 memcpy(ref->name, refname, len);
298 ref->flag = flag;
299 return ref;
302 static void clear_ref_dir(struct ref_dir *dir);
304 static void free_ref_entry(struct ref_entry *entry)
306 if (entry->flag & REF_DIR) {
308 * Do not use get_ref_dir() here, as that might
309 * trigger the reading of loose refs.
311 clear_ref_dir(&entry->u.subdir);
313 free(entry);
317 * Add a ref_entry to the end of dir (unsorted). Entry is always
318 * stored directly in dir; no recursion into subdirectories is
319 * done.
321 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
323 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
324 dir->entries[dir->nr++] = entry;
325 /* optimize for the case that entries are added in order */
326 if (dir->nr == 1 ||
327 (dir->nr == dir->sorted + 1 &&
328 strcmp(dir->entries[dir->nr - 2]->name,
329 dir->entries[dir->nr - 1]->name) < 0))
330 dir->sorted = dir->nr;
334 * Clear and free all entries in dir, recursively.
336 static void clear_ref_dir(struct ref_dir *dir)
338 int i;
339 for (i = 0; i < dir->nr; i++)
340 free_ref_entry(dir->entries[i]);
341 free(dir->entries);
342 dir->sorted = dir->nr = dir->alloc = 0;
343 dir->entries = NULL;
347 * Create a struct ref_entry object for the specified dirname.
348 * dirname is the name of the directory with a trailing slash (e.g.,
349 * "refs/heads/") or "" for the top-level directory.
351 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
352 const char *dirname, size_t len,
353 int incomplete)
355 struct ref_entry *direntry;
356 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
357 memcpy(direntry->name, dirname, len);
358 direntry->name[len] = '\0';
359 direntry->u.subdir.ref_cache = ref_cache;
360 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
361 return direntry;
364 static int ref_entry_cmp(const void *a, const void *b)
366 struct ref_entry *one = *(struct ref_entry **)a;
367 struct ref_entry *two = *(struct ref_entry **)b;
368 return strcmp(one->name, two->name);
371 static void sort_ref_dir(struct ref_dir *dir);
373 struct string_slice {
374 size_t len;
375 const char *str;
378 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
380 const struct string_slice *key = key_;
381 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
382 int cmp = strncmp(key->str, ent->name, key->len);
383 if (cmp)
384 return cmp;
385 return '\0' - (unsigned char)ent->name[key->len];
389 * Return the index of the entry with the given refname from the
390 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
391 * no such entry is found. dir must already be complete.
393 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
395 struct ref_entry **r;
396 struct string_slice key;
398 if (refname == NULL || !dir->nr)
399 return -1;
401 sort_ref_dir(dir);
402 key.len = len;
403 key.str = refname;
404 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
405 ref_entry_cmp_sslice);
407 if (r == NULL)
408 return -1;
410 return r - dir->entries;
414 * Search for a directory entry directly within dir (without
415 * recursing). Sort dir if necessary. subdirname must be a directory
416 * name (i.e., end in '/'). If mkdir is set, then create the
417 * directory if it is missing; otherwise, return NULL if the desired
418 * directory cannot be found. dir must already be complete.
420 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
421 const char *subdirname, size_t len,
422 int mkdir)
424 int entry_index = search_ref_dir(dir, subdirname, len);
425 struct ref_entry *entry;
426 if (entry_index == -1) {
427 if (!mkdir)
428 return NULL;
430 * Since dir is complete, the absence of a subdir
431 * means that the subdir really doesn't exist;
432 * therefore, create an empty record for it but mark
433 * the record complete.
435 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
436 add_entry_to_dir(dir, entry);
437 } else {
438 entry = dir->entries[entry_index];
440 return get_ref_dir(entry);
444 * If refname is a reference name, find the ref_dir within the dir
445 * tree that should hold refname. If refname is a directory name
446 * (i.e., ends in '/'), then return that ref_dir itself. dir must
447 * represent the top-level directory and must already be complete.
448 * Sort ref_dirs and recurse into subdirectories as necessary. If
449 * mkdir is set, then create any missing directories; otherwise,
450 * return NULL if the desired directory cannot be found.
452 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
453 const char *refname, int mkdir)
455 const char *slash;
456 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
457 size_t dirnamelen = slash - refname + 1;
458 struct ref_dir *subdir;
459 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
460 if (!subdir) {
461 dir = NULL;
462 break;
464 dir = subdir;
467 return dir;
471 * Find the value entry with the given name in dir, sorting ref_dirs
472 * and recursing into subdirectories as necessary. If the name is not
473 * found or it corresponds to a directory entry, return NULL.
475 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
477 int entry_index;
478 struct ref_entry *entry;
479 dir = find_containing_dir(dir, refname, 0);
480 if (!dir)
481 return NULL;
482 entry_index = search_ref_dir(dir, refname, strlen(refname));
483 if (entry_index == -1)
484 return NULL;
485 entry = dir->entries[entry_index];
486 return (entry->flag & REF_DIR) ? NULL : entry;
490 * Remove the entry with the given name from dir, recursing into
491 * subdirectories as necessary. If refname is the name of a directory
492 * (i.e., ends with '/'), then remove the directory and its contents.
493 * If the removal was successful, return the number of entries
494 * remaining in the directory entry that contained the deleted entry.
495 * If the name was not found, return -1. Please note that this
496 * function only deletes the entry from the cache; it does not delete
497 * it from the filesystem or ensure that other cache entries (which
498 * might be symbolic references to the removed entry) are updated.
499 * Nor does it remove any containing dir entries that might be made
500 * empty by the removal. dir must represent the top-level directory
501 * and must already be complete.
503 static int remove_entry(struct ref_dir *dir, const char *refname)
505 int refname_len = strlen(refname);
506 int entry_index;
507 struct ref_entry *entry;
508 int is_dir = refname[refname_len - 1] == '/';
509 if (is_dir) {
511 * refname represents a reference directory. Remove
512 * the trailing slash; otherwise we will get the
513 * directory *representing* refname rather than the
514 * one *containing* it.
516 char *dirname = xmemdupz(refname, refname_len - 1);
517 dir = find_containing_dir(dir, dirname, 0);
518 free(dirname);
519 } else {
520 dir = find_containing_dir(dir, refname, 0);
522 if (!dir)
523 return -1;
524 entry_index = search_ref_dir(dir, refname, refname_len);
525 if (entry_index == -1)
526 return -1;
527 entry = dir->entries[entry_index];
529 memmove(&dir->entries[entry_index],
530 &dir->entries[entry_index + 1],
531 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
533 dir->nr--;
534 if (dir->sorted > entry_index)
535 dir->sorted--;
536 free_ref_entry(entry);
537 return dir->nr;
541 * Add a ref_entry to the ref_dir (unsorted), recursing into
542 * subdirectories as necessary. dir must represent the top-level
543 * directory. Return 0 on success.
545 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
547 dir = find_containing_dir(dir, ref->name, 1);
548 if (!dir)
549 return -1;
550 add_entry_to_dir(dir, ref);
551 return 0;
555 * Emit a warning and return true iff ref1 and ref2 have the same name
556 * and the same sha1. Die if they have the same name but different
557 * sha1s.
559 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
561 if (strcmp(ref1->name, ref2->name))
562 return 0;
564 /* Duplicate name; make sure that they don't conflict: */
566 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
567 /* This is impossible by construction */
568 die("Reference directory conflict: %s", ref1->name);
570 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
571 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
573 warning("Duplicated ref: %s", ref1->name);
574 return 1;
578 * Sort the entries in dir non-recursively (if they are not already
579 * sorted) and remove any duplicate entries.
581 static void sort_ref_dir(struct ref_dir *dir)
583 int i, j;
584 struct ref_entry *last = NULL;
587 * This check also prevents passing a zero-length array to qsort(),
588 * which is a problem on some platforms.
590 if (dir->sorted == dir->nr)
591 return;
593 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
595 /* Remove any duplicates: */
596 for (i = 0, j = 0; j < dir->nr; j++) {
597 struct ref_entry *entry = dir->entries[j];
598 if (last && is_dup_ref(last, entry))
599 free_ref_entry(entry);
600 else
601 last = dir->entries[i++] = entry;
603 dir->sorted = dir->nr = i;
606 /* Include broken references in a do_for_each_ref*() iteration: */
607 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
610 * Return true iff the reference described by entry can be resolved to
611 * an object in the database. Emit a warning if the referred-to
612 * object does not exist.
614 static int ref_resolves_to_object(struct ref_entry *entry)
616 if (entry->flag & REF_ISBROKEN)
617 return 0;
618 if (!has_sha1_file(entry->u.value.sha1)) {
619 error("%s does not point to a valid object!", entry->name);
620 return 0;
622 return 1;
626 * current_ref is a performance hack: when iterating over references
627 * using the for_each_ref*() functions, current_ref is set to the
628 * current reference's entry before calling the callback function. If
629 * the callback function calls peel_ref(), then peel_ref() first
630 * checks whether the reference to be peeled is the current reference
631 * (it usually is) and if so, returns that reference's peeled version
632 * if it is available. This avoids a refname lookup in a common case.
634 static struct ref_entry *current_ref;
636 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
638 struct ref_entry_cb {
639 const char *base;
640 int trim;
641 int flags;
642 each_ref_fn *fn;
643 void *cb_data;
647 * Handle one reference in a do_for_each_ref*()-style iteration,
648 * calling an each_ref_fn for each entry.
650 static int do_one_ref(struct ref_entry *entry, void *cb_data)
652 struct ref_entry_cb *data = cb_data;
653 struct ref_entry *old_current_ref;
654 int retval;
656 if (!starts_with(entry->name, data->base))
657 return 0;
659 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
660 !ref_resolves_to_object(entry))
661 return 0;
663 /* Store the old value, in case this is a recursive call: */
664 old_current_ref = current_ref;
665 current_ref = entry;
666 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
667 entry->flag, data->cb_data);
668 current_ref = old_current_ref;
669 return retval;
673 * Call fn for each reference in dir that has index in the range
674 * offset <= index < dir->nr. Recurse into subdirectories that are in
675 * that index range, sorting them before iterating. This function
676 * does not sort dir itself; it should be sorted beforehand. fn is
677 * called for all references, including broken ones.
679 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
680 each_ref_entry_fn fn, void *cb_data)
682 int i;
683 assert(dir->sorted == dir->nr);
684 for (i = offset; i < dir->nr; i++) {
685 struct ref_entry *entry = dir->entries[i];
686 int retval;
687 if (entry->flag & REF_DIR) {
688 struct ref_dir *subdir = get_ref_dir(entry);
689 sort_ref_dir(subdir);
690 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
691 } else {
692 retval = fn(entry, cb_data);
694 if (retval)
695 return retval;
697 return 0;
701 * Call fn for each reference in the union of dir1 and dir2, in order
702 * by refname. Recurse into subdirectories. If a value entry appears
703 * in both dir1 and dir2, then only process the version that is in
704 * dir2. The input dirs must already be sorted, but subdirs will be
705 * sorted as needed. fn is called for all references, including
706 * broken ones.
708 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
709 struct ref_dir *dir2,
710 each_ref_entry_fn fn, void *cb_data)
712 int retval;
713 int i1 = 0, i2 = 0;
715 assert(dir1->sorted == dir1->nr);
716 assert(dir2->sorted == dir2->nr);
717 while (1) {
718 struct ref_entry *e1, *e2;
719 int cmp;
720 if (i1 == dir1->nr) {
721 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
723 if (i2 == dir2->nr) {
724 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
726 e1 = dir1->entries[i1];
727 e2 = dir2->entries[i2];
728 cmp = strcmp(e1->name, e2->name);
729 if (cmp == 0) {
730 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
731 /* Both are directories; descend them in parallel. */
732 struct ref_dir *subdir1 = get_ref_dir(e1);
733 struct ref_dir *subdir2 = get_ref_dir(e2);
734 sort_ref_dir(subdir1);
735 sort_ref_dir(subdir2);
736 retval = do_for_each_entry_in_dirs(
737 subdir1, subdir2, fn, cb_data);
738 i1++;
739 i2++;
740 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
741 /* Both are references; ignore the one from dir1. */
742 retval = fn(e2, cb_data);
743 i1++;
744 i2++;
745 } else {
746 die("conflict between reference and directory: %s",
747 e1->name);
749 } else {
750 struct ref_entry *e;
751 if (cmp < 0) {
752 e = e1;
753 i1++;
754 } else {
755 e = e2;
756 i2++;
758 if (e->flag & REF_DIR) {
759 struct ref_dir *subdir = get_ref_dir(e);
760 sort_ref_dir(subdir);
761 retval = do_for_each_entry_in_dir(
762 subdir, 0, fn, cb_data);
763 } else {
764 retval = fn(e, cb_data);
767 if (retval)
768 return retval;
773 * Load all of the refs from the dir into our in-memory cache. The hard work
774 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
775 * through all of the sub-directories. We do not even need to care about
776 * sorting, as traversal order does not matter to us.
778 static void prime_ref_dir(struct ref_dir *dir)
780 int i;
781 for (i = 0; i < dir->nr; i++) {
782 struct ref_entry *entry = dir->entries[i];
783 if (entry->flag & REF_DIR)
784 prime_ref_dir(get_ref_dir(entry));
788 * Return true iff refname1 and refname2 conflict with each other.
789 * Two reference names conflict if one of them exactly matches the
790 * leading components of the other; e.g., "foo/bar" conflicts with
791 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
792 * "foo/barbados".
794 static int names_conflict(const char *refname1, const char *refname2)
796 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
798 return (*refname1 == '\0' && *refname2 == '/')
799 || (*refname1 == '/' && *refname2 == '\0');
802 struct name_conflict_cb {
803 const char *refname;
804 const char *conflicting_refname;
805 const char **skip;
806 int skipnum;
809 static int name_conflict_fn(struct ref_entry *entry, void *cb_data)
811 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
812 int i;
813 for (i = 0; i < data->skipnum; i++)
814 if (!strcmp(entry->name, data->skip[i]))
815 return 0;
816 if (names_conflict(data->refname, entry->name)) {
817 data->conflicting_refname = entry->name;
818 return 1;
820 return 0;
824 * Return true iff a reference named refname could be created without
825 * conflicting with the name of an existing reference in dir. If
826 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
827 * (e.g., because oldrefname is scheduled for deletion in the same
828 * operation). skip contains a list of refs we want to skip checking for
829 * conflicts with.
831 static int is_refname_available(const char *refname,
832 struct ref_dir *dir,
833 const char **skip, int skipnum)
835 struct name_conflict_cb data;
836 data.refname = refname;
837 data.conflicting_refname = NULL;
838 data.skip = skip;
839 data.skipnum = skipnum;
841 sort_ref_dir(dir);
842 if (do_for_each_entry_in_dir(dir, 0, name_conflict_fn, &data)) {
843 error("'%s' exists; cannot create '%s'",
844 data.conflicting_refname, refname);
845 return 0;
847 return 1;
850 struct packed_ref_cache {
851 struct ref_entry *root;
854 * Count of references to the data structure in this instance,
855 * including the pointer from ref_cache::packed if any. The
856 * data will not be freed as long as the reference count is
857 * nonzero.
859 unsigned int referrers;
862 * Iff the packed-refs file associated with this instance is
863 * currently locked for writing, this points at the associated
864 * lock (which is owned by somebody else). The referrer count
865 * is also incremented when the file is locked and decremented
866 * when it is unlocked.
868 struct lock_file *lock;
870 /* The metadata from when this packed-refs cache was read */
871 struct stat_validity validity;
875 * Future: need to be in "struct repository"
876 * when doing a full libification.
878 static struct ref_cache {
879 struct ref_cache *next;
880 struct ref_entry *loose;
881 struct packed_ref_cache *packed;
883 * The submodule name, or "" for the main repo. We allocate
884 * length 1 rather than FLEX_ARRAY so that the main ref_cache
885 * is initialized correctly.
887 char name[1];
888 } ref_cache, *submodule_ref_caches;
890 /* Lock used for the main packed-refs file: */
891 static struct lock_file packlock;
894 * Increment the reference count of *packed_refs.
896 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
898 packed_refs->referrers++;
902 * Decrease the reference count of *packed_refs. If it goes to zero,
903 * free *packed_refs and return true; otherwise return false.
905 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
907 if (!--packed_refs->referrers) {
908 free_ref_entry(packed_refs->root);
909 stat_validity_clear(&packed_refs->validity);
910 free(packed_refs);
911 return 1;
912 } else {
913 return 0;
917 static void clear_packed_ref_cache(struct ref_cache *refs)
919 if (refs->packed) {
920 struct packed_ref_cache *packed_refs = refs->packed;
922 if (packed_refs->lock)
923 die("internal error: packed-ref cache cleared while locked");
924 refs->packed = NULL;
925 release_packed_ref_cache(packed_refs);
929 static void clear_loose_ref_cache(struct ref_cache *refs)
931 if (refs->loose) {
932 free_ref_entry(refs->loose);
933 refs->loose = NULL;
937 static struct ref_cache *create_ref_cache(const char *submodule)
939 int len;
940 struct ref_cache *refs;
941 if (!submodule)
942 submodule = "";
943 len = strlen(submodule) + 1;
944 refs = xcalloc(1, sizeof(struct ref_cache) + len);
945 memcpy(refs->name, submodule, len);
946 return refs;
950 * Return a pointer to a ref_cache for the specified submodule. For
951 * the main repository, use submodule==NULL. The returned structure
952 * will be allocated and initialized but not necessarily populated; it
953 * should not be freed.
955 static struct ref_cache *get_ref_cache(const char *submodule)
957 struct ref_cache *refs;
959 if (!submodule || !*submodule)
960 return &ref_cache;
962 for (refs = submodule_ref_caches; refs; refs = refs->next)
963 if (!strcmp(submodule, refs->name))
964 return refs;
966 refs = create_ref_cache(submodule);
967 refs->next = submodule_ref_caches;
968 submodule_ref_caches = refs;
969 return refs;
972 /* The length of a peeled reference line in packed-refs, including EOL: */
973 #define PEELED_LINE_LENGTH 42
976 * The packed-refs header line that we write out. Perhaps other
977 * traits will be added later. The trailing space is required.
979 static const char PACKED_REFS_HEADER[] =
980 "# pack-refs with: peeled fully-peeled \n";
983 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
984 * Return a pointer to the refname within the line (null-terminated),
985 * or NULL if there was a problem.
987 static const char *parse_ref_line(char *line, unsigned char *sha1)
990 * 42: the answer to everything.
992 * In this case, it happens to be the answer to
993 * 40 (length of sha1 hex representation)
994 * +1 (space in between hex and name)
995 * +1 (newline at the end of the line)
997 int len = strlen(line) - 42;
999 if (len <= 0)
1000 return NULL;
1001 if (get_sha1_hex(line, sha1) < 0)
1002 return NULL;
1003 if (!isspace(line[40]))
1004 return NULL;
1005 line += 41;
1006 if (isspace(*line))
1007 return NULL;
1008 if (line[len] != '\n')
1009 return NULL;
1010 line[len] = 0;
1012 return line;
1016 * Read f, which is a packed-refs file, into dir.
1018 * A comment line of the form "# pack-refs with: " may contain zero or
1019 * more traits. We interpret the traits as follows:
1021 * No traits:
1023 * Probably no references are peeled. But if the file contains a
1024 * peeled value for a reference, we will use it.
1026 * peeled:
1028 * References under "refs/tags/", if they *can* be peeled, *are*
1029 * peeled in this file. References outside of "refs/tags/" are
1030 * probably not peeled even if they could have been, but if we find
1031 * a peeled value for such a reference we will use it.
1033 * fully-peeled:
1035 * All references in the file that can be peeled are peeled.
1036 * Inversely (and this is more important), any references in the
1037 * file for which no peeled value is recorded is not peelable. This
1038 * trait should typically be written alongside "peeled" for
1039 * compatibility with older clients, but we do not require it
1040 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1042 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1044 struct ref_entry *last = NULL;
1045 char refline[PATH_MAX];
1046 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1048 while (fgets(refline, sizeof(refline), f)) {
1049 unsigned char sha1[20];
1050 const char *refname;
1051 static const char header[] = "# pack-refs with:";
1053 if (!strncmp(refline, header, sizeof(header)-1)) {
1054 const char *traits = refline + sizeof(header) - 1;
1055 if (strstr(traits, " fully-peeled "))
1056 peeled = PEELED_FULLY;
1057 else if (strstr(traits, " peeled "))
1058 peeled = PEELED_TAGS;
1059 /* perhaps other traits later as well */
1060 continue;
1063 refname = parse_ref_line(refline, sha1);
1064 if (refname) {
1065 last = create_ref_entry(refname, sha1, REF_ISPACKED, 1);
1066 if (peeled == PEELED_FULLY ||
1067 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1068 last->flag |= REF_KNOWS_PEELED;
1069 add_ref(dir, last);
1070 continue;
1072 if (last &&
1073 refline[0] == '^' &&
1074 strlen(refline) == PEELED_LINE_LENGTH &&
1075 refline[PEELED_LINE_LENGTH - 1] == '\n' &&
1076 !get_sha1_hex(refline + 1, sha1)) {
1077 hashcpy(last->u.value.peeled, sha1);
1079 * Regardless of what the file header said,
1080 * we definitely know the value of *this*
1081 * reference:
1083 last->flag |= REF_KNOWS_PEELED;
1089 * Get the packed_ref_cache for the specified ref_cache, creating it
1090 * if necessary.
1092 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1094 const char *packed_refs_file;
1096 if (*refs->name)
1097 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1098 else
1099 packed_refs_file = git_path("packed-refs");
1101 if (refs->packed &&
1102 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1103 clear_packed_ref_cache(refs);
1105 if (!refs->packed) {
1106 FILE *f;
1108 refs->packed = xcalloc(1, sizeof(*refs->packed));
1109 acquire_packed_ref_cache(refs->packed);
1110 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1111 f = fopen(packed_refs_file, "r");
1112 if (f) {
1113 stat_validity_update(&refs->packed->validity, fileno(f));
1114 read_packed_refs(f, get_ref_dir(refs->packed->root));
1115 fclose(f);
1118 return refs->packed;
1121 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1123 return get_ref_dir(packed_ref_cache->root);
1126 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1128 return get_packed_ref_dir(get_packed_ref_cache(refs));
1131 void add_packed_ref(const char *refname, const unsigned char *sha1)
1133 struct packed_ref_cache *packed_ref_cache =
1134 get_packed_ref_cache(&ref_cache);
1136 if (!packed_ref_cache->lock)
1137 die("internal error: packed refs not locked");
1138 add_ref(get_packed_ref_dir(packed_ref_cache),
1139 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1143 * Read the loose references from the namespace dirname into dir
1144 * (without recursing). dirname must end with '/'. dir must be the
1145 * directory entry corresponding to dirname.
1147 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1149 struct ref_cache *refs = dir->ref_cache;
1150 DIR *d;
1151 const char *path;
1152 struct dirent *de;
1153 int dirnamelen = strlen(dirname);
1154 struct strbuf refname;
1156 if (*refs->name)
1157 path = git_path_submodule(refs->name, "%s", dirname);
1158 else
1159 path = git_path("%s", dirname);
1161 d = opendir(path);
1162 if (!d)
1163 return;
1165 strbuf_init(&refname, dirnamelen + 257);
1166 strbuf_add(&refname, dirname, dirnamelen);
1168 while ((de = readdir(d)) != NULL) {
1169 unsigned char sha1[20];
1170 struct stat st;
1171 int flag;
1172 const char *refdir;
1174 if (de->d_name[0] == '.')
1175 continue;
1176 if (has_extension(de->d_name, ".lock"))
1177 continue;
1178 strbuf_addstr(&refname, de->d_name);
1179 refdir = *refs->name
1180 ? git_path_submodule(refs->name, "%s", refname.buf)
1181 : git_path("%s", refname.buf);
1182 if (stat(refdir, &st) < 0) {
1183 ; /* silently ignore */
1184 } else if (S_ISDIR(st.st_mode)) {
1185 strbuf_addch(&refname, '/');
1186 add_entry_to_dir(dir,
1187 create_dir_entry(refs, refname.buf,
1188 refname.len, 1));
1189 } else {
1190 if (*refs->name) {
1191 hashclr(sha1);
1192 flag = 0;
1193 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1194 hashclr(sha1);
1195 flag |= REF_ISBROKEN;
1197 } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
1198 hashclr(sha1);
1199 flag |= REF_ISBROKEN;
1201 add_entry_to_dir(dir,
1202 create_ref_entry(refname.buf, sha1, flag, 1));
1204 strbuf_setlen(&refname, dirnamelen);
1206 strbuf_release(&refname);
1207 closedir(d);
1210 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1212 if (!refs->loose) {
1214 * Mark the top-level directory complete because we
1215 * are about to read the only subdirectory that can
1216 * hold references:
1218 refs->loose = create_dir_entry(refs, "", 0, 0);
1220 * Create an incomplete entry for "refs/":
1222 add_entry_to_dir(get_ref_dir(refs->loose),
1223 create_dir_entry(refs, "refs/", 5, 1));
1225 return get_ref_dir(refs->loose);
1228 /* We allow "recursive" symbolic refs. Only within reason, though */
1229 #define MAXDEPTH 5
1230 #define MAXREFLEN (1024)
1233 * Called by resolve_gitlink_ref_recursive() after it failed to read
1234 * from the loose refs in ref_cache refs. Find <refname> in the
1235 * packed-refs file for the submodule.
1237 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1238 const char *refname, unsigned char *sha1)
1240 struct ref_entry *ref;
1241 struct ref_dir *dir = get_packed_refs(refs);
1243 ref = find_ref(dir, refname);
1244 if (ref == NULL)
1245 return -1;
1247 hashcpy(sha1, ref->u.value.sha1);
1248 return 0;
1251 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1252 const char *refname, unsigned char *sha1,
1253 int recursion)
1255 int fd, len;
1256 char buffer[128], *p;
1257 char *path;
1259 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1260 return -1;
1261 path = *refs->name
1262 ? git_path_submodule(refs->name, "%s", refname)
1263 : git_path("%s", refname);
1264 fd = open(path, O_RDONLY);
1265 if (fd < 0)
1266 return resolve_gitlink_packed_ref(refs, refname, sha1);
1268 len = read(fd, buffer, sizeof(buffer)-1);
1269 close(fd);
1270 if (len < 0)
1271 return -1;
1272 while (len && isspace(buffer[len-1]))
1273 len--;
1274 buffer[len] = 0;
1276 /* Was it a detached head or an old-fashioned symlink? */
1277 if (!get_sha1_hex(buffer, sha1))
1278 return 0;
1280 /* Symref? */
1281 if (strncmp(buffer, "ref:", 4))
1282 return -1;
1283 p = buffer + 4;
1284 while (isspace(*p))
1285 p++;
1287 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1290 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1292 int len = strlen(path), retval;
1293 char *submodule;
1294 struct ref_cache *refs;
1296 while (len && path[len-1] == '/')
1297 len--;
1298 if (!len)
1299 return -1;
1300 submodule = xstrndup(path, len);
1301 refs = get_ref_cache(submodule);
1302 free(submodule);
1304 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1305 return retval;
1309 * Return the ref_entry for the given refname from the packed
1310 * references. If it does not exist, return NULL.
1312 static struct ref_entry *get_packed_ref(const char *refname)
1314 return find_ref(get_packed_refs(&ref_cache), refname);
1318 * A loose ref file doesn't exist; check for a packed ref. The
1319 * options are forwarded from resolve_safe_unsafe().
1321 static const char *handle_missing_loose_ref(const char *refname,
1322 unsigned char *sha1,
1323 int reading,
1324 int *flag)
1326 struct ref_entry *entry;
1329 * The loose reference file does not exist; check for a packed
1330 * reference.
1332 entry = get_packed_ref(refname);
1333 if (entry) {
1334 hashcpy(sha1, entry->u.value.sha1);
1335 if (flag)
1336 *flag |= REF_ISPACKED;
1337 return refname;
1339 /* The reference is not a packed reference, either. */
1340 if (reading) {
1341 return NULL;
1342 } else {
1343 hashclr(sha1);
1344 return refname;
1348 /* This function needs to return a meaningful errno on failure */
1349 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1351 int depth = MAXDEPTH;
1352 ssize_t len;
1353 char buffer[256];
1354 static char refname_buffer[256];
1356 if (flag)
1357 *flag = 0;
1359 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1360 errno = EINVAL;
1361 return NULL;
1364 for (;;) {
1365 char path[PATH_MAX];
1366 struct stat st;
1367 char *buf;
1368 int fd;
1370 if (--depth < 0) {
1371 errno = ELOOP;
1372 return NULL;
1375 git_snpath(path, sizeof(path), "%s", refname);
1378 * We might have to loop back here to avoid a race
1379 * condition: first we lstat() the file, then we try
1380 * to read it as a link or as a file. But if somebody
1381 * changes the type of the file (file <-> directory
1382 * <-> symlink) between the lstat() and reading, then
1383 * we don't want to report that as an error but rather
1384 * try again starting with the lstat().
1386 stat_ref:
1387 if (lstat(path, &st) < 0) {
1388 if (errno == ENOENT)
1389 return handle_missing_loose_ref(refname, sha1,
1390 reading, flag);
1391 else
1392 return NULL;
1395 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1396 if (S_ISLNK(st.st_mode)) {
1397 len = readlink(path, buffer, sizeof(buffer)-1);
1398 if (len < 0) {
1399 if (errno == ENOENT || errno == EINVAL)
1400 /* inconsistent with lstat; retry */
1401 goto stat_ref;
1402 else
1403 return NULL;
1405 buffer[len] = 0;
1406 if (starts_with(buffer, "refs/") &&
1407 !check_refname_format(buffer, 0)) {
1408 strcpy(refname_buffer, buffer);
1409 refname = refname_buffer;
1410 if (flag)
1411 *flag |= REF_ISSYMREF;
1412 continue;
1416 /* Is it a directory? */
1417 if (S_ISDIR(st.st_mode)) {
1418 errno = EISDIR;
1419 return NULL;
1423 * Anything else, just open it and try to use it as
1424 * a ref
1426 fd = open(path, O_RDONLY);
1427 if (fd < 0) {
1428 if (errno == ENOENT)
1429 /* inconsistent with lstat; retry */
1430 goto stat_ref;
1431 else
1432 return NULL;
1434 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1435 if (len < 0) {
1436 int save_errno = errno;
1437 close(fd);
1438 errno = save_errno;
1439 return NULL;
1441 close(fd);
1442 while (len && isspace(buffer[len-1]))
1443 len--;
1444 buffer[len] = '\0';
1447 * Is it a symbolic ref?
1449 if (!starts_with(buffer, "ref:")) {
1451 * Please note that FETCH_HEAD has a second
1452 * line containing other data.
1454 if (get_sha1_hex(buffer, sha1) ||
1455 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1456 if (flag)
1457 *flag |= REF_ISBROKEN;
1458 errno = EINVAL;
1459 return NULL;
1461 return refname;
1463 if (flag)
1464 *flag |= REF_ISSYMREF;
1465 buf = buffer + 4;
1466 while (isspace(*buf))
1467 buf++;
1468 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1469 if (flag)
1470 *flag |= REF_ISBROKEN;
1471 errno = EINVAL;
1472 return NULL;
1474 refname = strcpy(refname_buffer, buf);
1478 char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1480 const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1481 return ret ? xstrdup(ret) : NULL;
1484 /* The argument to filter_refs */
1485 struct ref_filter {
1486 const char *pattern;
1487 each_ref_fn *fn;
1488 void *cb_data;
1491 int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1493 if (resolve_ref_unsafe(refname, sha1, reading, flags))
1494 return 0;
1495 return -1;
1498 int read_ref(const char *refname, unsigned char *sha1)
1500 return read_ref_full(refname, sha1, 1, NULL);
1503 int ref_exists(const char *refname)
1505 unsigned char sha1[20];
1506 return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1509 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1510 void *data)
1512 struct ref_filter *filter = (struct ref_filter *)data;
1513 if (wildmatch(filter->pattern, refname, 0, NULL))
1514 return 0;
1515 return filter->fn(refname, sha1, flags, filter->cb_data);
1518 enum peel_status {
1519 /* object was peeled successfully: */
1520 PEEL_PEELED = 0,
1523 * object cannot be peeled because the named object (or an
1524 * object referred to by a tag in the peel chain), does not
1525 * exist.
1527 PEEL_INVALID = -1,
1529 /* object cannot be peeled because it is not a tag: */
1530 PEEL_NON_TAG = -2,
1532 /* ref_entry contains no peeled value because it is a symref: */
1533 PEEL_IS_SYMREF = -3,
1536 * ref_entry cannot be peeled because it is broken (i.e., the
1537 * symbolic reference cannot even be resolved to an object
1538 * name):
1540 PEEL_BROKEN = -4
1544 * Peel the named object; i.e., if the object is a tag, resolve the
1545 * tag recursively until a non-tag is found. If successful, store the
1546 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1547 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1548 * and leave sha1 unchanged.
1550 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1552 struct object *o = lookup_unknown_object(name);
1554 if (o->type == OBJ_NONE) {
1555 int type = sha1_object_info(name, NULL);
1556 if (type < 0)
1557 return PEEL_INVALID;
1558 o->type = type;
1561 if (o->type != OBJ_TAG)
1562 return PEEL_NON_TAG;
1564 o = deref_tag_noverify(o);
1565 if (!o)
1566 return PEEL_INVALID;
1568 hashcpy(sha1, o->sha1);
1569 return PEEL_PEELED;
1573 * Peel the entry (if possible) and return its new peel_status. If
1574 * repeel is true, re-peel the entry even if there is an old peeled
1575 * value that is already stored in it.
1577 * It is OK to call this function with a packed reference entry that
1578 * might be stale and might even refer to an object that has since
1579 * been garbage-collected. In such a case, if the entry has
1580 * REF_KNOWS_PEELED then leave the status unchanged and return
1581 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1583 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1585 enum peel_status status;
1587 if (entry->flag & REF_KNOWS_PEELED) {
1588 if (repeel) {
1589 entry->flag &= ~REF_KNOWS_PEELED;
1590 hashclr(entry->u.value.peeled);
1591 } else {
1592 return is_null_sha1(entry->u.value.peeled) ?
1593 PEEL_NON_TAG : PEEL_PEELED;
1596 if (entry->flag & REF_ISBROKEN)
1597 return PEEL_BROKEN;
1598 if (entry->flag & REF_ISSYMREF)
1599 return PEEL_IS_SYMREF;
1601 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1602 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1603 entry->flag |= REF_KNOWS_PEELED;
1604 return status;
1607 int peel_ref(const char *refname, unsigned char *sha1)
1609 int flag;
1610 unsigned char base[20];
1612 if (current_ref && (current_ref->name == refname
1613 || !strcmp(current_ref->name, refname))) {
1614 if (peel_entry(current_ref, 0))
1615 return -1;
1616 hashcpy(sha1, current_ref->u.value.peeled);
1617 return 0;
1620 if (read_ref_full(refname, base, 1, &flag))
1621 return -1;
1624 * If the reference is packed, read its ref_entry from the
1625 * cache in the hope that we already know its peeled value.
1626 * We only try this optimization on packed references because
1627 * (a) forcing the filling of the loose reference cache could
1628 * be expensive and (b) loose references anyway usually do not
1629 * have REF_KNOWS_PEELED.
1631 if (flag & REF_ISPACKED) {
1632 struct ref_entry *r = get_packed_ref(refname);
1633 if (r) {
1634 if (peel_entry(r, 0))
1635 return -1;
1636 hashcpy(sha1, r->u.value.peeled);
1637 return 0;
1641 return peel_object(base, sha1);
1644 struct warn_if_dangling_data {
1645 FILE *fp;
1646 const char *refname;
1647 const struct string_list *refnames;
1648 const char *msg_fmt;
1651 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1652 int flags, void *cb_data)
1654 struct warn_if_dangling_data *d = cb_data;
1655 const char *resolves_to;
1656 unsigned char junk[20];
1658 if (!(flags & REF_ISSYMREF))
1659 return 0;
1661 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1662 if (!resolves_to
1663 || (d->refname
1664 ? strcmp(resolves_to, d->refname)
1665 : !string_list_has_string(d->refnames, resolves_to))) {
1666 return 0;
1669 fprintf(d->fp, d->msg_fmt, refname);
1670 fputc('\n', d->fp);
1671 return 0;
1674 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1676 struct warn_if_dangling_data data;
1678 data.fp = fp;
1679 data.refname = refname;
1680 data.refnames = NULL;
1681 data.msg_fmt = msg_fmt;
1682 for_each_rawref(warn_if_dangling_symref, &data);
1685 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1687 struct warn_if_dangling_data data;
1689 data.fp = fp;
1690 data.refname = NULL;
1691 data.refnames = refnames;
1692 data.msg_fmt = msg_fmt;
1693 for_each_rawref(warn_if_dangling_symref, &data);
1697 * Call fn for each reference in the specified ref_cache, omitting
1698 * references not in the containing_dir of base. fn is called for all
1699 * references, including broken ones. If fn ever returns a non-zero
1700 * value, stop the iteration and return that value; otherwise, return
1701 * 0.
1703 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1704 each_ref_entry_fn fn, void *cb_data)
1706 struct packed_ref_cache *packed_ref_cache;
1707 struct ref_dir *loose_dir;
1708 struct ref_dir *packed_dir;
1709 int retval = 0;
1712 * We must make sure that all loose refs are read before accessing the
1713 * packed-refs file; this avoids a race condition in which loose refs
1714 * are migrated to the packed-refs file by a simultaneous process, but
1715 * our in-memory view is from before the migration. get_packed_ref_cache()
1716 * takes care of making sure our view is up to date with what is on
1717 * disk.
1719 loose_dir = get_loose_refs(refs);
1720 if (base && *base) {
1721 loose_dir = find_containing_dir(loose_dir, base, 0);
1723 if (loose_dir)
1724 prime_ref_dir(loose_dir);
1726 packed_ref_cache = get_packed_ref_cache(refs);
1727 acquire_packed_ref_cache(packed_ref_cache);
1728 packed_dir = get_packed_ref_dir(packed_ref_cache);
1729 if (base && *base) {
1730 packed_dir = find_containing_dir(packed_dir, base, 0);
1733 if (packed_dir && loose_dir) {
1734 sort_ref_dir(packed_dir);
1735 sort_ref_dir(loose_dir);
1736 retval = do_for_each_entry_in_dirs(
1737 packed_dir, loose_dir, fn, cb_data);
1738 } else if (packed_dir) {
1739 sort_ref_dir(packed_dir);
1740 retval = do_for_each_entry_in_dir(
1741 packed_dir, 0, fn, cb_data);
1742 } else if (loose_dir) {
1743 sort_ref_dir(loose_dir);
1744 retval = do_for_each_entry_in_dir(
1745 loose_dir, 0, fn, cb_data);
1748 release_packed_ref_cache(packed_ref_cache);
1749 return retval;
1753 * Call fn for each reference in the specified ref_cache for which the
1754 * refname begins with base. If trim is non-zero, then trim that many
1755 * characters off the beginning of each refname before passing the
1756 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1757 * broken references in the iteration. If fn ever returns a non-zero
1758 * value, stop the iteration and return that value; otherwise, return
1759 * 0.
1761 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1762 each_ref_fn fn, int trim, int flags, void *cb_data)
1764 struct ref_entry_cb data;
1765 data.base = base;
1766 data.trim = trim;
1767 data.flags = flags;
1768 data.fn = fn;
1769 data.cb_data = cb_data;
1771 return do_for_each_entry(refs, base, do_one_ref, &data);
1774 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1776 unsigned char sha1[20];
1777 int flag;
1779 if (submodule) {
1780 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1781 return fn("HEAD", sha1, 0, cb_data);
1783 return 0;
1786 if (!read_ref_full("HEAD", sha1, 1, &flag))
1787 return fn("HEAD", sha1, flag, cb_data);
1789 return 0;
1792 int head_ref(each_ref_fn fn, void *cb_data)
1794 return do_head_ref(NULL, fn, cb_data);
1797 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1799 return do_head_ref(submodule, fn, cb_data);
1802 int for_each_ref(each_ref_fn fn, void *cb_data)
1804 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1807 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1809 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1812 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1814 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1817 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1818 each_ref_fn fn, void *cb_data)
1820 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1823 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1825 return for_each_ref_in("refs/tags/", fn, cb_data);
1828 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1830 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1833 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1835 return for_each_ref_in("refs/heads/", fn, cb_data);
1838 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1840 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1843 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1845 return for_each_ref_in("refs/remotes/", fn, cb_data);
1848 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1850 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1853 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1855 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
1858 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1860 struct strbuf buf = STRBUF_INIT;
1861 int ret = 0;
1862 unsigned char sha1[20];
1863 int flag;
1865 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1866 if (!read_ref_full(buf.buf, sha1, 1, &flag))
1867 ret = fn(buf.buf, sha1, flag, cb_data);
1868 strbuf_release(&buf);
1870 return ret;
1873 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1875 struct strbuf buf = STRBUF_INIT;
1876 int ret;
1877 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1878 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1879 strbuf_release(&buf);
1880 return ret;
1883 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1884 const char *prefix, void *cb_data)
1886 struct strbuf real_pattern = STRBUF_INIT;
1887 struct ref_filter filter;
1888 int ret;
1890 if (!prefix && !starts_with(pattern, "refs/"))
1891 strbuf_addstr(&real_pattern, "refs/");
1892 else if (prefix)
1893 strbuf_addstr(&real_pattern, prefix);
1894 strbuf_addstr(&real_pattern, pattern);
1896 if (!has_glob_specials(pattern)) {
1897 /* Append implied '/' '*' if not present. */
1898 if (real_pattern.buf[real_pattern.len - 1] != '/')
1899 strbuf_addch(&real_pattern, '/');
1900 /* No need to check for '*', there is none. */
1901 strbuf_addch(&real_pattern, '*');
1904 filter.pattern = real_pattern.buf;
1905 filter.fn = fn;
1906 filter.cb_data = cb_data;
1907 ret = for_each_ref(filter_refs, &filter);
1909 strbuf_release(&real_pattern);
1910 return ret;
1913 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1915 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1918 int for_each_rawref(each_ref_fn fn, void *cb_data)
1920 return do_for_each_ref(&ref_cache, "", fn, 0,
1921 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1924 const char *prettify_refname(const char *name)
1926 return name + (
1927 starts_with(name, "refs/heads/") ? 11 :
1928 starts_with(name, "refs/tags/") ? 10 :
1929 starts_with(name, "refs/remotes/") ? 13 :
1933 static const char *ref_rev_parse_rules[] = {
1934 "%.*s",
1935 "refs/%.*s",
1936 "refs/tags/%.*s",
1937 "refs/heads/%.*s",
1938 "refs/remotes/%.*s",
1939 "refs/remotes/%.*s/HEAD",
1940 NULL
1943 int refname_match(const char *abbrev_name, const char *full_name)
1945 const char **p;
1946 const int abbrev_name_len = strlen(abbrev_name);
1948 for (p = ref_rev_parse_rules; *p; p++) {
1949 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1950 return 1;
1954 return 0;
1957 /* This function should make sure errno is meaningful on error */
1958 static struct ref_lock *verify_lock(struct ref_lock *lock,
1959 const unsigned char *old_sha1, int mustexist)
1961 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1962 int save_errno = errno;
1963 error("Can't verify ref %s", lock->ref_name);
1964 unlock_ref(lock);
1965 errno = save_errno;
1966 return NULL;
1968 if (hashcmp(lock->old_sha1, old_sha1)) {
1969 error("Ref %s is at %s but expected %s", lock->ref_name,
1970 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1971 unlock_ref(lock);
1972 errno = EBUSY;
1973 return NULL;
1975 return lock;
1978 static int remove_empty_directories(const char *file)
1980 /* we want to create a file but there is a directory there;
1981 * if that is an empty directory (or a directory that contains
1982 * only empty directories), remove them.
1984 struct strbuf path;
1985 int result, save_errno;
1987 strbuf_init(&path, 20);
1988 strbuf_addstr(&path, file);
1990 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1991 save_errno = errno;
1993 strbuf_release(&path);
1994 errno = save_errno;
1996 return result;
2000 * *string and *len will only be substituted, and *string returned (for
2001 * later free()ing) if the string passed in is a magic short-hand form
2002 * to name a branch.
2004 static char *substitute_branch_name(const char **string, int *len)
2006 struct strbuf buf = STRBUF_INIT;
2007 int ret = interpret_branch_name(*string, *len, &buf);
2009 if (ret == *len) {
2010 size_t size;
2011 *string = strbuf_detach(&buf, &size);
2012 *len = size;
2013 return (char *)*string;
2016 return NULL;
2019 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2021 char *last_branch = substitute_branch_name(&str, &len);
2022 const char **p, *r;
2023 int refs_found = 0;
2025 *ref = NULL;
2026 for (p = ref_rev_parse_rules; *p; p++) {
2027 char fullref[PATH_MAX];
2028 unsigned char sha1_from_ref[20];
2029 unsigned char *this_result;
2030 int flag;
2032 this_result = refs_found ? sha1_from_ref : sha1;
2033 mksnpath(fullref, sizeof(fullref), *p, len, str);
2034 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
2035 if (r) {
2036 if (!refs_found++)
2037 *ref = xstrdup(r);
2038 if (!warn_ambiguous_refs)
2039 break;
2040 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2041 warning("ignoring dangling symref %s.", fullref);
2042 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2043 warning("ignoring broken ref %s.", fullref);
2046 free(last_branch);
2047 return refs_found;
2050 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2052 char *last_branch = substitute_branch_name(&str, &len);
2053 const char **p;
2054 int logs_found = 0;
2056 *log = NULL;
2057 for (p = ref_rev_parse_rules; *p; p++) {
2058 unsigned char hash[20];
2059 char path[PATH_MAX];
2060 const char *ref, *it;
2062 mksnpath(path, sizeof(path), *p, len, str);
2063 ref = resolve_ref_unsafe(path, hash, 1, NULL);
2064 if (!ref)
2065 continue;
2066 if (reflog_exists(path))
2067 it = path;
2068 else if (strcmp(ref, path) && reflog_exists(ref))
2069 it = ref;
2070 else
2071 continue;
2072 if (!logs_found++) {
2073 *log = xstrdup(it);
2074 hashcpy(sha1, hash);
2076 if (!warn_ambiguous_refs)
2077 break;
2079 free(last_branch);
2080 return logs_found;
2083 /* This function should make sure errno is meaningful on error */
2084 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2085 const unsigned char *old_sha1,
2086 int flags, int *type_p,
2087 const char **skip, int skipnum)
2089 char *ref_file;
2090 const char *orig_refname = refname;
2091 struct ref_lock *lock;
2092 int last_errno = 0;
2093 int type, lflags;
2094 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2095 int missing = 0;
2096 int attempts_remaining = 3;
2098 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
2099 errno = EINVAL;
2100 return NULL;
2103 lock = xcalloc(1, sizeof(struct ref_lock));
2104 lock->lock_fd = -1;
2106 refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
2107 if (!refname && errno == EISDIR) {
2108 /* we are trying to lock foo but we used to
2109 * have foo/bar which now does not exist;
2110 * it is normal for the empty directory 'foo'
2111 * to remain.
2113 ref_file = git_path("%s", orig_refname);
2114 if (remove_empty_directories(ref_file)) {
2115 last_errno = errno;
2116 error("there are still refs under '%s'", orig_refname);
2117 goto error_return;
2119 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
2121 if (type_p)
2122 *type_p = type;
2123 if (!refname) {
2124 last_errno = errno;
2125 error("unable to resolve reference %s: %s",
2126 orig_refname, strerror(errno));
2127 goto error_return;
2129 missing = is_null_sha1(lock->old_sha1);
2130 /* When the ref did not exist and we are creating it,
2131 * make sure there is no existing ref that is packed
2132 * whose name begins with our refname, nor a ref whose
2133 * name is a proper prefix of our refname.
2135 if (missing &&
2136 !is_refname_available(refname, get_packed_refs(&ref_cache),
2137 skip, skipnum)) {
2138 last_errno = ENOTDIR;
2139 goto error_return;
2142 lock->lk = xcalloc(1, sizeof(struct lock_file));
2144 lflags = 0;
2145 if (flags & REF_NODEREF) {
2146 refname = orig_refname;
2147 lflags |= LOCK_NODEREF;
2149 lock->ref_name = xstrdup(refname);
2150 lock->orig_ref_name = xstrdup(orig_refname);
2151 ref_file = git_path("%s", refname);
2152 if (missing)
2153 lock->force_write = 1;
2154 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2155 lock->force_write = 1;
2157 retry:
2158 switch (safe_create_leading_directories(ref_file)) {
2159 case SCLD_OK:
2160 break; /* success */
2161 case SCLD_VANISHED:
2162 if (--attempts_remaining > 0)
2163 goto retry;
2164 /* fall through */
2165 default:
2166 last_errno = errno;
2167 error("unable to create directory for %s", ref_file);
2168 goto error_return;
2171 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2172 if (lock->lock_fd < 0) {
2173 if (errno == ENOENT && --attempts_remaining > 0)
2175 * Maybe somebody just deleted one of the
2176 * directories leading to ref_file. Try
2177 * again:
2179 goto retry;
2180 else
2181 unable_to_lock_index_die(ref_file, errno);
2183 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2185 error_return:
2186 unlock_ref(lock);
2187 errno = last_errno;
2188 return NULL;
2191 struct ref_lock *lock_any_ref_for_update(const char *refname,
2192 const unsigned char *old_sha1,
2193 int flags, int *type_p)
2195 return lock_ref_sha1_basic(refname, old_sha1, flags, type_p, NULL, 0);
2199 * Write an entry to the packed-refs file for the specified refname.
2200 * If peeled is non-NULL, write it as the entry's peeled value.
2202 static void write_packed_entry(int fd, char *refname, unsigned char *sha1,
2203 unsigned char *peeled)
2205 char line[PATH_MAX + 100];
2206 int len;
2208 len = snprintf(line, sizeof(line), "%s %s\n",
2209 sha1_to_hex(sha1), refname);
2210 /* this should not happen but just being defensive */
2211 if (len > sizeof(line))
2212 die("too long a refname '%s'", refname);
2213 write_or_die(fd, line, len);
2215 if (peeled) {
2216 if (snprintf(line, sizeof(line), "^%s\n",
2217 sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)
2218 die("internal error");
2219 write_or_die(fd, line, PEELED_LINE_LENGTH);
2224 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2226 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2228 int *fd = cb_data;
2229 enum peel_status peel_status = peel_entry(entry, 0);
2231 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2232 error("internal error: %s is not a valid packed reference!",
2233 entry->name);
2234 write_packed_entry(*fd, entry->name, entry->u.value.sha1,
2235 peel_status == PEEL_PEELED ?
2236 entry->u.value.peeled : NULL);
2237 return 0;
2240 /* This should return a meaningful errno on failure */
2241 int lock_packed_refs(int flags)
2243 struct packed_ref_cache *packed_ref_cache;
2245 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2246 return -1;
2248 * Get the current packed-refs while holding the lock. If the
2249 * packed-refs file has been modified since we last read it,
2250 * this will automatically invalidate the cache and re-read
2251 * the packed-refs file.
2253 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2254 packed_ref_cache->lock = &packlock;
2255 /* Increment the reference count to prevent it from being freed: */
2256 acquire_packed_ref_cache(packed_ref_cache);
2257 return 0;
2261 * Commit the packed refs changes.
2262 * On error we must make sure that errno contains a meaningful value.
2264 int commit_packed_refs(void)
2266 struct packed_ref_cache *packed_ref_cache =
2267 get_packed_ref_cache(&ref_cache);
2268 int error = 0;
2269 int save_errno = 0;
2271 if (!packed_ref_cache->lock)
2272 die("internal error: packed-refs not locked");
2273 write_or_die(packed_ref_cache->lock->fd,
2274 PACKED_REFS_HEADER, strlen(PACKED_REFS_HEADER));
2276 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2277 0, write_packed_entry_fn,
2278 &packed_ref_cache->lock->fd);
2279 if (commit_lock_file(packed_ref_cache->lock)) {
2280 save_errno = errno;
2281 error = -1;
2283 packed_ref_cache->lock = NULL;
2284 release_packed_ref_cache(packed_ref_cache);
2285 errno = save_errno;
2286 return error;
2289 void rollback_packed_refs(void)
2291 struct packed_ref_cache *packed_ref_cache =
2292 get_packed_ref_cache(&ref_cache);
2294 if (!packed_ref_cache->lock)
2295 die("internal error: packed-refs not locked");
2296 rollback_lock_file(packed_ref_cache->lock);
2297 packed_ref_cache->lock = NULL;
2298 release_packed_ref_cache(packed_ref_cache);
2299 clear_packed_ref_cache(&ref_cache);
2302 struct ref_to_prune {
2303 struct ref_to_prune *next;
2304 unsigned char sha1[20];
2305 char name[FLEX_ARRAY];
2308 struct pack_refs_cb_data {
2309 unsigned int flags;
2310 struct ref_dir *packed_refs;
2311 struct ref_to_prune *ref_to_prune;
2315 * An each_ref_entry_fn that is run over loose references only. If
2316 * the loose reference can be packed, add an entry in the packed ref
2317 * cache. If the reference should be pruned, also add it to
2318 * ref_to_prune in the pack_refs_cb_data.
2320 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2322 struct pack_refs_cb_data *cb = cb_data;
2323 enum peel_status peel_status;
2324 struct ref_entry *packed_entry;
2325 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2327 /* ALWAYS pack tags */
2328 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2329 return 0;
2331 /* Do not pack symbolic or broken refs: */
2332 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2333 return 0;
2335 /* Add a packed ref cache entry equivalent to the loose entry. */
2336 peel_status = peel_entry(entry, 1);
2337 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2338 die("internal error peeling reference %s (%s)",
2339 entry->name, sha1_to_hex(entry->u.value.sha1));
2340 packed_entry = find_ref(cb->packed_refs, entry->name);
2341 if (packed_entry) {
2342 /* Overwrite existing packed entry with info from loose entry */
2343 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2344 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2345 } else {
2346 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2347 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2348 add_ref(cb->packed_refs, packed_entry);
2350 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2352 /* Schedule the loose reference for pruning if requested. */
2353 if ((cb->flags & PACK_REFS_PRUNE)) {
2354 int namelen = strlen(entry->name) + 1;
2355 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2356 hashcpy(n->sha1, entry->u.value.sha1);
2357 strcpy(n->name, entry->name);
2358 n->next = cb->ref_to_prune;
2359 cb->ref_to_prune = n;
2361 return 0;
2365 * Remove empty parents, but spare refs/ and immediate subdirs.
2366 * Note: munges *name.
2368 static void try_remove_empty_parents(char *name)
2370 char *p, *q;
2371 int i;
2372 p = name;
2373 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2374 while (*p && *p != '/')
2375 p++;
2376 /* tolerate duplicate slashes; see check_refname_format() */
2377 while (*p == '/')
2378 p++;
2380 for (q = p; *q; q++)
2382 while (1) {
2383 while (q > p && *q != '/')
2384 q--;
2385 while (q > p && *(q-1) == '/')
2386 q--;
2387 if (q == p)
2388 break;
2389 *q = '\0';
2390 if (rmdir(git_path("%s", name)))
2391 break;
2395 /* make sure nobody touched the ref, and unlink */
2396 static void prune_ref(struct ref_to_prune *r)
2398 struct ref_transaction *transaction;
2399 struct strbuf err = STRBUF_INIT;
2401 if (check_refname_format(r->name + 5, 0))
2402 return;
2404 transaction = ref_transaction_begin(&err);
2405 if (!transaction ||
2406 ref_transaction_delete(transaction, r->name, r->sha1,
2407 REF_ISPRUNING, 1, NULL, &err) ||
2408 ref_transaction_commit(transaction, &err)) {
2409 ref_transaction_free(transaction);
2410 error("%s", err.buf);
2411 strbuf_release(&err);
2412 return;
2414 ref_transaction_free(transaction);
2415 try_remove_empty_parents(r->name);
2418 static void prune_refs(struct ref_to_prune *r)
2420 while (r) {
2421 prune_ref(r);
2422 r = r->next;
2426 int pack_refs(unsigned int flags)
2428 struct pack_refs_cb_data cbdata;
2430 memset(&cbdata, 0, sizeof(cbdata));
2431 cbdata.flags = flags;
2433 lock_packed_refs(LOCK_DIE_ON_ERROR);
2434 cbdata.packed_refs = get_packed_refs(&ref_cache);
2436 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2437 pack_if_possible_fn, &cbdata);
2439 if (commit_packed_refs())
2440 die_errno("unable to overwrite old ref-pack file");
2442 prune_refs(cbdata.ref_to_prune);
2443 return 0;
2447 * If entry is no longer needed in packed-refs, add it to the string
2448 * list pointed to by cb_data. Reasons for deleting entries:
2450 * - Entry is broken.
2451 * - Entry is overridden by a loose ref.
2452 * - Entry does not point at a valid object.
2454 * In the first and third cases, also emit an error message because these
2455 * are indications of repository corruption.
2457 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2459 struct string_list *refs_to_delete = cb_data;
2461 if (entry->flag & REF_ISBROKEN) {
2462 /* This shouldn't happen to packed refs. */
2463 error("%s is broken!", entry->name);
2464 string_list_append(refs_to_delete, entry->name);
2465 return 0;
2467 if (!has_sha1_file(entry->u.value.sha1)) {
2468 unsigned char sha1[20];
2469 int flags;
2471 if (read_ref_full(entry->name, sha1, 0, &flags))
2472 /* We should at least have found the packed ref. */
2473 die("Internal error");
2474 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2476 * This packed reference is overridden by a
2477 * loose reference, so it is OK that its value
2478 * is no longer valid; for example, it might
2479 * refer to an object that has been garbage
2480 * collected. For this purpose we don't even
2481 * care whether the loose reference itself is
2482 * invalid, broken, symbolic, etc. Silently
2483 * remove the packed reference.
2485 string_list_append(refs_to_delete, entry->name);
2486 return 0;
2489 * There is no overriding loose reference, so the fact
2490 * that this reference doesn't refer to a valid object
2491 * indicates some kind of repository corruption.
2492 * Report the problem, then omit the reference from
2493 * the output.
2495 error("%s does not point to a valid object!", entry->name);
2496 string_list_append(refs_to_delete, entry->name);
2497 return 0;
2500 return 0;
2503 int repack_without_refs(const char **refnames, int n, struct strbuf *err)
2505 struct ref_dir *packed;
2506 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2507 struct string_list_item *ref_to_delete;
2508 int i, ret, removed = 0;
2510 /* Look for a packed ref */
2511 for (i = 0; i < n; i++)
2512 if (get_packed_ref(refnames[i]))
2513 break;
2515 /* Avoid locking if we have nothing to do */
2516 if (i == n)
2517 return 0; /* no refname exists in packed refs */
2519 if (lock_packed_refs(0)) {
2520 if (err) {
2521 unable_to_lock_message(git_path("packed-refs"), errno,
2522 err);
2523 return -1;
2525 unable_to_lock_error(git_path("packed-refs"), errno);
2526 return error("cannot delete '%s' from packed refs", refnames[i]);
2528 packed = get_packed_refs(&ref_cache);
2530 /* Remove refnames from the cache */
2531 for (i = 0; i < n; i++)
2532 if (remove_entry(packed, refnames[i]) != -1)
2533 removed = 1;
2534 if (!removed) {
2536 * All packed entries disappeared while we were
2537 * acquiring the lock.
2539 rollback_packed_refs();
2540 return 0;
2543 /* Remove any other accumulated cruft */
2544 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2545 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2546 if (remove_entry(packed, ref_to_delete->string) == -1)
2547 die("internal error");
2550 /* Write what remains */
2551 ret = commit_packed_refs();
2552 if (ret && err)
2553 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2554 strerror(errno));
2555 return ret;
2558 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2560 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2561 /* loose */
2562 int res, i = strlen(lock->lk->filename) - 5; /* .lock */
2564 lock->lk->filename[i] = 0;
2565 res = unlink_or_msg(lock->lk->filename, err);
2566 lock->lk->filename[i] = '.';
2567 if (res)
2568 return 1;
2570 return 0;
2573 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2575 struct ref_transaction *transaction;
2576 struct strbuf err = STRBUF_INIT;
2578 transaction = ref_transaction_begin(&err);
2579 if (!transaction ||
2580 ref_transaction_delete(transaction, refname, sha1, delopt,
2581 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2582 ref_transaction_commit(transaction, &err)) {
2583 error("%s", err.buf);
2584 ref_transaction_free(transaction);
2585 strbuf_release(&err);
2586 return 1;
2588 ref_transaction_free(transaction);
2589 return 0;
2593 * People using contrib's git-new-workdir have .git/logs/refs ->
2594 * /some/other/path/.git/logs/refs, and that may live on another device.
2596 * IOW, to avoid cross device rename errors, the temporary renamed log must
2597 * live into logs/refs.
2599 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2601 static int rename_tmp_log(const char *newrefname)
2603 int attempts_remaining = 4;
2605 retry:
2606 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2607 case SCLD_OK:
2608 break; /* success */
2609 case SCLD_VANISHED:
2610 if (--attempts_remaining > 0)
2611 goto retry;
2612 /* fall through */
2613 default:
2614 error("unable to create directory for %s", newrefname);
2615 return -1;
2618 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2619 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2621 * rename(a, b) when b is an existing
2622 * directory ought to result in ISDIR, but
2623 * Solaris 5.8 gives ENOTDIR. Sheesh.
2625 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2626 error("Directory not empty: logs/%s", newrefname);
2627 return -1;
2629 goto retry;
2630 } else if (errno == ENOENT && --attempts_remaining > 0) {
2632 * Maybe another process just deleted one of
2633 * the directories in the path to newrefname.
2634 * Try again from the beginning.
2636 goto retry;
2637 } else {
2638 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2639 newrefname, strerror(errno));
2640 return -1;
2643 return 0;
2646 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2648 unsigned char sha1[20], orig_sha1[20];
2649 int flag = 0, logmoved = 0;
2650 struct ref_lock *lock;
2651 struct stat loginfo;
2652 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2653 const char *symref = NULL;
2655 if (log && S_ISLNK(loginfo.st_mode))
2656 return error("reflog for %s is a symlink", oldrefname);
2658 symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
2659 if (flag & REF_ISSYMREF)
2660 return error("refname %s is a symbolic ref, renaming it is not supported",
2661 oldrefname);
2662 if (!symref)
2663 return error("refname %s not found", oldrefname);
2665 if (!is_refname_available(newrefname, get_packed_refs(&ref_cache),
2666 &oldrefname, 1))
2667 return 1;
2669 if (!is_refname_available(newrefname, get_loose_refs(&ref_cache),
2670 &oldrefname, 1))
2671 return 1;
2673 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2674 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2675 oldrefname, strerror(errno));
2677 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2678 error("unable to delete old %s", oldrefname);
2679 goto rollback;
2682 if (!read_ref_full(newrefname, sha1, 1, NULL) &&
2683 delete_ref(newrefname, sha1, REF_NODEREF)) {
2684 if (errno==EISDIR) {
2685 if (remove_empty_directories(git_path("%s", newrefname))) {
2686 error("Directory not empty: %s", newrefname);
2687 goto rollback;
2689 } else {
2690 error("unable to delete existing %s", newrefname);
2691 goto rollback;
2695 if (log && rename_tmp_log(newrefname))
2696 goto rollback;
2698 logmoved = log;
2700 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL, NULL, 0);
2701 if (!lock) {
2702 error("unable to lock %s for update", newrefname);
2703 goto rollback;
2705 lock->force_write = 1;
2706 hashcpy(lock->old_sha1, orig_sha1);
2707 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
2708 error("unable to write current sha1 into %s", newrefname);
2709 goto rollback;
2712 return 0;
2714 rollback:
2715 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL, NULL, 0);
2716 if (!lock) {
2717 error("unable to lock %s for rollback", oldrefname);
2718 goto rollbacklog;
2721 lock->force_write = 1;
2722 flag = log_all_ref_updates;
2723 log_all_ref_updates = 0;
2724 if (write_ref_sha1(lock, orig_sha1, NULL))
2725 error("unable to write current sha1 into %s", oldrefname);
2726 log_all_ref_updates = flag;
2728 rollbacklog:
2729 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2730 error("unable to restore logfile %s from %s: %s",
2731 oldrefname, newrefname, strerror(errno));
2732 if (!logmoved && log &&
2733 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2734 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2735 oldrefname, strerror(errno));
2737 return 1;
2740 int close_ref(struct ref_lock *lock)
2742 if (close_lock_file(lock->lk))
2743 return -1;
2744 lock->lock_fd = -1;
2745 return 0;
2748 int commit_ref(struct ref_lock *lock)
2750 if (commit_lock_file(lock->lk))
2751 return -1;
2752 lock->lock_fd = -1;
2753 return 0;
2756 void unlock_ref(struct ref_lock *lock)
2758 /* Do not free lock->lk -- atexit() still looks at them */
2759 if (lock->lk)
2760 rollback_lock_file(lock->lk);
2761 free(lock->ref_name);
2762 free(lock->orig_ref_name);
2763 free(lock);
2767 * copy the reflog message msg to buf, which has been allocated sufficiently
2768 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2769 * because reflog file is one line per entry.
2771 static int copy_msg(char *buf, const char *msg)
2773 char *cp = buf;
2774 char c;
2775 int wasspace = 1;
2777 *cp++ = '\t';
2778 while ((c = *msg++)) {
2779 if (wasspace && isspace(c))
2780 continue;
2781 wasspace = isspace(c);
2782 if (wasspace)
2783 c = ' ';
2784 *cp++ = c;
2786 while (buf < cp && isspace(cp[-1]))
2787 cp--;
2788 *cp++ = '\n';
2789 return cp - buf;
2792 /* This function must set a meaningful errno on failure */
2793 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2795 int logfd, oflags = O_APPEND | O_WRONLY;
2797 git_snpath(logfile, bufsize, "logs/%s", refname);
2798 if (log_all_ref_updates &&
2799 (starts_with(refname, "refs/heads/") ||
2800 starts_with(refname, "refs/remotes/") ||
2801 starts_with(refname, "refs/notes/") ||
2802 !strcmp(refname, "HEAD"))) {
2803 if (safe_create_leading_directories(logfile) < 0) {
2804 int save_errno = errno;
2805 error("unable to create directory for %s", logfile);
2806 errno = save_errno;
2807 return -1;
2809 oflags |= O_CREAT;
2812 logfd = open(logfile, oflags, 0666);
2813 if (logfd < 0) {
2814 if (!(oflags & O_CREAT) && errno == ENOENT)
2815 return 0;
2817 if ((oflags & O_CREAT) && errno == EISDIR) {
2818 if (remove_empty_directories(logfile)) {
2819 int save_errno = errno;
2820 error("There are still logs under '%s'",
2821 logfile);
2822 errno = save_errno;
2823 return -1;
2825 logfd = open(logfile, oflags, 0666);
2828 if (logfd < 0) {
2829 int save_errno = errno;
2830 error("Unable to append to %s: %s", logfile,
2831 strerror(errno));
2832 errno = save_errno;
2833 return -1;
2837 adjust_shared_perm(logfile);
2838 close(logfd);
2839 return 0;
2842 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2843 const unsigned char *new_sha1, const char *msg)
2845 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2846 unsigned maxlen, len;
2847 int msglen;
2848 char log_file[PATH_MAX];
2849 char *logrec;
2850 const char *committer;
2852 if (log_all_ref_updates < 0)
2853 log_all_ref_updates = !is_bare_repository();
2855 result = log_ref_setup(refname, log_file, sizeof(log_file));
2856 if (result)
2857 return result;
2859 logfd = open(log_file, oflags);
2860 if (logfd < 0)
2861 return 0;
2862 msglen = msg ? strlen(msg) : 0;
2863 committer = git_committer_info(0);
2864 maxlen = strlen(committer) + msglen + 100;
2865 logrec = xmalloc(maxlen);
2866 len = sprintf(logrec, "%s %s %s\n",
2867 sha1_to_hex(old_sha1),
2868 sha1_to_hex(new_sha1),
2869 committer);
2870 if (msglen)
2871 len += copy_msg(logrec + len - 1, msg) - 1;
2872 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2873 free(logrec);
2874 if (written != len) {
2875 int save_errno = errno;
2876 close(logfd);
2877 error("Unable to append to %s", log_file);
2878 errno = save_errno;
2879 return -1;
2881 if (close(logfd)) {
2882 int save_errno = errno;
2883 error("Unable to append to %s", log_file);
2884 errno = save_errno;
2885 return -1;
2887 return 0;
2890 static int is_branch(const char *refname)
2892 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
2895 /* This function must return a meaningful errno */
2896 int write_ref_sha1(struct ref_lock *lock,
2897 const unsigned char *sha1, const char *logmsg)
2899 static char term = '\n';
2900 struct object *o;
2902 if (!lock) {
2903 errno = EINVAL;
2904 return -1;
2906 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2907 unlock_ref(lock);
2908 return 0;
2910 o = parse_object(sha1);
2911 if (!o) {
2912 error("Trying to write ref %s with nonexistent object %s",
2913 lock->ref_name, sha1_to_hex(sha1));
2914 unlock_ref(lock);
2915 errno = EINVAL;
2916 return -1;
2918 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2919 error("Trying to write non-commit object %s to branch %s",
2920 sha1_to_hex(sha1), lock->ref_name);
2921 unlock_ref(lock);
2922 errno = EINVAL;
2923 return -1;
2925 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2926 write_in_full(lock->lock_fd, &term, 1) != 1 ||
2927 close_ref(lock) < 0) {
2928 int save_errno = errno;
2929 error("Couldn't write %s", lock->lk->filename);
2930 unlock_ref(lock);
2931 errno = save_errno;
2932 return -1;
2934 clear_loose_ref_cache(&ref_cache);
2935 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2936 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2937 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2938 unlock_ref(lock);
2939 return -1;
2941 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2943 * Special hack: If a branch is updated directly and HEAD
2944 * points to it (may happen on the remote side of a push
2945 * for example) then logically the HEAD reflog should be
2946 * updated too.
2947 * A generic solution implies reverse symref information,
2948 * but finding all symrefs pointing to the given branch
2949 * would be rather costly for this rare event (the direct
2950 * update of a branch) to be worth it. So let's cheat and
2951 * check with HEAD only which should cover 99% of all usage
2952 * scenarios (even 100% of the default ones).
2954 unsigned char head_sha1[20];
2955 int head_flag;
2956 const char *head_ref;
2957 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2958 if (head_ref && (head_flag & REF_ISSYMREF) &&
2959 !strcmp(head_ref, lock->ref_name))
2960 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2962 if (commit_ref(lock)) {
2963 error("Couldn't set %s", lock->ref_name);
2964 unlock_ref(lock);
2965 return -1;
2967 unlock_ref(lock);
2968 return 0;
2971 int create_symref(const char *ref_target, const char *refs_heads_master,
2972 const char *logmsg)
2974 const char *lockpath;
2975 char ref[1000];
2976 int fd, len, written;
2977 char *git_HEAD = git_pathdup("%s", ref_target);
2978 unsigned char old_sha1[20], new_sha1[20];
2980 if (logmsg && read_ref(ref_target, old_sha1))
2981 hashclr(old_sha1);
2983 if (safe_create_leading_directories(git_HEAD) < 0)
2984 return error("unable to create directory for %s", git_HEAD);
2986 #ifndef NO_SYMLINK_HEAD
2987 if (prefer_symlink_refs) {
2988 unlink(git_HEAD);
2989 if (!symlink(refs_heads_master, git_HEAD))
2990 goto done;
2991 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2993 #endif
2995 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2996 if (sizeof(ref) <= len) {
2997 error("refname too long: %s", refs_heads_master);
2998 goto error_free_return;
3000 lockpath = mkpath("%s.lock", git_HEAD);
3001 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3002 if (fd < 0) {
3003 error("Unable to open %s for writing", lockpath);
3004 goto error_free_return;
3006 written = write_in_full(fd, ref, len);
3007 if (close(fd) != 0 || written != len) {
3008 error("Unable to write to %s", lockpath);
3009 goto error_unlink_return;
3011 if (rename(lockpath, git_HEAD) < 0) {
3012 error("Unable to create %s", git_HEAD);
3013 goto error_unlink_return;
3015 if (adjust_shared_perm(git_HEAD)) {
3016 error("Unable to fix permissions on %s", lockpath);
3017 error_unlink_return:
3018 unlink_or_warn(lockpath);
3019 error_free_return:
3020 free(git_HEAD);
3021 return -1;
3024 #ifndef NO_SYMLINK_HEAD
3025 done:
3026 #endif
3027 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3028 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3030 free(git_HEAD);
3031 return 0;
3034 struct read_ref_at_cb {
3035 const char *refname;
3036 unsigned long at_time;
3037 int cnt;
3038 int reccnt;
3039 unsigned char *sha1;
3040 int found_it;
3042 unsigned char osha1[20];
3043 unsigned char nsha1[20];
3044 int tz;
3045 unsigned long date;
3046 char **msg;
3047 unsigned long *cutoff_time;
3048 int *cutoff_tz;
3049 int *cutoff_cnt;
3052 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3053 const char *email, unsigned long timestamp, int tz,
3054 const char *message, void *cb_data)
3056 struct read_ref_at_cb *cb = cb_data;
3058 cb->reccnt++;
3059 cb->tz = tz;
3060 cb->date = timestamp;
3062 if (timestamp <= cb->at_time || cb->cnt == 0) {
3063 if (cb->msg)
3064 *cb->msg = xstrdup(message);
3065 if (cb->cutoff_time)
3066 *cb->cutoff_time = timestamp;
3067 if (cb->cutoff_tz)
3068 *cb->cutoff_tz = tz;
3069 if (cb->cutoff_cnt)
3070 *cb->cutoff_cnt = cb->reccnt - 1;
3072 * we have not yet updated cb->[n|o]sha1 so they still
3073 * hold the values for the previous record.
3075 if (!is_null_sha1(cb->osha1)) {
3076 hashcpy(cb->sha1, nsha1);
3077 if (hashcmp(cb->osha1, nsha1))
3078 warning("Log for ref %s has gap after %s.",
3079 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3081 else if (cb->date == cb->at_time)
3082 hashcpy(cb->sha1, nsha1);
3083 else if (hashcmp(nsha1, cb->sha1))
3084 warning("Log for ref %s unexpectedly ended on %s.",
3085 cb->refname, show_date(cb->date, cb->tz,
3086 DATE_RFC2822));
3087 hashcpy(cb->osha1, osha1);
3088 hashcpy(cb->nsha1, nsha1);
3089 cb->found_it = 1;
3090 return 1;
3092 hashcpy(cb->osha1, osha1);
3093 hashcpy(cb->nsha1, nsha1);
3094 if (cb->cnt > 0)
3095 cb->cnt--;
3096 return 0;
3099 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3100 const char *email, unsigned long timestamp,
3101 int tz, const char *message, void *cb_data)
3103 struct read_ref_at_cb *cb = cb_data;
3105 if (cb->msg)
3106 *cb->msg = xstrdup(message);
3107 if (cb->cutoff_time)
3108 *cb->cutoff_time = timestamp;
3109 if (cb->cutoff_tz)
3110 *cb->cutoff_tz = tz;
3111 if (cb->cutoff_cnt)
3112 *cb->cutoff_cnt = cb->reccnt;
3113 hashcpy(cb->sha1, osha1);
3114 if (is_null_sha1(cb->sha1))
3115 hashcpy(cb->sha1, nsha1);
3116 /* We just want the first entry */
3117 return 1;
3120 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
3121 unsigned char *sha1, char **msg,
3122 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3124 struct read_ref_at_cb cb;
3126 memset(&cb, 0, sizeof(cb));
3127 cb.refname = refname;
3128 cb.at_time = at_time;
3129 cb.cnt = cnt;
3130 cb.msg = msg;
3131 cb.cutoff_time = cutoff_time;
3132 cb.cutoff_tz = cutoff_tz;
3133 cb.cutoff_cnt = cutoff_cnt;
3134 cb.sha1 = sha1;
3136 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3138 if (!cb.reccnt)
3139 die("Log for %s is empty.", refname);
3140 if (cb.found_it)
3141 return 0;
3143 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3145 return 1;
3148 int reflog_exists(const char *refname)
3150 struct stat st;
3152 return !lstat(git_path("logs/%s", refname), &st) &&
3153 S_ISREG(st.st_mode);
3156 int delete_reflog(const char *refname)
3158 return remove_path(git_path("logs/%s", refname));
3161 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3163 unsigned char osha1[20], nsha1[20];
3164 char *email_end, *message;
3165 unsigned long timestamp;
3166 int tz;
3168 /* old SP new SP name <email> SP time TAB msg LF */
3169 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3170 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3171 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3172 !(email_end = strchr(sb->buf + 82, '>')) ||
3173 email_end[1] != ' ' ||
3174 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3175 !message || message[0] != ' ' ||
3176 (message[1] != '+' && message[1] != '-') ||
3177 !isdigit(message[2]) || !isdigit(message[3]) ||
3178 !isdigit(message[4]) || !isdigit(message[5]))
3179 return 0; /* corrupt? */
3180 email_end[1] = '\0';
3181 tz = strtol(message + 1, NULL, 10);
3182 if (message[6] != '\t')
3183 message += 6;
3184 else
3185 message += 7;
3186 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3189 static char *find_beginning_of_line(char *bob, char *scan)
3191 while (bob < scan && *(--scan) != '\n')
3192 ; /* keep scanning backwards */
3194 * Return either beginning of the buffer, or LF at the end of
3195 * the previous line.
3197 return scan;
3200 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3202 struct strbuf sb = STRBUF_INIT;
3203 FILE *logfp;
3204 long pos;
3205 int ret = 0, at_tail = 1;
3207 logfp = fopen(git_path("logs/%s", refname), "r");
3208 if (!logfp)
3209 return -1;
3211 /* Jump to the end */
3212 if (fseek(logfp, 0, SEEK_END) < 0)
3213 return error("cannot seek back reflog for %s: %s",
3214 refname, strerror(errno));
3215 pos = ftell(logfp);
3216 while (!ret && 0 < pos) {
3217 int cnt;
3218 size_t nread;
3219 char buf[BUFSIZ];
3220 char *endp, *scanp;
3222 /* Fill next block from the end */
3223 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3224 if (fseek(logfp, pos - cnt, SEEK_SET))
3225 return error("cannot seek back reflog for %s: %s",
3226 refname, strerror(errno));
3227 nread = fread(buf, cnt, 1, logfp);
3228 if (nread != 1)
3229 return error("cannot read %d bytes from reflog for %s: %s",
3230 cnt, refname, strerror(errno));
3231 pos -= cnt;
3233 scanp = endp = buf + cnt;
3234 if (at_tail && scanp[-1] == '\n')
3235 /* Looking at the final LF at the end of the file */
3236 scanp--;
3237 at_tail = 0;
3239 while (buf < scanp) {
3241 * terminating LF of the previous line, or the beginning
3242 * of the buffer.
3244 char *bp;
3246 bp = find_beginning_of_line(buf, scanp);
3248 if (*bp != '\n') {
3249 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3250 if (pos)
3251 break; /* need to fill another block */
3252 scanp = buf - 1; /* leave loop */
3253 } else {
3255 * (bp + 1) thru endp is the beginning of the
3256 * current line we have in sb
3258 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3259 scanp = bp;
3260 endp = bp + 1;
3262 ret = show_one_reflog_ent(&sb, fn, cb_data);
3263 strbuf_reset(&sb);
3264 if (ret)
3265 break;
3269 if (!ret && sb.len)
3270 ret = show_one_reflog_ent(&sb, fn, cb_data);
3272 fclose(logfp);
3273 strbuf_release(&sb);
3274 return ret;
3277 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3279 FILE *logfp;
3280 struct strbuf sb = STRBUF_INIT;
3281 int ret = 0;
3283 logfp = fopen(git_path("logs/%s", refname), "r");
3284 if (!logfp)
3285 return -1;
3287 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3288 ret = show_one_reflog_ent(&sb, fn, cb_data);
3289 fclose(logfp);
3290 strbuf_release(&sb);
3291 return ret;
3294 * Call fn for each reflog in the namespace indicated by name. name
3295 * must be empty or end with '/'. Name will be used as a scratch
3296 * space, but its contents will be restored before return.
3298 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3300 DIR *d = opendir(git_path("logs/%s", name->buf));
3301 int retval = 0;
3302 struct dirent *de;
3303 int oldlen = name->len;
3305 if (!d)
3306 return name->len ? errno : 0;
3308 while ((de = readdir(d)) != NULL) {
3309 struct stat st;
3311 if (de->d_name[0] == '.')
3312 continue;
3313 if (has_extension(de->d_name, ".lock"))
3314 continue;
3315 strbuf_addstr(name, de->d_name);
3316 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3317 ; /* silently ignore */
3318 } else {
3319 if (S_ISDIR(st.st_mode)) {
3320 strbuf_addch(name, '/');
3321 retval = do_for_each_reflog(name, fn, cb_data);
3322 } else {
3323 unsigned char sha1[20];
3324 if (read_ref_full(name->buf, sha1, 0, NULL))
3325 retval = error("bad ref for %s", name->buf);
3326 else
3327 retval = fn(name->buf, sha1, 0, cb_data);
3329 if (retval)
3330 break;
3332 strbuf_setlen(name, oldlen);
3334 closedir(d);
3335 return retval;
3338 int for_each_reflog(each_ref_fn fn, void *cb_data)
3340 int retval;
3341 struct strbuf name;
3342 strbuf_init(&name, PATH_MAX);
3343 retval = do_for_each_reflog(&name, fn, cb_data);
3344 strbuf_release(&name);
3345 return retval;
3349 * Information needed for a single ref update. Set new_sha1 to the
3350 * new value or to zero to delete the ref. To check the old value
3351 * while locking the ref, set have_old to 1 and set old_sha1 to the
3352 * value or to zero to ensure the ref does not exist before update.
3354 struct ref_update {
3355 unsigned char new_sha1[20];
3356 unsigned char old_sha1[20];
3357 int flags; /* REF_NODEREF? */
3358 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3359 struct ref_lock *lock;
3360 int type;
3361 char *msg;
3362 const char refname[FLEX_ARRAY];
3366 * Transaction states.
3367 * OPEN: The transaction is in a valid state and can accept new updates.
3368 * An OPEN transaction can be committed.
3369 * CLOSED: If an open transaction is successfully committed the state will
3370 * change to CLOSED. No further changes can be made to a CLOSED
3371 * transaction.
3372 * CLOSED means that all updates have been successfully committed and
3373 * the only thing that remains is to free the completed transaction.
3374 * ERROR: The transaction has failed and is no longer committable.
3375 * No further changes can be made to a CLOSED transaction and it must
3376 * be rolled back using transaction_free.
3378 enum ref_transaction_state {
3379 REF_TRANSACTION_OPEN = 0,
3380 REF_TRANSACTION_CLOSED = 1,
3381 REF_TRANSACTION_ERROR = 2,
3385 * Data structure for holding a reference transaction, which can
3386 * consist of checks and updates to multiple references, carried out
3387 * as atomically as possible. This structure is opaque to callers.
3389 struct ref_transaction {
3390 struct ref_update **updates;
3391 size_t alloc;
3392 size_t nr;
3393 enum ref_transaction_state state;
3396 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3398 return xcalloc(1, sizeof(struct ref_transaction));
3401 void ref_transaction_free(struct ref_transaction *transaction)
3403 int i;
3405 if (!transaction)
3406 return;
3408 for (i = 0; i < transaction->nr; i++) {
3409 free(transaction->updates[i]->msg);
3410 free(transaction->updates[i]);
3412 free(transaction->updates);
3413 free(transaction);
3416 static struct ref_update *add_update(struct ref_transaction *transaction,
3417 const char *refname)
3419 size_t len = strlen(refname);
3420 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3422 strcpy((char *)update->refname, refname);
3423 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3424 transaction->updates[transaction->nr++] = update;
3425 return update;
3428 int ref_transaction_update(struct ref_transaction *transaction,
3429 const char *refname,
3430 const unsigned char *new_sha1,
3431 const unsigned char *old_sha1,
3432 int flags, int have_old, const char *msg,
3433 struct strbuf *err)
3435 struct ref_update *update;
3437 if (transaction->state != REF_TRANSACTION_OPEN)
3438 die("BUG: update called for transaction that is not open");
3440 if (have_old && !old_sha1)
3441 die("BUG: have_old is true but old_sha1 is NULL");
3443 update = add_update(transaction, refname);
3444 hashcpy(update->new_sha1, new_sha1);
3445 update->flags = flags;
3446 update->have_old = have_old;
3447 if (have_old)
3448 hashcpy(update->old_sha1, old_sha1);
3449 if (msg)
3450 update->msg = xstrdup(msg);
3451 return 0;
3454 int ref_transaction_create(struct ref_transaction *transaction,
3455 const char *refname,
3456 const unsigned char *new_sha1,
3457 int flags, const char *msg,
3458 struct strbuf *err)
3460 struct ref_update *update;
3462 if (transaction->state != REF_TRANSACTION_OPEN)
3463 die("BUG: create called for transaction that is not open");
3465 if (!new_sha1 || is_null_sha1(new_sha1))
3466 die("BUG: create ref with null new_sha1");
3468 update = add_update(transaction, refname);
3470 hashcpy(update->new_sha1, new_sha1);
3471 hashclr(update->old_sha1);
3472 update->flags = flags;
3473 update->have_old = 1;
3474 if (msg)
3475 update->msg = xstrdup(msg);
3476 return 0;
3479 int ref_transaction_delete(struct ref_transaction *transaction,
3480 const char *refname,
3481 const unsigned char *old_sha1,
3482 int flags, int have_old, const char *msg,
3483 struct strbuf *err)
3485 struct ref_update *update;
3487 if (transaction->state != REF_TRANSACTION_OPEN)
3488 die("BUG: delete called for transaction that is not open");
3490 if (have_old && !old_sha1)
3491 die("BUG: have_old is true but old_sha1 is NULL");
3493 update = add_update(transaction, refname);
3494 update->flags = flags;
3495 update->have_old = have_old;
3496 if (have_old) {
3497 assert(!is_null_sha1(old_sha1));
3498 hashcpy(update->old_sha1, old_sha1);
3500 if (msg)
3501 update->msg = xstrdup(msg);
3502 return 0;
3505 int update_ref(const char *action, const char *refname,
3506 const unsigned char *sha1, const unsigned char *oldval,
3507 int flags, enum action_on_err onerr)
3509 struct ref_transaction *t;
3510 struct strbuf err = STRBUF_INIT;
3512 t = ref_transaction_begin(&err);
3513 if (!t ||
3514 ref_transaction_update(t, refname, sha1, oldval, flags,
3515 !!oldval, action, &err) ||
3516 ref_transaction_commit(t, &err)) {
3517 const char *str = "update_ref failed for ref '%s': %s";
3519 ref_transaction_free(t);
3520 switch (onerr) {
3521 case UPDATE_REFS_MSG_ON_ERR:
3522 error(str, refname, err.buf);
3523 break;
3524 case UPDATE_REFS_DIE_ON_ERR:
3525 die(str, refname, err.buf);
3526 break;
3527 case UPDATE_REFS_QUIET_ON_ERR:
3528 break;
3530 strbuf_release(&err);
3531 return 1;
3533 return 0;
3536 static int ref_update_compare(const void *r1, const void *r2)
3538 const struct ref_update * const *u1 = r1;
3539 const struct ref_update * const *u2 = r2;
3540 return strcmp((*u1)->refname, (*u2)->refname);
3543 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3544 struct strbuf *err)
3546 int i;
3547 for (i = 1; i < n; i++)
3548 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3549 const char *str =
3550 "Multiple updates for ref '%s' not allowed.";
3551 if (err)
3552 strbuf_addf(err, str, updates[i]->refname);
3554 return 1;
3556 return 0;
3559 int ref_transaction_commit(struct ref_transaction *transaction,
3560 struct strbuf *err)
3562 int ret = 0, delnum = 0, i, df_conflict = 0;
3563 const char **delnames;
3564 int n = transaction->nr;
3565 struct ref_update **updates = transaction->updates;
3567 if (transaction->state != REF_TRANSACTION_OPEN)
3568 die("BUG: commit called for transaction that is not open");
3570 if (!n) {
3571 transaction->state = REF_TRANSACTION_CLOSED;
3572 return 0;
3575 /* Allocate work space */
3576 delnames = xmalloc(sizeof(*delnames) * n);
3578 /* Copy, sort, and reject duplicate refs */
3579 qsort(updates, n, sizeof(*updates), ref_update_compare);
3580 if (ref_update_reject_duplicates(updates, n, err)) {
3581 ret = -1;
3582 goto cleanup;
3585 /* Acquire all locks while verifying old values */
3586 for (i = 0; i < n; i++) {
3587 struct ref_update *update = updates[i];
3589 update->lock = lock_ref_sha1_basic(update->refname,
3590 (update->have_old ?
3591 update->old_sha1 :
3592 NULL),
3593 update->flags,
3594 &update->type,
3595 delnames, delnum);
3596 if (!update->lock) {
3597 if (errno == ENOTDIR)
3598 df_conflict = 1;
3599 if (err)
3600 strbuf_addf(err, "Cannot lock the ref '%s'.",
3601 update->refname);
3602 ret = -1;
3603 goto cleanup;
3607 /* Perform updates first so live commits remain referenced */
3608 for (i = 0; i < n; i++) {
3609 struct ref_update *update = updates[i];
3611 if (!is_null_sha1(update->new_sha1)) {
3612 ret = write_ref_sha1(update->lock, update->new_sha1,
3613 update->msg);
3614 update->lock = NULL; /* freed by write_ref_sha1 */
3615 if (ret) {
3616 const char *str = "Cannot update the ref '%s'.";
3618 if (err)
3619 strbuf_addf(err, str, update->refname);
3620 ret = -1;
3621 goto cleanup;
3626 /* Perform deletes now that updates are safely completed */
3627 for (i = 0; i < n; i++) {
3628 struct ref_update *update = updates[i];
3630 if (update->lock) {
3631 if (delete_ref_loose(update->lock, update->type, err))
3632 ret = -1;
3634 if (!(update->flags & REF_ISPRUNING))
3635 delnames[delnum++] = update->lock->ref_name;
3639 if (repack_without_refs(delnames, delnum, err))
3640 ret = -1;
3641 for (i = 0; i < delnum; i++)
3642 unlink_or_warn(git_path("logs/%s", delnames[i]));
3643 clear_loose_ref_cache(&ref_cache);
3645 cleanup:
3646 transaction->state = ret ? REF_TRANSACTION_ERROR
3647 : REF_TRANSACTION_CLOSED;
3649 for (i = 0; i < n; i++)
3650 if (updates[i]->lock)
3651 unlock_ref(updates[i]->lock);
3652 free(delnames);
3653 if (df_conflict)
3654 ret = -2;
3655 return ret;
3658 char *shorten_unambiguous_ref(const char *refname, int strict)
3660 int i;
3661 static char **scanf_fmts;
3662 static int nr_rules;
3663 char *short_name;
3665 if (!nr_rules) {
3667 * Pre-generate scanf formats from ref_rev_parse_rules[].
3668 * Generate a format suitable for scanf from a
3669 * ref_rev_parse_rules rule by interpolating "%s" at the
3670 * location of the "%.*s".
3672 size_t total_len = 0;
3673 size_t offset = 0;
3675 /* the rule list is NULL terminated, count them first */
3676 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3677 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3678 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3680 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3682 offset = 0;
3683 for (i = 0; i < nr_rules; i++) {
3684 assert(offset < total_len);
3685 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3686 offset += snprintf(scanf_fmts[i], total_len - offset,
3687 ref_rev_parse_rules[i], 2, "%s") + 1;
3691 /* bail out if there are no rules */
3692 if (!nr_rules)
3693 return xstrdup(refname);
3695 /* buffer for scanf result, at most refname must fit */
3696 short_name = xstrdup(refname);
3698 /* skip first rule, it will always match */
3699 for (i = nr_rules - 1; i > 0 ; --i) {
3700 int j;
3701 int rules_to_fail = i;
3702 int short_name_len;
3704 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3705 continue;
3707 short_name_len = strlen(short_name);
3710 * in strict mode, all (except the matched one) rules
3711 * must fail to resolve to a valid non-ambiguous ref
3713 if (strict)
3714 rules_to_fail = nr_rules;
3717 * check if the short name resolves to a valid ref,
3718 * but use only rules prior to the matched one
3720 for (j = 0; j < rules_to_fail; j++) {
3721 const char *rule = ref_rev_parse_rules[j];
3722 char refname[PATH_MAX];
3724 /* skip matched rule */
3725 if (i == j)
3726 continue;
3729 * the short name is ambiguous, if it resolves
3730 * (with this previous rule) to a valid ref
3731 * read_ref() returns 0 on success
3733 mksnpath(refname, sizeof(refname),
3734 rule, short_name_len, short_name);
3735 if (ref_exists(refname))
3736 break;
3740 * short name is non-ambiguous if all previous rules
3741 * haven't resolved to a valid ref
3743 if (j == rules_to_fail)
3744 return short_name;
3747 free(short_name);
3748 return xstrdup(refname);
3751 static struct string_list *hide_refs;
3753 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3755 if (!strcmp("transfer.hiderefs", var) ||
3756 /* NEEDSWORK: use parse_config_key() once both are merged */
3757 (starts_with(var, section) && var[strlen(section)] == '.' &&
3758 !strcmp(var + strlen(section), ".hiderefs"))) {
3759 char *ref;
3760 int len;
3762 if (!value)
3763 return config_error_nonbool(var);
3764 ref = xstrdup(value);
3765 len = strlen(ref);
3766 while (len && ref[len - 1] == '/')
3767 ref[--len] = '\0';
3768 if (!hide_refs) {
3769 hide_refs = xcalloc(1, sizeof(*hide_refs));
3770 hide_refs->strdup_strings = 1;
3772 string_list_append(hide_refs, ref);
3774 return 0;
3777 int ref_is_hidden(const char *refname)
3779 struct string_list_item *item;
3781 if (!hide_refs)
3782 return 0;
3783 for_each_string_list_item(item, hide_refs) {
3784 int len;
3785 if (!starts_with(refname, item->string))
3786 continue;
3787 len = strlen(item->string);
3788 if (!refname[len] || refname[len] == '/')
3789 return 1;
3791 return 0;