request-pull: update the "pull" command generation logic
[git] / bisect.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "diff.h"
4 #include "revision.h"
5 #include "refs.h"
6 #include "list-objects.h"
7 #include "quote.h"
8 #include "sha1-lookup.h"
9 #include "run-command.h"
10 #include "log-tree.h"
11 #include "bisect.h"
12 #include "sha1-array.h"
13
14 static struct sha1_array good_revs;
15 static struct sha1_array skipped_revs;
16
17 static const unsigned char *current_bad_sha1;
18
19 struct argv_array {
20         const char **argv;
21         int argv_nr;
22         int argv_alloc;
23 };
24
25 static const char *argv_checkout[] = {"checkout", "-q", NULL, "--", NULL};
26 static const char *argv_show_branch[] = {"show-branch", NULL, NULL};
27 static const char *argv_update_ref[] = {"update-ref", "--no-deref", "BISECT_HEAD", NULL, NULL};
28
29 /* bits #0-15 in revision.h */
30
31 #define COUNTED         (1u<<16)
32
33 /*
34  * This is a truly stupid algorithm, but it's only
35  * used for bisection, and we just don't care enough.
36  *
37  * We care just barely enough to avoid recursing for
38  * non-merge entries.
39  */
40 static int count_distance(struct commit_list *entry)
41 {
42         int nr = 0;
43
44         while (entry) {
45                 struct commit *commit = entry->item;
46                 struct commit_list *p;
47
48                 if (commit->object.flags & (UNINTERESTING | COUNTED))
49                         break;
50                 if (!(commit->object.flags & TREESAME))
51                         nr++;
52                 commit->object.flags |= COUNTED;
53                 p = commit->parents;
54                 entry = p;
55                 if (p) {
56                         p = p->next;
57                         while (p) {
58                                 nr += count_distance(p);
59                                 p = p->next;
60                         }
61                 }
62         }
63
64         return nr;
65 }
66
67 static void clear_distance(struct commit_list *list)
68 {
69         while (list) {
70                 struct commit *commit = list->item;
71                 commit->object.flags &= ~COUNTED;
72                 list = list->next;
73         }
74 }
75
76 #define DEBUG_BISECT 0
77
78 static inline int weight(struct commit_list *elem)
79 {
80         return *((int*)(elem->item->util));
81 }
82
83 static inline void weight_set(struct commit_list *elem, int weight)
84 {
85         *((int*)(elem->item->util)) = weight;
86 }
87
88 static int count_interesting_parents(struct commit *commit)
89 {
90         struct commit_list *p;
91         int count;
92
93         for (count = 0, p = commit->parents; p; p = p->next) {
94                 if (p->item->object.flags & UNINTERESTING)
95                         continue;
96                 count++;
97         }
98         return count;
99 }
100
101 static inline int halfway(struct commit_list *p, int nr)
102 {
103         /*
104          * Don't short-cut something we are not going to return!
105          */
106         if (p->item->object.flags & TREESAME)
107                 return 0;
108         if (DEBUG_BISECT)
109                 return 0;
110         /*
111          * 2 and 3 are halfway of 5.
112          * 3 is halfway of 6 but 2 and 4 are not.
113          */
114         switch (2 * weight(p) - nr) {
115         case -1: case 0: case 1:
116                 return 1;
117         default:
118                 return 0;
119         }
120 }
121
122 #if !DEBUG_BISECT
123 #define show_list(a,b,c,d) do { ; } while (0)
124 #else
125 static void show_list(const char *debug, int counted, int nr,
126                       struct commit_list *list)
127 {
128         struct commit_list *p;
129
130         fprintf(stderr, "%s (%d/%d)\n", debug, counted, nr);
131
132         for (p = list; p; p = p->next) {
133                 struct commit_list *pp;
134                 struct commit *commit = p->item;
135                 unsigned flags = commit->object.flags;
136                 enum object_type type;
137                 unsigned long size;
138                 char *buf = read_sha1_file(commit->object.sha1, &type, &size);
139                 const char *subject_start;
140                 int subject_len;
141
142                 fprintf(stderr, "%c%c%c ",
143                         (flags & TREESAME) ? ' ' : 'T',
144                         (flags & UNINTERESTING) ? 'U' : ' ',
145                         (flags & COUNTED) ? 'C' : ' ');
146                 if (commit->util)
147                         fprintf(stderr, "%3d", weight(p));
148                 else
149                         fprintf(stderr, "---");
150                 fprintf(stderr, " %.*s", 8, sha1_to_hex(commit->object.sha1));
151                 for (pp = commit->parents; pp; pp = pp->next)
152                         fprintf(stderr, " %.*s", 8,
153                                 sha1_to_hex(pp->item->object.sha1));
154
155                 subject_len = find_commit_subject(buf, &subject_start);
156                 if (subject_len)
157                         fprintf(stderr, " %.*s", subject_len, subject_start);
158                 fprintf(stderr, "\n");
159         }
160 }
161 #endif /* DEBUG_BISECT */
162
163 static struct commit_list *best_bisection(struct commit_list *list, int nr)
164 {
165         struct commit_list *p, *best;
166         int best_distance = -1;
167
168         best = list;
169         for (p = list; p; p = p->next) {
170                 int distance;
171                 unsigned flags = p->item->object.flags;
172
173                 if (flags & TREESAME)
174                         continue;
175                 distance = weight(p);
176                 if (nr - distance < distance)
177                         distance = nr - distance;
178                 if (distance > best_distance) {
179                         best = p;
180                         best_distance = distance;
181                 }
182         }
183
184         return best;
185 }
186
187 struct commit_dist {
188         struct commit *commit;
189         int distance;
190 };
191
192 static int compare_commit_dist(const void *a_, const void *b_)
193 {
194         struct commit_dist *a, *b;
195
196         a = (struct commit_dist *)a_;
197         b = (struct commit_dist *)b_;
198         if (a->distance != b->distance)
199                 return b->distance - a->distance; /* desc sort */
200         return hashcmp(a->commit->object.sha1, b->commit->object.sha1);
201 }
202
203 static struct commit_list *best_bisection_sorted(struct commit_list *list, int nr)
204 {
205         struct commit_list *p;
206         struct commit_dist *array = xcalloc(nr, sizeof(*array));
207         int cnt, i;
208
209         for (p = list, cnt = 0; p; p = p->next) {
210                 int distance;
211                 unsigned flags = p->item->object.flags;
212
213                 if (flags & TREESAME)
214                         continue;
215                 distance = weight(p);
216                 if (nr - distance < distance)
217                         distance = nr - distance;
218                 array[cnt].commit = p->item;
219                 array[cnt].distance = distance;
220                 cnt++;
221         }
222         qsort(array, cnt, sizeof(*array), compare_commit_dist);
223         for (p = list, i = 0; i < cnt; i++) {
224                 struct name_decoration *r = xmalloc(sizeof(*r) + 100);
225                 struct object *obj = &(array[i].commit->object);
226
227                 sprintf(r->name, "dist=%d", array[i].distance);
228                 r->next = add_decoration(&name_decoration, obj, r);
229                 p->item = array[i].commit;
230                 p = p->next;
231         }
232         if (p)
233                 p->next = NULL;
234         free(array);
235         return list;
236 }
237
238 /*
239  * zero or positive weight is the number of interesting commits it can
240  * reach, including itself.  Especially, weight = 0 means it does not
241  * reach any tree-changing commits (e.g. just above uninteresting one
242  * but traversal is with pathspec).
243  *
244  * weight = -1 means it has one parent and its distance is yet to
245  * be computed.
246  *
247  * weight = -2 means it has more than one parent and its distance is
248  * unknown.  After running count_distance() first, they will get zero
249  * or positive distance.
250  */
251 static struct commit_list *do_find_bisection(struct commit_list *list,
252                                              int nr, int *weights,
253                                              int find_all)
254 {
255         int n, counted;
256         struct commit_list *p;
257
258         counted = 0;
259
260         for (n = 0, p = list; p; p = p->next) {
261                 struct commit *commit = p->item;
262                 unsigned flags = commit->object.flags;
263
264                 p->item->util = &weights[n++];
265                 switch (count_interesting_parents(commit)) {
266                 case 0:
267                         if (!(flags & TREESAME)) {
268                                 weight_set(p, 1);
269                                 counted++;
270                                 show_list("bisection 2 count one",
271                                           counted, nr, list);
272                         }
273                         /*
274                          * otherwise, it is known not to reach any
275                          * tree-changing commit and gets weight 0.
276                          */
277                         break;
278                 case 1:
279                         weight_set(p, -1);
280                         break;
281                 default:
282                         weight_set(p, -2);
283                         break;
284                 }
285         }
286
287         show_list("bisection 2 initialize", counted, nr, list);
288
289         /*
290          * If you have only one parent in the resulting set
291          * then you can reach one commit more than that parent
292          * can reach.  So we do not have to run the expensive
293          * count_distance() for single strand of pearls.
294          *
295          * However, if you have more than one parents, you cannot
296          * just add their distance and one for yourself, since
297          * they usually reach the same ancestor and you would
298          * end up counting them twice that way.
299          *
300          * So we will first count distance of merges the usual
301          * way, and then fill the blanks using cheaper algorithm.
302          */
303         for (p = list; p; p = p->next) {
304                 if (p->item->object.flags & UNINTERESTING)
305                         continue;
306                 if (weight(p) != -2)
307                         continue;
308                 weight_set(p, count_distance(p));
309                 clear_distance(list);
310
311                 /* Does it happen to be at exactly half-way? */
312                 if (!find_all && halfway(p, nr))
313                         return p;
314                 counted++;
315         }
316
317         show_list("bisection 2 count_distance", counted, nr, list);
318
319         while (counted < nr) {
320                 for (p = list; p; p = p->next) {
321                         struct commit_list *q;
322                         unsigned flags = p->item->object.flags;
323
324                         if (0 <= weight(p))
325                                 continue;
326                         for (q = p->item->parents; q; q = q->next) {
327                                 if (q->item->object.flags & UNINTERESTING)
328                                         continue;
329                                 if (0 <= weight(q))
330                                         break;
331                         }
332                         if (!q)
333                                 continue;
334
335                         /*
336                          * weight for p is unknown but q is known.
337                          * add one for p itself if p is to be counted,
338                          * otherwise inherit it from q directly.
339                          */
340                         if (!(flags & TREESAME)) {
341                                 weight_set(p, weight(q)+1);
342                                 counted++;
343                                 show_list("bisection 2 count one",
344                                           counted, nr, list);
345                         }
346                         else
347                                 weight_set(p, weight(q));
348
349                         /* Does it happen to be at exactly half-way? */
350                         if (!find_all && halfway(p, nr))
351                                 return p;
352                 }
353         }
354
355         show_list("bisection 2 counted all", counted, nr, list);
356
357         if (!find_all)
358                 return best_bisection(list, nr);
359         else
360                 return best_bisection_sorted(list, nr);
361 }
362
363 struct commit_list *find_bisection(struct commit_list *list,
364                                           int *reaches, int *all,
365                                           int find_all)
366 {
367         int nr, on_list;
368         struct commit_list *p, *best, *next, *last;
369         int *weights;
370
371         show_list("bisection 2 entry", 0, 0, list);
372
373         /*
374          * Count the number of total and tree-changing items on the
375          * list, while reversing the list.
376          */
377         for (nr = on_list = 0, last = NULL, p = list;
378              p;
379              p = next) {
380                 unsigned flags = p->item->object.flags;
381
382                 next = p->next;
383                 if (flags & UNINTERESTING)
384                         continue;
385                 p->next = last;
386                 last = p;
387                 if (!(flags & TREESAME))
388                         nr++;
389                 on_list++;
390         }
391         list = last;
392         show_list("bisection 2 sorted", 0, nr, list);
393
394         *all = nr;
395         weights = xcalloc(on_list, sizeof(*weights));
396
397         /* Do the real work of finding bisection commit. */
398         best = do_find_bisection(list, nr, weights, find_all);
399         if (best) {
400                 if (!find_all)
401                         best->next = NULL;
402                 *reaches = weight(best);
403         }
404         free(weights);
405         return best;
406 }
407
408 static void argv_array_push(struct argv_array *array, const char *string)
409 {
410         ALLOC_GROW(array->argv, array->argv_nr + 1, array->argv_alloc);
411         array->argv[array->argv_nr++] = string;
412 }
413
414 static void argv_array_push_sha1(struct argv_array *array,
415                                  const unsigned char *sha1,
416                                  const char *format)
417 {
418         struct strbuf buf = STRBUF_INIT;
419         strbuf_addf(&buf, format, sha1_to_hex(sha1));
420         argv_array_push(array, strbuf_detach(&buf, NULL));
421 }
422
423 static int register_ref(const char *refname, const unsigned char *sha1,
424                         int flags, void *cb_data)
425 {
426         if (!strcmp(refname, "bad")) {
427                 current_bad_sha1 = sha1;
428         } else if (!prefixcmp(refname, "good-")) {
429                 sha1_array_append(&good_revs, sha1);
430         } else if (!prefixcmp(refname, "skip-")) {
431                 sha1_array_append(&skipped_revs, sha1);
432         }
433
434         return 0;
435 }
436
437 static int read_bisect_refs(void)
438 {
439         return for_each_ref_in("refs/bisect/", register_ref, NULL);
440 }
441
442 static void read_bisect_paths(struct argv_array *array)
443 {
444         struct strbuf str = STRBUF_INIT;
445         const char *filename = git_path("BISECT_NAMES");
446         FILE *fp = fopen(filename, "r");
447
448         if (!fp)
449                 die_errno("Could not open file '%s'", filename);
450
451         while (strbuf_getline(&str, fp, '\n') != EOF) {
452                 char *quoted;
453                 int res;
454
455                 strbuf_trim(&str);
456                 quoted = strbuf_detach(&str, NULL);
457                 res = sq_dequote_to_argv(quoted, &array->argv,
458                                          &array->argv_nr, &array->argv_alloc);
459                 if (res)
460                         die("Badly quoted content in file '%s': %s",
461                             filename, quoted);
462         }
463
464         strbuf_release(&str);
465         fclose(fp);
466 }
467
468 static char *join_sha1_array_hex(struct sha1_array *array, char delim)
469 {
470         struct strbuf joined_hexs = STRBUF_INIT;
471         int i;
472
473         for (i = 0; i < array->nr; i++) {
474                 strbuf_addstr(&joined_hexs, sha1_to_hex(array->sha1[i]));
475                 if (i + 1 < array->nr)
476                         strbuf_addch(&joined_hexs, delim);
477         }
478
479         return strbuf_detach(&joined_hexs, NULL);
480 }
481
482 /*
483  * In this function, passing a not NULL skipped_first is very special.
484  * It means that we want to know if the first commit in the list is
485  * skipped because we will want to test a commit away from it if it is
486  * indeed skipped.
487  * So if the first commit is skipped, we cannot take the shortcut to
488  * just "return list" when we find the first non skipped commit, we
489  * have to return a fully filtered list.
490  *
491  * We use (*skipped_first == -1) to mean "it has been found that the
492  * first commit is not skipped". In this case *skipped_first is set back
493  * to 0 just before the function returns.
494  */
495 struct commit_list *filter_skipped(struct commit_list *list,
496                                    struct commit_list **tried,
497                                    int show_all,
498                                    int *count,
499                                    int *skipped_first)
500 {
501         struct commit_list *filtered = NULL, **f = &filtered;
502
503         *tried = NULL;
504
505         if (skipped_first)
506                 *skipped_first = 0;
507         if (count)
508                 *count = 0;
509
510         if (!skipped_revs.nr)
511                 return list;
512
513         while (list) {
514                 struct commit_list *next = list->next;
515                 list->next = NULL;
516                 if (0 <= sha1_array_lookup(&skipped_revs,
517                                            list->item->object.sha1)) {
518                         if (skipped_first && !*skipped_first)
519                                 *skipped_first = 1;
520                         /* Move current to tried list */
521                         *tried = list;
522                         tried = &list->next;
523                 } else {
524                         if (!show_all) {
525                                 if (!skipped_first || !*skipped_first)
526                                         return list;
527                         } else if (skipped_first && !*skipped_first) {
528                                 /* This means we know it's not skipped */
529                                 *skipped_first = -1;
530                         }
531                         /* Move current to filtered list */
532                         *f = list;
533                         f = &list->next;
534                         if (count)
535                                 (*count)++;
536                 }
537                 list = next;
538         }
539
540         if (skipped_first && *skipped_first == -1)
541                 *skipped_first = 0;
542
543         return filtered;
544 }
545
546 #define PRN_MODULO 32768
547
548 /*
549  * This is a pseudo random number generator based on "man 3 rand".
550  * It is not used properly because the seed is the argument and it
551  * is increased by one between each call, but that should not matter
552  * for this application.
553  */
554 static int get_prn(int count) {
555         count = count * 1103515245 + 12345;
556         return ((unsigned)(count/65536) % PRN_MODULO);
557 }
558
559 /*
560  * Custom integer square root from
561  * http://en.wikipedia.org/wiki/Integer_square_root
562  */
563 static int sqrti(int val)
564 {
565         float d, x = val;
566
567         if (val == 0)
568                 return 0;
569
570         do {
571                 float y = (x + (float)val / x) / 2;
572                 d = (y > x) ? y - x : x - y;
573                 x = y;
574         } while (d >= 0.5);
575
576         return (int)x;
577 }
578
579 static struct commit_list *skip_away(struct commit_list *list, int count)
580 {
581         struct commit_list *cur, *previous;
582         int prn, index, i;
583
584         prn = get_prn(count);
585         index = (count * prn / PRN_MODULO) * sqrti(prn) / sqrti(PRN_MODULO);
586
587         cur = list;
588         previous = NULL;
589
590         for (i = 0; cur; cur = cur->next, i++) {
591                 if (i == index) {
592                         if (hashcmp(cur->item->object.sha1, current_bad_sha1))
593                                 return cur;
594                         if (previous)
595                                 return previous;
596                         return list;
597                 }
598                 previous = cur;
599         }
600
601         return list;
602 }
603
604 static struct commit_list *managed_skipped(struct commit_list *list,
605                                            struct commit_list **tried)
606 {
607         int count, skipped_first;
608
609         *tried = NULL;
610
611         if (!skipped_revs.nr)
612                 return list;
613
614         list = filter_skipped(list, tried, 0, &count, &skipped_first);
615
616         if (!skipped_first)
617                 return list;
618
619         return skip_away(list, count);
620 }
621
622 static void bisect_rev_setup(struct rev_info *revs, const char *prefix,
623                              const char *bad_format, const char *good_format,
624                              int read_paths)
625 {
626         struct argv_array rev_argv = { NULL, 0, 0 };
627         int i;
628
629         init_revisions(revs, prefix);
630         revs->abbrev = 0;
631         revs->commit_format = CMIT_FMT_UNSPECIFIED;
632
633         /* rev_argv.argv[0] will be ignored by setup_revisions */
634         argv_array_push(&rev_argv, xstrdup("bisect_rev_setup"));
635         argv_array_push_sha1(&rev_argv, current_bad_sha1, bad_format);
636         for (i = 0; i < good_revs.nr; i++)
637                 argv_array_push_sha1(&rev_argv, good_revs.sha1[i],
638                                      good_format);
639         argv_array_push(&rev_argv, xstrdup("--"));
640         if (read_paths)
641                 read_bisect_paths(&rev_argv);
642         argv_array_push(&rev_argv, NULL);
643
644         setup_revisions(rev_argv.argv_nr, rev_argv.argv, revs, NULL);
645 }
646
647 static void bisect_common(struct rev_info *revs)
648 {
649         if (prepare_revision_walk(revs))
650                 die("revision walk setup failed");
651         if (revs->tree_objects)
652                 mark_edges_uninteresting(revs->commits, revs, NULL);
653 }
654
655 static void exit_if_skipped_commits(struct commit_list *tried,
656                                     const unsigned char *bad)
657 {
658         if (!tried)
659                 return;
660
661         printf("There are only 'skip'ped commits left to test.\n"
662                "The first bad commit could be any of:\n");
663         print_commit_list(tried, "%s\n", "%s\n");
664         if (bad)
665                 printf("%s\n", sha1_to_hex(bad));
666         printf("We cannot bisect more!\n");
667         exit(2);
668 }
669
670 static int is_expected_rev(const unsigned char *sha1)
671 {
672         const char *filename = git_path("BISECT_EXPECTED_REV");
673         struct stat st;
674         struct strbuf str = STRBUF_INIT;
675         FILE *fp;
676         int res = 0;
677
678         if (stat(filename, &st) || !S_ISREG(st.st_mode))
679                 return 0;
680
681         fp = fopen(filename, "r");
682         if (!fp)
683                 return 0;
684
685         if (strbuf_getline(&str, fp, '\n') != EOF)
686                 res = !strcmp(str.buf, sha1_to_hex(sha1));
687
688         strbuf_release(&str);
689         fclose(fp);
690
691         return res;
692 }
693
694 static void mark_expected_rev(char *bisect_rev_hex)
695 {
696         int len = strlen(bisect_rev_hex);
697         const char *filename = git_path("BISECT_EXPECTED_REV");
698         int fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
699
700         if (fd < 0)
701                 die_errno("could not create file '%s'", filename);
702
703         bisect_rev_hex[len] = '\n';
704         write_or_die(fd, bisect_rev_hex, len + 1);
705         bisect_rev_hex[len] = '\0';
706
707         if (close(fd) < 0)
708                 die("closing file %s: %s", filename, strerror(errno));
709 }
710
711 static int bisect_checkout(char *bisect_rev_hex, int no_checkout)
712 {
713         int res;
714
715         mark_expected_rev(bisect_rev_hex);
716
717         argv_checkout[2] = bisect_rev_hex;
718         if (no_checkout) {
719                 argv_update_ref[3] = bisect_rev_hex;
720                 if (run_command_v_opt(argv_update_ref, RUN_GIT_CMD))
721                         die("update-ref --no-deref HEAD failed on %s",
722                             bisect_rev_hex);
723         } else {
724                 res = run_command_v_opt(argv_checkout, RUN_GIT_CMD);
725                 if (res)
726                         exit(res);
727         }
728
729         argv_show_branch[1] = bisect_rev_hex;
730         return run_command_v_opt(argv_show_branch, RUN_GIT_CMD);
731 }
732
733 static struct commit *get_commit_reference(const unsigned char *sha1)
734 {
735         struct commit *r = lookup_commit_reference(sha1);
736         if (!r)
737                 die("Not a valid commit name %s", sha1_to_hex(sha1));
738         return r;
739 }
740
741 static struct commit **get_bad_and_good_commits(int *rev_nr)
742 {
743         int len = 1 + good_revs.nr;
744         struct commit **rev = xmalloc(len * sizeof(*rev));
745         int i, n = 0;
746
747         rev[n++] = get_commit_reference(current_bad_sha1);
748         for (i = 0; i < good_revs.nr; i++)
749                 rev[n++] = get_commit_reference(good_revs.sha1[i]);
750         *rev_nr = n;
751
752         return rev;
753 }
754
755 static void handle_bad_merge_base(void)
756 {
757         if (is_expected_rev(current_bad_sha1)) {
758                 char *bad_hex = sha1_to_hex(current_bad_sha1);
759                 char *good_hex = join_sha1_array_hex(&good_revs, ' ');
760
761                 fprintf(stderr, "The merge base %s is bad.\n"
762                         "This means the bug has been fixed "
763                         "between %s and [%s].\n",
764                         bad_hex, bad_hex, good_hex);
765
766                 exit(3);
767         }
768
769         fprintf(stderr, "Some good revs are not ancestor of the bad rev.\n"
770                 "git bisect cannot work properly in this case.\n"
771                 "Maybe you mistake good and bad revs?\n");
772         exit(1);
773 }
774
775 static void handle_skipped_merge_base(const unsigned char *mb)
776 {
777         char *mb_hex = sha1_to_hex(mb);
778         char *bad_hex = sha1_to_hex(current_bad_sha1);
779         char *good_hex = join_sha1_array_hex(&good_revs, ' ');
780
781         warning("the merge base between %s and [%s] "
782                 "must be skipped.\n"
783                 "So we cannot be sure the first bad commit is "
784                 "between %s and %s.\n"
785                 "We continue anyway.",
786                 bad_hex, good_hex, mb_hex, bad_hex);
787         free(good_hex);
788 }
789
790 /*
791  * "check_merge_bases" checks that merge bases are not "bad".
792  *
793  * - If one is "bad", it means the user assumed something wrong
794  * and we must exit with a non 0 error code.
795  * - If one is "good", that's good, we have nothing to do.
796  * - If one is "skipped", we can't know but we should warn.
797  * - If we don't know, we should check it out and ask the user to test.
798  */
799 static void check_merge_bases(int no_checkout)
800 {
801         struct commit_list *result;
802         int rev_nr;
803         struct commit **rev = get_bad_and_good_commits(&rev_nr);
804
805         result = get_merge_bases_many(rev[0], rev_nr - 1, rev + 1, 0);
806
807         for (; result; result = result->next) {
808                 const unsigned char *mb = result->item->object.sha1;
809                 if (!hashcmp(mb, current_bad_sha1)) {
810                         handle_bad_merge_base();
811                 } else if (0 <= sha1_array_lookup(&good_revs, mb)) {
812                         continue;
813                 } else if (0 <= sha1_array_lookup(&skipped_revs, mb)) {
814                         handle_skipped_merge_base(mb);
815                 } else {
816                         printf("Bisecting: a merge base must be tested\n");
817                         exit(bisect_checkout(sha1_to_hex(mb), no_checkout));
818                 }
819         }
820
821         free(rev);
822         free_commit_list(result);
823 }
824
825 static int check_ancestors(const char *prefix)
826 {
827         struct rev_info revs;
828         struct object_array pending_copy;
829         int i, res;
830
831         bisect_rev_setup(&revs, prefix, "^%s", "%s", 0);
832
833         /* Save pending objects, so they can be cleaned up later. */
834         memset(&pending_copy, 0, sizeof(pending_copy));
835         for (i = 0; i < revs.pending.nr; i++)
836                 add_object_array(revs.pending.objects[i].item,
837                                  revs.pending.objects[i].name,
838                                  &pending_copy);
839
840         bisect_common(&revs);
841         res = (revs.commits != NULL);
842
843         /* Clean up objects used, as they will be reused. */
844         for (i = 0; i < pending_copy.nr; i++) {
845                 struct object *o = pending_copy.objects[i].item;
846                 clear_commit_marks((struct commit *)o, ALL_REV_FLAGS);
847         }
848
849         return res;
850 }
851
852 /*
853  * "check_good_are_ancestors_of_bad" checks that all "good" revs are
854  * ancestor of the "bad" rev.
855  *
856  * If that's not the case, we need to check the merge bases.
857  * If a merge base must be tested by the user, its source code will be
858  * checked out to be tested by the user and we will exit.
859  */
860 static void check_good_are_ancestors_of_bad(const char *prefix, int no_checkout)
861 {
862         const char *filename = git_path("BISECT_ANCESTORS_OK");
863         struct stat st;
864         int fd;
865
866         if (!current_bad_sha1)
867                 die("a bad revision is needed");
868
869         /* Check if file BISECT_ANCESTORS_OK exists. */
870         if (!stat(filename, &st) && S_ISREG(st.st_mode))
871                 return;
872
873         /* Bisecting with no good rev is ok. */
874         if (good_revs.nr == 0)
875                 return;
876
877         /* Check if all good revs are ancestor of the bad rev. */
878         if (check_ancestors(prefix))
879                 check_merge_bases(no_checkout);
880
881         /* Create file BISECT_ANCESTORS_OK. */
882         fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
883         if (fd < 0)
884                 warning("could not create file '%s': %s",
885                         filename, strerror(errno));
886         else
887                 close(fd);
888 }
889
890 /*
891  * This does "git diff-tree --pretty COMMIT" without one fork+exec.
892  */
893 static void show_diff_tree(const char *prefix, struct commit *commit)
894 {
895         struct rev_info opt;
896
897         /* diff-tree init */
898         init_revisions(&opt, prefix);
899         git_config(git_diff_basic_config, NULL); /* no "diff" UI options */
900         opt.abbrev = 0;
901         opt.diff = 1;
902
903         /* This is what "--pretty" does */
904         opt.verbose_header = 1;
905         opt.use_terminator = 0;
906         opt.commit_format = CMIT_FMT_DEFAULT;
907
908         /* diff-tree init */
909         if (!opt.diffopt.output_format)
910                 opt.diffopt.output_format = DIFF_FORMAT_RAW;
911
912         log_tree_commit(&opt, commit);
913 }
914
915 /*
916  * We use the convention that exiting with an exit code 10 means that
917  * the bisection process finished successfully.
918  * In this case the calling shell script should exit 0.
919  *
920  * If no_checkout is non-zero, the bisection process does not
921  * checkout the trial commit but instead simply updates BISECT_HEAD.
922  */
923 int bisect_next_all(const char *prefix, int no_checkout)
924 {
925         struct rev_info revs;
926         struct commit_list *tried;
927         int reaches = 0, all = 0, nr, steps;
928         const unsigned char *bisect_rev;
929         char bisect_rev_hex[41];
930
931         if (read_bisect_refs())
932                 die("reading bisect refs failed");
933
934         check_good_are_ancestors_of_bad(prefix, no_checkout);
935
936         bisect_rev_setup(&revs, prefix, "%s", "^%s", 1);
937         revs.limited = 1;
938
939         bisect_common(&revs);
940
941         revs.commits = find_bisection(revs.commits, &reaches, &all,
942                                        !!skipped_revs.nr);
943         revs.commits = managed_skipped(revs.commits, &tried);
944
945         if (!revs.commits) {
946                 /*
947                  * We should exit here only if the "bad"
948                  * commit is also a "skip" commit.
949                  */
950                 exit_if_skipped_commits(tried, NULL);
951
952                 printf("%s was both good and bad\n",
953                        sha1_to_hex(current_bad_sha1));
954                 exit(1);
955         }
956
957         if (!all) {
958                 fprintf(stderr, "No testable commit found.\n"
959                         "Maybe you started with bad path parameters?\n");
960                 exit(4);
961         }
962
963         bisect_rev = revs.commits->item->object.sha1;
964         memcpy(bisect_rev_hex, sha1_to_hex(bisect_rev), 41);
965
966         if (!hashcmp(bisect_rev, current_bad_sha1)) {
967                 exit_if_skipped_commits(tried, current_bad_sha1);
968                 printf("%s is the first bad commit\n", bisect_rev_hex);
969                 show_diff_tree(prefix, revs.commits->item);
970                 /* This means the bisection process succeeded. */
971                 exit(10);
972         }
973
974         nr = all - reaches - 1;
975         steps = estimate_bisect_steps(all);
976         printf("Bisecting: %d revision%s left to test after this "
977                "(roughly %d step%s)\n", nr, (nr == 1 ? "" : "s"),
978                steps, (steps == 1 ? "" : "s"));
979
980         return bisect_checkout(bisect_rev_hex, no_checkout);
981 }
982