Merge branch 'mt/patch-id-stable' into jch
[git/jrn.git] / refs.c
blobb1e317da3e361591b3f8843f47df89d21bb96ad9
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
6 #include "string-list.h"
8 /*
9 * How to handle various characters in refnames:
10 * 0: An acceptable character for refs
11 * 1: End-of-component
12 * 2: ., look for a preceding . to reject .. in refs
13 * 3: {, look for a preceding @ to reject @{ in refs
14 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
16 static unsigned char refname_disposition[256] = {
17 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
18 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
19 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
28 * Used as a flag to ref_transaction_delete when a loose ref is being
29 * pruned.
31 #define REF_ISPRUNING 0x0100
33 * Try to read one refname component from the front of refname.
34 * Return the length of the component found, or -1 if the component is
35 * not legal. It is legal if it is something reasonable to have under
36 * ".git/refs/"; We do not like it if:
38 * - any path component of it begins with ".", or
39 * - it has double dots "..", or
40 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
41 * - it ends with a "/".
42 * - it ends with ".lock"
43 * - it contains a "\" (backslash)
45 static int check_refname_component(const char *refname, int flags)
47 const char *cp;
48 char last = '\0';
50 for (cp = refname; ; cp++) {
51 int ch = *cp & 255;
52 unsigned char disp = refname_disposition[ch];
53 switch (disp) {
54 case 1:
55 goto out;
56 case 2:
57 if (last == '.')
58 return -1; /* Refname contains "..". */
59 break;
60 case 3:
61 if (last == '@')
62 return -1; /* Refname contains "@{". */
63 break;
64 case 4:
65 return -1;
67 last = ch;
69 out:
70 if (cp == refname)
71 return 0; /* Component has zero length. */
72 if (refname[0] == '.') {
73 if (!(flags & REFNAME_DOT_COMPONENT))
74 return -1; /* Component starts with '.'. */
76 * Even if leading dots are allowed, don't allow "."
77 * as a component (".." is prevented by a rule above).
79 if (refname[1] == '\0')
80 return -1; /* Component equals ".". */
82 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
83 return -1; /* Refname ends with ".lock". */
84 return cp - refname;
87 int check_refname_format(const char *refname, int flags)
89 int component_len, component_count = 0;
91 if (!strcmp(refname, "@"))
92 /* Refname is a single character '@'. */
93 return -1;
95 while (1) {
96 /* We are at the start of a path component. */
97 component_len = check_refname_component(refname, flags);
98 if (component_len <= 0) {
99 if ((flags & REFNAME_REFSPEC_PATTERN) &&
100 refname[0] == '*' &&
101 (refname[1] == '\0' || refname[1] == '/')) {
102 /* Accept one wildcard as a full refname component. */
103 flags &= ~REFNAME_REFSPEC_PATTERN;
104 component_len = 1;
105 } else {
106 return -1;
109 component_count++;
110 if (refname[component_len] == '\0')
111 break;
112 /* Skip to next component. */
113 refname += component_len + 1;
116 if (refname[component_len - 1] == '.')
117 return -1; /* Refname ends with '.'. */
118 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
119 return -1; /* Refname has only one component. */
120 return 0;
123 struct ref_entry;
126 * Information used (along with the information in ref_entry) to
127 * describe a single cached reference. This data structure only
128 * occurs embedded in a union in struct ref_entry, and only when
129 * (ref_entry->flag & REF_DIR) is zero.
131 struct ref_value {
133 * The name of the object to which this reference resolves
134 * (which may be a tag object). If REF_ISBROKEN, this is
135 * null. If REF_ISSYMREF, then this is the name of the object
136 * referred to by the last reference in the symlink chain.
138 unsigned char sha1[20];
141 * If REF_KNOWS_PEELED, then this field holds the peeled value
142 * of this reference, or null if the reference is known not to
143 * be peelable. See the documentation for peel_ref() for an
144 * exact definition of "peelable".
146 unsigned char peeled[20];
149 struct ref_cache;
152 * Information used (along with the information in ref_entry) to
153 * describe a level in the hierarchy of references. This data
154 * structure only occurs embedded in a union in struct ref_entry, and
155 * only when (ref_entry.flag & REF_DIR) is set. In that case,
156 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
157 * in the directory have already been read:
159 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
160 * or packed references, already read.
162 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
163 * references that hasn't been read yet (nor has any of its
164 * subdirectories).
166 * Entries within a directory are stored within a growable array of
167 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
168 * sorted are sorted by their component name in strcmp() order and the
169 * remaining entries are unsorted.
171 * Loose references are read lazily, one directory at a time. When a
172 * directory of loose references is read, then all of the references
173 * in that directory are stored, and REF_INCOMPLETE stubs are created
174 * for any subdirectories, but the subdirectories themselves are not
175 * read. The reading is triggered by get_ref_dir().
177 struct ref_dir {
178 int nr, alloc;
181 * Entries with index 0 <= i < sorted are sorted by name. New
182 * entries are appended to the list unsorted, and are sorted
183 * only when required; thus we avoid the need to sort the list
184 * after the addition of every reference.
186 int sorted;
188 /* A pointer to the ref_cache that contains this ref_dir. */
189 struct ref_cache *ref_cache;
191 struct ref_entry **entries;
195 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
196 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see
197 * refs.h.
201 * The field ref_entry->u.value.peeled of this value entry contains
202 * the correct peeled value for the reference, which might be
203 * null_sha1 if the reference is not a tag or if it is broken.
205 #define REF_KNOWS_PEELED 0x08
207 /* ref_entry represents a directory of references */
208 #define REF_DIR 0x10
211 * Entry has not yet been read from disk (used only for REF_DIR
212 * entries representing loose references)
214 #define REF_INCOMPLETE 0x20
217 * A ref_entry represents either a reference or a "subdirectory" of
218 * references.
220 * Each directory in the reference namespace is represented by a
221 * ref_entry with (flags & REF_DIR) set and containing a subdir member
222 * that holds the entries in that directory that have been read so
223 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
224 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
225 * used for loose reference directories.
227 * References are represented by a ref_entry with (flags & REF_DIR)
228 * unset and a value member that describes the reference's value. The
229 * flag member is at the ref_entry level, but it is also needed to
230 * interpret the contents of the value field (in other words, a
231 * ref_value object is not very much use without the enclosing
232 * ref_entry).
234 * Reference names cannot end with slash and directories' names are
235 * always stored with a trailing slash (except for the top-level
236 * directory, which is always denoted by ""). This has two nice
237 * consequences: (1) when the entries in each subdir are sorted
238 * lexicographically by name (as they usually are), the references in
239 * a whole tree can be generated in lexicographic order by traversing
240 * the tree in left-to-right, depth-first order; (2) the names of
241 * references and subdirectories cannot conflict, and therefore the
242 * presence of an empty subdirectory does not block the creation of a
243 * similarly-named reference. (The fact that reference names with the
244 * same leading components can conflict *with each other* is a
245 * separate issue that is regulated by is_refname_available().)
247 * Please note that the name field contains the fully-qualified
248 * reference (or subdirectory) name. Space could be saved by only
249 * storing the relative names. But that would require the full names
250 * to be generated on the fly when iterating in do_for_each_ref(), and
251 * would break callback functions, who have always been able to assume
252 * that the name strings that they are passed will not be freed during
253 * the iteration.
255 struct ref_entry {
256 unsigned char flag; /* ISSYMREF? ISPACKED? */
257 union {
258 struct ref_value value; /* if not (flags&REF_DIR) */
259 struct ref_dir subdir; /* if (flags&REF_DIR) */
260 } u;
262 * The full name of the reference (e.g., "refs/heads/master")
263 * or the full name of the directory with a trailing slash
264 * (e.g., "refs/heads/"):
266 char name[FLEX_ARRAY];
269 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
271 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
273 struct ref_dir *dir;
274 assert(entry->flag & REF_DIR);
275 dir = &entry->u.subdir;
276 if (entry->flag & REF_INCOMPLETE) {
277 read_loose_refs(entry->name, dir);
278 entry->flag &= ~REF_INCOMPLETE;
280 return dir;
283 static struct ref_entry *create_ref_entry(const char *refname,
284 const unsigned char *sha1, int flag)
286 int len;
287 struct ref_entry *ref;
289 len = strlen(refname) + 1;
290 ref = xmalloc(sizeof(struct ref_entry) + len);
291 hashcpy(ref->u.value.sha1, sha1);
292 hashclr(ref->u.value.peeled);
293 memcpy(ref->name, refname, len);
294 ref->flag = flag;
295 return ref;
298 static void clear_ref_dir(struct ref_dir *dir);
300 static void free_ref_entry(struct ref_entry *entry)
302 if (entry->flag & REF_DIR) {
304 * Do not use get_ref_dir() here, as that might
305 * trigger the reading of loose refs.
307 clear_ref_dir(&entry->u.subdir);
309 free(entry);
313 * Add a ref_entry to the end of dir (unsorted). Entry is always
314 * stored directly in dir; no recursion into subdirectories is
315 * done.
317 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
319 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
320 dir->entries[dir->nr++] = entry;
321 /* optimize for the case that entries are added in order */
322 if (dir->nr == 1 ||
323 (dir->nr == dir->sorted + 1 &&
324 strcmp(dir->entries[dir->nr - 2]->name,
325 dir->entries[dir->nr - 1]->name) < 0))
326 dir->sorted = dir->nr;
330 * Clear and free all entries in dir, recursively.
332 static void clear_ref_dir(struct ref_dir *dir)
334 int i;
335 for (i = 0; i < dir->nr; i++)
336 free_ref_entry(dir->entries[i]);
337 free(dir->entries);
338 dir->sorted = dir->nr = dir->alloc = 0;
339 dir->entries = NULL;
343 * Create a struct ref_entry object for the specified dirname.
344 * dirname is the name of the directory with a trailing slash (e.g.,
345 * "refs/heads/") or "" for the top-level directory.
347 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
348 const char *dirname, size_t len,
349 int incomplete)
351 struct ref_entry *direntry;
352 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
353 memcpy(direntry->name, dirname, len);
354 direntry->name[len] = '\0';
355 direntry->u.subdir.ref_cache = ref_cache;
356 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
357 return direntry;
360 static int ref_entry_cmp(const void *a, const void *b)
362 struct ref_entry *one = *(struct ref_entry **)a;
363 struct ref_entry *two = *(struct ref_entry **)b;
364 return strcmp(one->name, two->name);
367 static void sort_ref_dir(struct ref_dir *dir);
369 struct string_slice {
370 size_t len;
371 const char *str;
374 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
376 const struct string_slice *key = key_;
377 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
378 int cmp = strncmp(key->str, ent->name, key->len);
379 if (cmp)
380 return cmp;
381 return '\0' - (unsigned char)ent->name[key->len];
385 * Return the index of the entry with the given refname from the
386 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
387 * no such entry is found. dir must already be complete.
389 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
391 struct ref_entry **r;
392 struct string_slice key;
394 if (refname == NULL || !dir->nr)
395 return -1;
397 sort_ref_dir(dir);
398 key.len = len;
399 key.str = refname;
400 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
401 ref_entry_cmp_sslice);
403 if (r == NULL)
404 return -1;
406 return r - dir->entries;
410 * Search for a directory entry directly within dir (without
411 * recursing). Sort dir if necessary. subdirname must be a directory
412 * name (i.e., end in '/'). If mkdir is set, then create the
413 * directory if it is missing; otherwise, return NULL if the desired
414 * directory cannot be found. dir must already be complete.
416 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
417 const char *subdirname, size_t len,
418 int mkdir)
420 int entry_index = search_ref_dir(dir, subdirname, len);
421 struct ref_entry *entry;
422 if (entry_index == -1) {
423 if (!mkdir)
424 return NULL;
426 * Since dir is complete, the absence of a subdir
427 * means that the subdir really doesn't exist;
428 * therefore, create an empty record for it but mark
429 * the record complete.
431 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
432 add_entry_to_dir(dir, entry);
433 } else {
434 entry = dir->entries[entry_index];
436 return get_ref_dir(entry);
440 * If refname is a reference name, find the ref_dir within the dir
441 * tree that should hold refname. If refname is a directory name
442 * (i.e., ends in '/'), then return that ref_dir itself. dir must
443 * represent the top-level directory and must already be complete.
444 * Sort ref_dirs and recurse into subdirectories as necessary. If
445 * mkdir is set, then create any missing directories; otherwise,
446 * return NULL if the desired directory cannot be found.
448 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
449 const char *refname, int mkdir)
451 const char *slash;
452 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
453 size_t dirnamelen = slash - refname + 1;
454 struct ref_dir *subdir;
455 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
456 if (!subdir) {
457 dir = NULL;
458 break;
460 dir = subdir;
463 return dir;
467 * Find the value entry with the given name in dir, sorting ref_dirs
468 * and recursing into subdirectories as necessary. If the name is not
469 * found or it corresponds to a directory entry, return NULL.
471 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
473 int entry_index;
474 struct ref_entry *entry;
475 dir = find_containing_dir(dir, refname, 0);
476 if (!dir)
477 return NULL;
478 entry_index = search_ref_dir(dir, refname, strlen(refname));
479 if (entry_index == -1)
480 return NULL;
481 entry = dir->entries[entry_index];
482 return (entry->flag & REF_DIR) ? NULL : entry;
486 * Remove the entry with the given name from dir, recursing into
487 * subdirectories as necessary. If refname is the name of a directory
488 * (i.e., ends with '/'), then remove the directory and its contents.
489 * If the removal was successful, return the number of entries
490 * remaining in the directory entry that contained the deleted entry.
491 * If the name was not found, return -1. Please note that this
492 * function only deletes the entry from the cache; it does not delete
493 * it from the filesystem or ensure that other cache entries (which
494 * might be symbolic references to the removed entry) are updated.
495 * Nor does it remove any containing dir entries that might be made
496 * empty by the removal. dir must represent the top-level directory
497 * and must already be complete.
499 static int remove_entry(struct ref_dir *dir, const char *refname)
501 int refname_len = strlen(refname);
502 int entry_index;
503 struct ref_entry *entry;
504 int is_dir = refname[refname_len - 1] == '/';
505 if (is_dir) {
507 * refname represents a reference directory. Remove
508 * the trailing slash; otherwise we will get the
509 * directory *representing* refname rather than the
510 * one *containing* it.
512 char *dirname = xmemdupz(refname, refname_len - 1);
513 dir = find_containing_dir(dir, dirname, 0);
514 free(dirname);
515 } else {
516 dir = find_containing_dir(dir, refname, 0);
518 if (!dir)
519 return -1;
520 entry_index = search_ref_dir(dir, refname, refname_len);
521 if (entry_index == -1)
522 return -1;
523 entry = dir->entries[entry_index];
525 memmove(&dir->entries[entry_index],
526 &dir->entries[entry_index + 1],
527 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
529 dir->nr--;
530 if (dir->sorted > entry_index)
531 dir->sorted--;
532 free_ref_entry(entry);
533 return dir->nr;
537 * Add a ref_entry to the ref_dir (unsorted), recursing into
538 * subdirectories as necessary. dir must represent the top-level
539 * directory. Return 0 on success.
541 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
543 dir = find_containing_dir(dir, ref->name, 1);
544 if (!dir)
545 return -1;
546 add_entry_to_dir(dir, ref);
547 return 0;
551 * Emit a warning and return true iff ref1 and ref2 have the same name
552 * and the same sha1. Die if they have the same name but different
553 * sha1s.
555 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
557 if (strcmp(ref1->name, ref2->name))
558 return 0;
560 /* Duplicate name; make sure that they don't conflict: */
562 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
563 /* This is impossible by construction */
564 die("Reference directory conflict: %s", ref1->name);
566 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
567 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
569 warning("Duplicated ref: %s", ref1->name);
570 return 1;
574 * Sort the entries in dir non-recursively (if they are not already
575 * sorted) and remove any duplicate entries.
577 static void sort_ref_dir(struct ref_dir *dir)
579 int i, j;
580 struct ref_entry *last = NULL;
583 * This check also prevents passing a zero-length array to qsort(),
584 * which is a problem on some platforms.
586 if (dir->sorted == dir->nr)
587 return;
589 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
591 /* Remove any duplicates: */
592 for (i = 0, j = 0; j < dir->nr; j++) {
593 struct ref_entry *entry = dir->entries[j];
594 if (last && is_dup_ref(last, entry))
595 free_ref_entry(entry);
596 else
597 last = dir->entries[i++] = entry;
599 dir->sorted = dir->nr = i;
602 /* Include broken references in a do_for_each_ref*() iteration: */
603 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
606 * Return true iff the reference described by entry can be resolved to
607 * an object in the database. Emit a warning if the referred-to
608 * object does not exist.
610 static int ref_resolves_to_object(struct ref_entry *entry)
612 if (entry->flag & REF_ISBROKEN)
613 return 0;
614 if (!has_sha1_file(entry->u.value.sha1)) {
615 error("%s does not point to a valid object!", entry->name);
616 return 0;
618 return 1;
622 * current_ref is a performance hack: when iterating over references
623 * using the for_each_ref*() functions, current_ref is set to the
624 * current reference's entry before calling the callback function. If
625 * the callback function calls peel_ref(), then peel_ref() first
626 * checks whether the reference to be peeled is the current reference
627 * (it usually is) and if so, returns that reference's peeled version
628 * if it is available. This avoids a refname lookup in a common case.
630 static struct ref_entry *current_ref;
632 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
634 struct ref_entry_cb {
635 const char *base;
636 int trim;
637 int flags;
638 each_ref_fn *fn;
639 void *cb_data;
643 * Handle one reference in a do_for_each_ref*()-style iteration,
644 * calling an each_ref_fn for each entry.
646 static int do_one_ref(struct ref_entry *entry, void *cb_data)
648 struct ref_entry_cb *data = cb_data;
649 struct ref_entry *old_current_ref;
650 int retval;
652 if (!starts_with(entry->name, data->base))
653 return 0;
655 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
656 !ref_resolves_to_object(entry))
657 return 0;
659 /* Store the old value, in case this is a recursive call: */
660 old_current_ref = current_ref;
661 current_ref = entry;
662 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
663 entry->flag, data->cb_data);
664 current_ref = old_current_ref;
665 return retval;
669 * Call fn for each reference in dir that has index in the range
670 * offset <= index < dir->nr. Recurse into subdirectories that are in
671 * that index range, sorting them before iterating. This function
672 * does not sort dir itself; it should be sorted beforehand. fn is
673 * called for all references, including broken ones.
675 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
676 each_ref_entry_fn fn, void *cb_data)
678 int i;
679 assert(dir->sorted == dir->nr);
680 for (i = offset; i < dir->nr; i++) {
681 struct ref_entry *entry = dir->entries[i];
682 int retval;
683 if (entry->flag & REF_DIR) {
684 struct ref_dir *subdir = get_ref_dir(entry);
685 sort_ref_dir(subdir);
686 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
687 } else {
688 retval = fn(entry, cb_data);
690 if (retval)
691 return retval;
693 return 0;
697 * Call fn for each reference in the union of dir1 and dir2, in order
698 * by refname. Recurse into subdirectories. If a value entry appears
699 * in both dir1 and dir2, then only process the version that is in
700 * dir2. The input dirs must already be sorted, but subdirs will be
701 * sorted as needed. fn is called for all references, including
702 * broken ones.
704 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
705 struct ref_dir *dir2,
706 each_ref_entry_fn fn, void *cb_data)
708 int retval;
709 int i1 = 0, i2 = 0;
711 assert(dir1->sorted == dir1->nr);
712 assert(dir2->sorted == dir2->nr);
713 while (1) {
714 struct ref_entry *e1, *e2;
715 int cmp;
716 if (i1 == dir1->nr) {
717 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
719 if (i2 == dir2->nr) {
720 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
722 e1 = dir1->entries[i1];
723 e2 = dir2->entries[i2];
724 cmp = strcmp(e1->name, e2->name);
725 if (cmp == 0) {
726 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
727 /* Both are directories; descend them in parallel. */
728 struct ref_dir *subdir1 = get_ref_dir(e1);
729 struct ref_dir *subdir2 = get_ref_dir(e2);
730 sort_ref_dir(subdir1);
731 sort_ref_dir(subdir2);
732 retval = do_for_each_entry_in_dirs(
733 subdir1, subdir2, fn, cb_data);
734 i1++;
735 i2++;
736 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
737 /* Both are references; ignore the one from dir1. */
738 retval = fn(e2, cb_data);
739 i1++;
740 i2++;
741 } else {
742 die("conflict between reference and directory: %s",
743 e1->name);
745 } else {
746 struct ref_entry *e;
747 if (cmp < 0) {
748 e = e1;
749 i1++;
750 } else {
751 e = e2;
752 i2++;
754 if (e->flag & REF_DIR) {
755 struct ref_dir *subdir = get_ref_dir(e);
756 sort_ref_dir(subdir);
757 retval = do_for_each_entry_in_dir(
758 subdir, 0, fn, cb_data);
759 } else {
760 retval = fn(e, cb_data);
763 if (retval)
764 return retval;
769 * Load all of the refs from the dir into our in-memory cache. The hard work
770 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
771 * through all of the sub-directories. We do not even need to care about
772 * sorting, as traversal order does not matter to us.
774 static void prime_ref_dir(struct ref_dir *dir)
776 int i;
777 for (i = 0; i < dir->nr; i++) {
778 struct ref_entry *entry = dir->entries[i];
779 if (entry->flag & REF_DIR)
780 prime_ref_dir(get_ref_dir(entry));
784 * Return true iff refname1 and refname2 conflict with each other.
785 * Two reference names conflict if one of them exactly matches the
786 * leading components of the other; e.g., "foo/bar" conflicts with
787 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
788 * "foo/barbados".
790 static int names_conflict(const char *refname1, const char *refname2)
792 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
794 return (*refname1 == '\0' && *refname2 == '/')
795 || (*refname1 == '/' && *refname2 == '\0');
798 struct name_conflict_cb {
799 const char *refname;
800 const char *conflicting_refname;
801 const char **skip;
802 int skipnum;
805 static int name_conflict_fn(struct ref_entry *entry, void *cb_data)
807 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
808 int i;
809 for (i = 0; i < data->skipnum; i++)
810 if (!strcmp(entry->name, data->skip[i]))
811 return 0;
812 if (names_conflict(data->refname, entry->name)) {
813 data->conflicting_refname = entry->name;
814 return 1;
816 return 0;
820 * Return true iff a reference named refname could be created without
821 * conflicting with the name of an existing reference in dir. If
822 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
823 * (e.g., because oldrefname is scheduled for deletion in the same
824 * operation). skip contains a list of refs we want to skip checking for
825 * conflicts with.
827 static int is_refname_available(const char *refname,
828 struct ref_dir *dir,
829 const char **skip, int skipnum)
831 struct name_conflict_cb data;
832 data.refname = refname;
833 data.conflicting_refname = NULL;
834 data.skip = skip;
835 data.skipnum = skipnum;
837 sort_ref_dir(dir);
838 if (do_for_each_entry_in_dir(dir, 0, name_conflict_fn, &data)) {
839 error("'%s' exists; cannot create '%s'",
840 data.conflicting_refname, refname);
841 return 0;
843 return 1;
846 struct packed_ref_cache {
847 struct ref_entry *root;
850 * Count of references to the data structure in this instance,
851 * including the pointer from ref_cache::packed if any. The
852 * data will not be freed as long as the reference count is
853 * nonzero.
855 unsigned int referrers;
858 * Iff the packed-refs file associated with this instance is
859 * currently locked for writing, this points at the associated
860 * lock (which is owned by somebody else). The referrer count
861 * is also incremented when the file is locked and decremented
862 * when it is unlocked.
864 struct lock_file *lock;
866 /* The metadata from when this packed-refs cache was read */
867 struct stat_validity validity;
871 * Future: need to be in "struct repository"
872 * when doing a full libification.
874 static struct ref_cache {
875 struct ref_cache *next;
876 struct ref_entry *loose;
877 struct packed_ref_cache *packed;
879 * The submodule name, or "" for the main repo. We allocate
880 * length 1 rather than FLEX_ARRAY so that the main ref_cache
881 * is initialized correctly.
883 char name[1];
884 } ref_cache, *submodule_ref_caches;
886 /* Lock used for the main packed-refs file: */
887 static struct lock_file packlock;
890 * Increment the reference count of *packed_refs.
892 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
894 packed_refs->referrers++;
898 * Decrease the reference count of *packed_refs. If it goes to zero,
899 * free *packed_refs and return true; otherwise return false.
901 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
903 if (!--packed_refs->referrers) {
904 free_ref_entry(packed_refs->root);
905 stat_validity_clear(&packed_refs->validity);
906 free(packed_refs);
907 return 1;
908 } else {
909 return 0;
913 static void clear_packed_ref_cache(struct ref_cache *refs)
915 if (refs->packed) {
916 struct packed_ref_cache *packed_refs = refs->packed;
918 if (packed_refs->lock)
919 die("internal error: packed-ref cache cleared while locked");
920 refs->packed = NULL;
921 release_packed_ref_cache(packed_refs);
925 static void clear_loose_ref_cache(struct ref_cache *refs)
927 if (refs->loose) {
928 free_ref_entry(refs->loose);
929 refs->loose = NULL;
933 static struct ref_cache *create_ref_cache(const char *submodule)
935 int len;
936 struct ref_cache *refs;
937 if (!submodule)
938 submodule = "";
939 len = strlen(submodule) + 1;
940 refs = xcalloc(1, sizeof(struct ref_cache) + len);
941 memcpy(refs->name, submodule, len);
942 return refs;
946 * Return a pointer to a ref_cache for the specified submodule. For
947 * the main repository, use submodule==NULL. The returned structure
948 * will be allocated and initialized but not necessarily populated; it
949 * should not be freed.
951 static struct ref_cache *get_ref_cache(const char *submodule)
953 struct ref_cache *refs;
955 if (!submodule || !*submodule)
956 return &ref_cache;
958 for (refs = submodule_ref_caches; refs; refs = refs->next)
959 if (!strcmp(submodule, refs->name))
960 return refs;
962 refs = create_ref_cache(submodule);
963 refs->next = submodule_ref_caches;
964 submodule_ref_caches = refs;
965 return refs;
968 /* The length of a peeled reference line in packed-refs, including EOL: */
969 #define PEELED_LINE_LENGTH 42
972 * The packed-refs header line that we write out. Perhaps other
973 * traits will be added later. The trailing space is required.
975 static const char PACKED_REFS_HEADER[] =
976 "# pack-refs with: peeled fully-peeled \n";
979 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
980 * Return a pointer to the refname within the line (null-terminated),
981 * or NULL if there was a problem.
983 static const char *parse_ref_line(char *line, unsigned char *sha1)
986 * 42: the answer to everything.
988 * In this case, it happens to be the answer to
989 * 40 (length of sha1 hex representation)
990 * +1 (space in between hex and name)
991 * +1 (newline at the end of the line)
993 int len = strlen(line) - 42;
995 if (len <= 0)
996 return NULL;
997 if (get_sha1_hex(line, sha1) < 0)
998 return NULL;
999 if (!isspace(line[40]))
1000 return NULL;
1001 line += 41;
1002 if (isspace(*line))
1003 return NULL;
1004 if (line[len] != '\n')
1005 return NULL;
1006 line[len] = 0;
1008 return line;
1012 * Read f, which is a packed-refs file, into dir.
1014 * A comment line of the form "# pack-refs with: " may contain zero or
1015 * more traits. We interpret the traits as follows:
1017 * No traits:
1019 * Probably no references are peeled. But if the file contains a
1020 * peeled value for a reference, we will use it.
1022 * peeled:
1024 * References under "refs/tags/", if they *can* be peeled, *are*
1025 * peeled in this file. References outside of "refs/tags/" are
1026 * probably not peeled even if they could have been, but if we find
1027 * a peeled value for such a reference we will use it.
1029 * fully-peeled:
1031 * All references in the file that can be peeled are peeled.
1032 * Inversely (and this is more important), any references in the
1033 * file for which no peeled value is recorded is not peelable. This
1034 * trait should typically be written alongside "peeled" for
1035 * compatibility with older clients, but we do not require it
1036 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1038 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1040 struct ref_entry *last = NULL;
1041 char refline[PATH_MAX];
1042 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1044 while (fgets(refline, sizeof(refline), f)) {
1045 unsigned char sha1[20];
1046 const char *refname;
1047 static const char header[] = "# pack-refs with:";
1049 if (!strncmp(refline, header, sizeof(header)-1)) {
1050 const char *traits = refline + sizeof(header) - 1;
1051 if (strstr(traits, " fully-peeled "))
1052 peeled = PEELED_FULLY;
1053 else if (strstr(traits, " peeled "))
1054 peeled = PEELED_TAGS;
1055 /* perhaps other traits later as well */
1056 continue;
1059 refname = parse_ref_line(refline, sha1);
1060 if (refname) {
1061 int flag = REF_ISPACKED;
1063 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) {
1064 flag |= REF_ISBROKEN;
1066 last = create_ref_entry(refname, sha1, flag);
1067 if (peeled == PEELED_FULLY ||
1068 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1069 last->flag |= REF_KNOWS_PEELED;
1070 add_ref(dir, last);
1071 continue;
1073 if (last &&
1074 refline[0] == '^' &&
1075 strlen(refline) == PEELED_LINE_LENGTH &&
1076 refline[PEELED_LINE_LENGTH - 1] == '\n' &&
1077 !get_sha1_hex(refline + 1, sha1)) {
1078 hashcpy(last->u.value.peeled, sha1);
1080 * Regardless of what the file header said,
1081 * we definitely know the value of *this*
1082 * reference:
1084 last->flag |= REF_KNOWS_PEELED;
1090 * Get the packed_ref_cache for the specified ref_cache, creating it
1091 * if necessary.
1093 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1095 const char *packed_refs_file;
1097 if (*refs->name)
1098 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1099 else
1100 packed_refs_file = git_path("packed-refs");
1102 if (refs->packed &&
1103 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1104 clear_packed_ref_cache(refs);
1106 if (!refs->packed) {
1107 FILE *f;
1109 refs->packed = xcalloc(1, sizeof(*refs->packed));
1110 acquire_packed_ref_cache(refs->packed);
1111 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1112 f = fopen(packed_refs_file, "r");
1113 if (f) {
1114 stat_validity_update(&refs->packed->validity, fileno(f));
1115 read_packed_refs(f, get_ref_dir(refs->packed->root));
1116 fclose(f);
1119 return refs->packed;
1122 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1124 return get_ref_dir(packed_ref_cache->root);
1127 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1129 return get_packed_ref_dir(get_packed_ref_cache(refs));
1132 void add_packed_ref(const char *refname, const unsigned char *sha1)
1134 struct packed_ref_cache *packed_ref_cache =
1135 get_packed_ref_cache(&ref_cache);
1137 if (!packed_ref_cache->lock)
1138 die("internal error: packed refs not locked");
1139 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
1140 die("Reference has invalid format: '%s'", refname);
1141 add_ref(get_packed_ref_dir(packed_ref_cache),
1142 create_ref_entry(refname, sha1, REF_ISPACKED));
1146 * Read the loose references from the namespace dirname into dir
1147 * (without recursing). dirname must end with '/'. dir must be the
1148 * directory entry corresponding to dirname.
1150 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1152 struct ref_cache *refs = dir->ref_cache;
1153 DIR *d;
1154 const char *path;
1155 struct dirent *de;
1156 int dirnamelen = strlen(dirname);
1157 struct strbuf refname;
1159 if (*refs->name)
1160 path = git_path_submodule(refs->name, "%s", dirname);
1161 else
1162 path = git_path("%s", dirname);
1164 d = opendir(path);
1165 if (!d)
1166 return;
1168 strbuf_init(&refname, dirnamelen + 257);
1169 strbuf_add(&refname, dirname, dirnamelen);
1171 while ((de = readdir(d)) != NULL) {
1172 unsigned char sha1[20];
1173 struct stat st;
1174 int flag;
1175 const char *refdir;
1177 if (de->d_name[0] == '.')
1178 continue;
1179 if (ends_with(de->d_name, ".lock"))
1180 continue;
1181 strbuf_addstr(&refname, de->d_name);
1182 refdir = *refs->name
1183 ? git_path_submodule(refs->name, "%s", refname.buf)
1184 : git_path("%s", refname.buf);
1185 if (stat(refdir, &st) < 0) {
1186 ; /* silently ignore */
1187 } else if (S_ISDIR(st.st_mode)) {
1188 strbuf_addch(&refname, '/');
1189 add_entry_to_dir(dir,
1190 create_dir_entry(refs, refname.buf,
1191 refname.len, 1));
1192 } else {
1193 if (*refs->name) {
1194 hashclr(sha1);
1195 flag = 0;
1196 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1197 hashclr(sha1);
1198 flag |= REF_ISBROKEN;
1200 } else if (read_ref_full(refname.buf, sha1,
1201 RESOLVE_REF_READING, &flag)) {
1202 hashclr(sha1);
1203 flag |= REF_ISBROKEN;
1205 if (check_refname_format(refname.buf, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) {
1206 hashclr(sha1);
1207 flag |= REF_ISBROKEN;
1209 add_entry_to_dir(dir,
1210 create_ref_entry(refname.buf, sha1, flag));
1212 strbuf_setlen(&refname, dirnamelen);
1214 strbuf_release(&refname);
1215 closedir(d);
1218 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1220 if (!refs->loose) {
1222 * Mark the top-level directory complete because we
1223 * are about to read the only subdirectory that can
1224 * hold references:
1226 refs->loose = create_dir_entry(refs, "", 0, 0);
1228 * Create an incomplete entry for "refs/":
1230 add_entry_to_dir(get_ref_dir(refs->loose),
1231 create_dir_entry(refs, "refs/", 5, 1));
1233 return get_ref_dir(refs->loose);
1236 /* We allow "recursive" symbolic refs. Only within reason, though */
1237 #define MAXDEPTH 5
1238 #define MAXREFLEN (1024)
1241 * Called by resolve_gitlink_ref_recursive() after it failed to read
1242 * from the loose refs in ref_cache refs. Find <refname> in the
1243 * packed-refs file for the submodule.
1245 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1246 const char *refname, unsigned char *sha1)
1248 struct ref_entry *ref;
1249 struct ref_dir *dir = get_packed_refs(refs);
1251 ref = find_ref(dir, refname);
1252 if (ref == NULL)
1253 return -1;
1255 hashcpy(sha1, ref->u.value.sha1);
1256 return 0;
1259 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1260 const char *refname, unsigned char *sha1,
1261 int recursion)
1263 int fd, len;
1264 char buffer[128], *p;
1265 const char *path;
1267 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1268 return -1;
1269 path = *refs->name
1270 ? git_path_submodule(refs->name, "%s", refname)
1271 : git_path("%s", refname);
1272 fd = open(path, O_RDONLY);
1273 if (fd < 0)
1274 return resolve_gitlink_packed_ref(refs, refname, sha1);
1276 len = read(fd, buffer, sizeof(buffer)-1);
1277 close(fd);
1278 if (len < 0)
1279 return -1;
1280 while (len && isspace(buffer[len-1]))
1281 len--;
1282 buffer[len] = 0;
1284 /* Was it a detached head or an old-fashioned symlink? */
1285 if (!get_sha1_hex(buffer, sha1))
1286 return 0;
1288 /* Symref? */
1289 if (strncmp(buffer, "ref:", 4))
1290 return -1;
1291 p = buffer + 4;
1292 while (isspace(*p))
1293 p++;
1295 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1298 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1300 int len = strlen(path), retval;
1301 char *submodule;
1302 struct ref_cache *refs;
1304 while (len && path[len-1] == '/')
1305 len--;
1306 if (!len)
1307 return -1;
1308 submodule = xstrndup(path, len);
1309 refs = get_ref_cache(submodule);
1310 free(submodule);
1312 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1313 return retval;
1317 * Return the ref_entry for the given refname from the packed
1318 * references. If it does not exist, return NULL.
1320 static struct ref_entry *get_packed_ref(const char *refname)
1322 return find_ref(get_packed_refs(&ref_cache), refname);
1326 * A loose ref file doesn't exist; check for a packed ref. The
1327 * options are forwarded from resolve_safe_unsafe().
1329 static const char *handle_missing_loose_ref(const char *refname,
1330 unsigned char *sha1,
1331 int reading,
1332 int *flag)
1334 struct ref_entry *entry;
1337 * The loose reference file does not exist; check for a packed
1338 * reference.
1340 entry = get_packed_ref(refname);
1341 if (entry) {
1342 hashcpy(sha1, entry->u.value.sha1);
1343 if (flag)
1344 *flag |= REF_ISPACKED;
1345 return refname;
1347 /* The reference is not a packed reference, either. */
1348 if (reading) {
1349 return NULL;
1350 } else {
1351 hashclr(sha1);
1352 return refname;
1356 /* This function needs to return a meaningful errno on failure */
1357 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int flags, int *ref_flag)
1359 struct strbuf sb_path = STRBUF_INIT;
1360 int depth = MAXDEPTH;
1361 ssize_t len;
1362 char buffer[256];
1363 static char refname_buffer[256];
1364 const char *ret;
1366 if (ref_flag)
1367 *ref_flag = 0;
1369 if (!(flags & RESOLVE_REF_ALLOW_BAD_NAME) &&
1370 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1371 errno = EINVAL;
1372 return NULL;
1374 for (;;) {
1375 const char *path;
1376 struct stat st;
1377 char *buf;
1378 int fd;
1380 if (--depth < 0) {
1381 errno = ELOOP;
1382 goto fail;
1385 strbuf_reset(&sb_path);
1386 strbuf_git_path(&sb_path, "%s", refname);
1387 path = sb_path.buf;
1390 * We might have to loop back here to avoid a race
1391 * condition: first we lstat() the file, then we try
1392 * to read it as a link or as a file. But if somebody
1393 * changes the type of the file (file <-> directory
1394 * <-> symlink) between the lstat() and reading, then
1395 * we don't want to report that as an error but rather
1396 * try again starting with the lstat().
1398 stat_ref:
1399 if (lstat(path, &st) < 0) {
1400 if (errno == ENOENT)
1401 ret = handle_missing_loose_ref(refname, sha1,
1402 flags & RESOLVE_REF_READING,
1403 ref_flag);
1404 else
1405 ret = NULL;
1406 goto done;
1409 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1410 if (S_ISLNK(st.st_mode)) {
1411 len = readlink(path, buffer, sizeof(buffer)-1);
1412 if (len < 0) {
1413 if (errno == ENOENT || errno == EINVAL)
1414 /* inconsistent with lstat; retry */
1415 goto stat_ref;
1416 else
1417 goto fail;
1419 buffer[len] = 0;
1420 if (starts_with(buffer, "refs/") &&
1421 !check_refname_format(buffer, 0)) {
1422 strcpy(refname_buffer, buffer);
1423 refname = refname_buffer;
1424 if (ref_flag)
1425 *ref_flag |= REF_ISSYMREF;
1426 continue;
1430 /* Is it a directory? */
1431 if (S_ISDIR(st.st_mode)) {
1432 errno = EISDIR;
1433 goto fail;
1437 * Anything else, just open it and try to use it as
1438 * a ref
1440 fd = open(path, O_RDONLY);
1441 if (fd < 0) {
1442 if (errno == ENOENT)
1443 /* inconsistent with lstat; retry */
1444 goto stat_ref;
1445 else
1446 goto fail;
1449 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1450 if (len < 0) {
1451 int save_errno = errno;
1452 close(fd);
1453 errno = save_errno;
1454 goto fail;
1456 close(fd);
1457 while (len && isspace(buffer[len-1]))
1458 len--;
1459 buffer[len] = '\0';
1462 * Is it a symbolic ref?
1464 if (!starts_with(buffer, "ref:")) {
1466 * Please note that FETCH_HEAD has a second
1467 * line containing other data.
1469 if (get_sha1_hex(buffer, sha1) ||
1470 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1471 if (ref_flag)
1472 *ref_flag |= REF_ISBROKEN;
1473 errno = EINVAL;
1474 goto fail;
1476 ret = refname;
1477 goto done;
1479 if (ref_flag)
1480 *ref_flag |= REF_ISSYMREF;
1481 buf = buffer + 4;
1482 while (isspace(*buf))
1483 buf++;
1484 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1485 if (ref_flag)
1486 *ref_flag |= REF_ISBROKEN;
1487 errno = EINVAL;
1488 goto fail;
1490 refname = strcpy(refname_buffer, buf);
1492 fail:
1493 ret = NULL;
1494 done:
1495 strbuf_release(&sb_path);
1496 return ret;
1499 char *resolve_refdup(const char *ref, unsigned char *sha1, int flags, int *ref_flag)
1501 const char *ret = resolve_ref_unsafe(ref, sha1, flags, ref_flag);
1502 return ret ? xstrdup(ret) : NULL;
1505 /* The argument to filter_refs */
1506 struct ref_filter {
1507 const char *pattern;
1508 each_ref_fn *fn;
1509 void *cb_data;
1512 int read_ref_full(const char *refname, unsigned char *sha1, int flags, int *ref_flag)
1514 if (resolve_ref_unsafe(refname, sha1, flags, ref_flag))
1515 return 0;
1516 return -1;
1519 int read_ref(const char *refname, unsigned char *sha1)
1521 return read_ref_full(refname, sha1, RESOLVE_REF_READING, NULL);
1524 int ref_exists(const char *refname)
1526 unsigned char sha1[20];
1527 return !!resolve_ref_unsafe(refname, sha1, RESOLVE_REF_READING, NULL);
1530 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1531 void *data)
1533 struct ref_filter *filter = (struct ref_filter *)data;
1534 if (wildmatch(filter->pattern, refname, 0, NULL))
1535 return 0;
1536 return filter->fn(refname, sha1, flags, filter->cb_data);
1539 enum peel_status {
1540 /* object was peeled successfully: */
1541 PEEL_PEELED = 0,
1544 * object cannot be peeled because the named object (or an
1545 * object referred to by a tag in the peel chain), does not
1546 * exist.
1548 PEEL_INVALID = -1,
1550 /* object cannot be peeled because it is not a tag: */
1551 PEEL_NON_TAG = -2,
1553 /* ref_entry contains no peeled value because it is a symref: */
1554 PEEL_IS_SYMREF = -3,
1557 * ref_entry cannot be peeled because it is broken (i.e., the
1558 * symbolic reference cannot even be resolved to an object
1559 * name):
1561 PEEL_BROKEN = -4
1565 * Peel the named object; i.e., if the object is a tag, resolve the
1566 * tag recursively until a non-tag is found. If successful, store the
1567 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1568 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1569 * and leave sha1 unchanged.
1571 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1573 struct object *o = lookup_unknown_object(name);
1575 if (o->type == OBJ_NONE) {
1576 int type = sha1_object_info(name, NULL);
1577 if (type < 0 || !object_as_type(o, type, 0))
1578 return PEEL_INVALID;
1581 if (o->type != OBJ_TAG)
1582 return PEEL_NON_TAG;
1584 o = deref_tag_noverify(o);
1585 if (!o)
1586 return PEEL_INVALID;
1588 hashcpy(sha1, o->sha1);
1589 return PEEL_PEELED;
1593 * Peel the entry (if possible) and return its new peel_status. If
1594 * repeel is true, re-peel the entry even if there is an old peeled
1595 * value that is already stored in it.
1597 * It is OK to call this function with a packed reference entry that
1598 * might be stale and might even refer to an object that has since
1599 * been garbage-collected. In such a case, if the entry has
1600 * REF_KNOWS_PEELED then leave the status unchanged and return
1601 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1603 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1605 enum peel_status status;
1607 if (entry->flag & REF_KNOWS_PEELED) {
1608 if (repeel) {
1609 entry->flag &= ~REF_KNOWS_PEELED;
1610 hashclr(entry->u.value.peeled);
1611 } else {
1612 return is_null_sha1(entry->u.value.peeled) ?
1613 PEEL_NON_TAG : PEEL_PEELED;
1616 if (entry->flag & REF_ISBROKEN)
1617 return PEEL_BROKEN;
1618 if (entry->flag & REF_ISSYMREF)
1619 return PEEL_IS_SYMREF;
1621 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1622 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1623 entry->flag |= REF_KNOWS_PEELED;
1624 return status;
1627 int peel_ref(const char *refname, unsigned char *sha1)
1629 int flag;
1630 unsigned char base[20];
1632 if (current_ref && (current_ref->name == refname
1633 || !strcmp(current_ref->name, refname))) {
1634 if (peel_entry(current_ref, 0))
1635 return -1;
1636 hashcpy(sha1, current_ref->u.value.peeled);
1637 return 0;
1640 if (read_ref_full(refname, base, RESOLVE_REF_READING, &flag))
1641 return -1;
1644 * If the reference is packed, read its ref_entry from the
1645 * cache in the hope that we already know its peeled value.
1646 * We only try this optimization on packed references because
1647 * (a) forcing the filling of the loose reference cache could
1648 * be expensive and (b) loose references anyway usually do not
1649 * have REF_KNOWS_PEELED.
1651 if (flag & REF_ISPACKED) {
1652 struct ref_entry *r = get_packed_ref(refname);
1653 if (r) {
1654 if (peel_entry(r, 0))
1655 return -1;
1656 hashcpy(sha1, r->u.value.peeled);
1657 return 0;
1661 return peel_object(base, sha1);
1664 struct warn_if_dangling_data {
1665 FILE *fp;
1666 const char *refname;
1667 const struct string_list *refnames;
1668 const char *msg_fmt;
1671 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1672 int flags, void *cb_data)
1674 struct warn_if_dangling_data *d = cb_data;
1675 const char *resolves_to;
1676 unsigned char junk[20];
1678 if (!(flags & REF_ISSYMREF))
1679 return 0;
1681 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1682 if (!resolves_to
1683 || (d->refname
1684 ? strcmp(resolves_to, d->refname)
1685 : !string_list_has_string(d->refnames, resolves_to))) {
1686 return 0;
1689 fprintf(d->fp, d->msg_fmt, refname);
1690 fputc('\n', d->fp);
1691 return 0;
1694 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1696 struct warn_if_dangling_data data;
1698 data.fp = fp;
1699 data.refname = refname;
1700 data.refnames = NULL;
1701 data.msg_fmt = msg_fmt;
1702 for_each_rawref(warn_if_dangling_symref, &data);
1705 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1707 struct warn_if_dangling_data data;
1709 data.fp = fp;
1710 data.refname = NULL;
1711 data.refnames = refnames;
1712 data.msg_fmt = msg_fmt;
1713 for_each_rawref(warn_if_dangling_symref, &data);
1717 * Call fn for each reference in the specified ref_cache, omitting
1718 * references not in the containing_dir of base. fn is called for all
1719 * references, including broken ones. If fn ever returns a non-zero
1720 * value, stop the iteration and return that value; otherwise, return
1721 * 0.
1723 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1724 each_ref_entry_fn fn, void *cb_data)
1726 struct packed_ref_cache *packed_ref_cache;
1727 struct ref_dir *loose_dir;
1728 struct ref_dir *packed_dir;
1729 int retval = 0;
1732 * We must make sure that all loose refs are read before accessing the
1733 * packed-refs file; this avoids a race condition in which loose refs
1734 * are migrated to the packed-refs file by a simultaneous process, but
1735 * our in-memory view is from before the migration. get_packed_ref_cache()
1736 * takes care of making sure our view is up to date with what is on
1737 * disk.
1739 loose_dir = get_loose_refs(refs);
1740 if (base && *base) {
1741 loose_dir = find_containing_dir(loose_dir, base, 0);
1743 if (loose_dir)
1744 prime_ref_dir(loose_dir);
1746 packed_ref_cache = get_packed_ref_cache(refs);
1747 acquire_packed_ref_cache(packed_ref_cache);
1748 packed_dir = get_packed_ref_dir(packed_ref_cache);
1749 if (base && *base) {
1750 packed_dir = find_containing_dir(packed_dir, base, 0);
1753 if (packed_dir && loose_dir) {
1754 sort_ref_dir(packed_dir);
1755 sort_ref_dir(loose_dir);
1756 retval = do_for_each_entry_in_dirs(
1757 packed_dir, loose_dir, fn, cb_data);
1758 } else if (packed_dir) {
1759 sort_ref_dir(packed_dir);
1760 retval = do_for_each_entry_in_dir(
1761 packed_dir, 0, fn, cb_data);
1762 } else if (loose_dir) {
1763 sort_ref_dir(loose_dir);
1764 retval = do_for_each_entry_in_dir(
1765 loose_dir, 0, fn, cb_data);
1768 release_packed_ref_cache(packed_ref_cache);
1769 return retval;
1773 * Call fn for each reference in the specified ref_cache for which the
1774 * refname begins with base. If trim is non-zero, then trim that many
1775 * characters off the beginning of each refname before passing the
1776 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1777 * broken references in the iteration. If fn ever returns a non-zero
1778 * value, stop the iteration and return that value; otherwise, return
1779 * 0.
1781 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1782 each_ref_fn fn, int trim, int flags, void *cb_data)
1784 struct ref_entry_cb data;
1785 data.base = base;
1786 data.trim = trim;
1787 data.flags = flags;
1788 data.fn = fn;
1789 data.cb_data = cb_data;
1791 return do_for_each_entry(refs, base, do_one_ref, &data);
1794 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1796 unsigned char sha1[20];
1797 int flag;
1799 if (submodule) {
1800 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1801 return fn("HEAD", sha1, 0, cb_data);
1803 return 0;
1806 if (!read_ref_full("HEAD", sha1, RESOLVE_REF_READING, &flag))
1807 return fn("HEAD", sha1, flag, cb_data);
1809 return 0;
1812 int head_ref(each_ref_fn fn, void *cb_data)
1814 return do_head_ref(NULL, fn, cb_data);
1817 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1819 return do_head_ref(submodule, fn, cb_data);
1822 int for_each_ref(each_ref_fn fn, void *cb_data)
1824 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1827 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1829 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1832 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1834 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1837 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1838 each_ref_fn fn, void *cb_data)
1840 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1843 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1845 return for_each_ref_in("refs/tags/", fn, cb_data);
1848 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1850 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1853 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1855 return for_each_ref_in("refs/heads/", fn, cb_data);
1858 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1860 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1863 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1865 return for_each_ref_in("refs/remotes/", fn, cb_data);
1868 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1870 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1873 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1875 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
1878 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1880 struct strbuf buf = STRBUF_INIT;
1881 int ret = 0;
1882 unsigned char sha1[20];
1883 int flag;
1885 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1886 if (!read_ref_full(buf.buf, sha1, RESOLVE_REF_READING, &flag))
1887 ret = fn(buf.buf, sha1, flag, cb_data);
1888 strbuf_release(&buf);
1890 return ret;
1893 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1895 struct strbuf buf = STRBUF_INIT;
1896 int ret;
1897 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1898 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1899 strbuf_release(&buf);
1900 return ret;
1903 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1904 const char *prefix, void *cb_data)
1906 struct strbuf real_pattern = STRBUF_INIT;
1907 struct ref_filter filter;
1908 int ret;
1910 if (!prefix && !starts_with(pattern, "refs/"))
1911 strbuf_addstr(&real_pattern, "refs/");
1912 else if (prefix)
1913 strbuf_addstr(&real_pattern, prefix);
1914 strbuf_addstr(&real_pattern, pattern);
1916 if (!has_glob_specials(pattern)) {
1917 /* Append implied '/' '*' if not present. */
1918 if (real_pattern.buf[real_pattern.len - 1] != '/')
1919 strbuf_addch(&real_pattern, '/');
1920 /* No need to check for '*', there is none. */
1921 strbuf_addch(&real_pattern, '*');
1924 filter.pattern = real_pattern.buf;
1925 filter.fn = fn;
1926 filter.cb_data = cb_data;
1927 ret = for_each_ref(filter_refs, &filter);
1929 strbuf_release(&real_pattern);
1930 return ret;
1933 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1935 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1938 int for_each_rawref(each_ref_fn fn, void *cb_data)
1940 return do_for_each_ref(&ref_cache, "", fn, 0,
1941 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1944 const char *prettify_refname(const char *name)
1946 return name + (
1947 starts_with(name, "refs/heads/") ? 11 :
1948 starts_with(name, "refs/tags/") ? 10 :
1949 starts_with(name, "refs/remotes/") ? 13 :
1953 static const char *ref_rev_parse_rules[] = {
1954 "%.*s",
1955 "refs/%.*s",
1956 "refs/tags/%.*s",
1957 "refs/heads/%.*s",
1958 "refs/remotes/%.*s",
1959 "refs/remotes/%.*s/HEAD",
1960 NULL
1963 int refname_match(const char *abbrev_name, const char *full_name)
1965 const char **p;
1966 const int abbrev_name_len = strlen(abbrev_name);
1968 for (p = ref_rev_parse_rules; *p; p++) {
1969 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1970 return 1;
1974 return 0;
1977 /* This function should make sure errno is meaningful on error */
1978 static struct ref_lock *verify_lock(struct ref_lock *lock,
1979 const unsigned char *old_sha1, int mustexist)
1981 if (read_ref_full(lock->ref_name, lock->old_sha1,
1982 mustexist ? RESOLVE_REF_READING : 0, NULL)) {
1983 int save_errno = errno;
1984 error("Can't verify ref %s", lock->ref_name);
1985 unlock_ref(lock);
1986 errno = save_errno;
1987 return NULL;
1989 if (hashcmp(lock->old_sha1, old_sha1)) {
1990 error("Ref %s is at %s but expected %s", lock->ref_name,
1991 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1992 unlock_ref(lock);
1993 errno = EBUSY;
1994 return NULL;
1996 return lock;
1999 static int remove_empty_directories(const char *file)
2001 /* we want to create a file but there is a directory there;
2002 * if that is an empty directory (or a directory that contains
2003 * only empty directories), remove them.
2005 struct strbuf path;
2006 int result, save_errno;
2008 strbuf_init(&path, 20);
2009 strbuf_addstr(&path, file);
2011 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2012 save_errno = errno;
2014 strbuf_release(&path);
2015 errno = save_errno;
2017 return result;
2021 * *string and *len will only be substituted, and *string returned (for
2022 * later free()ing) if the string passed in is a magic short-hand form
2023 * to name a branch.
2025 static char *substitute_branch_name(const char **string, int *len)
2027 struct strbuf buf = STRBUF_INIT;
2028 int ret = interpret_branch_name(*string, *len, &buf);
2030 if (ret == *len) {
2031 size_t size;
2032 *string = strbuf_detach(&buf, &size);
2033 *len = size;
2034 return (char *)*string;
2037 return NULL;
2040 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2042 char *last_branch = substitute_branch_name(&str, &len);
2043 const char **p, *r;
2044 int refs_found = 0;
2046 *ref = NULL;
2047 for (p = ref_rev_parse_rules; *p; p++) {
2048 char fullref[PATH_MAX];
2049 unsigned char sha1_from_ref[20];
2050 unsigned char *this_result;
2051 int flag;
2053 this_result = refs_found ? sha1_from_ref : sha1;
2054 mksnpath(fullref, sizeof(fullref), *p, len, str);
2055 r = resolve_ref_unsafe(fullref, this_result,
2056 RESOLVE_REF_READING, &flag);
2057 if (r) {
2058 if (!refs_found++)
2059 *ref = xstrdup(r);
2060 if (!warn_ambiguous_refs)
2061 break;
2062 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2063 warning("ignoring dangling symref %s.", fullref);
2064 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2065 warning("ignoring broken ref %s.", fullref);
2068 free(last_branch);
2069 return refs_found;
2072 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2074 char *last_branch = substitute_branch_name(&str, &len);
2075 const char **p;
2076 int logs_found = 0;
2078 *log = NULL;
2079 for (p = ref_rev_parse_rules; *p; p++) {
2080 unsigned char hash[20];
2081 char path[PATH_MAX];
2082 const char *ref, *it;
2084 mksnpath(path, sizeof(path), *p, len, str);
2085 ref = resolve_ref_unsafe(path, hash, RESOLVE_REF_READING, NULL);
2086 if (!ref)
2087 continue;
2088 if (reflog_exists(path))
2089 it = path;
2090 else if (strcmp(ref, path) && reflog_exists(ref))
2091 it = ref;
2092 else
2093 continue;
2094 if (!logs_found++) {
2095 *log = xstrdup(it);
2096 hashcpy(sha1, hash);
2098 if (!warn_ambiguous_refs)
2099 break;
2101 free(last_branch);
2102 return logs_found;
2105 /* This function should make sure errno is meaningful on error */
2106 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2107 const unsigned char *old_sha1,
2108 int flags, int *type_p,
2109 const char **skip, int skipnum)
2111 const char *ref_file;
2112 const char *orig_refname = refname;
2113 struct ref_lock *lock;
2114 int last_errno = 0;
2115 int type, lflags;
2116 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2117 int resolve_flags;
2118 int missing = 0;
2119 int attempts_remaining = 3;
2120 int bad_refname;
2122 lock = xcalloc(1, sizeof(struct ref_lock));
2123 lock->lock_fd = -1;
2125 bad_refname = check_refname_format(refname, REFNAME_ALLOW_ONELEVEL);
2127 resolve_flags = RESOLVE_REF_ALLOW_BAD_NAME;
2128 if (mustexist)
2129 resolve_flags |= RESOLVE_REF_READING;
2131 refname = resolve_ref_unsafe(refname, lock->old_sha1, resolve_flags,
2132 &type);
2133 if (!refname && errno == EISDIR) {
2134 /* we are trying to lock foo but we used to
2135 * have foo/bar which now does not exist;
2136 * it is normal for the empty directory 'foo'
2137 * to remain.
2139 ref_file = git_path("%s", orig_refname);
2140 if (remove_empty_directories(ref_file)) {
2141 last_errno = errno;
2142 error("there are still refs under '%s'", orig_refname);
2143 goto error_return;
2145 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1,
2146 resolve_flags, &type);
2148 if (type_p)
2149 *type_p = type;
2150 if (!refname) {
2151 last_errno = errno;
2152 error("unable to resolve reference %s: %s",
2153 orig_refname, strerror(errno));
2154 goto error_return;
2156 missing = is_null_sha1(lock->old_sha1);
2157 /* When the ref did not exist and we are creating it,
2158 * make sure there is no existing ref that is packed
2159 * whose name begins with our refname, nor a ref whose
2160 * name is a proper prefix of our refname.
2162 if (missing &&
2163 !is_refname_available(refname, get_packed_refs(&ref_cache),
2164 skip, skipnum)) {
2165 last_errno = ENOTDIR;
2166 goto error_return;
2169 lock->lk = xcalloc(1, sizeof(struct lock_file));
2171 lflags = 0;
2172 if (flags & REF_NODEREF) {
2173 refname = orig_refname;
2174 lflags |= LOCK_NODEREF;
2176 lock->ref_name = xstrdup(refname);
2177 lock->orig_ref_name = xstrdup(orig_refname);
2178 ref_file = git_path("%s", refname);
2179 if (missing)
2180 lock->force_write = 1;
2181 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2182 lock->force_write = 1;
2184 retry:
2185 switch (safe_create_leading_directories_const(ref_file)) {
2186 case SCLD_OK:
2187 break; /* success */
2188 case SCLD_VANISHED:
2189 if (--attempts_remaining > 0)
2190 goto retry;
2191 /* fall through */
2192 default:
2193 last_errno = errno;
2194 error("unable to create directory for %s", ref_file);
2195 goto error_return;
2198 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2199 if (lock->lock_fd < 0) {
2200 if (errno == ENOENT && --attempts_remaining > 0)
2202 * Maybe somebody just deleted one of the
2203 * directories leading to ref_file. Try
2204 * again:
2206 goto retry;
2207 else
2208 unable_to_lock_index_die(ref_file, errno);
2210 if (bad_refname)
2211 return lock;
2212 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2214 error_return:
2215 unlock_ref(lock);
2216 errno = last_errno;
2217 return NULL;
2220 struct ref_lock *lock_any_ref_for_update(const char *refname,
2221 const unsigned char *old_sha1,
2222 int flags, int *type_p)
2224 return lock_ref_sha1_basic(refname, old_sha1, flags, type_p, NULL, 0);
2228 * Write an entry to the packed-refs file for the specified refname.
2229 * If peeled is non-NULL, write it as the entry's peeled value.
2231 static void write_packed_entry(int fd, char *refname, unsigned char *sha1,
2232 unsigned char *peeled)
2234 char line[PATH_MAX + 100];
2235 int len;
2237 len = snprintf(line, sizeof(line), "%s %s\n",
2238 sha1_to_hex(sha1), refname);
2239 /* this should not happen but just being defensive */
2240 if (len > sizeof(line))
2241 die("too long a refname '%s'", refname);
2242 write_or_die(fd, line, len);
2244 if (peeled) {
2245 if (snprintf(line, sizeof(line), "^%s\n",
2246 sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)
2247 die("internal error");
2248 write_or_die(fd, line, PEELED_LINE_LENGTH);
2253 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2255 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2257 int *fd = cb_data;
2258 enum peel_status peel_status = peel_entry(entry, 0);
2260 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2261 error("internal error: %s is not a valid packed reference!",
2262 entry->name);
2263 write_packed_entry(*fd, entry->name, entry->u.value.sha1,
2264 peel_status == PEEL_PEELED ?
2265 entry->u.value.peeled : NULL);
2266 return 0;
2269 /* This should return a meaningful errno on failure */
2270 int lock_packed_refs(int flags)
2272 struct packed_ref_cache *packed_ref_cache;
2274 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2275 return -1;
2277 * Get the current packed-refs while holding the lock. If the
2278 * packed-refs file has been modified since we last read it,
2279 * this will automatically invalidate the cache and re-read
2280 * the packed-refs file.
2282 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2283 packed_ref_cache->lock = &packlock;
2284 /* Increment the reference count to prevent it from being freed: */
2285 acquire_packed_ref_cache(packed_ref_cache);
2286 return 0;
2290 * Commit the packed refs changes.
2291 * On error we must make sure that errno contains a meaningful value.
2293 int commit_packed_refs(void)
2295 struct packed_ref_cache *packed_ref_cache =
2296 get_packed_ref_cache(&ref_cache);
2297 int error = 0;
2298 int save_errno = 0;
2300 if (!packed_ref_cache->lock)
2301 die("internal error: packed-refs not locked");
2302 write_or_die(packed_ref_cache->lock->fd,
2303 PACKED_REFS_HEADER, strlen(PACKED_REFS_HEADER));
2305 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2306 0, write_packed_entry_fn,
2307 &packed_ref_cache->lock->fd);
2308 if (commit_lock_file(packed_ref_cache->lock)) {
2309 save_errno = errno;
2310 error = -1;
2312 packed_ref_cache->lock = NULL;
2313 release_packed_ref_cache(packed_ref_cache);
2314 errno = save_errno;
2315 return error;
2318 void rollback_packed_refs(void)
2320 struct packed_ref_cache *packed_ref_cache =
2321 get_packed_ref_cache(&ref_cache);
2323 if (!packed_ref_cache->lock)
2324 die("internal error: packed-refs not locked");
2325 rollback_lock_file(packed_ref_cache->lock);
2326 packed_ref_cache->lock = NULL;
2327 release_packed_ref_cache(packed_ref_cache);
2328 clear_packed_ref_cache(&ref_cache);
2331 struct ref_to_prune {
2332 struct ref_to_prune *next;
2333 unsigned char sha1[20];
2334 char name[FLEX_ARRAY];
2337 struct pack_refs_cb_data {
2338 unsigned int flags;
2339 struct ref_dir *packed_refs;
2340 struct ref_to_prune *ref_to_prune;
2344 * An each_ref_entry_fn that is run over loose references only. If
2345 * the loose reference can be packed, add an entry in the packed ref
2346 * cache. If the reference should be pruned, also add it to
2347 * ref_to_prune in the pack_refs_cb_data.
2349 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2351 struct pack_refs_cb_data *cb = cb_data;
2352 enum peel_status peel_status;
2353 struct ref_entry *packed_entry;
2354 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2356 /* ALWAYS pack tags */
2357 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2358 return 0;
2360 /* Do not pack symbolic or broken refs: */
2361 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2362 return 0;
2364 /* Add a packed ref cache entry equivalent to the loose entry. */
2365 peel_status = peel_entry(entry, 1);
2366 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2367 die("internal error peeling reference %s (%s)",
2368 entry->name, sha1_to_hex(entry->u.value.sha1));
2369 packed_entry = find_ref(cb->packed_refs, entry->name);
2370 if (packed_entry) {
2371 /* Overwrite existing packed entry with info from loose entry */
2372 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2373 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2374 } else {
2375 packed_entry = create_ref_entry(entry->name,
2376 entry->u.value.sha1,
2377 REF_ISPACKED | REF_KNOWS_PEELED);
2378 add_ref(cb->packed_refs, packed_entry);
2380 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2382 /* Schedule the loose reference for pruning if requested. */
2383 if ((cb->flags & PACK_REFS_PRUNE)) {
2384 int namelen = strlen(entry->name) + 1;
2385 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2386 hashcpy(n->sha1, entry->u.value.sha1);
2387 strcpy(n->name, entry->name);
2388 n->next = cb->ref_to_prune;
2389 cb->ref_to_prune = n;
2391 return 0;
2395 * Remove empty parents, but spare refs/ and immediate subdirs.
2396 * Note: munges *name.
2398 static void try_remove_empty_parents(char *name)
2400 char *p, *q;
2401 int i;
2402 p = name;
2403 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2404 while (*p && *p != '/')
2405 p++;
2406 /* tolerate duplicate slashes; see check_refname_format() */
2407 while (*p == '/')
2408 p++;
2410 for (q = p; *q; q++)
2412 while (1) {
2413 while (q > p && *q != '/')
2414 q--;
2415 while (q > p && *(q-1) == '/')
2416 q--;
2417 if (q == p)
2418 break;
2419 *q = '\0';
2420 if (rmdir(git_path("%s", name)))
2421 break;
2425 /* make sure nobody touched the ref, and unlink */
2426 static void prune_ref(struct ref_to_prune *r)
2428 struct ref_transaction *transaction;
2429 struct strbuf err = STRBUF_INIT;
2431 if (check_refname_format(r->name + 5, 0))
2432 return;
2434 transaction = ref_transaction_begin(&err);
2435 if (!transaction ||
2436 ref_transaction_delete(transaction, r->name, r->sha1,
2437 REF_ISPRUNING, 1, NULL, &err) ||
2438 ref_transaction_commit(transaction, &err)) {
2439 ref_transaction_free(transaction);
2440 error("%s", err.buf);
2441 strbuf_release(&err);
2442 return;
2444 ref_transaction_free(transaction);
2445 try_remove_empty_parents(r->name);
2448 static void prune_refs(struct ref_to_prune *r)
2450 while (r) {
2451 prune_ref(r);
2452 r = r->next;
2456 int pack_refs(unsigned int flags)
2458 struct pack_refs_cb_data cbdata;
2460 memset(&cbdata, 0, sizeof(cbdata));
2461 cbdata.flags = flags;
2463 lock_packed_refs(LOCK_DIE_ON_ERROR);
2464 cbdata.packed_refs = get_packed_refs(&ref_cache);
2466 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2467 pack_if_possible_fn, &cbdata);
2469 if (commit_packed_refs())
2470 die_errno("unable to overwrite old ref-pack file");
2472 prune_refs(cbdata.ref_to_prune);
2473 return 0;
2477 * If entry is no longer needed in packed-refs, add it to the string
2478 * list pointed to by cb_data. Reasons for deleting entries:
2480 * - Entry is broken.
2481 * - Entry is overridden by a loose ref.
2482 * - Entry does not point at a valid object.
2484 * In the first and third cases, also emit an error message because these
2485 * are indications of repository corruption.
2487 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2489 struct string_list *refs_to_delete = cb_data;
2491 if (entry->flag & REF_ISBROKEN) {
2492 /* This shouldn't happen to packed refs. */
2493 error("%s is broken!", entry->name);
2494 string_list_append(refs_to_delete, entry->name);
2495 return 0;
2497 if (!has_sha1_file(entry->u.value.sha1)) {
2498 unsigned char sha1[20];
2499 int flags;
2501 if (read_ref_full(entry->name, sha1, 0, &flags))
2502 /* We should at least have found the packed ref. */
2503 die("Internal error");
2504 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2506 * This packed reference is overridden by a
2507 * loose reference, so it is OK that its value
2508 * is no longer valid; for example, it might
2509 * refer to an object that has been garbage
2510 * collected. For this purpose we don't even
2511 * care whether the loose reference itself is
2512 * invalid, broken, symbolic, etc. Silently
2513 * remove the packed reference.
2515 string_list_append(refs_to_delete, entry->name);
2516 return 0;
2519 * There is no overriding loose reference, so the fact
2520 * that this reference doesn't refer to a valid object
2521 * indicates some kind of repository corruption.
2522 * Report the problem, then omit the reference from
2523 * the output.
2525 error("%s does not point to a valid object!", entry->name);
2526 string_list_append(refs_to_delete, entry->name);
2527 return 0;
2530 return 0;
2533 int repack_without_refs(const char **refnames, int n, struct strbuf *err)
2535 struct ref_dir *packed;
2536 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2537 struct string_list_item *ref_to_delete;
2538 int i, ret, removed = 0;
2540 /* Look for a packed ref */
2541 for (i = 0; i < n; i++)
2542 if (get_packed_ref(refnames[i]))
2543 break;
2545 /* Avoid locking if we have nothing to do */
2546 if (i == n)
2547 return 0; /* no refname exists in packed refs */
2549 if (lock_packed_refs(0)) {
2550 if (err) {
2551 unable_to_lock_message(git_path("packed-refs"), errno,
2552 err);
2553 return -1;
2555 unable_to_lock_error(git_path("packed-refs"), errno);
2556 return error("cannot delete '%s' from packed refs", refnames[i]);
2558 packed = get_packed_refs(&ref_cache);
2560 /* Remove refnames from the cache */
2561 for (i = 0; i < n; i++)
2562 if (remove_entry(packed, refnames[i]) != -1)
2563 removed = 1;
2564 if (!removed) {
2566 * All packed entries disappeared while we were
2567 * acquiring the lock.
2569 rollback_packed_refs();
2570 return 0;
2573 /* Remove any other accumulated cruft */
2574 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2575 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2576 if (remove_entry(packed, ref_to_delete->string) == -1)
2577 die("internal error");
2580 /* Write what remains */
2581 ret = commit_packed_refs();
2582 if (ret && err)
2583 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2584 strerror(errno));
2585 return ret;
2588 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2590 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2591 /* loose */
2592 int res, i = strlen(lock->lk->filename) - 5; /* .lock */
2594 lock->lk->filename[i] = 0;
2595 res = unlink_or_msg(lock->lk->filename, err);
2596 lock->lk->filename[i] = '.';
2597 if (res)
2598 return 1;
2600 return 0;
2603 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2605 struct ref_transaction *transaction;
2606 struct strbuf err = STRBUF_INIT;
2608 transaction = ref_transaction_begin(&err);
2609 if (!transaction ||
2610 ref_transaction_delete(transaction, refname, sha1, delopt,
2611 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2612 ref_transaction_commit(transaction, &err)) {
2613 error("%s", err.buf);
2614 ref_transaction_free(transaction);
2615 strbuf_release(&err);
2616 return 1;
2618 ref_transaction_free(transaction);
2619 return 0;
2623 * People using contrib's git-new-workdir have .git/logs/refs ->
2624 * /some/other/path/.git/logs/refs, and that may live on another device.
2626 * IOW, to avoid cross device rename errors, the temporary renamed log must
2627 * live into logs/refs.
2629 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2631 static int rename_tmp_log(const char *newrefname)
2633 int attempts_remaining = 4;
2635 retry:
2636 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {
2637 case SCLD_OK:
2638 break; /* success */
2639 case SCLD_VANISHED:
2640 if (--attempts_remaining > 0)
2641 goto retry;
2642 /* fall through */
2643 default:
2644 error("unable to create directory for %s", newrefname);
2645 return -1;
2648 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2649 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2651 * rename(a, b) when b is an existing
2652 * directory ought to result in ISDIR, but
2653 * Solaris 5.8 gives ENOTDIR. Sheesh.
2655 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2656 error("Directory not empty: logs/%s", newrefname);
2657 return -1;
2659 goto retry;
2660 } else if (errno == ENOENT && --attempts_remaining > 0) {
2662 * Maybe another process just deleted one of
2663 * the directories in the path to newrefname.
2664 * Try again from the beginning.
2666 goto retry;
2667 } else {
2668 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2669 newrefname, strerror(errno));
2670 return -1;
2673 return 0;
2676 static int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1,
2677 const char *logmsg);
2679 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2681 unsigned char sha1[20], orig_sha1[20];
2682 int flag = 0, logmoved = 0;
2683 struct ref_lock *lock;
2684 struct stat loginfo;
2685 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2686 const char *symref = NULL;
2688 if (log && S_ISLNK(loginfo.st_mode))
2689 return error("reflog for %s is a symlink", oldrefname);
2691 symref = resolve_ref_unsafe(oldrefname, orig_sha1,
2692 RESOLVE_REF_READING, &flag);
2693 if (flag & REF_ISSYMREF)
2694 return error("refname %s is a symbolic ref, renaming it is not supported",
2695 oldrefname);
2696 if (!symref)
2697 return error("refname %s not found", oldrefname);
2699 if (!is_refname_available(newrefname, get_packed_refs(&ref_cache),
2700 &oldrefname, 1))
2701 return 1;
2703 if (!is_refname_available(newrefname, get_loose_refs(&ref_cache),
2704 &oldrefname, 1))
2705 return 1;
2707 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2708 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2709 oldrefname, strerror(errno));
2711 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2712 error("unable to delete old %s", oldrefname);
2713 goto rollback;
2716 if (!read_ref_full(newrefname, sha1, RESOLVE_REF_READING, NULL) &&
2717 delete_ref(newrefname, sha1, REF_NODEREF)) {
2718 if (errno==EISDIR) {
2719 if (remove_empty_directories(git_path("%s", newrefname))) {
2720 error("Directory not empty: %s", newrefname);
2721 goto rollback;
2723 } else {
2724 error("unable to delete existing %s", newrefname);
2725 goto rollback;
2729 if (log && rename_tmp_log(newrefname))
2730 goto rollback;
2732 logmoved = log;
2734 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL, NULL, 0);
2735 if (!lock) {
2736 error("unable to lock %s for update", newrefname);
2737 goto rollback;
2739 lock->force_write = 1;
2740 hashcpy(lock->old_sha1, orig_sha1);
2741 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
2742 error("unable to write current sha1 into %s", newrefname);
2743 goto rollback;
2746 return 0;
2748 rollback:
2749 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL, NULL, 0);
2750 if (!lock) {
2751 error("unable to lock %s for rollback", oldrefname);
2752 goto rollbacklog;
2755 lock->force_write = 1;
2756 flag = log_all_ref_updates;
2757 log_all_ref_updates = 0;
2758 if (write_ref_sha1(lock, orig_sha1, NULL))
2759 error("unable to write current sha1 into %s", oldrefname);
2760 log_all_ref_updates = flag;
2762 rollbacklog:
2763 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2764 error("unable to restore logfile %s from %s: %s",
2765 oldrefname, newrefname, strerror(errno));
2766 if (!logmoved && log &&
2767 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2768 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2769 oldrefname, strerror(errno));
2771 return 1;
2774 int close_ref(struct ref_lock *lock)
2776 if (close_lock_file(lock->lk))
2777 return -1;
2778 lock->lock_fd = -1;
2779 return 0;
2782 int commit_ref(struct ref_lock *lock)
2784 if (commit_lock_file(lock->lk))
2785 return -1;
2786 lock->lock_fd = -1;
2787 return 0;
2790 void unlock_ref(struct ref_lock *lock)
2792 /* Do not free lock->lk -- atexit() still looks at them */
2793 if (lock->lk)
2794 rollback_lock_file(lock->lk);
2795 free(lock->ref_name);
2796 free(lock->orig_ref_name);
2797 free(lock);
2801 * copy the reflog message msg to buf, which has been allocated sufficiently
2802 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2803 * because reflog file is one line per entry.
2805 static int copy_msg(char *buf, const char *msg)
2807 char *cp = buf;
2808 char c;
2809 int wasspace = 1;
2811 *cp++ = '\t';
2812 while ((c = *msg++)) {
2813 if (wasspace && isspace(c))
2814 continue;
2815 wasspace = isspace(c);
2816 if (wasspace)
2817 c = ' ';
2818 *cp++ = c;
2820 while (buf < cp && isspace(cp[-1]))
2821 cp--;
2822 *cp++ = '\n';
2823 return cp - buf;
2826 /* This function must set a meaningful errno on failure */
2827 int log_ref_setup(const char *refname, struct strbuf *logfile)
2829 int logfd, oflags = O_APPEND | O_WRONLY;
2831 strbuf_git_path(logfile, "logs/%s", refname);
2832 if (log_all_ref_updates &&
2833 (starts_with(refname, "refs/heads/") ||
2834 starts_with(refname, "refs/remotes/") ||
2835 starts_with(refname, "refs/notes/") ||
2836 !strcmp(refname, "HEAD"))) {
2837 if (safe_create_leading_directories(logfile->buf) < 0) {
2838 int save_errno = errno;
2839 error("unable to create directory for %s", logfile->buf);
2840 errno = save_errno;
2841 return -1;
2843 oflags |= O_CREAT;
2846 logfd = open(logfile->buf, oflags, 0666);
2847 if (logfd < 0) {
2848 if (!(oflags & O_CREAT) && errno == ENOENT)
2849 return 0;
2851 if ((oflags & O_CREAT) && errno == EISDIR) {
2852 if (remove_empty_directories(logfile->buf)) {
2853 int save_errno = errno;
2854 error("There are still logs under '%s'",
2855 logfile->buf);
2856 errno = save_errno;
2857 return -1;
2859 logfd = open(logfile->buf, oflags, 0666);
2862 if (logfd < 0) {
2863 int save_errno = errno;
2864 error("Unable to append to %s: %s", logfile->buf,
2865 strerror(errno));
2866 errno = save_errno;
2867 return -1;
2871 adjust_shared_perm(logfile->buf);
2872 close(logfd);
2873 return 0;
2876 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2877 const unsigned char *new_sha1, const char *msg)
2879 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2880 unsigned maxlen, len;
2881 int msglen;
2882 struct strbuf sb_log_file = STRBUF_INIT;
2883 const char *log_file;
2884 char *logrec;
2885 const char *committer;
2887 if (log_all_ref_updates < 0)
2888 log_all_ref_updates = !is_bare_repository();
2890 result = log_ref_setup(refname, &sb_log_file);
2891 if (result)
2892 goto done;
2893 log_file = sb_log_file.buf;
2895 logfd = open(log_file, oflags);
2896 if (logfd < 0)
2897 goto done;
2898 msglen = msg ? strlen(msg) : 0;
2899 committer = git_committer_info(0);
2900 maxlen = strlen(committer) + msglen + 100;
2901 logrec = xmalloc(maxlen);
2902 len = sprintf(logrec, "%s %s %s\n",
2903 sha1_to_hex(old_sha1),
2904 sha1_to_hex(new_sha1),
2905 committer);
2906 if (msglen)
2907 len += copy_msg(logrec + len - 1, msg) - 1;
2908 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2909 free(logrec);
2910 if (written != len) {
2911 int save_errno = errno;
2912 close(logfd);
2913 error("Unable to append to %s", log_file);
2914 errno = save_errno;
2915 result = -1;
2917 if (close(logfd)) {
2918 int save_errno = errno;
2919 error("Unable to append to %s", log_file);
2920 errno = save_errno;
2921 result = -1;
2923 done:
2924 strbuf_release(&sb_log_file);
2925 return result;
2928 int is_branch(const char *refname)
2930 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
2934 * Writes sha1 into the ref specified by the lock. Makes sure that errno
2935 * is sane on error.
2937 static int write_ref_sha1(struct ref_lock *lock,
2938 const unsigned char *sha1, const char *logmsg)
2940 static char term = '\n';
2941 struct object *o;
2943 if (!lock) {
2944 errno = EINVAL;
2945 return -1;
2947 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2948 unlock_ref(lock);
2949 return 0;
2951 o = parse_object(sha1);
2952 if (!o) {
2953 error("Trying to write ref %s with nonexistent object %s",
2954 lock->ref_name, sha1_to_hex(sha1));
2955 unlock_ref(lock);
2956 errno = EINVAL;
2957 return -1;
2959 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2960 error("Trying to write non-commit object %s to branch %s",
2961 sha1_to_hex(sha1), lock->ref_name);
2962 unlock_ref(lock);
2963 errno = EINVAL;
2964 return -1;
2966 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2967 write_in_full(lock->lock_fd, &term, 1) != 1 ||
2968 close_ref(lock) < 0) {
2969 int save_errno = errno;
2970 error("Couldn't write %s", lock->lk->filename);
2971 unlock_ref(lock);
2972 errno = save_errno;
2973 return -1;
2975 clear_loose_ref_cache(&ref_cache);
2976 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2977 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2978 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2979 unlock_ref(lock);
2980 return -1;
2982 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2984 * Special hack: If a branch is updated directly and HEAD
2985 * points to it (may happen on the remote side of a push
2986 * for example) then logically the HEAD reflog should be
2987 * updated too.
2988 * A generic solution implies reverse symref information,
2989 * but finding all symrefs pointing to the given branch
2990 * would be rather costly for this rare event (the direct
2991 * update of a branch) to be worth it. So let's cheat and
2992 * check with HEAD only which should cover 99% of all usage
2993 * scenarios (even 100% of the default ones).
2995 unsigned char head_sha1[20];
2996 int head_flag;
2997 const char *head_ref;
2998 head_ref = resolve_ref_unsafe("HEAD", head_sha1,
2999 RESOLVE_REF_READING, &head_flag);
3000 if (head_ref && (head_flag & REF_ISSYMREF) &&
3001 !strcmp(head_ref, lock->ref_name))
3002 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3004 if (commit_ref(lock)) {
3005 error("Couldn't set %s", lock->ref_name);
3006 unlock_ref(lock);
3007 return -1;
3009 unlock_ref(lock);
3010 return 0;
3013 int create_symref(const char *ref_target, const char *refs_heads_master,
3014 const char *logmsg)
3016 const char *lockpath;
3017 char ref[1000];
3018 int fd, len, written;
3019 char *git_HEAD = git_pathdup("%s", ref_target);
3020 unsigned char old_sha1[20], new_sha1[20];
3022 if (logmsg && read_ref(ref_target, old_sha1))
3023 hashclr(old_sha1);
3025 if (safe_create_leading_directories(git_HEAD) < 0)
3026 return error("unable to create directory for %s", git_HEAD);
3028 #ifndef NO_SYMLINK_HEAD
3029 if (prefer_symlink_refs) {
3030 unlink(git_HEAD);
3031 if (!symlink(refs_heads_master, git_HEAD))
3032 goto done;
3033 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3035 #endif
3037 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3038 if (sizeof(ref) <= len) {
3039 error("refname too long: %s", refs_heads_master);
3040 goto error_free_return;
3042 lockpath = mkpath("%s.lock", git_HEAD);
3043 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3044 if (fd < 0) {
3045 error("Unable to open %s for writing", lockpath);
3046 goto error_free_return;
3048 written = write_in_full(fd, ref, len);
3049 if (close(fd) != 0 || written != len) {
3050 error("Unable to write to %s", lockpath);
3051 goto error_unlink_return;
3053 if (rename(lockpath, git_HEAD) < 0) {
3054 error("Unable to create %s", git_HEAD);
3055 goto error_unlink_return;
3057 if (adjust_shared_perm(git_HEAD)) {
3058 error("Unable to fix permissions on %s", lockpath);
3059 error_unlink_return:
3060 unlink_or_warn(lockpath);
3061 error_free_return:
3062 free(git_HEAD);
3063 return -1;
3066 #ifndef NO_SYMLINK_HEAD
3067 done:
3068 #endif
3069 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3070 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3072 free(git_HEAD);
3073 return 0;
3076 struct read_ref_at_cb {
3077 const char *refname;
3078 unsigned long at_time;
3079 int cnt;
3080 int reccnt;
3081 unsigned char *sha1;
3082 int found_it;
3084 unsigned char osha1[20];
3085 unsigned char nsha1[20];
3086 int tz;
3087 unsigned long date;
3088 char **msg;
3089 unsigned long *cutoff_time;
3090 int *cutoff_tz;
3091 int *cutoff_cnt;
3094 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3095 const char *email, unsigned long timestamp, int tz,
3096 const char *message, void *cb_data)
3098 struct read_ref_at_cb *cb = cb_data;
3100 cb->reccnt++;
3101 cb->tz = tz;
3102 cb->date = timestamp;
3104 if (timestamp <= cb->at_time || cb->cnt == 0) {
3105 if (cb->msg)
3106 *cb->msg = xstrdup(message);
3107 if (cb->cutoff_time)
3108 *cb->cutoff_time = timestamp;
3109 if (cb->cutoff_tz)
3110 *cb->cutoff_tz = tz;
3111 if (cb->cutoff_cnt)
3112 *cb->cutoff_cnt = cb->reccnt - 1;
3114 * we have not yet updated cb->[n|o]sha1 so they still
3115 * hold the values for the previous record.
3117 if (!is_null_sha1(cb->osha1)) {
3118 hashcpy(cb->sha1, nsha1);
3119 if (hashcmp(cb->osha1, nsha1))
3120 warning("Log for ref %s has gap after %s.",
3121 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3123 else if (cb->date == cb->at_time)
3124 hashcpy(cb->sha1, nsha1);
3125 else if (hashcmp(nsha1, cb->sha1))
3126 warning("Log for ref %s unexpectedly ended on %s.",
3127 cb->refname, show_date(cb->date, cb->tz,
3128 DATE_RFC2822));
3129 hashcpy(cb->osha1, osha1);
3130 hashcpy(cb->nsha1, nsha1);
3131 cb->found_it = 1;
3132 return 1;
3134 hashcpy(cb->osha1, osha1);
3135 hashcpy(cb->nsha1, nsha1);
3136 if (cb->cnt > 0)
3137 cb->cnt--;
3138 return 0;
3141 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3142 const char *email, unsigned long timestamp,
3143 int tz, const char *message, void *cb_data)
3145 struct read_ref_at_cb *cb = cb_data;
3147 if (cb->msg)
3148 *cb->msg = xstrdup(message);
3149 if (cb->cutoff_time)
3150 *cb->cutoff_time = timestamp;
3151 if (cb->cutoff_tz)
3152 *cb->cutoff_tz = tz;
3153 if (cb->cutoff_cnt)
3154 *cb->cutoff_cnt = cb->reccnt;
3155 hashcpy(cb->sha1, osha1);
3156 if (is_null_sha1(cb->sha1))
3157 hashcpy(cb->sha1, nsha1);
3158 /* We just want the first entry */
3159 return 1;
3162 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
3163 unsigned char *sha1, char **msg,
3164 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3166 struct read_ref_at_cb cb;
3168 memset(&cb, 0, sizeof(cb));
3169 cb.refname = refname;
3170 cb.at_time = at_time;
3171 cb.cnt = cnt;
3172 cb.msg = msg;
3173 cb.cutoff_time = cutoff_time;
3174 cb.cutoff_tz = cutoff_tz;
3175 cb.cutoff_cnt = cutoff_cnt;
3176 cb.sha1 = sha1;
3178 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3180 if (!cb.reccnt)
3181 die("Log for %s is empty.", refname);
3182 if (cb.found_it)
3183 return 0;
3185 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3187 return 1;
3190 int reflog_exists(const char *refname)
3192 struct stat st;
3194 return !lstat(git_path("logs/%s", refname), &st) &&
3195 S_ISREG(st.st_mode);
3198 int delete_reflog(const char *refname)
3200 return remove_path(git_path("logs/%s", refname));
3203 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3205 unsigned char osha1[20], nsha1[20];
3206 char *email_end, *message;
3207 unsigned long timestamp;
3208 int tz;
3210 /* old SP new SP name <email> SP time TAB msg LF */
3211 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3212 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3213 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3214 !(email_end = strchr(sb->buf + 82, '>')) ||
3215 email_end[1] != ' ' ||
3216 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3217 !message || message[0] != ' ' ||
3218 (message[1] != '+' && message[1] != '-') ||
3219 !isdigit(message[2]) || !isdigit(message[3]) ||
3220 !isdigit(message[4]) || !isdigit(message[5]))
3221 return 0; /* corrupt? */
3222 email_end[1] = '\0';
3223 tz = strtol(message + 1, NULL, 10);
3224 if (message[6] != '\t')
3225 message += 6;
3226 else
3227 message += 7;
3228 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3231 static char *find_beginning_of_line(char *bob, char *scan)
3233 while (bob < scan && *(--scan) != '\n')
3234 ; /* keep scanning backwards */
3236 * Return either beginning of the buffer, or LF at the end of
3237 * the previous line.
3239 return scan;
3242 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3244 struct strbuf sb = STRBUF_INIT;
3245 FILE *logfp;
3246 long pos;
3247 int ret = 0, at_tail = 1;
3249 logfp = fopen(git_path("logs/%s", refname), "r");
3250 if (!logfp)
3251 return -1;
3253 /* Jump to the end */
3254 if (fseek(logfp, 0, SEEK_END) < 0)
3255 return error("cannot seek back reflog for %s: %s",
3256 refname, strerror(errno));
3257 pos = ftell(logfp);
3258 while (!ret && 0 < pos) {
3259 int cnt;
3260 size_t nread;
3261 char buf[BUFSIZ];
3262 char *endp, *scanp;
3264 /* Fill next block from the end */
3265 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3266 if (fseek(logfp, pos - cnt, SEEK_SET))
3267 return error("cannot seek back reflog for %s: %s",
3268 refname, strerror(errno));
3269 nread = fread(buf, cnt, 1, logfp);
3270 if (nread != 1)
3271 return error("cannot read %d bytes from reflog for %s: %s",
3272 cnt, refname, strerror(errno));
3273 pos -= cnt;
3275 scanp = endp = buf + cnt;
3276 if (at_tail && scanp[-1] == '\n')
3277 /* Looking at the final LF at the end of the file */
3278 scanp--;
3279 at_tail = 0;
3281 while (buf < scanp) {
3283 * terminating LF of the previous line, or the beginning
3284 * of the buffer.
3286 char *bp;
3288 bp = find_beginning_of_line(buf, scanp);
3290 if (*bp != '\n') {
3291 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3292 if (pos)
3293 break; /* need to fill another block */
3294 scanp = buf - 1; /* leave loop */
3295 } else {
3297 * (bp + 1) thru endp is the beginning of the
3298 * current line we have in sb
3300 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3301 scanp = bp;
3302 endp = bp + 1;
3304 ret = show_one_reflog_ent(&sb, fn, cb_data);
3305 strbuf_reset(&sb);
3306 if (ret)
3307 break;
3311 if (!ret && sb.len)
3312 ret = show_one_reflog_ent(&sb, fn, cb_data);
3314 fclose(logfp);
3315 strbuf_release(&sb);
3316 return ret;
3319 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3321 FILE *logfp;
3322 struct strbuf sb = STRBUF_INIT;
3323 int ret = 0;
3325 logfp = fopen(git_path("logs/%s", refname), "r");
3326 if (!logfp)
3327 return -1;
3329 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3330 ret = show_one_reflog_ent(&sb, fn, cb_data);
3331 fclose(logfp);
3332 strbuf_release(&sb);
3333 return ret;
3336 * Call fn for each reflog in the namespace indicated by name. name
3337 * must be empty or end with '/'. Name will be used as a scratch
3338 * space, but its contents will be restored before return.
3340 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3342 DIR *d = opendir(git_path("logs/%s", name->buf));
3343 int retval = 0;
3344 struct dirent *de;
3345 int oldlen = name->len;
3347 if (!d)
3348 return name->len ? errno : 0;
3350 while ((de = readdir(d)) != NULL) {
3351 struct stat st;
3353 if (de->d_name[0] == '.')
3354 continue;
3355 if (ends_with(de->d_name, ".lock"))
3356 continue;
3357 strbuf_addstr(name, de->d_name);
3358 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3359 ; /* silently ignore */
3360 } else {
3361 if (S_ISDIR(st.st_mode)) {
3362 strbuf_addch(name, '/');
3363 retval = do_for_each_reflog(name, fn, cb_data);
3364 } else {
3365 unsigned char sha1[20];
3366 if (read_ref_full(name->buf, sha1, 0, NULL))
3367 retval = error("bad ref for %s", name->buf);
3368 else
3369 retval = fn(name->buf, sha1, 0, cb_data);
3371 if (retval)
3372 break;
3374 strbuf_setlen(name, oldlen);
3376 closedir(d);
3377 return retval;
3380 int for_each_reflog(each_ref_fn fn, void *cb_data)
3382 int retval;
3383 struct strbuf name;
3384 strbuf_init(&name, PATH_MAX);
3385 retval = do_for_each_reflog(&name, fn, cb_data);
3386 strbuf_release(&name);
3387 return retval;
3391 * Information needed for a single ref update. Set new_sha1 to the
3392 * new value or to zero to delete the ref. To check the old value
3393 * while locking the ref, set have_old to 1 and set old_sha1 to the
3394 * value or to zero to ensure the ref does not exist before update.
3396 struct ref_update {
3397 unsigned char new_sha1[20];
3398 unsigned char old_sha1[20];
3399 int flags; /* REF_NODEREF? */
3400 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3401 struct ref_lock *lock;
3402 int type;
3403 char *msg;
3404 const char refname[FLEX_ARRAY];
3408 * Transaction states.
3409 * OPEN: The transaction is in a valid state and can accept new updates.
3410 * An OPEN transaction can be committed.
3411 * CLOSED: If an open transaction is successfully committed the state will
3412 * change to CLOSED. No further changes can be made to a CLOSED
3413 * transaction.
3414 * CLOSED means that all updates have been successfully committed and
3415 * the only thing that remains is to free the completed transaction.
3416 * ERROR: The transaction has failed and is no longer committable.
3417 * No further changes can be made to a CLOSED transaction and it must
3418 * be rolled back using transaction_free.
3420 enum ref_transaction_state {
3421 REF_TRANSACTION_OPEN = 0,
3422 REF_TRANSACTION_CLOSED = 1,
3423 REF_TRANSACTION_ERROR = 2,
3427 * Data structure for holding a reference transaction, which can
3428 * consist of checks and updates to multiple references, carried out
3429 * as atomically as possible. This structure is opaque to callers.
3431 struct ref_transaction {
3432 struct ref_update **updates;
3433 size_t alloc;
3434 size_t nr;
3435 enum ref_transaction_state state;
3438 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3440 return xcalloc(1, sizeof(struct ref_transaction));
3443 void ref_transaction_free(struct ref_transaction *transaction)
3445 int i;
3447 if (!transaction)
3448 return;
3450 for (i = 0; i < transaction->nr; i++) {
3451 free(transaction->updates[i]->msg);
3452 free(transaction->updates[i]);
3454 free(transaction->updates);
3455 free(transaction);
3458 static struct ref_update *add_update(struct ref_transaction *transaction,
3459 const char *refname)
3461 size_t len = strlen(refname);
3462 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3464 strcpy((char *)update->refname, refname);
3465 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3466 transaction->updates[transaction->nr++] = update;
3467 return update;
3470 int ref_transaction_update(struct ref_transaction *transaction,
3471 const char *refname,
3472 const unsigned char *new_sha1,
3473 const unsigned char *old_sha1,
3474 int flags, int have_old, const char *msg,
3475 struct strbuf *err)
3477 struct ref_update *update;
3479 if (transaction->state != REF_TRANSACTION_OPEN)
3480 die("BUG: update called for transaction that is not open");
3482 if (have_old && !old_sha1)
3483 die("BUG: have_old is true but old_sha1 is NULL");
3485 if (!is_null_sha1(new_sha1) &&
3486 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3487 strbuf_addf(err, "Bad refname: %s", refname);
3488 return -1;
3491 update = add_update(transaction, refname);
3492 hashcpy(update->new_sha1, new_sha1);
3493 update->flags = flags;
3494 update->have_old = have_old;
3495 if (have_old)
3496 hashcpy(update->old_sha1, old_sha1);
3497 if (msg)
3498 update->msg = xstrdup(msg);
3499 return 0;
3502 int ref_transaction_create(struct ref_transaction *transaction,
3503 const char *refname,
3504 const unsigned char *new_sha1,
3505 int flags, const char *msg,
3506 struct strbuf *err)
3508 struct ref_update *update;
3510 if (transaction->state != REF_TRANSACTION_OPEN)
3511 die("BUG: create called for transaction that is not open");
3513 if (!new_sha1 || is_null_sha1(new_sha1))
3514 die("BUG: create ref with null new_sha1");
3516 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3517 strbuf_addf(err, "Bad refname: %s", refname);
3518 return -1;
3521 update = add_update(transaction, refname);
3523 hashcpy(update->new_sha1, new_sha1);
3524 hashclr(update->old_sha1);
3525 update->flags = flags;
3526 update->have_old = 1;
3527 if (msg)
3528 update->msg = xstrdup(msg);
3529 return 0;
3532 int ref_transaction_delete(struct ref_transaction *transaction,
3533 const char *refname,
3534 const unsigned char *old_sha1,
3535 int flags, int have_old, const char *msg,
3536 struct strbuf *err)
3538 struct ref_update *update;
3540 if (transaction->state != REF_TRANSACTION_OPEN)
3541 die("BUG: delete called for transaction that is not open");
3543 if (have_old && !old_sha1)
3544 die("BUG: have_old is true but old_sha1 is NULL");
3546 update = add_update(transaction, refname);
3547 update->flags = flags;
3548 update->have_old = have_old;
3549 if (have_old) {
3550 assert(!is_null_sha1(old_sha1));
3551 hashcpy(update->old_sha1, old_sha1);
3553 if (msg)
3554 update->msg = xstrdup(msg);
3555 return 0;
3558 int update_ref(const char *action, const char *refname,
3559 const unsigned char *sha1, const unsigned char *oldval,
3560 int flags, enum action_on_err onerr)
3562 struct ref_transaction *t;
3563 struct strbuf err = STRBUF_INIT;
3565 t = ref_transaction_begin(&err);
3566 if (!t ||
3567 ref_transaction_update(t, refname, sha1, oldval, flags,
3568 !!oldval, action, &err) ||
3569 ref_transaction_commit(t, &err)) {
3570 const char *str = "update_ref failed for ref '%s': %s";
3572 ref_transaction_free(t);
3573 switch (onerr) {
3574 case UPDATE_REFS_MSG_ON_ERR:
3575 error(str, refname, err.buf);
3576 break;
3577 case UPDATE_REFS_DIE_ON_ERR:
3578 die(str, refname, err.buf);
3579 break;
3580 case UPDATE_REFS_QUIET_ON_ERR:
3581 break;
3583 strbuf_release(&err);
3584 return 1;
3586 return 0;
3589 static int ref_update_compare(const void *r1, const void *r2)
3591 const struct ref_update * const *u1 = r1;
3592 const struct ref_update * const *u2 = r2;
3593 return strcmp((*u1)->refname, (*u2)->refname);
3596 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3597 struct strbuf *err)
3599 int i;
3600 for (i = 1; i < n; i++)
3601 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3602 const char *str =
3603 "Multiple updates for ref '%s' not allowed.";
3604 if (err)
3605 strbuf_addf(err, str, updates[i]->refname);
3607 return 1;
3609 return 0;
3612 int ref_transaction_commit(struct ref_transaction *transaction,
3613 struct strbuf *err)
3615 int ret = 0, delnum = 0, i, df_conflict = 0;
3616 const char **delnames;
3617 int n = transaction->nr;
3618 struct ref_update **updates = transaction->updates;
3620 if (transaction->state != REF_TRANSACTION_OPEN)
3621 die("BUG: commit called for transaction that is not open");
3623 if (!n) {
3624 transaction->state = REF_TRANSACTION_CLOSED;
3625 return 0;
3628 /* Allocate work space */
3629 delnames = xmalloc(sizeof(*delnames) * n);
3631 /* Copy, sort, and reject duplicate refs */
3632 qsort(updates, n, sizeof(*updates), ref_update_compare);
3633 if (ref_update_reject_duplicates(updates, n, err)) {
3634 ret = -1;
3635 goto cleanup;
3638 /* Acquire all locks while verifying old values */
3639 for (i = 0; i < n; i++) {
3640 struct ref_update *update = updates[i];
3642 update->lock = lock_ref_sha1_basic(update->refname,
3643 (update->have_old ?
3644 update->old_sha1 :
3645 NULL),
3646 update->flags,
3647 &update->type,
3648 delnames, delnum);
3649 if (!update->lock) {
3650 if (errno == ENOTDIR)
3651 df_conflict = 1;
3652 if (err)
3653 strbuf_addf(err, "Cannot lock the ref '%s'.",
3654 update->refname);
3655 ret = -1;
3656 goto cleanup;
3660 /* Perform updates first so live commits remain referenced */
3661 for (i = 0; i < n; i++) {
3662 struct ref_update *update = updates[i];
3664 if (!is_null_sha1(update->new_sha1)) {
3665 ret = write_ref_sha1(update->lock, update->new_sha1,
3666 update->msg);
3667 update->lock = NULL; /* freed by write_ref_sha1 */
3668 if (ret) {
3669 const char *str = "Cannot update the ref '%s'.";
3671 if (err)
3672 strbuf_addf(err, str, update->refname);
3673 ret = -1;
3674 goto cleanup;
3679 /* Perform deletes now that updates are safely completed */
3680 for (i = 0; i < n; i++) {
3681 struct ref_update *update = updates[i];
3683 if (update->lock) {
3684 if (delete_ref_loose(update->lock, update->type, err))
3685 ret = -1;
3687 if (!(update->flags & REF_ISPRUNING))
3688 delnames[delnum++] = update->lock->ref_name;
3692 if (repack_without_refs(delnames, delnum, err))
3693 ret = -1;
3694 for (i = 0; i < delnum; i++)
3695 unlink_or_warn(git_path("logs/%s", delnames[i]));
3696 clear_loose_ref_cache(&ref_cache);
3698 cleanup:
3699 transaction->state = ret ? REF_TRANSACTION_ERROR
3700 : REF_TRANSACTION_CLOSED;
3702 for (i = 0; i < n; i++)
3703 if (updates[i]->lock)
3704 unlock_ref(updates[i]->lock);
3705 free(delnames);
3706 if (df_conflict)
3707 ret = -2;
3708 return ret;
3711 char *shorten_unambiguous_ref(const char *refname, int strict)
3713 int i;
3714 static char **scanf_fmts;
3715 static int nr_rules;
3716 char *short_name;
3718 if (!nr_rules) {
3720 * Pre-generate scanf formats from ref_rev_parse_rules[].
3721 * Generate a format suitable for scanf from a
3722 * ref_rev_parse_rules rule by interpolating "%s" at the
3723 * location of the "%.*s".
3725 size_t total_len = 0;
3726 size_t offset = 0;
3728 /* the rule list is NULL terminated, count them first */
3729 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3730 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3731 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3733 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3735 offset = 0;
3736 for (i = 0; i < nr_rules; i++) {
3737 assert(offset < total_len);
3738 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3739 offset += snprintf(scanf_fmts[i], total_len - offset,
3740 ref_rev_parse_rules[i], 2, "%s") + 1;
3744 /* bail out if there are no rules */
3745 if (!nr_rules)
3746 return xstrdup(refname);
3748 /* buffer for scanf result, at most refname must fit */
3749 short_name = xstrdup(refname);
3751 /* skip first rule, it will always match */
3752 for (i = nr_rules - 1; i > 0 ; --i) {
3753 int j;
3754 int rules_to_fail = i;
3755 int short_name_len;
3757 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3758 continue;
3760 short_name_len = strlen(short_name);
3763 * in strict mode, all (except the matched one) rules
3764 * must fail to resolve to a valid non-ambiguous ref
3766 if (strict)
3767 rules_to_fail = nr_rules;
3770 * check if the short name resolves to a valid ref,
3771 * but use only rules prior to the matched one
3773 for (j = 0; j < rules_to_fail; j++) {
3774 const char *rule = ref_rev_parse_rules[j];
3775 char refname[PATH_MAX];
3777 /* skip matched rule */
3778 if (i == j)
3779 continue;
3782 * the short name is ambiguous, if it resolves
3783 * (with this previous rule) to a valid ref
3784 * read_ref() returns 0 on success
3786 mksnpath(refname, sizeof(refname),
3787 rule, short_name_len, short_name);
3788 if (ref_exists(refname))
3789 break;
3793 * short name is non-ambiguous if all previous rules
3794 * haven't resolved to a valid ref
3796 if (j == rules_to_fail)
3797 return short_name;
3800 free(short_name);
3801 return xstrdup(refname);
3804 static struct string_list *hide_refs;
3806 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3808 if (!strcmp("transfer.hiderefs", var) ||
3809 /* NEEDSWORK: use parse_config_key() once both are merged */
3810 (starts_with(var, section) && var[strlen(section)] == '.' &&
3811 !strcmp(var + strlen(section), ".hiderefs"))) {
3812 char *ref;
3813 int len;
3815 if (!value)
3816 return config_error_nonbool(var);
3817 ref = xstrdup(value);
3818 len = strlen(ref);
3819 while (len && ref[len - 1] == '/')
3820 ref[--len] = '\0';
3821 if (!hide_refs) {
3822 hide_refs = xcalloc(1, sizeof(*hide_refs));
3823 hide_refs->strdup_strings = 1;
3825 string_list_append(hide_refs, ref);
3827 return 0;
3830 int ref_is_hidden(const char *refname)
3832 struct string_list_item *item;
3834 if (!hide_refs)
3835 return 0;
3836 for_each_string_list_item(item, hide_refs) {
3837 int len;
3838 if (!starts_with(refname, item->string))
3839 continue;
3840 len = strlen(item->string);
3841 if (!refname[len] || refname[len] == '/')
3842 return 1;
3844 return 0;