apply: avoid using fixed-size buffer in write_out_one_reject()
[git.git] / bisect.c
blob60aae2fe50d4edaa520c9cf9f7e4a23ed6c60085
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "diff.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "revision.h"
9 #include "refs.h"
10 #include "list-objects.h"
11 #include "quote.h"
12 #include "run-command.h"
13 #include "log-tree.h"
14 #include "bisect.h"
15 #include "oid-array.h"
16 #include "strvec.h"
17 #include "commit-slab.h"
18 #include "commit-reach.h"
19 #include "object-name.h"
20 #include "object-store-ll.h"
21 #include "path.h"
22 #include "dir.h"
24 static struct oid_array good_revs;
25 static struct oid_array skipped_revs;
27 static struct object_id *current_bad_oid;
29 static const char *term_bad;
30 static const char *term_good;
32 /* Remember to update object flag allocation in object.h */
33 #define COUNTED (1u<<16)
36 * This is a truly stupid algorithm, but it's only
37 * used for bisection, and we just don't care enough.
39 * We care just barely enough to avoid recursing for
40 * non-merge entries.
42 static int count_distance(struct commit_list *entry)
44 int nr = 0;
46 while (entry) {
47 struct commit *commit = entry->item;
48 struct commit_list *p;
50 if (commit->object.flags & (UNINTERESTING | COUNTED))
51 break;
52 if (!(commit->object.flags & TREESAME))
53 nr++;
54 commit->object.flags |= COUNTED;
55 p = commit->parents;
56 entry = p;
57 if (p) {
58 p = p->next;
59 while (p) {
60 nr += count_distance(p);
61 p = p->next;
66 return nr;
69 static void clear_distance(struct commit_list *list)
71 while (list) {
72 struct commit *commit = list->item;
73 commit->object.flags &= ~COUNTED;
74 list = list->next;
78 define_commit_slab(commit_weight, int *);
79 static struct commit_weight commit_weight;
81 #define DEBUG_BISECT 0
83 static inline int weight(struct commit_list *elem)
85 return **commit_weight_at(&commit_weight, elem->item);
88 static inline void weight_set(struct commit_list *elem, int weight)
90 **commit_weight_at(&commit_weight, elem->item) = weight;
93 static int count_interesting_parents(struct commit *commit, unsigned bisect_flags)
95 struct commit_list *p;
96 int count;
98 for (count = 0, p = commit->parents; p; p = p->next) {
99 if (!(p->item->object.flags & UNINTERESTING))
100 count++;
101 if (bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY)
102 break;
104 return count;
107 static inline int approx_halfway(struct commit_list *p, int nr)
109 int diff;
112 * Don't short-cut something we are not going to return!
114 if (p->item->object.flags & TREESAME)
115 return 0;
116 if (DEBUG_BISECT)
117 return 0;
119 * For small number of commits 2 and 3 are halfway of 5, and
120 * 3 is halfway of 6 but 2 and 4 are not.
122 diff = 2 * weight(p) - nr;
123 switch (diff) {
124 case -1: case 0: case 1:
125 return 1;
126 default:
128 * For large number of commits we are not so strict, it's
129 * good enough if it's within ~0.1% of the halfway point,
130 * e.g. 5000 is exactly halfway of 10000, but we consider
131 * the values [4996, 5004] as halfway as well.
133 if (abs(diff) < nr / 1024)
134 return 1;
135 return 0;
139 static void show_list(const char *debug, int counted, int nr,
140 struct commit_list *list)
142 struct commit_list *p;
144 if (!DEBUG_BISECT)
145 return;
147 fprintf(stderr, "%s (%d/%d)\n", debug, counted, nr);
149 for (p = list; p; p = p->next) {
150 struct commit_list *pp;
151 struct commit *commit = p->item;
152 unsigned commit_flags = commit->object.flags;
153 enum object_type type;
154 unsigned long size;
155 char *buf = repo_read_object_file(the_repository,
156 &commit->object.oid, &type,
157 &size);
158 const char *subject_start;
159 int subject_len;
161 if (!buf)
162 die(_("unable to read %s"), oid_to_hex(&commit->object.oid));
164 fprintf(stderr, "%c%c%c ",
165 (commit_flags & TREESAME) ? ' ' : 'T',
166 (commit_flags & UNINTERESTING) ? 'U' : ' ',
167 (commit_flags & COUNTED) ? 'C' : ' ');
168 if (*commit_weight_at(&commit_weight, p->item))
169 fprintf(stderr, "%3d", weight(p));
170 else
171 fprintf(stderr, "---");
172 fprintf(stderr, " %.*s", 8, oid_to_hex(&commit->object.oid));
173 for (pp = commit->parents; pp; pp = pp->next)
174 fprintf(stderr, " %.*s", 8,
175 oid_to_hex(&pp->item->object.oid));
177 subject_len = find_commit_subject(buf, &subject_start);
178 if (subject_len)
179 fprintf(stderr, " %.*s", subject_len, subject_start);
180 fprintf(stderr, "\n");
184 static struct commit_list *best_bisection(struct commit_list *list, int nr)
186 struct commit_list *p, *best;
187 int best_distance = -1;
189 best = list;
190 for (p = list; p; p = p->next) {
191 int distance;
192 unsigned commit_flags = p->item->object.flags;
194 if (commit_flags & TREESAME)
195 continue;
196 distance = weight(p);
197 if (nr - distance < distance)
198 distance = nr - distance;
199 if (distance > best_distance) {
200 best = p;
201 best_distance = distance;
205 return best;
208 struct commit_dist {
209 struct commit *commit;
210 int distance;
213 static int compare_commit_dist(const void *a_, const void *b_)
215 struct commit_dist *a, *b;
217 a = (struct commit_dist *)a_;
218 b = (struct commit_dist *)b_;
219 if (a->distance != b->distance)
220 return b->distance - a->distance; /* desc sort */
221 return oidcmp(&a->commit->object.oid, &b->commit->object.oid);
224 static struct commit_list *best_bisection_sorted(struct commit_list *list, int nr)
226 struct commit_list *p;
227 struct commit_dist *array = xcalloc(nr, sizeof(*array));
228 struct strbuf buf = STRBUF_INIT;
229 int cnt, i;
231 for (p = list, cnt = 0; p; p = p->next) {
232 int distance;
233 unsigned commit_flags = p->item->object.flags;
235 if (commit_flags & TREESAME)
236 continue;
237 distance = weight(p);
238 if (nr - distance < distance)
239 distance = nr - distance;
240 array[cnt].commit = p->item;
241 array[cnt].distance = distance;
242 cnt++;
244 QSORT(array, cnt, compare_commit_dist);
245 for (p = list, i = 0; i < cnt; i++) {
246 struct object *obj = &(array[i].commit->object);
248 strbuf_reset(&buf);
249 strbuf_addf(&buf, "dist=%d", array[i].distance);
250 add_name_decoration(DECORATION_NONE, buf.buf, obj);
252 p->item = array[i].commit;
253 if (i < cnt - 1)
254 p = p->next;
256 if (p) {
257 free_commit_list(p->next);
258 p->next = NULL;
260 strbuf_release(&buf);
261 free(array);
262 return list;
266 * zero or positive weight is the number of interesting commits it can
267 * reach, including itself. Especially, weight = 0 means it does not
268 * reach any tree-changing commits (e.g. just above uninteresting one
269 * but traversal is with pathspec).
271 * weight = -1 means it has one parent and its distance is yet to
272 * be computed.
274 * weight = -2 means it has more than one parent and its distance is
275 * unknown. After running count_distance() first, they will get zero
276 * or positive distance.
278 static struct commit_list *do_find_bisection(struct commit_list *list,
279 int nr, int *weights,
280 unsigned bisect_flags)
282 int n, counted;
283 struct commit_list *p;
285 counted = 0;
287 for (n = 0, p = list; p; p = p->next) {
288 struct commit *commit = p->item;
289 unsigned commit_flags = commit->object.flags;
291 *commit_weight_at(&commit_weight, p->item) = &weights[n++];
292 switch (count_interesting_parents(commit, bisect_flags)) {
293 case 0:
294 if (!(commit_flags & TREESAME)) {
295 weight_set(p, 1);
296 counted++;
297 show_list("bisection 2 count one",
298 counted, nr, list);
301 * otherwise, it is known not to reach any
302 * tree-changing commit and gets weight 0.
304 break;
305 case 1:
306 weight_set(p, -1);
307 break;
308 default:
309 weight_set(p, -2);
310 break;
314 show_list("bisection 2 initialize", counted, nr, list);
317 * If you have only one parent in the resulting set
318 * then you can reach one commit more than that parent
319 * can reach. So we do not have to run the expensive
320 * count_distance() for single strand of pearls.
322 * However, if you have more than one parents, you cannot
323 * just add their distance and one for yourself, since
324 * they usually reach the same ancestor and you would
325 * end up counting them twice that way.
327 * So we will first count distance of merges the usual
328 * way, and then fill the blanks using cheaper algorithm.
330 for (p = list; p; p = p->next) {
331 if (p->item->object.flags & UNINTERESTING)
332 continue;
333 if (weight(p) != -2)
334 continue;
335 if (bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY)
336 BUG("shouldn't be calling count-distance in fp mode");
337 weight_set(p, count_distance(p));
338 clear_distance(list);
340 /* Does it happen to be at half-way? */
341 if (!(bisect_flags & FIND_BISECTION_ALL) &&
342 approx_halfway(p, nr))
343 return p;
344 counted++;
347 show_list("bisection 2 count_distance", counted, nr, list);
349 while (counted < nr) {
350 for (p = list; p; p = p->next) {
351 struct commit_list *q;
352 unsigned commit_flags = p->item->object.flags;
354 if (0 <= weight(p))
355 continue;
357 for (q = p->item->parents;
359 q = bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY ? NULL : q->next) {
360 if (q->item->object.flags & UNINTERESTING)
361 continue;
362 if (0 <= weight(q))
363 break;
365 if (!q)
366 continue;
369 * weight for p is unknown but q is known.
370 * add one for p itself if p is to be counted,
371 * otherwise inherit it from q directly.
373 if (!(commit_flags & TREESAME)) {
374 weight_set(p, weight(q)+1);
375 counted++;
376 show_list("bisection 2 count one",
377 counted, nr, list);
379 else
380 weight_set(p, weight(q));
382 /* Does it happen to be at half-way? */
383 if (!(bisect_flags & FIND_BISECTION_ALL) &&
384 approx_halfway(p, nr))
385 return p;
389 show_list("bisection 2 counted all", counted, nr, list);
391 if (!(bisect_flags & FIND_BISECTION_ALL))
392 return best_bisection(list, nr);
393 else
394 return best_bisection_sorted(list, nr);
397 void find_bisection(struct commit_list **commit_list, int *reaches,
398 int *all, unsigned bisect_flags)
400 int nr, on_list;
401 struct commit_list *list, *p, *best, *next, *last;
402 int *weights;
404 show_list("bisection 2 entry", 0, 0, *commit_list);
405 init_commit_weight(&commit_weight);
408 * Count the number of total and tree-changing items on the
409 * list, while reversing the list.
411 for (nr = on_list = 0, last = NULL, p = *commit_list;
413 p = next) {
414 unsigned commit_flags = p->item->object.flags;
416 next = p->next;
417 if (commit_flags & UNINTERESTING) {
418 free(p);
419 continue;
421 p->next = last;
422 last = p;
423 if (!(commit_flags & TREESAME))
424 nr++;
425 on_list++;
427 list = last;
428 show_list("bisection 2 sorted", 0, nr, list);
430 *all = nr;
431 CALLOC_ARRAY(weights, on_list);
433 /* Do the real work of finding bisection commit. */
434 best = do_find_bisection(list, nr, weights, bisect_flags);
435 if (best) {
436 if (!(bisect_flags & FIND_BISECTION_ALL)) {
437 list->item = best->item;
438 free_commit_list(list->next);
439 best = list;
440 best->next = NULL;
442 *reaches = weight(best);
444 free(weights);
445 *commit_list = best;
446 clear_commit_weight(&commit_weight);
449 static int register_ref(const char *refname, const struct object_id *oid,
450 int flags UNUSED, void *cb_data UNUSED)
452 struct strbuf good_prefix = STRBUF_INIT;
453 strbuf_addstr(&good_prefix, term_good);
454 strbuf_addstr(&good_prefix, "-");
456 if (!strcmp(refname, term_bad)) {
457 current_bad_oid = xmalloc(sizeof(*current_bad_oid));
458 oidcpy(current_bad_oid, oid);
459 } else if (starts_with(refname, good_prefix.buf)) {
460 oid_array_append(&good_revs, oid);
461 } else if (starts_with(refname, "skip-")) {
462 oid_array_append(&skipped_revs, oid);
465 strbuf_release(&good_prefix);
467 return 0;
470 static int read_bisect_refs(void)
472 return for_each_ref_in("refs/bisect/", register_ref, NULL);
475 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
476 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
477 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
478 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
479 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
480 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
481 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
483 static void read_bisect_paths(struct strvec *array)
485 struct strbuf str = STRBUF_INIT;
486 const char *filename = git_path_bisect_names();
487 FILE *fp = xfopen(filename, "r");
489 while (strbuf_getline_lf(&str, fp) != EOF) {
490 strbuf_trim(&str);
491 if (sq_dequote_to_strvec(str.buf, array))
492 die(_("Badly quoted content in file '%s': %s"),
493 filename, str.buf);
496 strbuf_release(&str);
497 fclose(fp);
500 static char *join_oid_array_hex(struct oid_array *array, char delim)
502 struct strbuf joined_hexs = STRBUF_INIT;
503 int i;
505 for (i = 0; i < array->nr; i++) {
506 strbuf_addstr(&joined_hexs, oid_to_hex(array->oid + i));
507 if (i + 1 < array->nr)
508 strbuf_addch(&joined_hexs, delim);
511 return strbuf_detach(&joined_hexs, NULL);
515 * In this function, passing a not NULL skipped_first is very special.
516 * It means that we want to know if the first commit in the list is
517 * skipped because we will want to test a commit away from it if it is
518 * indeed skipped.
519 * So if the first commit is skipped, we cannot take the shortcut to
520 * just "return list" when we find the first non skipped commit, we
521 * have to return a fully filtered list.
523 * We use (*skipped_first == -1) to mean "it has been found that the
524 * first commit is not skipped". In this case *skipped_first is set back
525 * to 0 just before the function returns.
527 struct commit_list *filter_skipped(struct commit_list *list,
528 struct commit_list **tried,
529 int show_all,
530 int *count,
531 int *skipped_first)
533 struct commit_list *filtered = NULL, **f = &filtered;
535 *tried = NULL;
537 if (skipped_first)
538 *skipped_first = 0;
539 if (count)
540 *count = 0;
542 if (!skipped_revs.nr)
543 return list;
545 while (list) {
546 struct commit_list *next = list->next;
547 list->next = NULL;
548 if (0 <= oid_array_lookup(&skipped_revs, &list->item->object.oid)) {
549 if (skipped_first && !*skipped_first)
550 *skipped_first = 1;
551 /* Move current to tried list */
552 *tried = list;
553 tried = &list->next;
554 } else {
555 if (!show_all) {
556 if (!skipped_first || !*skipped_first)
557 return list;
558 } else if (skipped_first && !*skipped_first) {
559 /* This means we know it's not skipped */
560 *skipped_first = -1;
562 /* Move current to filtered list */
563 *f = list;
564 f = &list->next;
565 if (count)
566 (*count)++;
568 list = next;
571 if (skipped_first && *skipped_first == -1)
572 *skipped_first = 0;
574 return filtered;
577 #define PRN_MODULO 32768
580 * This is a pseudo random number generator based on "man 3 rand".
581 * It is not used properly because the seed is the argument and it
582 * is increased by one between each call, but that should not matter
583 * for this application.
585 static unsigned get_prn(unsigned count)
587 count = count * 1103515245 + 12345;
588 return (count/65536) % PRN_MODULO;
592 * Custom integer square root from
593 * https://en.wikipedia.org/wiki/Integer_square_root
595 static int sqrti(int val)
597 float d, x = val;
599 if (!val)
600 return 0;
602 do {
603 float y = (x + (float)val / x) / 2;
604 d = (y > x) ? y - x : x - y;
605 x = y;
606 } while (d >= 0.5);
608 return (int)x;
611 static struct commit_list *skip_away(struct commit_list *list, int count)
613 struct commit_list *cur, *previous;
614 int prn, index, i;
616 prn = get_prn(count);
617 index = (count * prn / PRN_MODULO) * sqrti(prn) / sqrti(PRN_MODULO);
619 cur = list;
620 previous = NULL;
622 for (i = 0; cur; cur = cur->next, i++) {
623 if (i == index) {
624 if (!oideq(&cur->item->object.oid, current_bad_oid))
625 return cur;
626 if (previous)
627 return previous;
628 return list;
630 previous = cur;
633 return list;
636 static struct commit_list *managed_skipped(struct commit_list *list,
637 struct commit_list **tried)
639 int count, skipped_first;
641 *tried = NULL;
643 if (!skipped_revs.nr)
644 return list;
646 list = filter_skipped(list, tried, 0, &count, &skipped_first);
648 if (!skipped_first)
649 return list;
651 return skip_away(list, count);
654 static void bisect_rev_setup(struct repository *r, struct rev_info *revs,
655 struct strvec *rev_argv,
656 const char *prefix,
657 const char *bad_format, const char *good_format,
658 int read_paths)
660 struct setup_revision_opt opt = {
661 .free_removed_argv_elements = 1,
663 int i;
665 repo_init_revisions(r, revs, prefix);
666 revs->abbrev = 0;
667 revs->commit_format = CMIT_FMT_UNSPECIFIED;
669 /* rev_argv.argv[0] will be ignored by setup_revisions */
670 strvec_push(rev_argv, "bisect_rev_setup");
671 strvec_pushf(rev_argv, bad_format, oid_to_hex(current_bad_oid));
672 for (i = 0; i < good_revs.nr; i++)
673 strvec_pushf(rev_argv, good_format,
674 oid_to_hex(good_revs.oid + i));
675 strvec_push(rev_argv, "--");
676 if (read_paths)
677 read_bisect_paths(rev_argv);
679 setup_revisions(rev_argv->nr, rev_argv->v, revs, &opt);
682 static void bisect_common(struct rev_info *revs)
684 if (prepare_revision_walk(revs))
685 die("revision walk setup failed");
686 if (revs->tree_objects)
687 mark_edges_uninteresting(revs, NULL, 0);
690 static enum bisect_error error_if_skipped_commits(struct commit_list *tried,
691 const struct object_id *bad)
693 if (!tried)
694 return BISECT_OK;
696 printf("There are only 'skip'ped commits left to test.\n"
697 "The first %s commit could be any of:\n", term_bad);
699 for ( ; tried; tried = tried->next)
700 printf("%s\n", oid_to_hex(&tried->item->object.oid));
702 if (bad)
703 printf("%s\n", oid_to_hex(bad));
704 printf(_("We cannot bisect more!\n"));
706 return BISECT_ONLY_SKIPPED_LEFT;
709 static int is_expected_rev(const struct object_id *oid)
711 struct object_id expected_oid;
712 if (read_ref("BISECT_EXPECTED_REV", &expected_oid))
713 return 0;
714 return oideq(oid, &expected_oid);
717 enum bisect_error bisect_checkout(const struct object_id *bisect_rev,
718 int no_checkout)
720 struct commit *commit;
721 struct pretty_print_context pp = {0};
722 struct strbuf commit_msg = STRBUF_INIT;
724 update_ref(NULL, "BISECT_EXPECTED_REV", bisect_rev, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
726 if (no_checkout) {
727 update_ref(NULL, "BISECT_HEAD", bisect_rev, NULL, 0,
728 UPDATE_REFS_DIE_ON_ERR);
729 } else {
730 struct child_process cmd = CHILD_PROCESS_INIT;
732 cmd.git_cmd = 1;
733 strvec_pushl(&cmd.args, "checkout", "-q",
734 oid_to_hex(bisect_rev), "--", NULL);
735 if (run_command(&cmd))
737 * Errors in `run_command()` itself, signaled by res < 0,
738 * and errors in the child process, signaled by res > 0
739 * can both be treated as regular BISECT_FAILED (-1).
741 return BISECT_FAILED;
744 commit = lookup_commit_reference(the_repository, bisect_rev);
745 repo_format_commit_message(the_repository, commit, "[%H] %s%n",
746 &commit_msg, &pp);
747 fputs(commit_msg.buf, stdout);
748 strbuf_release(&commit_msg);
750 return BISECT_OK;
753 static struct commit *get_commit_reference(struct repository *r,
754 const struct object_id *oid)
756 struct commit *c = lookup_commit_reference(r, oid);
757 if (!c)
758 die(_("Not a valid commit name %s"), oid_to_hex(oid));
759 return c;
762 static struct commit **get_bad_and_good_commits(struct repository *r,
763 int *rev_nr)
765 struct commit **rev;
766 int i, n = 0;
768 ALLOC_ARRAY(rev, 1 + good_revs.nr);
769 rev[n++] = get_commit_reference(r, current_bad_oid);
770 for (i = 0; i < good_revs.nr; i++)
771 rev[n++] = get_commit_reference(r, good_revs.oid + i);
772 *rev_nr = n;
774 return rev;
777 static enum bisect_error handle_bad_merge_base(void)
779 if (is_expected_rev(current_bad_oid)) {
780 char *bad_hex = oid_to_hex(current_bad_oid);
781 char *good_hex = join_oid_array_hex(&good_revs, ' ');
782 if (!strcmp(term_bad, "bad") && !strcmp(term_good, "good")) {
783 fprintf(stderr, _("The merge base %s is bad.\n"
784 "This means the bug has been fixed "
785 "between %s and [%s].\n"),
786 bad_hex, bad_hex, good_hex);
787 } else if (!strcmp(term_bad, "new") && !strcmp(term_good, "old")) {
788 fprintf(stderr, _("The merge base %s is new.\n"
789 "The property has changed "
790 "between %s and [%s].\n"),
791 bad_hex, bad_hex, good_hex);
792 } else {
793 fprintf(stderr, _("The merge base %s is %s.\n"
794 "This means the first '%s' commit is "
795 "between %s and [%s].\n"),
796 bad_hex, term_bad, term_good, bad_hex, good_hex);
798 return BISECT_MERGE_BASE_CHECK;
801 fprintf(stderr, _("Some %s revs are not ancestors of the %s rev.\n"
802 "git bisect cannot work properly in this case.\n"
803 "Maybe you mistook %s and %s revs?\n"),
804 term_good, term_bad, term_good, term_bad);
805 return BISECT_FAILED;
808 static void handle_skipped_merge_base(const struct object_id *mb)
810 char *mb_hex = oid_to_hex(mb);
811 char *bad_hex = oid_to_hex(current_bad_oid);
812 char *good_hex = join_oid_array_hex(&good_revs, ' ');
814 warning(_("the merge base between %s and [%s] "
815 "must be skipped.\n"
816 "So we cannot be sure the first %s commit is "
817 "between %s and %s.\n"
818 "We continue anyway."),
819 bad_hex, good_hex, term_bad, mb_hex, bad_hex);
820 free(good_hex);
824 * "check_merge_bases" checks that merge bases are not "bad" (or "new").
826 * - If one is "bad" (or "new"), it means the user assumed something wrong
827 * and we must return error with a non 0 error code.
828 * - If one is "good" (or "old"), that's good, we have nothing to do.
829 * - If one is "skipped", we can't know but we should warn.
830 * - If we don't know, we should check it out and ask the user to test.
831 * - If a merge base must be tested, on success return
832 * BISECT_INTERNAL_SUCCESS_MERGE_BASE (-11) a special condition
833 * for early success, this will be converted back to 0 in
834 * check_good_are_ancestors_of_bad().
836 static enum bisect_error check_merge_bases(int rev_nr, struct commit **rev, int no_checkout)
838 enum bisect_error res = BISECT_OK;
839 struct commit_list *result = NULL;
841 if (repo_get_merge_bases_many(the_repository, rev[0], rev_nr - 1,
842 rev + 1, &result) < 0)
843 exit(128);
845 for (; result; result = result->next) {
846 const struct object_id *mb = &result->item->object.oid;
847 if (oideq(mb, current_bad_oid)) {
848 res = handle_bad_merge_base();
849 break;
850 } else if (0 <= oid_array_lookup(&good_revs, mb)) {
851 continue;
852 } else if (0 <= oid_array_lookup(&skipped_revs, mb)) {
853 handle_skipped_merge_base(mb);
854 } else {
855 printf(_("Bisecting: a merge base must be tested\n"));
856 res = bisect_checkout(mb, no_checkout);
857 if (!res)
858 /* indicate early success */
859 res = BISECT_INTERNAL_SUCCESS_MERGE_BASE;
860 break;
864 free_commit_list(result);
865 return res;
868 static int check_ancestors(struct repository *r, int rev_nr,
869 struct commit **rev, const char *prefix)
871 struct strvec rev_argv = STRVEC_INIT;
872 struct rev_info revs;
873 int res;
875 bisect_rev_setup(r, &revs, &rev_argv, prefix, "^%s", "%s", 0);
877 bisect_common(&revs);
878 res = (revs.commits != NULL);
880 /* Clean up objects used, as they will be reused. */
881 clear_commit_marks_many(rev_nr, rev, ALL_REV_FLAGS);
883 release_revisions(&revs);
884 strvec_clear(&rev_argv);
885 return res;
889 * "check_good_are_ancestors_of_bad" checks that all "good" revs are
890 * ancestor of the "bad" rev.
892 * If that's not the case, we need to check the merge bases.
893 * If a merge base must be tested by the user, its source code will be
894 * checked out to be tested by the user and we will return.
897 static enum bisect_error check_good_are_ancestors_of_bad(struct repository *r,
898 const char *prefix,
899 int no_checkout)
901 char *filename;
902 struct stat st;
903 int fd, rev_nr;
904 enum bisect_error res = BISECT_OK;
905 struct commit **rev;
907 if (!current_bad_oid)
908 return error(_("a %s revision is needed"), term_bad);
910 filename = git_pathdup("BISECT_ANCESTORS_OK");
912 /* Check if file BISECT_ANCESTORS_OK exists. */
913 if (!stat(filename, &st) && S_ISREG(st.st_mode))
914 goto done;
916 /* Bisecting with no good rev is ok. */
917 if (!good_revs.nr)
918 goto done;
920 /* Check if all good revs are ancestor of the bad rev. */
922 rev = get_bad_and_good_commits(r, &rev_nr);
923 if (check_ancestors(r, rev_nr, rev, prefix))
924 res = check_merge_bases(rev_nr, rev, no_checkout);
925 free(rev);
927 if (!res) {
928 /* Create file BISECT_ANCESTORS_OK. */
929 fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
930 if (fd < 0)
932 * BISECT_ANCESTORS_OK file is not absolutely necessary,
933 * the bisection process will continue at the next
934 * bisection step.
935 * So, just signal with a warning that something
936 * might be wrong.
938 warning_errno(_("could not create file '%s'"),
939 filename);
940 else
941 close(fd);
943 done:
944 free(filename);
945 return res;
949 * This does "git diff-tree --pretty COMMIT" without one fork+exec.
951 static void show_diff_tree(struct repository *r,
952 const char *prefix,
953 struct commit *commit)
955 const char *argv[] = {
956 "diff-tree", "--pretty", "--stat", "--summary", "--cc", NULL
958 struct rev_info opt;
960 git_config(git_diff_ui_config, NULL);
961 repo_init_revisions(r, &opt, prefix);
963 setup_revisions(ARRAY_SIZE(argv) - 1, argv, &opt, NULL);
964 log_tree_commit(&opt, commit);
965 release_revisions(&opt);
969 * The terms used for this bisect session are stored in BISECT_TERMS.
970 * We read them and store them to adapt the messages accordingly.
971 * Default is bad/good.
973 void read_bisect_terms(const char **read_bad, const char **read_good)
975 struct strbuf str = STRBUF_INIT;
976 const char *filename = git_path_bisect_terms();
977 FILE *fp = fopen(filename, "r");
979 if (!fp) {
980 if (errno == ENOENT) {
981 *read_bad = "bad";
982 *read_good = "good";
983 return;
984 } else {
985 die_errno(_("could not read file '%s'"), filename);
987 } else {
988 strbuf_getline_lf(&str, fp);
989 *read_bad = strbuf_detach(&str, NULL);
990 strbuf_getline_lf(&str, fp);
991 *read_good = strbuf_detach(&str, NULL);
993 strbuf_release(&str);
994 fclose(fp);
998 * We use the convention that return BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND (-10) means
999 * the bisection process finished successfully.
1000 * In this case the calling function or command should not turn a
1001 * BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND return code into an error or a non zero exit code.
1003 * Checking BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND
1004 * in bisect_helper::bisect_next() and only transforming it to 0 at
1005 * the end of bisect_helper::cmd_bisect__helper() helps bypassing
1006 * all the code related to finding a commit to test.
1008 enum bisect_error bisect_next_all(struct repository *r, const char *prefix)
1010 struct strvec rev_argv = STRVEC_INIT;
1011 struct rev_info revs = REV_INFO_INIT;
1012 struct commit_list *tried;
1013 int reaches = 0, all = 0, nr, steps;
1014 enum bisect_error res = BISECT_OK;
1015 struct object_id *bisect_rev;
1016 char *steps_msg;
1018 * If no_checkout is non-zero, the bisection process does not
1019 * checkout the trial commit but instead simply updates BISECT_HEAD.
1021 int no_checkout = ref_exists("BISECT_HEAD");
1022 unsigned bisect_flags = 0;
1024 read_bisect_terms(&term_bad, &term_good);
1025 if (read_bisect_refs())
1026 die(_("reading bisect refs failed"));
1028 if (file_exists(git_path_bisect_first_parent()))
1029 bisect_flags |= FIND_BISECTION_FIRST_PARENT_ONLY;
1031 if (skipped_revs.nr)
1032 bisect_flags |= FIND_BISECTION_ALL;
1034 res = check_good_are_ancestors_of_bad(r, prefix, no_checkout);
1035 if (res)
1036 goto cleanup;
1038 bisect_rev_setup(r, &revs, &rev_argv, prefix, "%s", "^%s", 1);
1040 revs.first_parent_only = !!(bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY);
1041 revs.limited = 1;
1043 bisect_common(&revs);
1045 find_bisection(&revs.commits, &reaches, &all, bisect_flags);
1046 revs.commits = managed_skipped(revs.commits, &tried);
1048 if (!revs.commits) {
1050 * We should return error here only if the "bad"
1051 * commit is also a "skip" commit.
1053 res = error_if_skipped_commits(tried, NULL);
1054 if (res < 0)
1055 goto cleanup;
1056 printf(_("%s was both %s and %s\n"),
1057 oid_to_hex(current_bad_oid),
1058 term_good,
1059 term_bad);
1061 res = BISECT_FAILED;
1062 goto cleanup;
1065 if (!all) {
1066 fprintf(stderr, _("No testable commit found.\n"
1067 "Maybe you started with bad path arguments?\n"));
1069 res = BISECT_NO_TESTABLE_COMMIT;
1070 goto cleanup;
1073 bisect_rev = &revs.commits->item->object.oid;
1075 if (oideq(bisect_rev, current_bad_oid)) {
1076 res = error_if_skipped_commits(tried, current_bad_oid);
1077 if (res)
1078 return res;
1079 printf("%s is the first %s commit\n", oid_to_hex(bisect_rev),
1080 term_bad);
1082 show_diff_tree(r, prefix, revs.commits->item);
1084 * This means the bisection process succeeded.
1085 * Using BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND (-10)
1086 * so that the call chain can simply check
1087 * for negative return values for early returns up
1088 * until the cmd_bisect__helper() caller.
1090 res = BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
1091 goto cleanup;
1094 nr = all - reaches - 1;
1095 steps = estimate_bisect_steps(all);
1097 steps_msg = xstrfmt(Q_("(roughly %d step)", "(roughly %d steps)",
1098 steps), steps);
1100 * TRANSLATORS: the last %s will be replaced with "(roughly %d
1101 * steps)" translation.
1103 printf(Q_("Bisecting: %d revision left to test after this %s\n",
1104 "Bisecting: %d revisions left to test after this %s\n",
1105 nr), nr, steps_msg);
1106 free(steps_msg);
1107 /* Clean up objects used, as they will be reused. */
1108 repo_clear_commit_marks(r, ALL_REV_FLAGS);
1110 res = bisect_checkout(bisect_rev, no_checkout);
1111 cleanup:
1112 release_revisions(&revs);
1113 strvec_clear(&rev_argv);
1114 return res;
1117 static inline int log2i(int n)
1119 int log2 = 0;
1121 for (; n > 1; n >>= 1)
1122 log2++;
1124 return log2;
1127 static inline int exp2i(int n)
1129 return 1 << n;
1133 * Estimate the number of bisect steps left (after the current step)
1135 * For any x between 0 included and 2^n excluded, the probability for
1136 * n - 1 steps left looks like:
1138 * P(2^n + x) == (2^n - x) / (2^n + x)
1140 * and P(2^n + x) < 0.5 means 2^n < 3x
1142 int estimate_bisect_steps(int all)
1144 int n, x, e;
1146 if (all < 3)
1147 return 0;
1149 n = log2i(all);
1150 e = exp2i(n);
1151 x = all - e;
1153 return (e < 3 * x) ? n : n - 1;
1156 static int mark_for_removal(const char *refname,
1157 const struct object_id *oid UNUSED,
1158 int flag UNUSED, void *cb_data)
1160 struct string_list *refs = cb_data;
1161 char *ref = xstrfmt("refs/bisect%s", refname);
1162 string_list_append(refs, ref);
1163 return 0;
1166 int bisect_clean_state(void)
1168 int result = 0;
1170 /* There may be some refs packed during bisection */
1171 struct string_list refs_for_removal = STRING_LIST_INIT_NODUP;
1172 for_each_ref_in("refs/bisect", mark_for_removal, (void *) &refs_for_removal);
1173 string_list_append(&refs_for_removal, xstrdup("BISECT_HEAD"));
1174 string_list_append(&refs_for_removal, xstrdup("BISECT_EXPECTED_REV"));
1175 result = delete_refs("bisect: remove", &refs_for_removal, REF_NO_DEREF);
1176 refs_for_removal.strdup_strings = 1;
1177 string_list_clear(&refs_for_removal, 0);
1178 unlink_or_warn(git_path_bisect_ancestors_ok());
1179 unlink_or_warn(git_path_bisect_log());
1180 unlink_or_warn(git_path_bisect_names());
1181 unlink_or_warn(git_path_bisect_run());
1182 unlink_or_warn(git_path_bisect_terms());
1183 unlink_or_warn(git_path_bisect_first_parent());
1185 * Cleanup BISECT_START last to support the --no-checkout option
1186 * introduced in the commit 4796e823a.
1188 unlink_or_warn(git_path_bisect_start());
1190 return result;