Merge branch 'kn/ref-transaction-symref'
[git.git] / bisect.c
blob4ea703bec116da8997061b56eb263e79362c20d7
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 refs_for_each_ref_in(get_main_ref_store(the_repository),
473 "refs/bisect/", register_ref, NULL);
476 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
477 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
478 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
479 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
480 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
481 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
482 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
484 static void read_bisect_paths(struct strvec *array)
486 struct strbuf str = STRBUF_INIT;
487 const char *filename = git_path_bisect_names();
488 FILE *fp = xfopen(filename, "r");
490 while (strbuf_getline_lf(&str, fp) != EOF) {
491 strbuf_trim(&str);
492 if (sq_dequote_to_strvec(str.buf, array))
493 die(_("Badly quoted content in file '%s': %s"),
494 filename, str.buf);
497 strbuf_release(&str);
498 fclose(fp);
501 static char *join_oid_array_hex(struct oid_array *array, char delim)
503 struct strbuf joined_hexs = STRBUF_INIT;
504 int i;
506 for (i = 0; i < array->nr; i++) {
507 strbuf_addstr(&joined_hexs, oid_to_hex(array->oid + i));
508 if (i + 1 < array->nr)
509 strbuf_addch(&joined_hexs, delim);
512 return strbuf_detach(&joined_hexs, NULL);
516 * In this function, passing a not NULL skipped_first is very special.
517 * It means that we want to know if the first commit in the list is
518 * skipped because we will want to test a commit away from it if it is
519 * indeed skipped.
520 * So if the first commit is skipped, we cannot take the shortcut to
521 * just "return list" when we find the first non skipped commit, we
522 * have to return a fully filtered list.
524 * We use (*skipped_first == -1) to mean "it has been found that the
525 * first commit is not skipped". In this case *skipped_first is set back
526 * to 0 just before the function returns.
528 struct commit_list *filter_skipped(struct commit_list *list,
529 struct commit_list **tried,
530 int show_all,
531 int *count,
532 int *skipped_first)
534 struct commit_list *filtered = NULL, **f = &filtered;
536 *tried = NULL;
538 if (skipped_first)
539 *skipped_first = 0;
540 if (count)
541 *count = 0;
543 if (!skipped_revs.nr)
544 return list;
546 while (list) {
547 struct commit_list *next = list->next;
548 list->next = NULL;
549 if (0 <= oid_array_lookup(&skipped_revs, &list->item->object.oid)) {
550 if (skipped_first && !*skipped_first)
551 *skipped_first = 1;
552 /* Move current to tried list */
553 *tried = list;
554 tried = &list->next;
555 } else {
556 if (!show_all) {
557 if (!skipped_first || !*skipped_first)
558 return list;
559 } else if (skipped_first && !*skipped_first) {
560 /* This means we know it's not skipped */
561 *skipped_first = -1;
563 /* Move current to filtered list */
564 *f = list;
565 f = &list->next;
566 if (count)
567 (*count)++;
569 list = next;
572 if (skipped_first && *skipped_first == -1)
573 *skipped_first = 0;
575 return filtered;
578 #define PRN_MODULO 32768
581 * This is a pseudo random number generator based on "man 3 rand".
582 * It is not used properly because the seed is the argument and it
583 * is increased by one between each call, but that should not matter
584 * for this application.
586 static unsigned get_prn(unsigned count)
588 count = count * 1103515245 + 12345;
589 return (count/65536) % PRN_MODULO;
593 * Custom integer square root from
594 * https://en.wikipedia.org/wiki/Integer_square_root
596 static int sqrti(int val)
598 float d, x = val;
600 if (!val)
601 return 0;
603 do {
604 float y = (x + (float)val / x) / 2;
605 d = (y > x) ? y - x : x - y;
606 x = y;
607 } while (d >= 0.5);
609 return (int)x;
612 static struct commit_list *skip_away(struct commit_list *list, int count)
614 struct commit_list *cur, *previous;
615 int prn, index, i;
617 prn = get_prn(count);
618 index = (count * prn / PRN_MODULO) * sqrti(prn) / sqrti(PRN_MODULO);
620 cur = list;
621 previous = NULL;
623 for (i = 0; cur; cur = cur->next, i++) {
624 if (i == index) {
625 if (!oideq(&cur->item->object.oid, current_bad_oid))
626 return cur;
627 if (previous)
628 return previous;
629 return list;
631 previous = cur;
634 return list;
637 static struct commit_list *managed_skipped(struct commit_list *list,
638 struct commit_list **tried)
640 int count, skipped_first;
642 *tried = NULL;
644 if (!skipped_revs.nr)
645 return list;
647 list = filter_skipped(list, tried, 0, &count, &skipped_first);
649 if (!skipped_first)
650 return list;
652 return skip_away(list, count);
655 static void bisect_rev_setup(struct repository *r, struct rev_info *revs,
656 struct strvec *rev_argv,
657 const char *prefix,
658 const char *bad_format, const char *good_format,
659 int read_paths)
661 struct setup_revision_opt opt = {
662 .free_removed_argv_elements = 1,
664 int i;
666 repo_init_revisions(r, revs, prefix);
667 revs->abbrev = 0;
668 revs->commit_format = CMIT_FMT_UNSPECIFIED;
670 /* rev_argv.argv[0] will be ignored by setup_revisions */
671 strvec_push(rev_argv, "bisect_rev_setup");
672 strvec_pushf(rev_argv, bad_format, oid_to_hex(current_bad_oid));
673 for (i = 0; i < good_revs.nr; i++)
674 strvec_pushf(rev_argv, good_format,
675 oid_to_hex(good_revs.oid + i));
676 strvec_push(rev_argv, "--");
677 if (read_paths)
678 read_bisect_paths(rev_argv);
680 setup_revisions(rev_argv->nr, rev_argv->v, revs, &opt);
683 static void bisect_common(struct rev_info *revs)
685 if (prepare_revision_walk(revs))
686 die("revision walk setup failed");
687 if (revs->tree_objects)
688 mark_edges_uninteresting(revs, NULL, 0);
691 static enum bisect_error error_if_skipped_commits(struct commit_list *tried,
692 const struct object_id *bad)
694 if (!tried)
695 return BISECT_OK;
697 printf("There are only 'skip'ped commits left to test.\n"
698 "The first %s commit could be any of:\n", term_bad);
700 for ( ; tried; tried = tried->next)
701 printf("%s\n", oid_to_hex(&tried->item->object.oid));
703 if (bad)
704 printf("%s\n", oid_to_hex(bad));
705 printf(_("We cannot bisect more!\n"));
707 return BISECT_ONLY_SKIPPED_LEFT;
710 static int is_expected_rev(const struct object_id *oid)
712 struct object_id expected_oid;
713 if (refs_read_ref(get_main_ref_store(the_repository), "BISECT_EXPECTED_REV", &expected_oid))
714 return 0;
715 return oideq(oid, &expected_oid);
718 enum bisect_error bisect_checkout(const struct object_id *bisect_rev,
719 int no_checkout)
721 struct commit *commit;
722 struct pretty_print_context pp = {0};
723 struct strbuf commit_msg = STRBUF_INIT;
725 refs_update_ref(get_main_ref_store(the_repository), NULL,
726 "BISECT_EXPECTED_REV", bisect_rev, NULL, 0,
727 UPDATE_REFS_DIE_ON_ERR);
729 if (no_checkout) {
730 refs_update_ref(get_main_ref_store(the_repository), NULL,
731 "BISECT_HEAD", bisect_rev, NULL, 0,
732 UPDATE_REFS_DIE_ON_ERR);
733 } else {
734 struct child_process cmd = CHILD_PROCESS_INIT;
736 cmd.git_cmd = 1;
737 strvec_pushl(&cmd.args, "checkout", "-q",
738 oid_to_hex(bisect_rev), "--", NULL);
739 if (run_command(&cmd))
741 * Errors in `run_command()` itself, signaled by res < 0,
742 * and errors in the child process, signaled by res > 0
743 * can both be treated as regular BISECT_FAILED (-1).
745 return BISECT_FAILED;
748 commit = lookup_commit_reference(the_repository, bisect_rev);
749 repo_format_commit_message(the_repository, commit, "[%H] %s%n",
750 &commit_msg, &pp);
751 fputs(commit_msg.buf, stdout);
752 strbuf_release(&commit_msg);
754 return BISECT_OK;
757 static struct commit *get_commit_reference(struct repository *r,
758 const struct object_id *oid)
760 struct commit *c = lookup_commit_reference(r, oid);
761 if (!c)
762 die(_("Not a valid commit name %s"), oid_to_hex(oid));
763 return c;
766 static struct commit **get_bad_and_good_commits(struct repository *r,
767 int *rev_nr)
769 struct commit **rev;
770 int i, n = 0;
772 ALLOC_ARRAY(rev, 1 + good_revs.nr);
773 rev[n++] = get_commit_reference(r, current_bad_oid);
774 for (i = 0; i < good_revs.nr; i++)
775 rev[n++] = get_commit_reference(r, good_revs.oid + i);
776 *rev_nr = n;
778 return rev;
781 static enum bisect_error handle_bad_merge_base(void)
783 if (is_expected_rev(current_bad_oid)) {
784 char *bad_hex = oid_to_hex(current_bad_oid);
785 char *good_hex = join_oid_array_hex(&good_revs, ' ');
786 if (!strcmp(term_bad, "bad") && !strcmp(term_good, "good")) {
787 fprintf(stderr, _("The merge base %s is bad.\n"
788 "This means the bug has been fixed "
789 "between %s and [%s].\n"),
790 bad_hex, bad_hex, good_hex);
791 } else if (!strcmp(term_bad, "new") && !strcmp(term_good, "old")) {
792 fprintf(stderr, _("The merge base %s is new.\n"
793 "The property has changed "
794 "between %s and [%s].\n"),
795 bad_hex, bad_hex, good_hex);
796 } else {
797 fprintf(stderr, _("The merge base %s is %s.\n"
798 "This means the first '%s' commit is "
799 "between %s and [%s].\n"),
800 bad_hex, term_bad, term_good, bad_hex, good_hex);
802 return BISECT_MERGE_BASE_CHECK;
805 fprintf(stderr, _("Some %s revs are not ancestors of the %s rev.\n"
806 "git bisect cannot work properly in this case.\n"
807 "Maybe you mistook %s and %s revs?\n"),
808 term_good, term_bad, term_good, term_bad);
809 return BISECT_FAILED;
812 static void handle_skipped_merge_base(const struct object_id *mb)
814 char *mb_hex = oid_to_hex(mb);
815 char *bad_hex = oid_to_hex(current_bad_oid);
816 char *good_hex = join_oid_array_hex(&good_revs, ' ');
818 warning(_("the merge base between %s and [%s] "
819 "must be skipped.\n"
820 "So we cannot be sure the first %s commit is "
821 "between %s and %s.\n"
822 "We continue anyway."),
823 bad_hex, good_hex, term_bad, mb_hex, bad_hex);
824 free(good_hex);
828 * "check_merge_bases" checks that merge bases are not "bad" (or "new").
830 * - If one is "bad" (or "new"), it means the user assumed something wrong
831 * and we must return error with a non 0 error code.
832 * - If one is "good" (or "old"), that's good, we have nothing to do.
833 * - If one is "skipped", we can't know but we should warn.
834 * - If we don't know, we should check it out and ask the user to test.
835 * - If a merge base must be tested, on success return
836 * BISECT_INTERNAL_SUCCESS_MERGE_BASE (-11) a special condition
837 * for early success, this will be converted back to 0 in
838 * check_good_are_ancestors_of_bad().
840 static enum bisect_error check_merge_bases(int rev_nr, struct commit **rev, int no_checkout)
842 enum bisect_error res = BISECT_OK;
843 struct commit_list *result = NULL;
845 if (repo_get_merge_bases_many(the_repository, rev[0], rev_nr - 1,
846 rev + 1, &result) < 0)
847 exit(128);
849 for (; result; result = result->next) {
850 const struct object_id *mb = &result->item->object.oid;
851 if (oideq(mb, current_bad_oid)) {
852 res = handle_bad_merge_base();
853 break;
854 } else if (0 <= oid_array_lookup(&good_revs, mb)) {
855 continue;
856 } else if (0 <= oid_array_lookup(&skipped_revs, mb)) {
857 handle_skipped_merge_base(mb);
858 } else {
859 printf(_("Bisecting: a merge base must be tested\n"));
860 res = bisect_checkout(mb, no_checkout);
861 if (!res)
862 /* indicate early success */
863 res = BISECT_INTERNAL_SUCCESS_MERGE_BASE;
864 break;
868 free_commit_list(result);
869 return res;
872 static int check_ancestors(struct repository *r, int rev_nr,
873 struct commit **rev, const char *prefix)
875 struct strvec rev_argv = STRVEC_INIT;
876 struct rev_info revs;
877 int res;
879 bisect_rev_setup(r, &revs, &rev_argv, prefix, "^%s", "%s", 0);
881 bisect_common(&revs);
882 res = (revs.commits != NULL);
884 /* Clean up objects used, as they will be reused. */
885 clear_commit_marks_many(rev_nr, rev, ALL_REV_FLAGS);
887 release_revisions(&revs);
888 strvec_clear(&rev_argv);
889 return res;
893 * "check_good_are_ancestors_of_bad" checks that all "good" revs are
894 * ancestor of the "bad" rev.
896 * If that's not the case, we need to check the merge bases.
897 * If a merge base must be tested by the user, its source code will be
898 * checked out to be tested by the user and we will return.
901 static enum bisect_error check_good_are_ancestors_of_bad(struct repository *r,
902 const char *prefix,
903 int no_checkout)
905 char *filename;
906 struct stat st;
907 int fd, rev_nr;
908 enum bisect_error res = BISECT_OK;
909 struct commit **rev;
911 if (!current_bad_oid)
912 return error(_("a %s revision is needed"), term_bad);
914 filename = git_pathdup("BISECT_ANCESTORS_OK");
916 /* Check if file BISECT_ANCESTORS_OK exists. */
917 if (!stat(filename, &st) && S_ISREG(st.st_mode))
918 goto done;
920 /* Bisecting with no good rev is ok. */
921 if (!good_revs.nr)
922 goto done;
924 /* Check if all good revs are ancestor of the bad rev. */
926 rev = get_bad_and_good_commits(r, &rev_nr);
927 if (check_ancestors(r, rev_nr, rev, prefix))
928 res = check_merge_bases(rev_nr, rev, no_checkout);
929 free(rev);
931 if (!res) {
932 /* Create file BISECT_ANCESTORS_OK. */
933 fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
934 if (fd < 0)
936 * BISECT_ANCESTORS_OK file is not absolutely necessary,
937 * the bisection process will continue at the next
938 * bisection step.
939 * So, just signal with a warning that something
940 * might be wrong.
942 warning_errno(_("could not create file '%s'"),
943 filename);
944 else
945 close(fd);
947 done:
948 free(filename);
949 return res;
953 * Display a commit summary to the user.
955 static void show_commit(struct commit *commit)
957 struct child_process show = CHILD_PROCESS_INIT;
960 * Call git show with --no-pager, as it would otherwise
961 * paginate the "git show" output only, not the output
962 * from bisect_next_all(); this can be fixed by moving
963 * it into a --format parameter, but that would override
964 * the user's default options for "git show", which we
965 * are trying to honour.
967 strvec_pushl(&show.args,
968 "--no-pager",
969 "show",
970 "--stat",
971 "--summary",
972 "--no-abbrev-commit",
973 "--diff-merges=first-parent",
974 oid_to_hex(&commit->object.oid), NULL);
975 show.git_cmd = 1;
976 if (run_command(&show))
977 die(_("unable to start 'show' for object '%s'"),
978 oid_to_hex(&commit->object.oid));
982 * The terms used for this bisect session are stored in BISECT_TERMS.
983 * We read them and store them to adapt the messages accordingly.
984 * Default is bad/good.
986 void read_bisect_terms(const char **read_bad, const char **read_good)
988 struct strbuf str = STRBUF_INIT;
989 const char *filename = git_path_bisect_terms();
990 FILE *fp = fopen(filename, "r");
992 if (!fp) {
993 if (errno == ENOENT) {
994 *read_bad = "bad";
995 *read_good = "good";
996 return;
997 } else {
998 die_errno(_("could not read file '%s'"), filename);
1000 } else {
1001 strbuf_getline_lf(&str, fp);
1002 *read_bad = strbuf_detach(&str, NULL);
1003 strbuf_getline_lf(&str, fp);
1004 *read_good = strbuf_detach(&str, NULL);
1006 strbuf_release(&str);
1007 fclose(fp);
1011 * We use the convention that return BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND (-10) means
1012 * the bisection process finished successfully.
1013 * In this case the calling function or command should not turn a
1014 * BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND return code into an error or a non zero exit code.
1016 * Checking BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND
1017 * in bisect_helper::bisect_next() and only transforming it to 0 at
1018 * the end of bisect_helper::cmd_bisect__helper() helps bypassing
1019 * all the code related to finding a commit to test.
1021 enum bisect_error bisect_next_all(struct repository *r, const char *prefix)
1023 struct strvec rev_argv = STRVEC_INIT;
1024 struct rev_info revs = REV_INFO_INIT;
1025 struct commit_list *tried;
1026 int reaches = 0, all = 0, nr, steps;
1027 enum bisect_error res = BISECT_OK;
1028 struct object_id *bisect_rev;
1029 char *steps_msg;
1031 * If no_checkout is non-zero, the bisection process does not
1032 * checkout the trial commit but instead simply updates BISECT_HEAD.
1034 int no_checkout = refs_ref_exists(get_main_ref_store(the_repository),
1035 "BISECT_HEAD");
1036 unsigned bisect_flags = 0;
1038 read_bisect_terms(&term_bad, &term_good);
1039 if (read_bisect_refs())
1040 die(_("reading bisect refs failed"));
1042 if (file_exists(git_path_bisect_first_parent()))
1043 bisect_flags |= FIND_BISECTION_FIRST_PARENT_ONLY;
1045 if (skipped_revs.nr)
1046 bisect_flags |= FIND_BISECTION_ALL;
1048 res = check_good_are_ancestors_of_bad(r, prefix, no_checkout);
1049 if (res)
1050 goto cleanup;
1052 bisect_rev_setup(r, &revs, &rev_argv, prefix, "%s", "^%s", 1);
1054 revs.first_parent_only = !!(bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY);
1055 revs.limited = 1;
1057 bisect_common(&revs);
1059 find_bisection(&revs.commits, &reaches, &all, bisect_flags);
1060 revs.commits = managed_skipped(revs.commits, &tried);
1062 if (!revs.commits) {
1064 * We should return error here only if the "bad"
1065 * commit is also a "skip" commit.
1067 res = error_if_skipped_commits(tried, NULL);
1068 if (res < 0)
1069 goto cleanup;
1070 printf(_("%s was both %s and %s\n"),
1071 oid_to_hex(current_bad_oid),
1072 term_good,
1073 term_bad);
1075 res = BISECT_FAILED;
1076 goto cleanup;
1079 if (!all) {
1080 fprintf(stderr, _("No testable commit found.\n"
1081 "Maybe you started with bad path arguments?\n"));
1083 res = BISECT_NO_TESTABLE_COMMIT;
1084 goto cleanup;
1087 bisect_rev = &revs.commits->item->object.oid;
1089 if (oideq(bisect_rev, current_bad_oid)) {
1090 res = error_if_skipped_commits(tried, current_bad_oid);
1091 if (res)
1092 return res;
1093 printf("%s is the first %s commit\n", oid_to_hex(bisect_rev),
1094 term_bad);
1096 show_commit(revs.commits->item);
1098 * This means the bisection process succeeded.
1099 * Using BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND (-10)
1100 * so that the call chain can simply check
1101 * for negative return values for early returns up
1102 * until the cmd_bisect__helper() caller.
1104 res = BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
1105 goto cleanup;
1108 nr = all - reaches - 1;
1109 steps = estimate_bisect_steps(all);
1111 steps_msg = xstrfmt(Q_("(roughly %d step)", "(roughly %d steps)",
1112 steps), steps);
1114 * TRANSLATORS: the last %s will be replaced with "(roughly %d
1115 * steps)" translation.
1117 printf(Q_("Bisecting: %d revision left to test after this %s\n",
1118 "Bisecting: %d revisions left to test after this %s\n",
1119 nr), nr, steps_msg);
1120 free(steps_msg);
1121 /* Clean up objects used, as they will be reused. */
1122 repo_clear_commit_marks(r, ALL_REV_FLAGS);
1124 res = bisect_checkout(bisect_rev, no_checkout);
1125 cleanup:
1126 release_revisions(&revs);
1127 strvec_clear(&rev_argv);
1128 return res;
1131 static inline int log2i(int n)
1133 int log2 = 0;
1135 for (; n > 1; n >>= 1)
1136 log2++;
1138 return log2;
1141 static inline int exp2i(int n)
1143 return 1 << n;
1147 * Estimate the number of bisect steps left (after the current step)
1149 * For any x between 0 included and 2^n excluded, the probability for
1150 * n - 1 steps left looks like:
1152 * P(2^n + x) == (2^n - x) / (2^n + x)
1154 * and P(2^n + x) < 0.5 means 2^n < 3x
1156 int estimate_bisect_steps(int all)
1158 int n, x, e;
1160 if (all < 3)
1161 return 0;
1163 n = log2i(all);
1164 e = exp2i(n);
1165 x = all - e;
1167 return (e < 3 * x) ? n : n - 1;
1170 static int mark_for_removal(const char *refname,
1171 const struct object_id *oid UNUSED,
1172 int flag UNUSED, void *cb_data)
1174 struct string_list *refs = cb_data;
1175 char *ref = xstrfmt("refs/bisect%s", refname);
1176 string_list_append(refs, ref);
1177 return 0;
1180 int bisect_clean_state(void)
1182 int result = 0;
1184 /* There may be some refs packed during bisection */
1185 struct string_list refs_for_removal = STRING_LIST_INIT_NODUP;
1186 refs_for_each_ref_in(get_main_ref_store(the_repository),
1187 "refs/bisect", mark_for_removal,
1188 (void *) &refs_for_removal);
1189 string_list_append(&refs_for_removal, xstrdup("BISECT_HEAD"));
1190 string_list_append(&refs_for_removal, xstrdup("BISECT_EXPECTED_REV"));
1191 result = refs_delete_refs(get_main_ref_store(the_repository),
1192 "bisect: remove", &refs_for_removal,
1193 REF_NO_DEREF);
1194 refs_for_removal.strdup_strings = 1;
1195 string_list_clear(&refs_for_removal, 0);
1196 unlink_or_warn(git_path_bisect_ancestors_ok());
1197 unlink_or_warn(git_path_bisect_log());
1198 unlink_or_warn(git_path_bisect_names());
1199 unlink_or_warn(git_path_bisect_run());
1200 unlink_or_warn(git_path_bisect_terms());
1201 unlink_or_warn(git_path_bisect_first_parent());
1203 * Cleanup BISECT_START last to support the --no-checkout option
1204 * introduced in the commit 4796e823a.
1206 unlink_or_warn(git_path_bisect_start());
1208 return result;