RelNotes: minor typo fixes in 2.43.0 draft
[alt-git.git] / bisect.c
blob1be8e0a2711df9d29c1ba903fd4e8901379ea406
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 "hash-lookup.h"
13 #include "run-command.h"
14 #include "log-tree.h"
15 #include "bisect.h"
16 #include "oid-array.h"
17 #include "strvec.h"
18 #include "commit-slab.h"
19 #include "commit-reach.h"
20 #include "object-name.h"
21 #include "object-store-ll.h"
22 #include "path.h"
23 #include "dir.h"
25 static struct oid_array good_revs;
26 static struct oid_array skipped_revs;
28 static struct object_id *current_bad_oid;
30 static const char *term_bad;
31 static const char *term_good;
33 /* Remember to update object flag allocation in object.h */
34 #define COUNTED (1u<<16)
37 * This is a truly stupid algorithm, but it's only
38 * used for bisection, and we just don't care enough.
40 * We care just barely enough to avoid recursing for
41 * non-merge entries.
43 static int count_distance(struct commit_list *entry)
45 int nr = 0;
47 while (entry) {
48 struct commit *commit = entry->item;
49 struct commit_list *p;
51 if (commit->object.flags & (UNINTERESTING | COUNTED))
52 break;
53 if (!(commit->object.flags & TREESAME))
54 nr++;
55 commit->object.flags |= COUNTED;
56 p = commit->parents;
57 entry = p;
58 if (p) {
59 p = p->next;
60 while (p) {
61 nr += count_distance(p);
62 p = p->next;
67 return nr;
70 static void clear_distance(struct commit_list *list)
72 while (list) {
73 struct commit *commit = list->item;
74 commit->object.flags &= ~COUNTED;
75 list = list->next;
79 define_commit_slab(commit_weight, int *);
80 static struct commit_weight commit_weight;
82 #define DEBUG_BISECT 0
84 static inline int weight(struct commit_list *elem)
86 return **commit_weight_at(&commit_weight, elem->item);
89 static inline void weight_set(struct commit_list *elem, int weight)
91 **commit_weight_at(&commit_weight, elem->item) = weight;
94 static int count_interesting_parents(struct commit *commit, unsigned bisect_flags)
96 struct commit_list *p;
97 int count;
99 for (count = 0, p = commit->parents; p; p = p->next) {
100 if (!(p->item->object.flags & UNINTERESTING))
101 count++;
102 if (bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY)
103 break;
105 return count;
108 static inline int approx_halfway(struct commit_list *p, int nr)
110 int diff;
113 * Don't short-cut something we are not going to return!
115 if (p->item->object.flags & TREESAME)
116 return 0;
117 if (DEBUG_BISECT)
118 return 0;
120 * For small number of commits 2 and 3 are halfway of 5, and
121 * 3 is halfway of 6 but 2 and 4 are not.
123 diff = 2 * weight(p) - nr;
124 switch (diff) {
125 case -1: case 0: case 1:
126 return 1;
127 default:
129 * For large number of commits we are not so strict, it's
130 * good enough if it's within ~0.1% of the halfway point,
131 * e.g. 5000 is exactly halfway of 10000, but we consider
132 * the values [4996, 5004] as halfway as well.
134 if (abs(diff) < nr / 1024)
135 return 1;
136 return 0;
140 static void show_list(const char *debug, int counted, int nr,
141 struct commit_list *list)
143 struct commit_list *p;
145 if (!DEBUG_BISECT)
146 return;
148 fprintf(stderr, "%s (%d/%d)\n", debug, counted, nr);
150 for (p = list; p; p = p->next) {
151 struct commit_list *pp;
152 struct commit *commit = p->item;
153 unsigned commit_flags = commit->object.flags;
154 enum object_type type;
155 unsigned long size;
156 char *buf = repo_read_object_file(the_repository,
157 &commit->object.oid, &type,
158 &size);
159 const char *subject_start;
160 int subject_len;
162 fprintf(stderr, "%c%c%c ",
163 (commit_flags & TREESAME) ? ' ' : 'T',
164 (commit_flags & UNINTERESTING) ? 'U' : ' ',
165 (commit_flags & COUNTED) ? 'C' : ' ');
166 if (*commit_weight_at(&commit_weight, p->item))
167 fprintf(stderr, "%3d", weight(p));
168 else
169 fprintf(stderr, "---");
170 fprintf(stderr, " %.*s", 8, oid_to_hex(&commit->object.oid));
171 for (pp = commit->parents; pp; pp = pp->next)
172 fprintf(stderr, " %.*s", 8,
173 oid_to_hex(&pp->item->object.oid));
175 subject_len = find_commit_subject(buf, &subject_start);
176 if (subject_len)
177 fprintf(stderr, " %.*s", subject_len, subject_start);
178 fprintf(stderr, "\n");
182 static struct commit_list *best_bisection(struct commit_list *list, int nr)
184 struct commit_list *p, *best;
185 int best_distance = -1;
187 best = list;
188 for (p = list; p; p = p->next) {
189 int distance;
190 unsigned commit_flags = p->item->object.flags;
192 if (commit_flags & TREESAME)
193 continue;
194 distance = weight(p);
195 if (nr - distance < distance)
196 distance = nr - distance;
197 if (distance > best_distance) {
198 best = p;
199 best_distance = distance;
203 return best;
206 struct commit_dist {
207 struct commit *commit;
208 int distance;
211 static int compare_commit_dist(const void *a_, const void *b_)
213 struct commit_dist *a, *b;
215 a = (struct commit_dist *)a_;
216 b = (struct commit_dist *)b_;
217 if (a->distance != b->distance)
218 return b->distance - a->distance; /* desc sort */
219 return oidcmp(&a->commit->object.oid, &b->commit->object.oid);
222 static struct commit_list *best_bisection_sorted(struct commit_list *list, int nr)
224 struct commit_list *p;
225 struct commit_dist *array = xcalloc(nr, sizeof(*array));
226 struct strbuf buf = STRBUF_INIT;
227 int cnt, i;
229 for (p = list, cnt = 0; p; p = p->next) {
230 int distance;
231 unsigned commit_flags = p->item->object.flags;
233 if (commit_flags & TREESAME)
234 continue;
235 distance = weight(p);
236 if (nr - distance < distance)
237 distance = nr - distance;
238 array[cnt].commit = p->item;
239 array[cnt].distance = distance;
240 cnt++;
242 QSORT(array, cnt, compare_commit_dist);
243 for (p = list, i = 0; i < cnt; i++) {
244 struct object *obj = &(array[i].commit->object);
246 strbuf_reset(&buf);
247 strbuf_addf(&buf, "dist=%d", array[i].distance);
248 add_name_decoration(DECORATION_NONE, buf.buf, obj);
250 p->item = array[i].commit;
251 if (i < cnt - 1)
252 p = p->next;
254 if (p) {
255 free_commit_list(p->next);
256 p->next = NULL;
258 strbuf_release(&buf);
259 free(array);
260 return list;
264 * zero or positive weight is the number of interesting commits it can
265 * reach, including itself. Especially, weight = 0 means it does not
266 * reach any tree-changing commits (e.g. just above uninteresting one
267 * but traversal is with pathspec).
269 * weight = -1 means it has one parent and its distance is yet to
270 * be computed.
272 * weight = -2 means it has more than one parent and its distance is
273 * unknown. After running count_distance() first, they will get zero
274 * or positive distance.
276 static struct commit_list *do_find_bisection(struct commit_list *list,
277 int nr, int *weights,
278 unsigned bisect_flags)
280 int n, counted;
281 struct commit_list *p;
283 counted = 0;
285 for (n = 0, p = list; p; p = p->next) {
286 struct commit *commit = p->item;
287 unsigned commit_flags = commit->object.flags;
289 *commit_weight_at(&commit_weight, p->item) = &weights[n++];
290 switch (count_interesting_parents(commit, bisect_flags)) {
291 case 0:
292 if (!(commit_flags & TREESAME)) {
293 weight_set(p, 1);
294 counted++;
295 show_list("bisection 2 count one",
296 counted, nr, list);
299 * otherwise, it is known not to reach any
300 * tree-changing commit and gets weight 0.
302 break;
303 case 1:
304 weight_set(p, -1);
305 break;
306 default:
307 weight_set(p, -2);
308 break;
312 show_list("bisection 2 initialize", counted, nr, list);
315 * If you have only one parent in the resulting set
316 * then you can reach one commit more than that parent
317 * can reach. So we do not have to run the expensive
318 * count_distance() for single strand of pearls.
320 * However, if you have more than one parents, you cannot
321 * just add their distance and one for yourself, since
322 * they usually reach the same ancestor and you would
323 * end up counting them twice that way.
325 * So we will first count distance of merges the usual
326 * way, and then fill the blanks using cheaper algorithm.
328 for (p = list; p; p = p->next) {
329 if (p->item->object.flags & UNINTERESTING)
330 continue;
331 if (weight(p) != -2)
332 continue;
333 if (bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY)
334 BUG("shouldn't be calling count-distance in fp mode");
335 weight_set(p, count_distance(p));
336 clear_distance(list);
338 /* Does it happen to be at half-way? */
339 if (!(bisect_flags & FIND_BISECTION_ALL) &&
340 approx_halfway(p, nr))
341 return p;
342 counted++;
345 show_list("bisection 2 count_distance", counted, nr, list);
347 while (counted < nr) {
348 for (p = list; p; p = p->next) {
349 struct commit_list *q;
350 unsigned commit_flags = p->item->object.flags;
352 if (0 <= weight(p))
353 continue;
355 for (q = p->item->parents;
357 q = bisect_flags & FIND_BISECTION_FIRST_PARENT_ONLY ? NULL : q->next) {
358 if (q->item->object.flags & UNINTERESTING)
359 continue;
360 if (0 <= weight(q))
361 break;
363 if (!q)
364 continue;
367 * weight for p is unknown but q is known.
368 * add one for p itself if p is to be counted,
369 * otherwise inherit it from q directly.
371 if (!(commit_flags & TREESAME)) {
372 weight_set(p, weight(q)+1);
373 counted++;
374 show_list("bisection 2 count one",
375 counted, nr, list);
377 else
378 weight_set(p, weight(q));
380 /* Does it happen to be at half-way? */
381 if (!(bisect_flags & FIND_BISECTION_ALL) &&
382 approx_halfway(p, nr))
383 return p;
387 show_list("bisection 2 counted all", counted, nr, list);
389 if (!(bisect_flags & FIND_BISECTION_ALL))
390 return best_bisection(list, nr);
391 else
392 return best_bisection_sorted(list, nr);
395 void find_bisection(struct commit_list **commit_list, int *reaches,
396 int *all, unsigned bisect_flags)
398 int nr, on_list;
399 struct commit_list *list, *p, *best, *next, *last;
400 int *weights;
402 show_list("bisection 2 entry", 0, 0, *commit_list);
403 init_commit_weight(&commit_weight);
406 * Count the number of total and tree-changing items on the
407 * list, while reversing the list.
409 for (nr = on_list = 0, last = NULL, p = *commit_list;
411 p = next) {
412 unsigned commit_flags = p->item->object.flags;
414 next = p->next;
415 if (commit_flags & UNINTERESTING) {
416 free(p);
417 continue;
419 p->next = last;
420 last = p;
421 if (!(commit_flags & TREESAME))
422 nr++;
423 on_list++;
425 list = last;
426 show_list("bisection 2 sorted", 0, nr, list);
428 *all = nr;
429 CALLOC_ARRAY(weights, on_list);
431 /* Do the real work of finding bisection commit. */
432 best = do_find_bisection(list, nr, weights, bisect_flags);
433 if (best) {
434 if (!(bisect_flags & FIND_BISECTION_ALL)) {
435 list->item = best->item;
436 free_commit_list(list->next);
437 best = list;
438 best->next = NULL;
440 *reaches = weight(best);
442 free(weights);
443 *commit_list = best;
444 clear_commit_weight(&commit_weight);
447 static int register_ref(const char *refname, const struct object_id *oid,
448 int flags UNUSED, void *cb_data UNUSED)
450 struct strbuf good_prefix = STRBUF_INIT;
451 strbuf_addstr(&good_prefix, term_good);
452 strbuf_addstr(&good_prefix, "-");
454 if (!strcmp(refname, term_bad)) {
455 current_bad_oid = xmalloc(sizeof(*current_bad_oid));
456 oidcpy(current_bad_oid, oid);
457 } else if (starts_with(refname, good_prefix.buf)) {
458 oid_array_append(&good_revs, oid);
459 } else if (starts_with(refname, "skip-")) {
460 oid_array_append(&skipped_revs, oid);
463 strbuf_release(&good_prefix);
465 return 0;
468 static int read_bisect_refs(void)
470 return for_each_ref_in("refs/bisect/", register_ref, NULL);
473 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
474 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
475 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
476 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
477 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
478 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
479 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
480 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
482 static void read_bisect_paths(struct strvec *array)
484 struct strbuf str = STRBUF_INIT;
485 const char *filename = git_path_bisect_names();
486 FILE *fp = xfopen(filename, "r");
488 while (strbuf_getline_lf(&str, fp) != EOF) {
489 strbuf_trim(&str);
490 if (sq_dequote_to_strvec(str.buf, array))
491 die(_("Badly quoted content in file '%s': %s"),
492 filename, str.buf);
495 strbuf_release(&str);
496 fclose(fp);
499 static char *join_oid_array_hex(struct oid_array *array, char delim)
501 struct strbuf joined_hexs = STRBUF_INIT;
502 int i;
504 for (i = 0; i < array->nr; i++) {
505 strbuf_addstr(&joined_hexs, oid_to_hex(array->oid + i));
506 if (i + 1 < array->nr)
507 strbuf_addch(&joined_hexs, delim);
510 return strbuf_detach(&joined_hexs, NULL);
514 * In this function, passing a not NULL skipped_first is very special.
515 * It means that we want to know if the first commit in the list is
516 * skipped because we will want to test a commit away from it if it is
517 * indeed skipped.
518 * So if the first commit is skipped, we cannot take the shortcut to
519 * just "return list" when we find the first non skipped commit, we
520 * have to return a fully filtered list.
522 * We use (*skipped_first == -1) to mean "it has been found that the
523 * first commit is not skipped". In this case *skipped_first is set back
524 * to 0 just before the function returns.
526 struct commit_list *filter_skipped(struct commit_list *list,
527 struct commit_list **tried,
528 int show_all,
529 int *count,
530 int *skipped_first)
532 struct commit_list *filtered = NULL, **f = &filtered;
534 *tried = NULL;
536 if (skipped_first)
537 *skipped_first = 0;
538 if (count)
539 *count = 0;
541 if (!skipped_revs.nr)
542 return list;
544 while (list) {
545 struct commit_list *next = list->next;
546 list->next = NULL;
547 if (0 <= oid_array_lookup(&skipped_revs, &list->item->object.oid)) {
548 if (skipped_first && !*skipped_first)
549 *skipped_first = 1;
550 /* Move current to tried list */
551 *tried = list;
552 tried = &list->next;
553 } else {
554 if (!show_all) {
555 if (!skipped_first || !*skipped_first)
556 return list;
557 } else if (skipped_first && !*skipped_first) {
558 /* This means we know it's not skipped */
559 *skipped_first = -1;
561 /* Move current to filtered list */
562 *f = list;
563 f = &list->next;
564 if (count)
565 (*count)++;
567 list = next;
570 if (skipped_first && *skipped_first == -1)
571 *skipped_first = 0;
573 return filtered;
576 #define PRN_MODULO 32768
579 * This is a pseudo random number generator based on "man 3 rand".
580 * It is not used properly because the seed is the argument and it
581 * is increased by one between each call, but that should not matter
582 * for this application.
584 static unsigned get_prn(unsigned count)
586 count = count * 1103515245 + 12345;
587 return (count/65536) % PRN_MODULO;
591 * Custom integer square root from
592 * https://en.wikipedia.org/wiki/Integer_square_root
594 static int sqrti(int val)
596 float d, x = val;
598 if (!val)
599 return 0;
601 do {
602 float y = (x + (float)val / x) / 2;
603 d = (y > x) ? y - x : x - y;
604 x = y;
605 } while (d >= 0.5);
607 return (int)x;
610 static struct commit_list *skip_away(struct commit_list *list, int count)
612 struct commit_list *cur, *previous;
613 int prn, index, i;
615 prn = get_prn(count);
616 index = (count * prn / PRN_MODULO) * sqrti(prn) / sqrti(PRN_MODULO);
618 cur = list;
619 previous = NULL;
621 for (i = 0; cur; cur = cur->next, i++) {
622 if (i == index) {
623 if (!oideq(&cur->item->object.oid, current_bad_oid))
624 return cur;
625 if (previous)
626 return previous;
627 return list;
629 previous = cur;
632 return list;
635 static struct commit_list *managed_skipped(struct commit_list *list,
636 struct commit_list **tried)
638 int count, skipped_first;
640 *tried = NULL;
642 if (!skipped_revs.nr)
643 return list;
645 list = filter_skipped(list, tried, 0, &count, &skipped_first);
647 if (!skipped_first)
648 return list;
650 return skip_away(list, count);
653 static void bisect_rev_setup(struct repository *r, struct rev_info *revs,
654 struct strvec *rev_argv,
655 const char *prefix,
656 const char *bad_format, const char *good_format,
657 int read_paths)
659 struct setup_revision_opt opt = {
660 .free_removed_argv_elements = 1,
662 int i;
664 repo_init_revisions(r, revs, prefix);
665 revs->abbrev = 0;
666 revs->commit_format = CMIT_FMT_UNSPECIFIED;
668 /* rev_argv.argv[0] will be ignored by setup_revisions */
669 strvec_push(rev_argv, "bisect_rev_setup");
670 strvec_pushf(rev_argv, bad_format, oid_to_hex(current_bad_oid));
671 for (i = 0; i < good_revs.nr; i++)
672 strvec_pushf(rev_argv, good_format,
673 oid_to_hex(good_revs.oid + i));
674 strvec_push(rev_argv, "--");
675 if (read_paths)
676 read_bisect_paths(rev_argv);
678 setup_revisions(rev_argv->nr, rev_argv->v, revs, &opt);
681 static void bisect_common(struct rev_info *revs)
683 if (prepare_revision_walk(revs))
684 die("revision walk setup failed");
685 if (revs->tree_objects)
686 mark_edges_uninteresting(revs, NULL, 0);
689 static enum bisect_error error_if_skipped_commits(struct commit_list *tried,
690 const struct object_id *bad)
692 if (!tried)
693 return BISECT_OK;
695 printf("There are only 'skip'ped commits left to test.\n"
696 "The first %s commit could be any of:\n", term_bad);
698 for ( ; tried; tried = tried->next)
699 printf("%s\n", oid_to_hex(&tried->item->object.oid));
701 if (bad)
702 printf("%s\n", oid_to_hex(bad));
703 printf(_("We cannot bisect more!\n"));
705 return BISECT_ONLY_SKIPPED_LEFT;
708 static int is_expected_rev(const struct object_id *oid)
710 const char *filename = git_path_bisect_expected_rev();
711 struct stat st;
712 struct strbuf str = STRBUF_INIT;
713 FILE *fp;
714 int res = 0;
716 if (stat(filename, &st) || !S_ISREG(st.st_mode))
717 return 0;
719 fp = fopen_or_warn(filename, "r");
720 if (!fp)
721 return 0;
723 if (strbuf_getline_lf(&str, fp) != EOF)
724 res = !strcmp(str.buf, oid_to_hex(oid));
726 strbuf_release(&str);
727 fclose(fp);
729 return res;
732 enum bisect_error bisect_checkout(const struct object_id *bisect_rev,
733 int no_checkout)
735 struct commit *commit;
736 struct pretty_print_context pp = {0};
737 struct strbuf commit_msg = STRBUF_INIT;
739 update_ref(NULL, "BISECT_EXPECTED_REV", bisect_rev, NULL, 0, UPDATE_REFS_DIE_ON_ERR);
741 if (no_checkout) {
742 update_ref(NULL, "BISECT_HEAD", bisect_rev, NULL, 0,
743 UPDATE_REFS_DIE_ON_ERR);
744 } else {
745 struct child_process cmd = CHILD_PROCESS_INIT;
747 cmd.git_cmd = 1;
748 strvec_pushl(&cmd.args, "checkout", "-q",
749 oid_to_hex(bisect_rev), "--", NULL);
750 if (run_command(&cmd))
752 * Errors in `run_command()` itself, signaled by res < 0,
753 * and errors in the child process, signaled by res > 0
754 * can both be treated as regular BISECT_FAILED (-1).
756 return BISECT_FAILED;
759 commit = lookup_commit_reference(the_repository, bisect_rev);
760 repo_format_commit_message(the_repository, commit, "[%H] %s%n",
761 &commit_msg, &pp);
762 fputs(commit_msg.buf, stdout);
763 strbuf_release(&commit_msg);
765 return BISECT_OK;
768 static struct commit *get_commit_reference(struct repository *r,
769 const struct object_id *oid)
771 struct commit *c = lookup_commit_reference(r, oid);
772 if (!c)
773 die(_("Not a valid commit name %s"), oid_to_hex(oid));
774 return c;
777 static struct commit **get_bad_and_good_commits(struct repository *r,
778 int *rev_nr)
780 struct commit **rev;
781 int i, n = 0;
783 ALLOC_ARRAY(rev, 1 + good_revs.nr);
784 rev[n++] = get_commit_reference(r, current_bad_oid);
785 for (i = 0; i < good_revs.nr; i++)
786 rev[n++] = get_commit_reference(r, good_revs.oid + i);
787 *rev_nr = n;
789 return rev;
792 static enum bisect_error handle_bad_merge_base(void)
794 if (is_expected_rev(current_bad_oid)) {
795 char *bad_hex = oid_to_hex(current_bad_oid);
796 char *good_hex = join_oid_array_hex(&good_revs, ' ');
797 if (!strcmp(term_bad, "bad") && !strcmp(term_good, "good")) {
798 fprintf(stderr, _("The merge base %s is bad.\n"
799 "This means the bug has been fixed "
800 "between %s and [%s].\n"),
801 bad_hex, bad_hex, good_hex);
802 } else if (!strcmp(term_bad, "new") && !strcmp(term_good, "old")) {
803 fprintf(stderr, _("The merge base %s is new.\n"
804 "The property has changed "
805 "between %s and [%s].\n"),
806 bad_hex, bad_hex, good_hex);
807 } else {
808 fprintf(stderr, _("The merge base %s is %s.\n"
809 "This means the first '%s' commit is "
810 "between %s and [%s].\n"),
811 bad_hex, term_bad, term_good, bad_hex, good_hex);
813 return BISECT_MERGE_BASE_CHECK;
816 fprintf(stderr, _("Some %s revs are not ancestors of the %s rev.\n"
817 "git bisect cannot work properly in this case.\n"
818 "Maybe you mistook %s and %s revs?\n"),
819 term_good, term_bad, term_good, term_bad);
820 return BISECT_FAILED;
823 static void handle_skipped_merge_base(const struct object_id *mb)
825 char *mb_hex = oid_to_hex(mb);
826 char *bad_hex = oid_to_hex(current_bad_oid);
827 char *good_hex = join_oid_array_hex(&good_revs, ' ');
829 warning(_("the merge base between %s and [%s] "
830 "must be skipped.\n"
831 "So we cannot be sure the first %s commit is "
832 "between %s and %s.\n"
833 "We continue anyway."),
834 bad_hex, good_hex, term_bad, mb_hex, bad_hex);
835 free(good_hex);
839 * "check_merge_bases" checks that merge bases are not "bad" (or "new").
841 * - If one is "bad" (or "new"), it means the user assumed something wrong
842 * and we must return error with a non 0 error code.
843 * - If one is "good" (or "old"), that's good, we have nothing to do.
844 * - If one is "skipped", we can't know but we should warn.
845 * - If we don't know, we should check it out and ask the user to test.
846 * - If a merge base must be tested, on success return
847 * BISECT_INTERNAL_SUCCESS_MERGE_BASE (-11) a special condition
848 * for early success, this will be converted back to 0 in
849 * check_good_are_ancestors_of_bad().
851 static enum bisect_error check_merge_bases(int rev_nr, struct commit **rev, int no_checkout)
853 enum bisect_error res = BISECT_OK;
854 struct commit_list *result;
856 result = repo_get_merge_bases_many(the_repository, rev[0], rev_nr - 1,
857 rev + 1);
859 for (; result; result = result->next) {
860 const struct object_id *mb = &result->item->object.oid;
861 if (oideq(mb, current_bad_oid)) {
862 res = handle_bad_merge_base();
863 break;
864 } else if (0 <= oid_array_lookup(&good_revs, mb)) {
865 continue;
866 } else if (0 <= oid_array_lookup(&skipped_revs, mb)) {
867 handle_skipped_merge_base(mb);
868 } else {
869 printf(_("Bisecting: a merge base must be tested\n"));
870 res = bisect_checkout(mb, no_checkout);
871 if (!res)
872 /* indicate early success */
873 res = BISECT_INTERNAL_SUCCESS_MERGE_BASE;
874 break;
878 free_commit_list(result);
879 return res;
882 static int check_ancestors(struct repository *r, int rev_nr,
883 struct commit **rev, const char *prefix)
885 struct strvec rev_argv = STRVEC_INIT;
886 struct rev_info revs;
887 int res;
889 bisect_rev_setup(r, &revs, &rev_argv, prefix, "^%s", "%s", 0);
891 bisect_common(&revs);
892 res = (revs.commits != NULL);
894 /* Clean up objects used, as they will be reused. */
895 clear_commit_marks_many(rev_nr, rev, ALL_REV_FLAGS);
897 release_revisions(&revs);
898 strvec_clear(&rev_argv);
899 return res;
903 * "check_good_are_ancestors_of_bad" checks that all "good" revs are
904 * ancestor of the "bad" rev.
906 * If that's not the case, we need to check the merge bases.
907 * If a merge base must be tested by the user, its source code will be
908 * checked out to be tested by the user and we will return.
911 static enum bisect_error check_good_are_ancestors_of_bad(struct repository *r,
912 const char *prefix,
913 int no_checkout)
915 char *filename;
916 struct stat st;
917 int fd, rev_nr;
918 enum bisect_error res = BISECT_OK;
919 struct commit **rev;
921 if (!current_bad_oid)
922 return error(_("a %s revision is needed"), term_bad);
924 filename = git_pathdup("BISECT_ANCESTORS_OK");
926 /* Check if file BISECT_ANCESTORS_OK exists. */
927 if (!stat(filename, &st) && S_ISREG(st.st_mode))
928 goto done;
930 /* Bisecting with no good rev is ok. */
931 if (!good_revs.nr)
932 goto done;
934 /* Check if all good revs are ancestor of the bad rev. */
936 rev = get_bad_and_good_commits(r, &rev_nr);
937 if (check_ancestors(r, rev_nr, rev, prefix))
938 res = check_merge_bases(rev_nr, rev, no_checkout);
939 free(rev);
941 if (!res) {
942 /* Create file BISECT_ANCESTORS_OK. */
943 fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
944 if (fd < 0)
946 * BISECT_ANCESTORS_OK file is not absolutely necessary,
947 * the bisection process will continue at the next
948 * bisection step.
949 * So, just signal with a warning that something
950 * might be wrong.
952 warning_errno(_("could not create file '%s'"),
953 filename);
954 else
955 close(fd);
957 done:
958 free(filename);
959 return res;
963 * This does "git diff-tree --pretty COMMIT" without one fork+exec.
965 static void show_diff_tree(struct repository *r,
966 const char *prefix,
967 struct commit *commit)
969 const char *argv[] = {
970 "diff-tree", "--pretty", "--stat", "--summary", "--cc", NULL
972 struct rev_info opt;
974 git_config(git_diff_ui_config, NULL);
975 repo_init_revisions(r, &opt, prefix);
977 setup_revisions(ARRAY_SIZE(argv) - 1, argv, &opt, NULL);
978 log_tree_commit(&opt, commit);
979 release_revisions(&opt);
983 * The terms used for this bisect session are stored in BISECT_TERMS.
984 * We read them and store them to adapt the messages accordingly.
985 * Default is bad/good.
987 void read_bisect_terms(const char **read_bad, const char **read_good)
989 struct strbuf str = STRBUF_INIT;
990 const char *filename = git_path_bisect_terms();
991 FILE *fp = fopen(filename, "r");
993 if (!fp) {
994 if (errno == ENOENT) {
995 *read_bad = "bad";
996 *read_good = "good";
997 return;
998 } else {
999 die_errno(_("could not read file '%s'"), filename);
1001 } else {
1002 strbuf_getline_lf(&str, fp);
1003 *read_bad = strbuf_detach(&str, NULL);
1004 strbuf_getline_lf(&str, fp);
1005 *read_good = strbuf_detach(&str, NULL);
1007 strbuf_release(&str);
1008 fclose(fp);
1012 * We use the convention that return BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND (-10) means
1013 * the bisection process finished successfully.
1014 * In this case the calling function or command should not turn a
1015 * BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND return code into an error or a non zero exit code.
1017 * Checking BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND
1018 * in bisect_helper::bisect_next() and only transforming it to 0 at
1019 * the end of bisect_helper::cmd_bisect__helper() helps bypassing
1020 * all the code related to finding a commit to test.
1022 enum bisect_error bisect_next_all(struct repository *r, const char *prefix)
1024 struct strvec rev_argv = STRVEC_INIT;
1025 struct rev_info revs = REV_INFO_INIT;
1026 struct commit_list *tried;
1027 int reaches = 0, all = 0, nr, steps;
1028 enum bisect_error res = BISECT_OK;
1029 struct object_id *bisect_rev;
1030 char *steps_msg;
1032 * If no_checkout is non-zero, the bisection process does not
1033 * checkout the trial commit but instead simply updates BISECT_HEAD.
1035 int no_checkout = ref_exists("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_diff_tree(r, prefix, 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 for_each_ref_in("refs/bisect", mark_for_removal, (void *) &refs_for_removal);
1187 string_list_append(&refs_for_removal, xstrdup("BISECT_HEAD"));
1188 result = delete_refs("bisect: remove", &refs_for_removal, REF_NO_DEREF);
1189 refs_for_removal.strdup_strings = 1;
1190 string_list_clear(&refs_for_removal, 0);
1191 unlink_or_warn(git_path_bisect_expected_rev());
1192 unlink_or_warn(git_path_bisect_ancestors_ok());
1193 unlink_or_warn(git_path_bisect_log());
1194 unlink_or_warn(git_path_bisect_names());
1195 unlink_or_warn(git_path_bisect_run());
1196 unlink_or_warn(git_path_bisect_terms());
1197 unlink_or_warn(git_path_bisect_first_parent());
1199 * Cleanup BISECT_START last to support the --no-checkout option
1200 * introduced in the commit 4796e823a.
1202 unlink_or_warn(git_path_bisect_start());
1204 return result;