refs: remove unused function invalidate_ref_cache
[alt-git.git] / refs.c
blobd20834054ba1ddb32c00aceb4896098dae0844f6
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 * Make sure "ref" is something reasonable to have under ".git/refs/";
10 * We do not like it if:
12 * - any path component of it begins with ".", or
13 * - it has double dots "..", or
14 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
15 * - it ends with a "/".
16 * - it ends with ".lock"
17 * - it contains a "\" (backslash)
20 /* Return true iff ch is not allowed in reference names. */
21 static inline int bad_ref_char(int ch)
23 if (((unsigned) ch) <= ' ' || ch == 0x7f ||
24 ch == '~' || ch == '^' || ch == ':' || ch == '\\')
25 return 1;
26 /* 2.13 Pattern Matching Notation */
27 if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
28 return 1;
29 return 0;
33 * Try to read one refname component from the front of refname. Return
34 * the length of the component found, or -1 if the component is not
35 * legal.
37 static int check_refname_component(const char *refname, int flags)
39 const char *cp;
40 char last = '\0';
42 for (cp = refname; ; cp++) {
43 char ch = *cp;
44 if (ch == '\0' || ch == '/')
45 break;
46 if (bad_ref_char(ch))
47 return -1; /* Illegal character in refname. */
48 if (last == '.' && ch == '.')
49 return -1; /* Refname contains "..". */
50 if (last == '@' && ch == '{')
51 return -1; /* Refname contains "@{". */
52 last = ch;
54 if (cp == refname)
55 return 0; /* Component has zero length. */
56 if (refname[0] == '.') {
57 if (!(flags & REFNAME_DOT_COMPONENT))
58 return -1; /* Component starts with '.'. */
60 * Even if leading dots are allowed, don't allow "."
61 * as a component (".." is prevented by a rule above).
63 if (refname[1] == '\0')
64 return -1; /* Component equals ".". */
66 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
67 return -1; /* Refname ends with ".lock". */
68 return cp - refname;
71 int check_refname_format(const char *refname, int flags)
73 int component_len, component_count = 0;
75 while (1) {
76 /* We are at the start of a path component. */
77 component_len = check_refname_component(refname, flags);
78 if (component_len <= 0) {
79 if ((flags & REFNAME_REFSPEC_PATTERN) &&
80 refname[0] == '*' &&
81 (refname[1] == '\0' || refname[1] == '/')) {
82 /* Accept one wildcard as a full refname component. */
83 flags &= ~REFNAME_REFSPEC_PATTERN;
84 component_len = 1;
85 } else {
86 return -1;
89 component_count++;
90 if (refname[component_len] == '\0')
91 break;
92 /* Skip to next component. */
93 refname += component_len + 1;
96 if (refname[component_len - 1] == '.')
97 return -1; /* Refname ends with '.'. */
98 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
99 return -1; /* Refname has only one component. */
100 return 0;
103 struct ref_entry;
106 * Information used (along with the information in ref_entry) to
107 * describe a single cached reference. This data structure only
108 * occurs embedded in a union in struct ref_entry, and only when
109 * (ref_entry->flag & REF_DIR) is zero.
111 struct ref_value {
113 * The name of the object to which this reference resolves
114 * (which may be a tag object). If REF_ISBROKEN, this is
115 * null. If REF_ISSYMREF, then this is the name of the object
116 * referred to by the last reference in the symlink chain.
118 unsigned char sha1[20];
121 * If REF_KNOWS_PEELED, then this field holds the peeled value
122 * of this reference, or null if the reference is known not to
123 * be peelable. See the documentation for peel_ref() for an
124 * exact definition of "peelable".
126 unsigned char peeled[20];
129 struct ref_cache;
132 * Information used (along with the information in ref_entry) to
133 * describe a level in the hierarchy of references. This data
134 * structure only occurs embedded in a union in struct ref_entry, and
135 * only when (ref_entry.flag & REF_DIR) is set. In that case,
136 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
137 * in the directory have already been read:
139 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
140 * or packed references, already read.
142 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
143 * references that hasn't been read yet (nor has any of its
144 * subdirectories).
146 * Entries within a directory are stored within a growable array of
147 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
148 * sorted are sorted by their component name in strcmp() order and the
149 * remaining entries are unsorted.
151 * Loose references are read lazily, one directory at a time. When a
152 * directory of loose references is read, then all of the references
153 * in that directory are stored, and REF_INCOMPLETE stubs are created
154 * for any subdirectories, but the subdirectories themselves are not
155 * read. The reading is triggered by get_ref_dir().
157 struct ref_dir {
158 int nr, alloc;
161 * Entries with index 0 <= i < sorted are sorted by name. New
162 * entries are appended to the list unsorted, and are sorted
163 * only when required; thus we avoid the need to sort the list
164 * after the addition of every reference.
166 int sorted;
168 /* A pointer to the ref_cache that contains this ref_dir. */
169 struct ref_cache *ref_cache;
171 struct ref_entry **entries;
175 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
176 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see
177 * refs.h.
181 * The field ref_entry->u.value.peeled of this value entry contains
182 * the correct peeled value for the reference, which might be
183 * null_sha1 if the reference is not a tag or if it is broken.
185 #define REF_KNOWS_PEELED 0x08
187 /* ref_entry represents a directory of references */
188 #define REF_DIR 0x10
191 * Entry has not yet been read from disk (used only for REF_DIR
192 * entries representing loose references)
194 #define REF_INCOMPLETE 0x20
197 * A ref_entry represents either a reference or a "subdirectory" of
198 * references.
200 * Each directory in the reference namespace is represented by a
201 * ref_entry with (flags & REF_DIR) set and containing a subdir member
202 * that holds the entries in that directory that have been read so
203 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
204 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
205 * used for loose reference directories.
207 * References are represented by a ref_entry with (flags & REF_DIR)
208 * unset and a value member that describes the reference's value. The
209 * flag member is at the ref_entry level, but it is also needed to
210 * interpret the contents of the value field (in other words, a
211 * ref_value object is not very much use without the enclosing
212 * ref_entry).
214 * Reference names cannot end with slash and directories' names are
215 * always stored with a trailing slash (except for the top-level
216 * directory, which is always denoted by ""). This has two nice
217 * consequences: (1) when the entries in each subdir are sorted
218 * lexicographically by name (as they usually are), the references in
219 * a whole tree can be generated in lexicographic order by traversing
220 * the tree in left-to-right, depth-first order; (2) the names of
221 * references and subdirectories cannot conflict, and therefore the
222 * presence of an empty subdirectory does not block the creation of a
223 * similarly-named reference. (The fact that reference names with the
224 * same leading components can conflict *with each other* is a
225 * separate issue that is regulated by is_refname_available().)
227 * Please note that the name field contains the fully-qualified
228 * reference (or subdirectory) name. Space could be saved by only
229 * storing the relative names. But that would require the full names
230 * to be generated on the fly when iterating in do_for_each_ref(), and
231 * would break callback functions, who have always been able to assume
232 * that the name strings that they are passed will not be freed during
233 * the iteration.
235 struct ref_entry {
236 unsigned char flag; /* ISSYMREF? ISPACKED? */
237 union {
238 struct ref_value value; /* if not (flags&REF_DIR) */
239 struct ref_dir subdir; /* if (flags&REF_DIR) */
240 } u;
242 * The full name of the reference (e.g., "refs/heads/master")
243 * or the full name of the directory with a trailing slash
244 * (e.g., "refs/heads/"):
246 char name[FLEX_ARRAY];
249 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
251 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
253 struct ref_dir *dir;
254 assert(entry->flag & REF_DIR);
255 dir = &entry->u.subdir;
256 if (entry->flag & REF_INCOMPLETE) {
257 read_loose_refs(entry->name, dir);
258 entry->flag &= ~REF_INCOMPLETE;
260 return dir;
263 static struct ref_entry *create_ref_entry(const char *refname,
264 const unsigned char *sha1, int flag,
265 int check_name)
267 int len;
268 struct ref_entry *ref;
270 if (check_name &&
271 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
272 die("Reference has invalid format: '%s'", refname);
273 len = strlen(refname) + 1;
274 ref = xmalloc(sizeof(struct ref_entry) + len);
275 hashcpy(ref->u.value.sha1, sha1);
276 hashclr(ref->u.value.peeled);
277 memcpy(ref->name, refname, len);
278 ref->flag = flag;
279 return ref;
282 static void clear_ref_dir(struct ref_dir *dir);
284 static void free_ref_entry(struct ref_entry *entry)
286 if (entry->flag & REF_DIR) {
288 * Do not use get_ref_dir() here, as that might
289 * trigger the reading of loose refs.
291 clear_ref_dir(&entry->u.subdir);
293 free(entry);
297 * Add a ref_entry to the end of dir (unsorted). Entry is always
298 * stored directly in dir; no recursion into subdirectories is
299 * done.
301 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
303 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
304 dir->entries[dir->nr++] = entry;
305 /* optimize for the case that entries are added in order */
306 if (dir->nr == 1 ||
307 (dir->nr == dir->sorted + 1 &&
308 strcmp(dir->entries[dir->nr - 2]->name,
309 dir->entries[dir->nr - 1]->name) < 0))
310 dir->sorted = dir->nr;
314 * Clear and free all entries in dir, recursively.
316 static void clear_ref_dir(struct ref_dir *dir)
318 int i;
319 for (i = 0; i < dir->nr; i++)
320 free_ref_entry(dir->entries[i]);
321 free(dir->entries);
322 dir->sorted = dir->nr = dir->alloc = 0;
323 dir->entries = NULL;
327 * Create a struct ref_entry object for the specified dirname.
328 * dirname is the name of the directory with a trailing slash (e.g.,
329 * "refs/heads/") or "" for the top-level directory.
331 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
332 const char *dirname, size_t len,
333 int incomplete)
335 struct ref_entry *direntry;
336 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
337 memcpy(direntry->name, dirname, len);
338 direntry->name[len] = '\0';
339 direntry->u.subdir.ref_cache = ref_cache;
340 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
341 return direntry;
344 static int ref_entry_cmp(const void *a, const void *b)
346 struct ref_entry *one = *(struct ref_entry **)a;
347 struct ref_entry *two = *(struct ref_entry **)b;
348 return strcmp(one->name, two->name);
351 static void sort_ref_dir(struct ref_dir *dir);
353 struct string_slice {
354 size_t len;
355 const char *str;
358 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
360 const struct string_slice *key = key_;
361 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
362 int cmp = strncmp(key->str, ent->name, key->len);
363 if (cmp)
364 return cmp;
365 return '\0' - (unsigned char)ent->name[key->len];
369 * Return the index of the entry with the given refname from the
370 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
371 * no such entry is found. dir must already be complete.
373 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
375 struct ref_entry **r;
376 struct string_slice key;
378 if (refname == NULL || !dir->nr)
379 return -1;
381 sort_ref_dir(dir);
382 key.len = len;
383 key.str = refname;
384 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
385 ref_entry_cmp_sslice);
387 if (r == NULL)
388 return -1;
390 return r - dir->entries;
394 * Search for a directory entry directly within dir (without
395 * recursing). Sort dir if necessary. subdirname must be a directory
396 * name (i.e., end in '/'). If mkdir is set, then create the
397 * directory if it is missing; otherwise, return NULL if the desired
398 * directory cannot be found. dir must already be complete.
400 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
401 const char *subdirname, size_t len,
402 int mkdir)
404 int entry_index = search_ref_dir(dir, subdirname, len);
405 struct ref_entry *entry;
406 if (entry_index == -1) {
407 if (!mkdir)
408 return NULL;
410 * Since dir is complete, the absence of a subdir
411 * means that the subdir really doesn't exist;
412 * therefore, create an empty record for it but mark
413 * the record complete.
415 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
416 add_entry_to_dir(dir, entry);
417 } else {
418 entry = dir->entries[entry_index];
420 return get_ref_dir(entry);
424 * If refname is a reference name, find the ref_dir within the dir
425 * tree that should hold refname. If refname is a directory name
426 * (i.e., ends in '/'), then return that ref_dir itself. dir must
427 * represent the top-level directory and must already be complete.
428 * Sort ref_dirs and recurse into subdirectories as necessary. If
429 * mkdir is set, then create any missing directories; otherwise,
430 * return NULL if the desired directory cannot be found.
432 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
433 const char *refname, int mkdir)
435 const char *slash;
436 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
437 size_t dirnamelen = slash - refname + 1;
438 struct ref_dir *subdir;
439 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
440 if (!subdir) {
441 dir = NULL;
442 break;
444 dir = subdir;
447 return dir;
451 * Find the value entry with the given name in dir, sorting ref_dirs
452 * and recursing into subdirectories as necessary. If the name is not
453 * found or it corresponds to a directory entry, return NULL.
455 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
457 int entry_index;
458 struct ref_entry *entry;
459 dir = find_containing_dir(dir, refname, 0);
460 if (!dir)
461 return NULL;
462 entry_index = search_ref_dir(dir, refname, strlen(refname));
463 if (entry_index == -1)
464 return NULL;
465 entry = dir->entries[entry_index];
466 return (entry->flag & REF_DIR) ? NULL : entry;
470 * Remove the entry with the given name from dir, recursing into
471 * subdirectories as necessary. If refname is the name of a directory
472 * (i.e., ends with '/'), then remove the directory and its contents.
473 * If the removal was successful, return the number of entries
474 * remaining in the directory entry that contained the deleted entry.
475 * If the name was not found, return -1. Please note that this
476 * function only deletes the entry from the cache; it does not delete
477 * it from the filesystem or ensure that other cache entries (which
478 * might be symbolic references to the removed entry) are updated.
479 * Nor does it remove any containing dir entries that might be made
480 * empty by the removal. dir must represent the top-level directory
481 * and must already be complete.
483 static int remove_entry(struct ref_dir *dir, const char *refname)
485 int refname_len = strlen(refname);
486 int entry_index;
487 struct ref_entry *entry;
488 int is_dir = refname[refname_len - 1] == '/';
489 if (is_dir) {
491 * refname represents a reference directory. Remove
492 * the trailing slash; otherwise we will get the
493 * directory *representing* refname rather than the
494 * one *containing* it.
496 char *dirname = xmemdupz(refname, refname_len - 1);
497 dir = find_containing_dir(dir, dirname, 0);
498 free(dirname);
499 } else {
500 dir = find_containing_dir(dir, refname, 0);
502 if (!dir)
503 return -1;
504 entry_index = search_ref_dir(dir, refname, refname_len);
505 if (entry_index == -1)
506 return -1;
507 entry = dir->entries[entry_index];
509 memmove(&dir->entries[entry_index],
510 &dir->entries[entry_index + 1],
511 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
513 dir->nr--;
514 if (dir->sorted > entry_index)
515 dir->sorted--;
516 free_ref_entry(entry);
517 return dir->nr;
521 * Add a ref_entry to the ref_dir (unsorted), recursing into
522 * subdirectories as necessary. dir must represent the top-level
523 * directory. Return 0 on success.
525 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
527 dir = find_containing_dir(dir, ref->name, 1);
528 if (!dir)
529 return -1;
530 add_entry_to_dir(dir, ref);
531 return 0;
535 * Emit a warning and return true iff ref1 and ref2 have the same name
536 * and the same sha1. Die if they have the same name but different
537 * sha1s.
539 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
541 if (strcmp(ref1->name, ref2->name))
542 return 0;
544 /* Duplicate name; make sure that they don't conflict: */
546 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
547 /* This is impossible by construction */
548 die("Reference directory conflict: %s", ref1->name);
550 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
551 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
553 warning("Duplicated ref: %s", ref1->name);
554 return 1;
558 * Sort the entries in dir non-recursively (if they are not already
559 * sorted) and remove any duplicate entries.
561 static void sort_ref_dir(struct ref_dir *dir)
563 int i, j;
564 struct ref_entry *last = NULL;
567 * This check also prevents passing a zero-length array to qsort(),
568 * which is a problem on some platforms.
570 if (dir->sorted == dir->nr)
571 return;
573 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
575 /* Remove any duplicates: */
576 for (i = 0, j = 0; j < dir->nr; j++) {
577 struct ref_entry *entry = dir->entries[j];
578 if (last && is_dup_ref(last, entry))
579 free_ref_entry(entry);
580 else
581 last = dir->entries[i++] = entry;
583 dir->sorted = dir->nr = i;
586 /* Include broken references in a do_for_each_ref*() iteration: */
587 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
590 * Return true iff the reference described by entry can be resolved to
591 * an object in the database. Emit a warning if the referred-to
592 * object does not exist.
594 static int ref_resolves_to_object(struct ref_entry *entry)
596 if (entry->flag & REF_ISBROKEN)
597 return 0;
598 if (!has_sha1_file(entry->u.value.sha1)) {
599 error("%s does not point to a valid object!", entry->name);
600 return 0;
602 return 1;
606 * current_ref is a performance hack: when iterating over references
607 * using the for_each_ref*() functions, current_ref is set to the
608 * current reference's entry before calling the callback function. If
609 * the callback function calls peel_ref(), then peel_ref() first
610 * checks whether the reference to be peeled is the current reference
611 * (it usually is) and if so, returns that reference's peeled version
612 * if it is available. This avoids a refname lookup in a common case.
614 static struct ref_entry *current_ref;
616 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
618 struct ref_entry_cb {
619 const char *base;
620 int trim;
621 int flags;
622 each_ref_fn *fn;
623 void *cb_data;
627 * Handle one reference in a do_for_each_ref*()-style iteration,
628 * calling an each_ref_fn for each entry.
630 static int do_one_ref(struct ref_entry *entry, void *cb_data)
632 struct ref_entry_cb *data = cb_data;
633 struct ref_entry *old_current_ref;
634 int retval;
636 if (prefixcmp(entry->name, data->base))
637 return 0;
639 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
640 !ref_resolves_to_object(entry))
641 return 0;
643 /* Store the old value, in case this is a recursive call: */
644 old_current_ref = current_ref;
645 current_ref = entry;
646 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
647 entry->flag, data->cb_data);
648 current_ref = old_current_ref;
649 return retval;
653 * Call fn for each reference in dir that has index in the range
654 * offset <= index < dir->nr. Recurse into subdirectories that are in
655 * that index range, sorting them before iterating. This function
656 * does not sort dir itself; it should be sorted beforehand. fn is
657 * called for all references, including broken ones.
659 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
660 each_ref_entry_fn fn, void *cb_data)
662 int i;
663 assert(dir->sorted == dir->nr);
664 for (i = offset; i < dir->nr; i++) {
665 struct ref_entry *entry = dir->entries[i];
666 int retval;
667 if (entry->flag & REF_DIR) {
668 struct ref_dir *subdir = get_ref_dir(entry);
669 sort_ref_dir(subdir);
670 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
671 } else {
672 retval = fn(entry, cb_data);
674 if (retval)
675 return retval;
677 return 0;
681 * Call fn for each reference in the union of dir1 and dir2, in order
682 * by refname. Recurse into subdirectories. If a value entry appears
683 * in both dir1 and dir2, then only process the version that is in
684 * dir2. The input dirs must already be sorted, but subdirs will be
685 * sorted as needed. fn is called for all references, including
686 * broken ones.
688 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
689 struct ref_dir *dir2,
690 each_ref_entry_fn fn, void *cb_data)
692 int retval;
693 int i1 = 0, i2 = 0;
695 assert(dir1->sorted == dir1->nr);
696 assert(dir2->sorted == dir2->nr);
697 while (1) {
698 struct ref_entry *e1, *e2;
699 int cmp;
700 if (i1 == dir1->nr) {
701 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
703 if (i2 == dir2->nr) {
704 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
706 e1 = dir1->entries[i1];
707 e2 = dir2->entries[i2];
708 cmp = strcmp(e1->name, e2->name);
709 if (cmp == 0) {
710 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
711 /* Both are directories; descend them in parallel. */
712 struct ref_dir *subdir1 = get_ref_dir(e1);
713 struct ref_dir *subdir2 = get_ref_dir(e2);
714 sort_ref_dir(subdir1);
715 sort_ref_dir(subdir2);
716 retval = do_for_each_entry_in_dirs(
717 subdir1, subdir2, fn, cb_data);
718 i1++;
719 i2++;
720 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
721 /* Both are references; ignore the one from dir1. */
722 retval = fn(e2, cb_data);
723 i1++;
724 i2++;
725 } else {
726 die("conflict between reference and directory: %s",
727 e1->name);
729 } else {
730 struct ref_entry *e;
731 if (cmp < 0) {
732 e = e1;
733 i1++;
734 } else {
735 e = e2;
736 i2++;
738 if (e->flag & REF_DIR) {
739 struct ref_dir *subdir = get_ref_dir(e);
740 sort_ref_dir(subdir);
741 retval = do_for_each_entry_in_dir(
742 subdir, 0, fn, cb_data);
743 } else {
744 retval = fn(e, cb_data);
747 if (retval)
748 return retval;
753 * Load all of the refs from the dir into our in-memory cache. The hard work
754 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
755 * through all of the sub-directories. We do not even need to care about
756 * sorting, as traversal order does not matter to us.
758 static void prime_ref_dir(struct ref_dir *dir)
760 int i;
761 for (i = 0; i < dir->nr; i++) {
762 struct ref_entry *entry = dir->entries[i];
763 if (entry->flag & REF_DIR)
764 prime_ref_dir(get_ref_dir(entry));
768 * Return true iff refname1 and refname2 conflict with each other.
769 * Two reference names conflict if one of them exactly matches the
770 * leading components of the other; e.g., "foo/bar" conflicts with
771 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
772 * "foo/barbados".
774 static int names_conflict(const char *refname1, const char *refname2)
776 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
778 return (*refname1 == '\0' && *refname2 == '/')
779 || (*refname1 == '/' && *refname2 == '\0');
782 struct name_conflict_cb {
783 const char *refname;
784 const char *oldrefname;
785 const char *conflicting_refname;
788 static int name_conflict_fn(struct ref_entry *entry, void *cb_data)
790 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
791 if (data->oldrefname && !strcmp(data->oldrefname, entry->name))
792 return 0;
793 if (names_conflict(data->refname, entry->name)) {
794 data->conflicting_refname = entry->name;
795 return 1;
797 return 0;
801 * Return true iff a reference named refname could be created without
802 * conflicting with the name of an existing reference in dir. If
803 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
804 * (e.g., because oldrefname is scheduled for deletion in the same
805 * operation).
807 static int is_refname_available(const char *refname, const char *oldrefname,
808 struct ref_dir *dir)
810 struct name_conflict_cb data;
811 data.refname = refname;
812 data.oldrefname = oldrefname;
813 data.conflicting_refname = NULL;
815 sort_ref_dir(dir);
816 if (do_for_each_entry_in_dir(dir, 0, name_conflict_fn, &data)) {
817 error("'%s' exists; cannot create '%s'",
818 data.conflicting_refname, refname);
819 return 0;
821 return 1;
824 struct packed_ref_cache {
825 struct ref_entry *root;
828 * Count of references to the data structure in this instance,
829 * including the pointer from ref_cache::packed if any. The
830 * data will not be freed as long as the reference count is
831 * nonzero.
833 unsigned int referrers;
836 * Iff the packed-refs file associated with this instance is
837 * currently locked for writing, this points at the associated
838 * lock (which is owned by somebody else). The referrer count
839 * is also incremented when the file is locked and decremented
840 * when it is unlocked.
842 struct lock_file *lock;
844 /* The metadata from when this packed-refs cache was read */
845 struct stat_validity validity;
849 * Future: need to be in "struct repository"
850 * when doing a full libification.
852 static struct ref_cache {
853 struct ref_cache *next;
854 struct ref_entry *loose;
855 struct packed_ref_cache *packed;
857 * The submodule name, or "" for the main repo. We allocate
858 * length 1 rather than FLEX_ARRAY so that the main ref_cache
859 * is initialized correctly.
861 char name[1];
862 } ref_cache, *submodule_ref_caches;
864 /* Lock used for the main packed-refs file: */
865 static struct lock_file packlock;
868 * Increment the reference count of *packed_refs.
870 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
872 packed_refs->referrers++;
876 * Decrease the reference count of *packed_refs. If it goes to zero,
877 * free *packed_refs and return true; otherwise return false.
879 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
881 if (!--packed_refs->referrers) {
882 free_ref_entry(packed_refs->root);
883 stat_validity_clear(&packed_refs->validity);
884 free(packed_refs);
885 return 1;
886 } else {
887 return 0;
891 static void clear_packed_ref_cache(struct ref_cache *refs)
893 if (refs->packed) {
894 struct packed_ref_cache *packed_refs = refs->packed;
896 if (packed_refs->lock)
897 die("internal error: packed-ref cache cleared while locked");
898 refs->packed = NULL;
899 release_packed_ref_cache(packed_refs);
903 static void clear_loose_ref_cache(struct ref_cache *refs)
905 if (refs->loose) {
906 free_ref_entry(refs->loose);
907 refs->loose = NULL;
911 static struct ref_cache *create_ref_cache(const char *submodule)
913 int len;
914 struct ref_cache *refs;
915 if (!submodule)
916 submodule = "";
917 len = strlen(submodule) + 1;
918 refs = xcalloc(1, sizeof(struct ref_cache) + len);
919 memcpy(refs->name, submodule, len);
920 return refs;
924 * Return a pointer to a ref_cache for the specified submodule. For
925 * the main repository, use submodule==NULL. The returned structure
926 * will be allocated and initialized but not necessarily populated; it
927 * should not be freed.
929 static struct ref_cache *get_ref_cache(const char *submodule)
931 struct ref_cache *refs;
933 if (!submodule || !*submodule)
934 return &ref_cache;
936 for (refs = submodule_ref_caches; refs; refs = refs->next)
937 if (!strcmp(submodule, refs->name))
938 return refs;
940 refs = create_ref_cache(submodule);
941 refs->next = submodule_ref_caches;
942 submodule_ref_caches = refs;
943 return refs;
946 /* The length of a peeled reference line in packed-refs, including EOL: */
947 #define PEELED_LINE_LENGTH 42
950 * The packed-refs header line that we write out. Perhaps other
951 * traits will be added later. The trailing space is required.
953 static const char PACKED_REFS_HEADER[] =
954 "# pack-refs with: peeled fully-peeled \n";
957 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
958 * Return a pointer to the refname within the line (null-terminated),
959 * or NULL if there was a problem.
961 static const char *parse_ref_line(char *line, unsigned char *sha1)
964 * 42: the answer to everything.
966 * In this case, it happens to be the answer to
967 * 40 (length of sha1 hex representation)
968 * +1 (space in between hex and name)
969 * +1 (newline at the end of the line)
971 int len = strlen(line) - 42;
973 if (len <= 0)
974 return NULL;
975 if (get_sha1_hex(line, sha1) < 0)
976 return NULL;
977 if (!isspace(line[40]))
978 return NULL;
979 line += 41;
980 if (isspace(*line))
981 return NULL;
982 if (line[len] != '\n')
983 return NULL;
984 line[len] = 0;
986 return line;
990 * Read f, which is a packed-refs file, into dir.
992 * A comment line of the form "# pack-refs with: " may contain zero or
993 * more traits. We interpret the traits as follows:
995 * No traits:
997 * Probably no references are peeled. But if the file contains a
998 * peeled value for a reference, we will use it.
1000 * peeled:
1002 * References under "refs/tags/", if they *can* be peeled, *are*
1003 * peeled in this file. References outside of "refs/tags/" are
1004 * probably not peeled even if they could have been, but if we find
1005 * a peeled value for such a reference we will use it.
1007 * fully-peeled:
1009 * All references in the file that can be peeled are peeled.
1010 * Inversely (and this is more important), any references in the
1011 * file for which no peeled value is recorded is not peelable. This
1012 * trait should typically be written alongside "peeled" for
1013 * compatibility with older clients, but we do not require it
1014 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1016 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1018 struct ref_entry *last = NULL;
1019 char refline[PATH_MAX];
1020 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1022 while (fgets(refline, sizeof(refline), f)) {
1023 unsigned char sha1[20];
1024 const char *refname;
1025 static const char header[] = "# pack-refs with:";
1027 if (!strncmp(refline, header, sizeof(header)-1)) {
1028 const char *traits = refline + sizeof(header) - 1;
1029 if (strstr(traits, " fully-peeled "))
1030 peeled = PEELED_FULLY;
1031 else if (strstr(traits, " peeled "))
1032 peeled = PEELED_TAGS;
1033 /* perhaps other traits later as well */
1034 continue;
1037 refname = parse_ref_line(refline, sha1);
1038 if (refname) {
1039 last = create_ref_entry(refname, sha1, REF_ISPACKED, 1);
1040 if (peeled == PEELED_FULLY ||
1041 (peeled == PEELED_TAGS && !prefixcmp(refname, "refs/tags/")))
1042 last->flag |= REF_KNOWS_PEELED;
1043 add_ref(dir, last);
1044 continue;
1046 if (last &&
1047 refline[0] == '^' &&
1048 strlen(refline) == PEELED_LINE_LENGTH &&
1049 refline[PEELED_LINE_LENGTH - 1] == '\n' &&
1050 !get_sha1_hex(refline + 1, sha1)) {
1051 hashcpy(last->u.value.peeled, sha1);
1053 * Regardless of what the file header said,
1054 * we definitely know the value of *this*
1055 * reference:
1057 last->flag |= REF_KNOWS_PEELED;
1063 * Get the packed_ref_cache for the specified ref_cache, creating it
1064 * if necessary.
1066 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1068 const char *packed_refs_file;
1070 if (*refs->name)
1071 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1072 else
1073 packed_refs_file = git_path("packed-refs");
1075 if (refs->packed &&
1076 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1077 clear_packed_ref_cache(refs);
1079 if (!refs->packed) {
1080 FILE *f;
1082 refs->packed = xcalloc(1, sizeof(*refs->packed));
1083 acquire_packed_ref_cache(refs->packed);
1084 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1085 f = fopen(packed_refs_file, "r");
1086 if (f) {
1087 stat_validity_update(&refs->packed->validity, fileno(f));
1088 read_packed_refs(f, get_ref_dir(refs->packed->root));
1089 fclose(f);
1092 return refs->packed;
1095 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1097 return get_ref_dir(packed_ref_cache->root);
1100 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1102 return get_packed_ref_dir(get_packed_ref_cache(refs));
1105 void add_packed_ref(const char *refname, const unsigned char *sha1)
1107 struct packed_ref_cache *packed_ref_cache =
1108 get_packed_ref_cache(&ref_cache);
1110 if (!packed_ref_cache->lock)
1111 die("internal error: packed refs not locked");
1112 add_ref(get_packed_ref_dir(packed_ref_cache),
1113 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1117 * Read the loose references from the namespace dirname into dir
1118 * (without recursing). dirname must end with '/'. dir must be the
1119 * directory entry corresponding to dirname.
1121 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1123 struct ref_cache *refs = dir->ref_cache;
1124 DIR *d;
1125 const char *path;
1126 struct dirent *de;
1127 int dirnamelen = strlen(dirname);
1128 struct strbuf refname;
1130 if (*refs->name)
1131 path = git_path_submodule(refs->name, "%s", dirname);
1132 else
1133 path = git_path("%s", dirname);
1135 d = opendir(path);
1136 if (!d)
1137 return;
1139 strbuf_init(&refname, dirnamelen + 257);
1140 strbuf_add(&refname, dirname, dirnamelen);
1142 while ((de = readdir(d)) != NULL) {
1143 unsigned char sha1[20];
1144 struct stat st;
1145 int flag;
1146 const char *refdir;
1148 if (de->d_name[0] == '.')
1149 continue;
1150 if (has_extension(de->d_name, ".lock"))
1151 continue;
1152 strbuf_addstr(&refname, de->d_name);
1153 refdir = *refs->name
1154 ? git_path_submodule(refs->name, "%s", refname.buf)
1155 : git_path("%s", refname.buf);
1156 if (stat(refdir, &st) < 0) {
1157 ; /* silently ignore */
1158 } else if (S_ISDIR(st.st_mode)) {
1159 strbuf_addch(&refname, '/');
1160 add_entry_to_dir(dir,
1161 create_dir_entry(refs, refname.buf,
1162 refname.len, 1));
1163 } else {
1164 if (*refs->name) {
1165 hashclr(sha1);
1166 flag = 0;
1167 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1168 hashclr(sha1);
1169 flag |= REF_ISBROKEN;
1171 } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
1172 hashclr(sha1);
1173 flag |= REF_ISBROKEN;
1175 add_entry_to_dir(dir,
1176 create_ref_entry(refname.buf, sha1, flag, 1));
1178 strbuf_setlen(&refname, dirnamelen);
1180 strbuf_release(&refname);
1181 closedir(d);
1184 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1186 if (!refs->loose) {
1188 * Mark the top-level directory complete because we
1189 * are about to read the only subdirectory that can
1190 * hold references:
1192 refs->loose = create_dir_entry(refs, "", 0, 0);
1194 * Create an incomplete entry for "refs/":
1196 add_entry_to_dir(get_ref_dir(refs->loose),
1197 create_dir_entry(refs, "refs/", 5, 1));
1199 return get_ref_dir(refs->loose);
1202 /* We allow "recursive" symbolic refs. Only within reason, though */
1203 #define MAXDEPTH 5
1204 #define MAXREFLEN (1024)
1207 * Called by resolve_gitlink_ref_recursive() after it failed to read
1208 * from the loose refs in ref_cache refs. Find <refname> in the
1209 * packed-refs file for the submodule.
1211 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1212 const char *refname, unsigned char *sha1)
1214 struct ref_entry *ref;
1215 struct ref_dir *dir = get_packed_refs(refs);
1217 ref = find_ref(dir, refname);
1218 if (ref == NULL)
1219 return -1;
1221 memcpy(sha1, ref->u.value.sha1, 20);
1222 return 0;
1225 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1226 const char *refname, unsigned char *sha1,
1227 int recursion)
1229 int fd, len;
1230 char buffer[128], *p;
1231 char *path;
1233 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1234 return -1;
1235 path = *refs->name
1236 ? git_path_submodule(refs->name, "%s", refname)
1237 : git_path("%s", refname);
1238 fd = open(path, O_RDONLY);
1239 if (fd < 0)
1240 return resolve_gitlink_packed_ref(refs, refname, sha1);
1242 len = read(fd, buffer, sizeof(buffer)-1);
1243 close(fd);
1244 if (len < 0)
1245 return -1;
1246 while (len && isspace(buffer[len-1]))
1247 len--;
1248 buffer[len] = 0;
1250 /* Was it a detached head or an old-fashioned symlink? */
1251 if (!get_sha1_hex(buffer, sha1))
1252 return 0;
1254 /* Symref? */
1255 if (strncmp(buffer, "ref:", 4))
1256 return -1;
1257 p = buffer + 4;
1258 while (isspace(*p))
1259 p++;
1261 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1264 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1266 int len = strlen(path), retval;
1267 char *submodule;
1268 struct ref_cache *refs;
1270 while (len && path[len-1] == '/')
1271 len--;
1272 if (!len)
1273 return -1;
1274 submodule = xstrndup(path, len);
1275 refs = get_ref_cache(submodule);
1276 free(submodule);
1278 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1279 return retval;
1283 * Return the ref_entry for the given refname from the packed
1284 * references. If it does not exist, return NULL.
1286 static struct ref_entry *get_packed_ref(const char *refname)
1288 return find_ref(get_packed_refs(&ref_cache), refname);
1292 * A loose ref file doesn't exist; check for a packed ref. The
1293 * options are forwarded from resolve_safe_unsafe().
1295 static const char *handle_missing_loose_ref(const char *refname,
1296 unsigned char *sha1,
1297 int reading,
1298 int *flag)
1300 struct ref_entry *entry;
1303 * The loose reference file does not exist; check for a packed
1304 * reference.
1306 entry = get_packed_ref(refname);
1307 if (entry) {
1308 hashcpy(sha1, entry->u.value.sha1);
1309 if (flag)
1310 *flag |= REF_ISPACKED;
1311 return refname;
1313 /* The reference is not a packed reference, either. */
1314 if (reading) {
1315 return NULL;
1316 } else {
1317 hashclr(sha1);
1318 return refname;
1322 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1324 int depth = MAXDEPTH;
1325 ssize_t len;
1326 char buffer[256];
1327 static char refname_buffer[256];
1329 if (flag)
1330 *flag = 0;
1332 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1333 return NULL;
1335 for (;;) {
1336 char path[PATH_MAX];
1337 struct stat st;
1338 char *buf;
1339 int fd;
1341 if (--depth < 0)
1342 return NULL;
1344 git_snpath(path, sizeof(path), "%s", refname);
1347 * We might have to loop back here to avoid a race
1348 * condition: first we lstat() the file, then we try
1349 * to read it as a link or as a file. But if somebody
1350 * changes the type of the file (file <-> directory
1351 * <-> symlink) between the lstat() and reading, then
1352 * we don't want to report that as an error but rather
1353 * try again starting with the lstat().
1355 stat_ref:
1356 if (lstat(path, &st) < 0) {
1357 if (errno == ENOENT)
1358 return handle_missing_loose_ref(refname, sha1,
1359 reading, flag);
1360 else
1361 return NULL;
1364 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1365 if (S_ISLNK(st.st_mode)) {
1366 len = readlink(path, buffer, sizeof(buffer)-1);
1367 if (len < 0) {
1368 if (errno == ENOENT || errno == EINVAL)
1369 /* inconsistent with lstat; retry */
1370 goto stat_ref;
1371 else
1372 return NULL;
1374 buffer[len] = 0;
1375 if (!prefixcmp(buffer, "refs/") &&
1376 !check_refname_format(buffer, 0)) {
1377 strcpy(refname_buffer, buffer);
1378 refname = refname_buffer;
1379 if (flag)
1380 *flag |= REF_ISSYMREF;
1381 continue;
1385 /* Is it a directory? */
1386 if (S_ISDIR(st.st_mode)) {
1387 errno = EISDIR;
1388 return NULL;
1392 * Anything else, just open it and try to use it as
1393 * a ref
1395 fd = open(path, O_RDONLY);
1396 if (fd < 0) {
1397 if (errno == ENOENT)
1398 /* inconsistent with lstat; retry */
1399 goto stat_ref;
1400 else
1401 return NULL;
1403 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1404 close(fd);
1405 if (len < 0)
1406 return NULL;
1407 while (len && isspace(buffer[len-1]))
1408 len--;
1409 buffer[len] = '\0';
1412 * Is it a symbolic ref?
1414 if (prefixcmp(buffer, "ref:")) {
1416 * Please note that FETCH_HEAD has a second
1417 * line containing other data.
1419 if (get_sha1_hex(buffer, sha1) ||
1420 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1421 if (flag)
1422 *flag |= REF_ISBROKEN;
1423 return NULL;
1425 return refname;
1427 if (flag)
1428 *flag |= REF_ISSYMREF;
1429 buf = buffer + 4;
1430 while (isspace(*buf))
1431 buf++;
1432 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1433 if (flag)
1434 *flag |= REF_ISBROKEN;
1435 return NULL;
1437 refname = strcpy(refname_buffer, buf);
1441 char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1443 const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1444 return ret ? xstrdup(ret) : NULL;
1447 /* The argument to filter_refs */
1448 struct ref_filter {
1449 const char *pattern;
1450 each_ref_fn *fn;
1451 void *cb_data;
1454 int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1456 if (resolve_ref_unsafe(refname, sha1, reading, flags))
1457 return 0;
1458 return -1;
1461 int read_ref(const char *refname, unsigned char *sha1)
1463 return read_ref_full(refname, sha1, 1, NULL);
1466 int ref_exists(const char *refname)
1468 unsigned char sha1[20];
1469 return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1472 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1473 void *data)
1475 struct ref_filter *filter = (struct ref_filter *)data;
1476 if (fnmatch(filter->pattern, refname, 0))
1477 return 0;
1478 return filter->fn(refname, sha1, flags, filter->cb_data);
1481 enum peel_status {
1482 /* object was peeled successfully: */
1483 PEEL_PEELED = 0,
1486 * object cannot be peeled because the named object (or an
1487 * object referred to by a tag in the peel chain), does not
1488 * exist.
1490 PEEL_INVALID = -1,
1492 /* object cannot be peeled because it is not a tag: */
1493 PEEL_NON_TAG = -2,
1495 /* ref_entry contains no peeled value because it is a symref: */
1496 PEEL_IS_SYMREF = -3,
1499 * ref_entry cannot be peeled because it is broken (i.e., the
1500 * symbolic reference cannot even be resolved to an object
1501 * name):
1503 PEEL_BROKEN = -4
1507 * Peel the named object; i.e., if the object is a tag, resolve the
1508 * tag recursively until a non-tag is found. If successful, store the
1509 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1510 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1511 * and leave sha1 unchanged.
1513 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1515 struct object *o = lookup_unknown_object(name);
1517 if (o->type == OBJ_NONE) {
1518 int type = sha1_object_info(name, NULL);
1519 if (type < 0)
1520 return PEEL_INVALID;
1521 o->type = type;
1524 if (o->type != OBJ_TAG)
1525 return PEEL_NON_TAG;
1527 o = deref_tag_noverify(o);
1528 if (!o)
1529 return PEEL_INVALID;
1531 hashcpy(sha1, o->sha1);
1532 return PEEL_PEELED;
1536 * Peel the entry (if possible) and return its new peel_status. If
1537 * repeel is true, re-peel the entry even if there is an old peeled
1538 * value that is already stored in it.
1540 * It is OK to call this function with a packed reference entry that
1541 * might be stale and might even refer to an object that has since
1542 * been garbage-collected. In such a case, if the entry has
1543 * REF_KNOWS_PEELED then leave the status unchanged and return
1544 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1546 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1548 enum peel_status status;
1550 if (entry->flag & REF_KNOWS_PEELED) {
1551 if (repeel) {
1552 entry->flag &= ~REF_KNOWS_PEELED;
1553 hashclr(entry->u.value.peeled);
1554 } else {
1555 return is_null_sha1(entry->u.value.peeled) ?
1556 PEEL_NON_TAG : PEEL_PEELED;
1559 if (entry->flag & REF_ISBROKEN)
1560 return PEEL_BROKEN;
1561 if (entry->flag & REF_ISSYMREF)
1562 return PEEL_IS_SYMREF;
1564 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1565 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1566 entry->flag |= REF_KNOWS_PEELED;
1567 return status;
1570 int peel_ref(const char *refname, unsigned char *sha1)
1572 int flag;
1573 unsigned char base[20];
1575 if (current_ref && (current_ref->name == refname
1576 || !strcmp(current_ref->name, refname))) {
1577 if (peel_entry(current_ref, 0))
1578 return -1;
1579 hashcpy(sha1, current_ref->u.value.peeled);
1580 return 0;
1583 if (read_ref_full(refname, base, 1, &flag))
1584 return -1;
1587 * If the reference is packed, read its ref_entry from the
1588 * cache in the hope that we already know its peeled value.
1589 * We only try this optimization on packed references because
1590 * (a) forcing the filling of the loose reference cache could
1591 * be expensive and (b) loose references anyway usually do not
1592 * have REF_KNOWS_PEELED.
1594 if (flag & REF_ISPACKED) {
1595 struct ref_entry *r = get_packed_ref(refname);
1596 if (r) {
1597 if (peel_entry(r, 0))
1598 return -1;
1599 hashcpy(sha1, r->u.value.peeled);
1600 return 0;
1604 return peel_object(base, sha1);
1607 struct warn_if_dangling_data {
1608 FILE *fp;
1609 const char *refname;
1610 const char *msg_fmt;
1613 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1614 int flags, void *cb_data)
1616 struct warn_if_dangling_data *d = cb_data;
1617 const char *resolves_to;
1618 unsigned char junk[20];
1620 if (!(flags & REF_ISSYMREF))
1621 return 0;
1623 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1624 if (!resolves_to || strcmp(resolves_to, d->refname))
1625 return 0;
1627 fprintf(d->fp, d->msg_fmt, refname);
1628 fputc('\n', d->fp);
1629 return 0;
1632 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1634 struct warn_if_dangling_data data;
1636 data.fp = fp;
1637 data.refname = refname;
1638 data.msg_fmt = msg_fmt;
1639 for_each_rawref(warn_if_dangling_symref, &data);
1643 * Call fn for each reference in the specified ref_cache, omitting
1644 * references not in the containing_dir of base. fn is called for all
1645 * references, including broken ones. If fn ever returns a non-zero
1646 * value, stop the iteration and return that value; otherwise, return
1647 * 0.
1649 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1650 each_ref_entry_fn fn, void *cb_data)
1652 struct packed_ref_cache *packed_ref_cache;
1653 struct ref_dir *loose_dir;
1654 struct ref_dir *packed_dir;
1655 int retval = 0;
1658 * We must make sure that all loose refs are read before accessing the
1659 * packed-refs file; this avoids a race condition in which loose refs
1660 * are migrated to the packed-refs file by a simultaneous process, but
1661 * our in-memory view is from before the migration. get_packed_ref_cache()
1662 * takes care of making sure our view is up to date with what is on
1663 * disk.
1665 loose_dir = get_loose_refs(refs);
1666 if (base && *base) {
1667 loose_dir = find_containing_dir(loose_dir, base, 0);
1669 if (loose_dir)
1670 prime_ref_dir(loose_dir);
1672 packed_ref_cache = get_packed_ref_cache(refs);
1673 acquire_packed_ref_cache(packed_ref_cache);
1674 packed_dir = get_packed_ref_dir(packed_ref_cache);
1675 if (base && *base) {
1676 packed_dir = find_containing_dir(packed_dir, base, 0);
1679 if (packed_dir && loose_dir) {
1680 sort_ref_dir(packed_dir);
1681 sort_ref_dir(loose_dir);
1682 retval = do_for_each_entry_in_dirs(
1683 packed_dir, loose_dir, fn, cb_data);
1684 } else if (packed_dir) {
1685 sort_ref_dir(packed_dir);
1686 retval = do_for_each_entry_in_dir(
1687 packed_dir, 0, fn, cb_data);
1688 } else if (loose_dir) {
1689 sort_ref_dir(loose_dir);
1690 retval = do_for_each_entry_in_dir(
1691 loose_dir, 0, fn, cb_data);
1694 release_packed_ref_cache(packed_ref_cache);
1695 return retval;
1699 * Call fn for each reference in the specified ref_cache for which the
1700 * refname begins with base. If trim is non-zero, then trim that many
1701 * characters off the beginning of each refname before passing the
1702 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1703 * broken references in the iteration. If fn ever returns a non-zero
1704 * value, stop the iteration and return that value; otherwise, return
1705 * 0.
1707 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1708 each_ref_fn fn, int trim, int flags, void *cb_data)
1710 struct ref_entry_cb data;
1711 data.base = base;
1712 data.trim = trim;
1713 data.flags = flags;
1714 data.fn = fn;
1715 data.cb_data = cb_data;
1717 return do_for_each_entry(refs, base, do_one_ref, &data);
1720 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1722 unsigned char sha1[20];
1723 int flag;
1725 if (submodule) {
1726 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1727 return fn("HEAD", sha1, 0, cb_data);
1729 return 0;
1732 if (!read_ref_full("HEAD", sha1, 1, &flag))
1733 return fn("HEAD", sha1, flag, cb_data);
1735 return 0;
1738 int head_ref(each_ref_fn fn, void *cb_data)
1740 return do_head_ref(NULL, fn, cb_data);
1743 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1745 return do_head_ref(submodule, fn, cb_data);
1748 int for_each_ref(each_ref_fn fn, void *cb_data)
1750 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1753 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1755 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1758 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1760 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1763 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1764 each_ref_fn fn, void *cb_data)
1766 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1769 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1771 return for_each_ref_in("refs/tags/", fn, cb_data);
1774 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1776 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1779 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1781 return for_each_ref_in("refs/heads/", fn, cb_data);
1784 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1786 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1789 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1791 return for_each_ref_in("refs/remotes/", fn, cb_data);
1794 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1796 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1799 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1801 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
1804 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1806 struct strbuf buf = STRBUF_INIT;
1807 int ret = 0;
1808 unsigned char sha1[20];
1809 int flag;
1811 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1812 if (!read_ref_full(buf.buf, sha1, 1, &flag))
1813 ret = fn(buf.buf, sha1, flag, cb_data);
1814 strbuf_release(&buf);
1816 return ret;
1819 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1821 struct strbuf buf = STRBUF_INIT;
1822 int ret;
1823 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1824 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1825 strbuf_release(&buf);
1826 return ret;
1829 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1830 const char *prefix, void *cb_data)
1832 struct strbuf real_pattern = STRBUF_INIT;
1833 struct ref_filter filter;
1834 int ret;
1836 if (!prefix && prefixcmp(pattern, "refs/"))
1837 strbuf_addstr(&real_pattern, "refs/");
1838 else if (prefix)
1839 strbuf_addstr(&real_pattern, prefix);
1840 strbuf_addstr(&real_pattern, pattern);
1842 if (!has_glob_specials(pattern)) {
1843 /* Append implied '/' '*' if not present. */
1844 if (real_pattern.buf[real_pattern.len - 1] != '/')
1845 strbuf_addch(&real_pattern, '/');
1846 /* No need to check for '*', there is none. */
1847 strbuf_addch(&real_pattern, '*');
1850 filter.pattern = real_pattern.buf;
1851 filter.fn = fn;
1852 filter.cb_data = cb_data;
1853 ret = for_each_ref(filter_refs, &filter);
1855 strbuf_release(&real_pattern);
1856 return ret;
1859 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1861 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1864 int for_each_rawref(each_ref_fn fn, void *cb_data)
1866 return do_for_each_ref(&ref_cache, "", fn, 0,
1867 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1870 const char *prettify_refname(const char *name)
1872 return name + (
1873 !prefixcmp(name, "refs/heads/") ? 11 :
1874 !prefixcmp(name, "refs/tags/") ? 10 :
1875 !prefixcmp(name, "refs/remotes/") ? 13 :
1879 const char *ref_rev_parse_rules[] = {
1880 "%.*s",
1881 "refs/%.*s",
1882 "refs/tags/%.*s",
1883 "refs/heads/%.*s",
1884 "refs/remotes/%.*s",
1885 "refs/remotes/%.*s/HEAD",
1886 NULL
1889 int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1891 const char **p;
1892 const int abbrev_name_len = strlen(abbrev_name);
1894 for (p = rules; *p; p++) {
1895 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1896 return 1;
1900 return 0;
1903 static struct ref_lock *verify_lock(struct ref_lock *lock,
1904 const unsigned char *old_sha1, int mustexist)
1906 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1907 error("Can't verify ref %s", lock->ref_name);
1908 unlock_ref(lock);
1909 return NULL;
1911 if (hashcmp(lock->old_sha1, old_sha1)) {
1912 error("Ref %s is at %s but expected %s", lock->ref_name,
1913 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1914 unlock_ref(lock);
1915 return NULL;
1917 return lock;
1920 static int remove_empty_directories(const char *file)
1922 /* we want to create a file but there is a directory there;
1923 * if that is an empty directory (or a directory that contains
1924 * only empty directories), remove them.
1926 struct strbuf path;
1927 int result;
1929 strbuf_init(&path, 20);
1930 strbuf_addstr(&path, file);
1932 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1934 strbuf_release(&path);
1936 return result;
1940 * *string and *len will only be substituted, and *string returned (for
1941 * later free()ing) if the string passed in is a magic short-hand form
1942 * to name a branch.
1944 static char *substitute_branch_name(const char **string, int *len)
1946 struct strbuf buf = STRBUF_INIT;
1947 int ret = interpret_branch_name(*string, &buf);
1949 if (ret == *len) {
1950 size_t size;
1951 *string = strbuf_detach(&buf, &size);
1952 *len = size;
1953 return (char *)*string;
1956 return NULL;
1959 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1961 char *last_branch = substitute_branch_name(&str, &len);
1962 const char **p, *r;
1963 int refs_found = 0;
1965 *ref = NULL;
1966 for (p = ref_rev_parse_rules; *p; p++) {
1967 char fullref[PATH_MAX];
1968 unsigned char sha1_from_ref[20];
1969 unsigned char *this_result;
1970 int flag;
1972 this_result = refs_found ? sha1_from_ref : sha1;
1973 mksnpath(fullref, sizeof(fullref), *p, len, str);
1974 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1975 if (r) {
1976 if (!refs_found++)
1977 *ref = xstrdup(r);
1978 if (!warn_ambiguous_refs)
1979 break;
1980 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1981 warning("ignoring dangling symref %s.", fullref);
1982 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1983 warning("ignoring broken ref %s.", fullref);
1986 free(last_branch);
1987 return refs_found;
1990 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1992 char *last_branch = substitute_branch_name(&str, &len);
1993 const char **p;
1994 int logs_found = 0;
1996 *log = NULL;
1997 for (p = ref_rev_parse_rules; *p; p++) {
1998 struct stat st;
1999 unsigned char hash[20];
2000 char path[PATH_MAX];
2001 const char *ref, *it;
2003 mksnpath(path, sizeof(path), *p, len, str);
2004 ref = resolve_ref_unsafe(path, hash, 1, NULL);
2005 if (!ref)
2006 continue;
2007 if (!stat(git_path("logs/%s", path), &st) &&
2008 S_ISREG(st.st_mode))
2009 it = path;
2010 else if (strcmp(ref, path) &&
2011 !stat(git_path("logs/%s", ref), &st) &&
2012 S_ISREG(st.st_mode))
2013 it = ref;
2014 else
2015 continue;
2016 if (!logs_found++) {
2017 *log = xstrdup(it);
2018 hashcpy(sha1, hash);
2020 if (!warn_ambiguous_refs)
2021 break;
2023 free(last_branch);
2024 return logs_found;
2027 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2028 const unsigned char *old_sha1,
2029 int flags, int *type_p)
2031 char *ref_file;
2032 const char *orig_refname = refname;
2033 struct ref_lock *lock;
2034 int last_errno = 0;
2035 int type, lflags;
2036 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2037 int missing = 0;
2039 lock = xcalloc(1, sizeof(struct ref_lock));
2040 lock->lock_fd = -1;
2042 refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
2043 if (!refname && errno == EISDIR) {
2044 /* we are trying to lock foo but we used to
2045 * have foo/bar which now does not exist;
2046 * it is normal for the empty directory 'foo'
2047 * to remain.
2049 ref_file = git_path("%s", orig_refname);
2050 if (remove_empty_directories(ref_file)) {
2051 last_errno = errno;
2052 error("there are still refs under '%s'", orig_refname);
2053 goto error_return;
2055 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
2057 if (type_p)
2058 *type_p = type;
2059 if (!refname) {
2060 last_errno = errno;
2061 error("unable to resolve reference %s: %s",
2062 orig_refname, strerror(errno));
2063 goto error_return;
2065 missing = is_null_sha1(lock->old_sha1);
2066 /* When the ref did not exist and we are creating it,
2067 * make sure there is no existing ref that is packed
2068 * whose name begins with our refname, nor a ref whose
2069 * name is a proper prefix of our refname.
2071 if (missing &&
2072 !is_refname_available(refname, NULL, get_packed_refs(&ref_cache))) {
2073 last_errno = ENOTDIR;
2074 goto error_return;
2077 lock->lk = xcalloc(1, sizeof(struct lock_file));
2079 lflags = LOCK_DIE_ON_ERROR;
2080 if (flags & REF_NODEREF) {
2081 refname = orig_refname;
2082 lflags |= LOCK_NODEREF;
2084 lock->ref_name = xstrdup(refname);
2085 lock->orig_ref_name = xstrdup(orig_refname);
2086 ref_file = git_path("%s", refname);
2087 if (missing)
2088 lock->force_write = 1;
2089 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2090 lock->force_write = 1;
2092 if (safe_create_leading_directories(ref_file)) {
2093 last_errno = errno;
2094 error("unable to create directory for %s", ref_file);
2095 goto error_return;
2098 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2099 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2101 error_return:
2102 unlock_ref(lock);
2103 errno = last_errno;
2104 return NULL;
2107 struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
2109 char refpath[PATH_MAX];
2110 if (check_refname_format(refname, 0))
2111 return NULL;
2112 strcpy(refpath, mkpath("refs/%s", refname));
2113 return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
2116 struct ref_lock *lock_any_ref_for_update(const char *refname,
2117 const unsigned char *old_sha1, int flags)
2119 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
2120 return NULL;
2121 return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
2125 * Write an entry to the packed-refs file for the specified refname.
2126 * If peeled is non-NULL, write it as the entry's peeled value.
2128 static void write_packed_entry(int fd, char *refname, unsigned char *sha1,
2129 unsigned char *peeled)
2131 char line[PATH_MAX + 100];
2132 int len;
2134 len = snprintf(line, sizeof(line), "%s %s\n",
2135 sha1_to_hex(sha1), refname);
2136 /* this should not happen but just being defensive */
2137 if (len > sizeof(line))
2138 die("too long a refname '%s'", refname);
2139 write_or_die(fd, line, len);
2141 if (peeled) {
2142 if (snprintf(line, sizeof(line), "^%s\n",
2143 sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)
2144 die("internal error");
2145 write_or_die(fd, line, PEELED_LINE_LENGTH);
2150 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2152 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2154 int *fd = cb_data;
2155 enum peel_status peel_status = peel_entry(entry, 0);
2157 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2158 error("internal error: %s is not a valid packed reference!",
2159 entry->name);
2160 write_packed_entry(*fd, entry->name, entry->u.value.sha1,
2161 peel_status == PEEL_PEELED ?
2162 entry->u.value.peeled : NULL);
2163 return 0;
2166 int lock_packed_refs(int flags)
2168 struct packed_ref_cache *packed_ref_cache;
2170 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2171 return -1;
2173 * Get the current packed-refs while holding the lock. If the
2174 * packed-refs file has been modified since we last read it,
2175 * this will automatically invalidate the cache and re-read
2176 * the packed-refs file.
2178 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2179 packed_ref_cache->lock = &packlock;
2180 /* Increment the reference count to prevent it from being freed: */
2181 acquire_packed_ref_cache(packed_ref_cache);
2182 return 0;
2185 int commit_packed_refs(void)
2187 struct packed_ref_cache *packed_ref_cache =
2188 get_packed_ref_cache(&ref_cache);
2189 int error = 0;
2191 if (!packed_ref_cache->lock)
2192 die("internal error: packed-refs not locked");
2193 write_or_die(packed_ref_cache->lock->fd,
2194 PACKED_REFS_HEADER, strlen(PACKED_REFS_HEADER));
2196 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2197 0, write_packed_entry_fn,
2198 &packed_ref_cache->lock->fd);
2199 if (commit_lock_file(packed_ref_cache->lock))
2200 error = -1;
2201 packed_ref_cache->lock = NULL;
2202 release_packed_ref_cache(packed_ref_cache);
2203 return error;
2206 void rollback_packed_refs(void)
2208 struct packed_ref_cache *packed_ref_cache =
2209 get_packed_ref_cache(&ref_cache);
2211 if (!packed_ref_cache->lock)
2212 die("internal error: packed-refs not locked");
2213 rollback_lock_file(packed_ref_cache->lock);
2214 packed_ref_cache->lock = NULL;
2215 release_packed_ref_cache(packed_ref_cache);
2216 clear_packed_ref_cache(&ref_cache);
2219 struct ref_to_prune {
2220 struct ref_to_prune *next;
2221 unsigned char sha1[20];
2222 char name[FLEX_ARRAY];
2225 struct pack_refs_cb_data {
2226 unsigned int flags;
2227 struct ref_dir *packed_refs;
2228 struct ref_to_prune *ref_to_prune;
2232 * An each_ref_entry_fn that is run over loose references only. If
2233 * the loose reference can be packed, add an entry in the packed ref
2234 * cache. If the reference should be pruned, also add it to
2235 * ref_to_prune in the pack_refs_cb_data.
2237 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2239 struct pack_refs_cb_data *cb = cb_data;
2240 enum peel_status peel_status;
2241 struct ref_entry *packed_entry;
2242 int is_tag_ref = !prefixcmp(entry->name, "refs/tags/");
2244 /* ALWAYS pack tags */
2245 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2246 return 0;
2248 /* Do not pack symbolic or broken refs: */
2249 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2250 return 0;
2252 /* Add a packed ref cache entry equivalent to the loose entry. */
2253 peel_status = peel_entry(entry, 1);
2254 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2255 die("internal error peeling reference %s (%s)",
2256 entry->name, sha1_to_hex(entry->u.value.sha1));
2257 packed_entry = find_ref(cb->packed_refs, entry->name);
2258 if (packed_entry) {
2259 /* Overwrite existing packed entry with info from loose entry */
2260 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2261 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2262 } else {
2263 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2264 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2265 add_ref(cb->packed_refs, packed_entry);
2267 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2269 /* Schedule the loose reference for pruning if requested. */
2270 if ((cb->flags & PACK_REFS_PRUNE)) {
2271 int namelen = strlen(entry->name) + 1;
2272 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2273 hashcpy(n->sha1, entry->u.value.sha1);
2274 strcpy(n->name, entry->name);
2275 n->next = cb->ref_to_prune;
2276 cb->ref_to_prune = n;
2278 return 0;
2282 * Remove empty parents, but spare refs/ and immediate subdirs.
2283 * Note: munges *name.
2285 static void try_remove_empty_parents(char *name)
2287 char *p, *q;
2288 int i;
2289 p = name;
2290 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2291 while (*p && *p != '/')
2292 p++;
2293 /* tolerate duplicate slashes; see check_refname_format() */
2294 while (*p == '/')
2295 p++;
2297 for (q = p; *q; q++)
2299 while (1) {
2300 while (q > p && *q != '/')
2301 q--;
2302 while (q > p && *(q-1) == '/')
2303 q--;
2304 if (q == p)
2305 break;
2306 *q = '\0';
2307 if (rmdir(git_path("%s", name)))
2308 break;
2312 /* make sure nobody touched the ref, and unlink */
2313 static void prune_ref(struct ref_to_prune *r)
2315 struct ref_lock *lock = lock_ref_sha1(r->name + 5, r->sha1);
2317 if (lock) {
2318 unlink_or_warn(git_path("%s", r->name));
2319 unlock_ref(lock);
2320 try_remove_empty_parents(r->name);
2324 static void prune_refs(struct ref_to_prune *r)
2326 while (r) {
2327 prune_ref(r);
2328 r = r->next;
2332 int pack_refs(unsigned int flags)
2334 struct pack_refs_cb_data cbdata;
2336 memset(&cbdata, 0, sizeof(cbdata));
2337 cbdata.flags = flags;
2339 lock_packed_refs(LOCK_DIE_ON_ERROR);
2340 cbdata.packed_refs = get_packed_refs(&ref_cache);
2342 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2343 pack_if_possible_fn, &cbdata);
2345 if (commit_packed_refs())
2346 die_errno("unable to overwrite old ref-pack file");
2348 prune_refs(cbdata.ref_to_prune);
2349 return 0;
2353 * If entry is no longer needed in packed-refs, add it to the string
2354 * list pointed to by cb_data. Reasons for deleting entries:
2356 * - Entry is broken.
2357 * - Entry is overridden by a loose ref.
2358 * - Entry does not point at a valid object.
2360 * In the first and third cases, also emit an error message because these
2361 * are indications of repository corruption.
2363 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2365 struct string_list *refs_to_delete = cb_data;
2367 if (entry->flag & REF_ISBROKEN) {
2368 /* This shouldn't happen to packed refs. */
2369 error("%s is broken!", entry->name);
2370 string_list_append(refs_to_delete, entry->name);
2371 return 0;
2373 if (!has_sha1_file(entry->u.value.sha1)) {
2374 unsigned char sha1[20];
2375 int flags;
2377 if (read_ref_full(entry->name, sha1, 0, &flags))
2378 /* We should at least have found the packed ref. */
2379 die("Internal error");
2380 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2382 * This packed reference is overridden by a
2383 * loose reference, so it is OK that its value
2384 * is no longer valid; for example, it might
2385 * refer to an object that has been garbage
2386 * collected. For this purpose we don't even
2387 * care whether the loose reference itself is
2388 * invalid, broken, symbolic, etc. Silently
2389 * remove the packed reference.
2391 string_list_append(refs_to_delete, entry->name);
2392 return 0;
2395 * There is no overriding loose reference, so the fact
2396 * that this reference doesn't refer to a valid object
2397 * indicates some kind of repository corruption.
2398 * Report the problem, then omit the reference from
2399 * the output.
2401 error("%s does not point to a valid object!", entry->name);
2402 string_list_append(refs_to_delete, entry->name);
2403 return 0;
2406 return 0;
2409 static int repack_without_ref(const char *refname)
2411 struct ref_dir *packed;
2412 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2413 struct string_list_item *ref_to_delete;
2415 if (!get_packed_ref(refname))
2416 return 0; /* refname does not exist in packed refs */
2418 if (lock_packed_refs(0)) {
2419 unable_to_lock_error(git_path("packed-refs"), errno);
2420 return error("cannot delete '%s' from packed refs", refname);
2422 packed = get_packed_refs(&ref_cache);
2424 /* Remove refname from the cache: */
2425 if (remove_entry(packed, refname) == -1) {
2427 * The packed entry disappeared while we were
2428 * acquiring the lock.
2430 rollback_packed_refs();
2431 return 0;
2434 /* Remove any other accumulated cruft: */
2435 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2436 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2437 if (remove_entry(packed, ref_to_delete->string) == -1)
2438 die("internal error");
2441 /* Write what remains: */
2442 return commit_packed_refs();
2445 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2447 struct ref_lock *lock;
2448 int err, i = 0, ret = 0, flag = 0;
2450 lock = lock_ref_sha1_basic(refname, sha1, delopt, &flag);
2451 if (!lock)
2452 return 1;
2453 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2454 /* loose */
2455 i = strlen(lock->lk->filename) - 5; /* .lock */
2456 lock->lk->filename[i] = 0;
2457 err = unlink_or_warn(lock->lk->filename);
2458 if (err && errno != ENOENT)
2459 ret = 1;
2461 lock->lk->filename[i] = '.';
2463 /* removing the loose one could have resurrected an earlier
2464 * packed one. Also, if it was not loose we need to repack
2465 * without it.
2467 ret |= repack_without_ref(lock->ref_name);
2469 unlink_or_warn(git_path("logs/%s", lock->ref_name));
2470 clear_loose_ref_cache(&ref_cache);
2471 unlock_ref(lock);
2472 return ret;
2476 * People using contrib's git-new-workdir have .git/logs/refs ->
2477 * /some/other/path/.git/logs/refs, and that may live on another device.
2479 * IOW, to avoid cross device rename errors, the temporary renamed log must
2480 * live into logs/refs.
2482 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2484 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2486 unsigned char sha1[20], orig_sha1[20];
2487 int flag = 0, logmoved = 0;
2488 struct ref_lock *lock;
2489 struct stat loginfo;
2490 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2491 const char *symref = NULL;
2493 if (log && S_ISLNK(loginfo.st_mode))
2494 return error("reflog for %s is a symlink", oldrefname);
2496 symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
2497 if (flag & REF_ISSYMREF)
2498 return error("refname %s is a symbolic ref, renaming it is not supported",
2499 oldrefname);
2500 if (!symref)
2501 return error("refname %s not found", oldrefname);
2503 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(&ref_cache)))
2504 return 1;
2506 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(&ref_cache)))
2507 return 1;
2509 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2510 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2511 oldrefname, strerror(errno));
2513 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2514 error("unable to delete old %s", oldrefname);
2515 goto rollback;
2518 if (!read_ref_full(newrefname, sha1, 1, &flag) &&
2519 delete_ref(newrefname, sha1, REF_NODEREF)) {
2520 if (errno==EISDIR) {
2521 if (remove_empty_directories(git_path("%s", newrefname))) {
2522 error("Directory not empty: %s", newrefname);
2523 goto rollback;
2525 } else {
2526 error("unable to delete existing %s", newrefname);
2527 goto rollback;
2531 if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2532 error("unable to create directory for %s", newrefname);
2533 goto rollback;
2536 retry:
2537 if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2538 if (errno==EISDIR || errno==ENOTDIR) {
2540 * rename(a, b) when b is an existing
2541 * directory ought to result in ISDIR, but
2542 * Solaris 5.8 gives ENOTDIR. Sheesh.
2544 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2545 error("Directory not empty: logs/%s", newrefname);
2546 goto rollback;
2548 goto retry;
2549 } else {
2550 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2551 newrefname, strerror(errno));
2552 goto rollback;
2555 logmoved = log;
2557 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
2558 if (!lock) {
2559 error("unable to lock %s for update", newrefname);
2560 goto rollback;
2562 lock->force_write = 1;
2563 hashcpy(lock->old_sha1, orig_sha1);
2564 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
2565 error("unable to write current sha1 into %s", newrefname);
2566 goto rollback;
2569 return 0;
2571 rollback:
2572 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
2573 if (!lock) {
2574 error("unable to lock %s for rollback", oldrefname);
2575 goto rollbacklog;
2578 lock->force_write = 1;
2579 flag = log_all_ref_updates;
2580 log_all_ref_updates = 0;
2581 if (write_ref_sha1(lock, orig_sha1, NULL))
2582 error("unable to write current sha1 into %s", oldrefname);
2583 log_all_ref_updates = flag;
2585 rollbacklog:
2586 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2587 error("unable to restore logfile %s from %s: %s",
2588 oldrefname, newrefname, strerror(errno));
2589 if (!logmoved && log &&
2590 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2591 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2592 oldrefname, strerror(errno));
2594 return 1;
2597 int close_ref(struct ref_lock *lock)
2599 if (close_lock_file(lock->lk))
2600 return -1;
2601 lock->lock_fd = -1;
2602 return 0;
2605 int commit_ref(struct ref_lock *lock)
2607 if (commit_lock_file(lock->lk))
2608 return -1;
2609 lock->lock_fd = -1;
2610 return 0;
2613 void unlock_ref(struct ref_lock *lock)
2615 /* Do not free lock->lk -- atexit() still looks at them */
2616 if (lock->lk)
2617 rollback_lock_file(lock->lk);
2618 free(lock->ref_name);
2619 free(lock->orig_ref_name);
2620 free(lock);
2624 * copy the reflog message msg to buf, which has been allocated sufficiently
2625 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2626 * because reflog file is one line per entry.
2628 static int copy_msg(char *buf, const char *msg)
2630 char *cp = buf;
2631 char c;
2632 int wasspace = 1;
2634 *cp++ = '\t';
2635 while ((c = *msg++)) {
2636 if (wasspace && isspace(c))
2637 continue;
2638 wasspace = isspace(c);
2639 if (wasspace)
2640 c = ' ';
2641 *cp++ = c;
2643 while (buf < cp && isspace(cp[-1]))
2644 cp--;
2645 *cp++ = '\n';
2646 return cp - buf;
2649 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2651 int logfd, oflags = O_APPEND | O_WRONLY;
2653 git_snpath(logfile, bufsize, "logs/%s", refname);
2654 if (log_all_ref_updates &&
2655 (!prefixcmp(refname, "refs/heads/") ||
2656 !prefixcmp(refname, "refs/remotes/") ||
2657 !prefixcmp(refname, "refs/notes/") ||
2658 !strcmp(refname, "HEAD"))) {
2659 if (safe_create_leading_directories(logfile) < 0)
2660 return error("unable to create directory for %s",
2661 logfile);
2662 oflags |= O_CREAT;
2665 logfd = open(logfile, oflags, 0666);
2666 if (logfd < 0) {
2667 if (!(oflags & O_CREAT) && errno == ENOENT)
2668 return 0;
2670 if ((oflags & O_CREAT) && errno == EISDIR) {
2671 if (remove_empty_directories(logfile)) {
2672 return error("There are still logs under '%s'",
2673 logfile);
2675 logfd = open(logfile, oflags, 0666);
2678 if (logfd < 0)
2679 return error("Unable to append to %s: %s",
2680 logfile, strerror(errno));
2683 adjust_shared_perm(logfile);
2684 close(logfd);
2685 return 0;
2688 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2689 const unsigned char *new_sha1, const char *msg)
2691 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2692 unsigned maxlen, len;
2693 int msglen;
2694 char log_file[PATH_MAX];
2695 char *logrec;
2696 const char *committer;
2698 if (log_all_ref_updates < 0)
2699 log_all_ref_updates = !is_bare_repository();
2701 result = log_ref_setup(refname, log_file, sizeof(log_file));
2702 if (result)
2703 return result;
2705 logfd = open(log_file, oflags);
2706 if (logfd < 0)
2707 return 0;
2708 msglen = msg ? strlen(msg) : 0;
2709 committer = git_committer_info(0);
2710 maxlen = strlen(committer) + msglen + 100;
2711 logrec = xmalloc(maxlen);
2712 len = sprintf(logrec, "%s %s %s\n",
2713 sha1_to_hex(old_sha1),
2714 sha1_to_hex(new_sha1),
2715 committer);
2716 if (msglen)
2717 len += copy_msg(logrec + len - 1, msg) - 1;
2718 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2719 free(logrec);
2720 if (close(logfd) != 0 || written != len)
2721 return error("Unable to append to %s", log_file);
2722 return 0;
2725 static int is_branch(const char *refname)
2727 return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2730 int write_ref_sha1(struct ref_lock *lock,
2731 const unsigned char *sha1, const char *logmsg)
2733 static char term = '\n';
2734 struct object *o;
2736 if (!lock)
2737 return -1;
2738 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2739 unlock_ref(lock);
2740 return 0;
2742 o = parse_object(sha1);
2743 if (!o) {
2744 error("Trying to write ref %s with nonexistent object %s",
2745 lock->ref_name, sha1_to_hex(sha1));
2746 unlock_ref(lock);
2747 return -1;
2749 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2750 error("Trying to write non-commit object %s to branch %s",
2751 sha1_to_hex(sha1), lock->ref_name);
2752 unlock_ref(lock);
2753 return -1;
2755 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2756 write_in_full(lock->lock_fd, &term, 1) != 1
2757 || close_ref(lock) < 0) {
2758 error("Couldn't write %s", lock->lk->filename);
2759 unlock_ref(lock);
2760 return -1;
2762 clear_loose_ref_cache(&ref_cache);
2763 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2764 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2765 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2766 unlock_ref(lock);
2767 return -1;
2769 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2771 * Special hack: If a branch is updated directly and HEAD
2772 * points to it (may happen on the remote side of a push
2773 * for example) then logically the HEAD reflog should be
2774 * updated too.
2775 * A generic solution implies reverse symref information,
2776 * but finding all symrefs pointing to the given branch
2777 * would be rather costly for this rare event (the direct
2778 * update of a branch) to be worth it. So let's cheat and
2779 * check with HEAD only which should cover 99% of all usage
2780 * scenarios (even 100% of the default ones).
2782 unsigned char head_sha1[20];
2783 int head_flag;
2784 const char *head_ref;
2785 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2786 if (head_ref && (head_flag & REF_ISSYMREF) &&
2787 !strcmp(head_ref, lock->ref_name))
2788 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2790 if (commit_ref(lock)) {
2791 error("Couldn't set %s", lock->ref_name);
2792 unlock_ref(lock);
2793 return -1;
2795 unlock_ref(lock);
2796 return 0;
2799 int create_symref(const char *ref_target, const char *refs_heads_master,
2800 const char *logmsg)
2802 const char *lockpath;
2803 char ref[1000];
2804 int fd, len, written;
2805 char *git_HEAD = git_pathdup("%s", ref_target);
2806 unsigned char old_sha1[20], new_sha1[20];
2808 if (logmsg && read_ref(ref_target, old_sha1))
2809 hashclr(old_sha1);
2811 if (safe_create_leading_directories(git_HEAD) < 0)
2812 return error("unable to create directory for %s", git_HEAD);
2814 #ifndef NO_SYMLINK_HEAD
2815 if (prefer_symlink_refs) {
2816 unlink(git_HEAD);
2817 if (!symlink(refs_heads_master, git_HEAD))
2818 goto done;
2819 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2821 #endif
2823 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2824 if (sizeof(ref) <= len) {
2825 error("refname too long: %s", refs_heads_master);
2826 goto error_free_return;
2828 lockpath = mkpath("%s.lock", git_HEAD);
2829 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2830 if (fd < 0) {
2831 error("Unable to open %s for writing", lockpath);
2832 goto error_free_return;
2834 written = write_in_full(fd, ref, len);
2835 if (close(fd) != 0 || written != len) {
2836 error("Unable to write to %s", lockpath);
2837 goto error_unlink_return;
2839 if (rename(lockpath, git_HEAD) < 0) {
2840 error("Unable to create %s", git_HEAD);
2841 goto error_unlink_return;
2843 if (adjust_shared_perm(git_HEAD)) {
2844 error("Unable to fix permissions on %s", lockpath);
2845 error_unlink_return:
2846 unlink_or_warn(lockpath);
2847 error_free_return:
2848 free(git_HEAD);
2849 return -1;
2852 #ifndef NO_SYMLINK_HEAD
2853 done:
2854 #endif
2855 if (logmsg && !read_ref(refs_heads_master, new_sha1))
2856 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2858 free(git_HEAD);
2859 return 0;
2862 static char *ref_msg(const char *line, const char *endp)
2864 const char *ep;
2865 line += 82;
2866 ep = memchr(line, '\n', endp - line);
2867 if (!ep)
2868 ep = endp;
2869 return xmemdupz(line, ep - line);
2872 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2873 unsigned char *sha1, char **msg,
2874 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2876 const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2877 char *tz_c;
2878 int logfd, tz, reccnt = 0;
2879 struct stat st;
2880 unsigned long date;
2881 unsigned char logged_sha1[20];
2882 void *log_mapped;
2883 size_t mapsz;
2885 logfile = git_path("logs/%s", refname);
2886 logfd = open(logfile, O_RDONLY, 0);
2887 if (logfd < 0)
2888 die_errno("Unable to read log '%s'", logfile);
2889 fstat(logfd, &st);
2890 if (!st.st_size)
2891 die("Log %s is empty.", logfile);
2892 mapsz = xsize_t(st.st_size);
2893 log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2894 logdata = log_mapped;
2895 close(logfd);
2897 lastrec = NULL;
2898 rec = logend = logdata + st.st_size;
2899 while (logdata < rec) {
2900 reccnt++;
2901 if (logdata < rec && *(rec-1) == '\n')
2902 rec--;
2903 lastgt = NULL;
2904 while (logdata < rec && *(rec-1) != '\n') {
2905 rec--;
2906 if (*rec == '>')
2907 lastgt = rec;
2909 if (!lastgt)
2910 die("Log %s is corrupt.", logfile);
2911 date = strtoul(lastgt + 1, &tz_c, 10);
2912 if (date <= at_time || cnt == 0) {
2913 tz = strtoul(tz_c, NULL, 10);
2914 if (msg)
2915 *msg = ref_msg(rec, logend);
2916 if (cutoff_time)
2917 *cutoff_time = date;
2918 if (cutoff_tz)
2919 *cutoff_tz = tz;
2920 if (cutoff_cnt)
2921 *cutoff_cnt = reccnt - 1;
2922 if (lastrec) {
2923 if (get_sha1_hex(lastrec, logged_sha1))
2924 die("Log %s is corrupt.", logfile);
2925 if (get_sha1_hex(rec + 41, sha1))
2926 die("Log %s is corrupt.", logfile);
2927 if (hashcmp(logged_sha1, sha1)) {
2928 warning("Log %s has gap after %s.",
2929 logfile, show_date(date, tz, DATE_RFC2822));
2932 else if (date == at_time) {
2933 if (get_sha1_hex(rec + 41, sha1))
2934 die("Log %s is corrupt.", logfile);
2936 else {
2937 if (get_sha1_hex(rec + 41, logged_sha1))
2938 die("Log %s is corrupt.", logfile);
2939 if (hashcmp(logged_sha1, sha1)) {
2940 warning("Log %s unexpectedly ended on %s.",
2941 logfile, show_date(date, tz, DATE_RFC2822));
2944 munmap(log_mapped, mapsz);
2945 return 0;
2947 lastrec = rec;
2948 if (cnt > 0)
2949 cnt--;
2952 rec = logdata;
2953 while (rec < logend && *rec != '>' && *rec != '\n')
2954 rec++;
2955 if (rec == logend || *rec == '\n')
2956 die("Log %s is corrupt.", logfile);
2957 date = strtoul(rec + 1, &tz_c, 10);
2958 tz = strtoul(tz_c, NULL, 10);
2959 if (get_sha1_hex(logdata, sha1))
2960 die("Log %s is corrupt.", logfile);
2961 if (is_null_sha1(sha1)) {
2962 if (get_sha1_hex(logdata + 41, sha1))
2963 die("Log %s is corrupt.", logfile);
2965 if (msg)
2966 *msg = ref_msg(logdata, logend);
2967 munmap(log_mapped, mapsz);
2969 if (cutoff_time)
2970 *cutoff_time = date;
2971 if (cutoff_tz)
2972 *cutoff_tz = tz;
2973 if (cutoff_cnt)
2974 *cutoff_cnt = reccnt;
2975 return 1;
2978 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2980 unsigned char osha1[20], nsha1[20];
2981 char *email_end, *message;
2982 unsigned long timestamp;
2983 int tz;
2985 /* old SP new SP name <email> SP time TAB msg LF */
2986 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
2987 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
2988 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
2989 !(email_end = strchr(sb->buf + 82, '>')) ||
2990 email_end[1] != ' ' ||
2991 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2992 !message || message[0] != ' ' ||
2993 (message[1] != '+' && message[1] != '-') ||
2994 !isdigit(message[2]) || !isdigit(message[3]) ||
2995 !isdigit(message[4]) || !isdigit(message[5]))
2996 return 0; /* corrupt? */
2997 email_end[1] = '\0';
2998 tz = strtol(message + 1, NULL, 10);
2999 if (message[6] != '\t')
3000 message += 6;
3001 else
3002 message += 7;
3003 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3006 static char *find_beginning_of_line(char *bob, char *scan)
3008 while (bob < scan && *(--scan) != '\n')
3009 ; /* keep scanning backwards */
3011 * Return either beginning of the buffer, or LF at the end of
3012 * the previous line.
3014 return scan;
3017 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3019 struct strbuf sb = STRBUF_INIT;
3020 FILE *logfp;
3021 long pos;
3022 int ret = 0, at_tail = 1;
3024 logfp = fopen(git_path("logs/%s", refname), "r");
3025 if (!logfp)
3026 return -1;
3028 /* Jump to the end */
3029 if (fseek(logfp, 0, SEEK_END) < 0)
3030 return error("cannot seek back reflog for %s: %s",
3031 refname, strerror(errno));
3032 pos = ftell(logfp);
3033 while (!ret && 0 < pos) {
3034 int cnt;
3035 size_t nread;
3036 char buf[BUFSIZ];
3037 char *endp, *scanp;
3039 /* Fill next block from the end */
3040 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3041 if (fseek(logfp, pos - cnt, SEEK_SET))
3042 return error("cannot seek back reflog for %s: %s",
3043 refname, strerror(errno));
3044 nread = fread(buf, cnt, 1, logfp);
3045 if (nread != 1)
3046 return error("cannot read %d bytes from reflog for %s: %s",
3047 cnt, refname, strerror(errno));
3048 pos -= cnt;
3050 scanp = endp = buf + cnt;
3051 if (at_tail && scanp[-1] == '\n')
3052 /* Looking at the final LF at the end of the file */
3053 scanp--;
3054 at_tail = 0;
3056 while (buf < scanp) {
3058 * terminating LF of the previous line, or the beginning
3059 * of the buffer.
3061 char *bp;
3063 bp = find_beginning_of_line(buf, scanp);
3065 if (*bp != '\n') {
3066 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3067 if (pos)
3068 break; /* need to fill another block */
3069 scanp = buf - 1; /* leave loop */
3070 } else {
3072 * (bp + 1) thru endp is the beginning of the
3073 * current line we have in sb
3075 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3076 scanp = bp;
3077 endp = bp + 1;
3079 ret = show_one_reflog_ent(&sb, fn, cb_data);
3080 strbuf_reset(&sb);
3081 if (ret)
3082 break;
3086 if (!ret && sb.len)
3087 ret = show_one_reflog_ent(&sb, fn, cb_data);
3089 fclose(logfp);
3090 strbuf_release(&sb);
3091 return ret;
3094 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3096 FILE *logfp;
3097 struct strbuf sb = STRBUF_INIT;
3098 int ret = 0;
3100 logfp = fopen(git_path("logs/%s", refname), "r");
3101 if (!logfp)
3102 return -1;
3104 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3105 ret = show_one_reflog_ent(&sb, fn, cb_data);
3106 fclose(logfp);
3107 strbuf_release(&sb);
3108 return ret;
3111 * Call fn for each reflog in the namespace indicated by name. name
3112 * must be empty or end with '/'. Name will be used as a scratch
3113 * space, but its contents will be restored before return.
3115 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3117 DIR *d = opendir(git_path("logs/%s", name->buf));
3118 int retval = 0;
3119 struct dirent *de;
3120 int oldlen = name->len;
3122 if (!d)
3123 return name->len ? errno : 0;
3125 while ((de = readdir(d)) != NULL) {
3126 struct stat st;
3128 if (de->d_name[0] == '.')
3129 continue;
3130 if (has_extension(de->d_name, ".lock"))
3131 continue;
3132 strbuf_addstr(name, de->d_name);
3133 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3134 ; /* silently ignore */
3135 } else {
3136 if (S_ISDIR(st.st_mode)) {
3137 strbuf_addch(name, '/');
3138 retval = do_for_each_reflog(name, fn, cb_data);
3139 } else {
3140 unsigned char sha1[20];
3141 if (read_ref_full(name->buf, sha1, 0, NULL))
3142 retval = error("bad ref for %s", name->buf);
3143 else
3144 retval = fn(name->buf, sha1, 0, cb_data);
3146 if (retval)
3147 break;
3149 strbuf_setlen(name, oldlen);
3151 closedir(d);
3152 return retval;
3155 int for_each_reflog(each_ref_fn fn, void *cb_data)
3157 int retval;
3158 struct strbuf name;
3159 strbuf_init(&name, PATH_MAX);
3160 retval = do_for_each_reflog(&name, fn, cb_data);
3161 strbuf_release(&name);
3162 return retval;
3165 int update_ref(const char *action, const char *refname,
3166 const unsigned char *sha1, const unsigned char *oldval,
3167 int flags, enum action_on_err onerr)
3169 static struct ref_lock *lock;
3170 lock = lock_any_ref_for_update(refname, oldval, flags);
3171 if (!lock) {
3172 const char *str = "Cannot lock the ref '%s'.";
3173 switch (onerr) {
3174 case MSG_ON_ERR: error(str, refname); break;
3175 case DIE_ON_ERR: die(str, refname); break;
3176 case QUIET_ON_ERR: break;
3178 return 1;
3180 if (write_ref_sha1(lock, sha1, action) < 0) {
3181 const char *str = "Cannot update the ref '%s'.";
3182 switch (onerr) {
3183 case MSG_ON_ERR: error(str, refname); break;
3184 case DIE_ON_ERR: die(str, refname); break;
3185 case QUIET_ON_ERR: break;
3187 return 1;
3189 return 0;
3192 struct ref *find_ref_by_name(const struct ref *list, const char *name)
3194 for ( ; list; list = list->next)
3195 if (!strcmp(list->name, name))
3196 return (struct ref *)list;
3197 return NULL;
3201 * generate a format suitable for scanf from a ref_rev_parse_rules
3202 * rule, that is replace the "%.*s" spec with a "%s" spec
3204 static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
3206 char *spec;
3208 spec = strstr(rule, "%.*s");
3209 if (!spec || strstr(spec + 4, "%.*s"))
3210 die("invalid rule in ref_rev_parse_rules: %s", rule);
3212 /* copy all until spec */
3213 strncpy(scanf_fmt, rule, spec - rule);
3214 scanf_fmt[spec - rule] = '\0';
3215 /* copy new spec */
3216 strcat(scanf_fmt, "%s");
3217 /* copy remaining rule */
3218 strcat(scanf_fmt, spec + 4);
3220 return;
3223 char *shorten_unambiguous_ref(const char *refname, int strict)
3225 int i;
3226 static char **scanf_fmts;
3227 static int nr_rules;
3228 char *short_name;
3230 /* pre generate scanf formats from ref_rev_parse_rules[] */
3231 if (!nr_rules) {
3232 size_t total_len = 0;
3234 /* the rule list is NULL terminated, count them first */
3235 for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
3236 /* no +1 because strlen("%s") < strlen("%.*s") */
3237 total_len += strlen(ref_rev_parse_rules[nr_rules]);
3239 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3241 total_len = 0;
3242 for (i = 0; i < nr_rules; i++) {
3243 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
3244 + total_len;
3245 gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
3246 total_len += strlen(ref_rev_parse_rules[i]);
3250 /* bail out if there are no rules */
3251 if (!nr_rules)
3252 return xstrdup(refname);
3254 /* buffer for scanf result, at most refname must fit */
3255 short_name = xstrdup(refname);
3257 /* skip first rule, it will always match */
3258 for (i = nr_rules - 1; i > 0 ; --i) {
3259 int j;
3260 int rules_to_fail = i;
3261 int short_name_len;
3263 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3264 continue;
3266 short_name_len = strlen(short_name);
3269 * in strict mode, all (except the matched one) rules
3270 * must fail to resolve to a valid non-ambiguous ref
3272 if (strict)
3273 rules_to_fail = nr_rules;
3276 * check if the short name resolves to a valid ref,
3277 * but use only rules prior to the matched one
3279 for (j = 0; j < rules_to_fail; j++) {
3280 const char *rule = ref_rev_parse_rules[j];
3281 char refname[PATH_MAX];
3283 /* skip matched rule */
3284 if (i == j)
3285 continue;
3288 * the short name is ambiguous, if it resolves
3289 * (with this previous rule) to a valid ref
3290 * read_ref() returns 0 on success
3292 mksnpath(refname, sizeof(refname),
3293 rule, short_name_len, short_name);
3294 if (ref_exists(refname))
3295 break;
3299 * short name is non-ambiguous if all previous rules
3300 * haven't resolved to a valid ref
3302 if (j == rules_to_fail)
3303 return short_name;
3306 free(short_name);
3307 return xstrdup(refname);
3310 static struct string_list *hide_refs;
3312 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3314 if (!strcmp("transfer.hiderefs", var) ||
3315 /* NEEDSWORK: use parse_config_key() once both are merged */
3316 (!prefixcmp(var, section) && var[strlen(section)] == '.' &&
3317 !strcmp(var + strlen(section), ".hiderefs"))) {
3318 char *ref;
3319 int len;
3321 if (!value)
3322 return config_error_nonbool(var);
3323 ref = xstrdup(value);
3324 len = strlen(ref);
3325 while (len && ref[len - 1] == '/')
3326 ref[--len] = '\0';
3327 if (!hide_refs) {
3328 hide_refs = xcalloc(1, sizeof(*hide_refs));
3329 hide_refs->strdup_strings = 1;
3331 string_list_append(hide_refs, ref);
3333 return 0;
3336 int ref_is_hidden(const char *refname)
3338 struct string_list_item *item;
3340 if (!hide_refs)
3341 return 0;
3342 for_each_string_list_item(item, hide_refs) {
3343 int len;
3344 if (prefixcmp(refname, item->string))
3345 continue;
3346 len = strlen(item->string);
3347 if (!refname[len] || refname[len] == '/')
3348 return 1;
3350 return 0;