Merge branch 'ds/commit-graph-merging-fix'
[git] / builtin / bisect--helper.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "bisect.h"
5 #include "refs.h"
6 #include "dir.h"
7 #include "strvec.h"
8 #include "run-command.h"
9 #include "prompt.h"
10 #include "quote.h"
11 #include "revision.h"
12
13 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
14 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
15 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
16 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
17 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
18 static GIT_PATH_FUNC(git_path_head_name, "head-name")
19 static GIT_PATH_FUNC(git_path_bisect_names, "BISECT_NAMES")
20 static GIT_PATH_FUNC(git_path_bisect_first_parent, "BISECT_FIRST_PARENT")
21
22 static const char * const git_bisect_helper_usage[] = {
23         N_("git bisect--helper --next-all"),
24         N_("git bisect--helper --write-terms <bad_term> <good_term>"),
25         N_("git bisect--helper --bisect-clean-state"),
26         N_("git bisect--helper --bisect-reset [<commit>]"),
27         N_("git bisect--helper --bisect-write [--no-log] <state> <revision> <good_term> <bad_term>"),
28         N_("git bisect--helper --bisect-check-and-set-terms <command> <good_term> <bad_term>"),
29         N_("git bisect--helper --bisect-next-check <good_term> <bad_term> [<term>]"),
30         N_("git bisect--helper --bisect-terms [--term-good | --term-old | --term-bad | --term-new]"),
31         N_("git bisect--helper --bisect-start [--term-{new,bad}=<term> --term-{old,good}=<term>]"
32                                             " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--] [<paths>...]"),
33         N_("git bisect--helper --bisect-next"),
34         N_("git bisect--helper --bisect-auto-next"),
35         N_("git bisect--helper --bisect-autostart"),
36         NULL
37 };
38
39 struct add_bisect_ref_data {
40         struct rev_info *revs;
41         unsigned int object_flags;
42 };
43
44 struct bisect_terms {
45         char *term_good;
46         char *term_bad;
47 };
48
49 static void free_terms(struct bisect_terms *terms)
50 {
51         FREE_AND_NULL(terms->term_good);
52         FREE_AND_NULL(terms->term_bad);
53 }
54
55 static void set_terms(struct bisect_terms *terms, const char *bad,
56                       const char *good)
57 {
58         free((void *)terms->term_good);
59         terms->term_good = xstrdup(good);
60         free((void *)terms->term_bad);
61         terms->term_bad = xstrdup(bad);
62 }
63
64 static const char vocab_bad[] = "bad|new";
65 static const char vocab_good[] = "good|old";
66
67 static int bisect_autostart(struct bisect_terms *terms);
68
69 /*
70  * Check whether the string `term` belongs to the set of strings
71  * included in the variable arguments.
72  */
73 LAST_ARG_MUST_BE_NULL
74 static int one_of(const char *term, ...)
75 {
76         int res = 0;
77         va_list matches;
78         const char *match;
79
80         va_start(matches, term);
81         while (!res && (match = va_arg(matches, const char *)))
82                 res = !strcmp(term, match);
83         va_end(matches);
84
85         return res;
86 }
87
88 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
89 {
90         FILE *fp = NULL;
91         int res = 0;
92
93         if (strcmp(mode, "w") && strcmp(mode, "a"))
94                 BUG("write-in-file does not support '%s' mode", mode);
95         fp = fopen(path, mode);
96         if (!fp)
97                 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
98         res = vfprintf(fp, format, args);
99
100         if (res < 0) {
101                 int saved_errno = errno;
102                 fclose(fp);
103                 errno = saved_errno;
104                 return error_errno(_("could not write to file '%s'"), path);
105         }
106
107         return fclose(fp);
108 }
109
110 static int write_to_file(const char *path, const char *format, ...)
111 {
112         int res;
113         va_list args;
114
115         va_start(args, format);
116         res = write_in_file(path, "w", format, args);
117         va_end(args);
118
119         return res;
120 }
121
122 static int append_to_file(const char *path, const char *format, ...)
123 {
124         int res;
125         va_list args;
126
127         va_start(args, format);
128         res = write_in_file(path, "a", format, args);
129         va_end(args);
130
131         return res;
132 }
133
134 static int check_term_format(const char *term, const char *orig_term)
135 {
136         int res;
137         char *new_term = xstrfmt("refs/bisect/%s", term);
138
139         res = check_refname_format(new_term, 0);
140         free(new_term);
141
142         if (res)
143                 return error(_("'%s' is not a valid term"), term);
144
145         if (one_of(term, "help", "start", "skip", "next", "reset",
146                         "visualize", "view", "replay", "log", "run", "terms", NULL))
147                 return error(_("can't use the builtin command '%s' as a term"), term);
148
149         /*
150          * In theory, nothing prevents swapping completely good and bad,
151          * but this situation could be confusing and hasn't been tested
152          * enough. Forbid it for now.
153          */
154
155         if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
156                  (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
157                 return error(_("can't change the meaning of the term '%s'"), term);
158
159         return 0;
160 }
161
162 static int write_terms(const char *bad, const char *good)
163 {
164         int res;
165
166         if (!strcmp(bad, good))
167                 return error(_("please use two different terms"));
168
169         if (check_term_format(bad, "bad") || check_term_format(good, "good"))
170                 return -1;
171
172         res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
173
174         return res;
175 }
176
177 static int is_expected_rev(const char *expected_hex)
178 {
179         struct strbuf actual_hex = STRBUF_INIT;
180         int res = 0;
181         if (strbuf_read_file(&actual_hex, git_path_bisect_expected_rev(), 0) >= 40) {
182                 strbuf_trim(&actual_hex);
183                 res = !strcmp(actual_hex.buf, expected_hex);
184         }
185         strbuf_release(&actual_hex);
186         return res;
187 }
188
189 static void check_expected_revs(const char **revs, int rev_nr)
190 {
191         int i;
192
193         for (i = 0; i < rev_nr; i++) {
194                 if (!is_expected_rev(revs[i])) {
195                         unlink_or_warn(git_path_bisect_ancestors_ok());
196                         unlink_or_warn(git_path_bisect_expected_rev());
197                 }
198         }
199 }
200
201 static int bisect_reset(const char *commit)
202 {
203         struct strbuf branch = STRBUF_INIT;
204
205         if (!commit) {
206                 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
207                         printf(_("We are not bisecting.\n"));
208                         return 0;
209                 }
210                 strbuf_rtrim(&branch);
211         } else {
212                 struct object_id oid;
213
214                 if (get_oid_commit(commit, &oid))
215                         return error(_("'%s' is not a valid commit"), commit);
216                 strbuf_addstr(&branch, commit);
217         }
218
219         if (!ref_exists("BISECT_HEAD")) {
220                 struct strvec argv = STRVEC_INIT;
221
222                 strvec_pushl(&argv, "checkout", branch.buf, "--", NULL);
223                 if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
224                         error(_("could not check out original"
225                                 " HEAD '%s'. Try 'git bisect"
226                                 " reset <commit>'."), branch.buf);
227                         strbuf_release(&branch);
228                         strvec_clear(&argv);
229                         return -1;
230                 }
231                 strvec_clear(&argv);
232         }
233
234         strbuf_release(&branch);
235         return bisect_clean_state();
236 }
237
238 static void log_commit(FILE *fp, char *fmt, const char *state,
239                        struct commit *commit)
240 {
241         struct pretty_print_context pp = {0};
242         struct strbuf commit_msg = STRBUF_INIT;
243         char *label = xstrfmt(fmt, state);
244
245         format_commit_message(commit, "%s", &commit_msg, &pp);
246
247         fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
248                 commit_msg.buf);
249
250         strbuf_release(&commit_msg);
251         free(label);
252 }
253
254 static int bisect_write(const char *state, const char *rev,
255                         const struct bisect_terms *terms, int nolog)
256 {
257         struct strbuf tag = STRBUF_INIT;
258         struct object_id oid;
259         struct commit *commit;
260         FILE *fp = NULL;
261         int res = 0;
262
263         if (!strcmp(state, terms->term_bad)) {
264                 strbuf_addf(&tag, "refs/bisect/%s", state);
265         } else if (one_of(state, terms->term_good, "skip", NULL)) {
266                 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
267         } else {
268                 res = error(_("Bad bisect_write argument: %s"), state);
269                 goto finish;
270         }
271
272         if (get_oid(rev, &oid)) {
273                 res = error(_("couldn't get the oid of the rev '%s'"), rev);
274                 goto finish;
275         }
276
277         if (update_ref(NULL, tag.buf, &oid, NULL, 0,
278                        UPDATE_REFS_MSG_ON_ERR)) {
279                 res = -1;
280                 goto finish;
281         }
282
283         fp = fopen(git_path_bisect_log(), "a");
284         if (!fp) {
285                 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
286                 goto finish;
287         }
288
289         commit = lookup_commit_reference(the_repository, &oid);
290         log_commit(fp, "%s", state, commit);
291
292         if (!nolog)
293                 fprintf(fp, "git bisect %s %s\n", state, rev);
294
295 finish:
296         if (fp)
297                 fclose(fp);
298         strbuf_release(&tag);
299         return res;
300 }
301
302 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
303 {
304         int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
305
306         if (one_of(cmd, "skip", "start", "terms", NULL))
307                 return 0;
308
309         if (has_term_file && strcmp(cmd, terms->term_bad) &&
310             strcmp(cmd, terms->term_good))
311                 return error(_("Invalid command: you're currently in a "
312                                 "%s/%s bisect"), terms->term_bad,
313                                 terms->term_good);
314
315         if (!has_term_file) {
316                 if (one_of(cmd, "bad", "good", NULL)) {
317                         set_terms(terms, "bad", "good");
318                         return write_terms(terms->term_bad, terms->term_good);
319                 }
320                 if (one_of(cmd, "new", "old", NULL)) {
321                         set_terms(terms, "new", "old");
322                         return write_terms(terms->term_bad, terms->term_good);
323                 }
324         }
325
326         return 0;
327 }
328
329 static int mark_good(const char *refname, const struct object_id *oid,
330                      int flag, void *cb_data)
331 {
332         int *m_good = (int *)cb_data;
333         *m_good = 0;
334         return 1;
335 }
336
337 static const char need_bad_and_good_revision_warning[] =
338         N_("You need to give me at least one %s and %s revision.\n"
339            "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
340
341 static const char need_bisect_start_warning[] =
342         N_("You need to start by \"git bisect start\".\n"
343            "You then need to give me at least one %s and %s revision.\n"
344            "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
345
346 static int decide_next(const struct bisect_terms *terms,
347                        const char *current_term, int missing_good,
348                        int missing_bad)
349 {
350         if (!missing_good && !missing_bad)
351                 return 0;
352         if (!current_term)
353                 return -1;
354
355         if (missing_good && !missing_bad &&
356             !strcmp(current_term, terms->term_good)) {
357                 char *yesno;
358                 /*
359                  * have bad (or new) but not good (or old). We could bisect
360                  * although this is less optimum.
361                  */
362                 warning(_("bisecting only with a %s commit"), terms->term_bad);
363                 if (!isatty(0))
364                         return 0;
365                 /*
366                  * TRANSLATORS: Make sure to include [Y] and [n] in your
367                  * translation. The program will only accept English input
368                  * at this point.
369                  */
370                 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
371                 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
372                         return -1;
373                 return 0;
374         }
375
376         if (!is_empty_or_missing_file(git_path_bisect_start()))
377                 return error(_(need_bad_and_good_revision_warning),
378                              vocab_bad, vocab_good, vocab_bad, vocab_good);
379         else
380                 return error(_(need_bisect_start_warning),
381                              vocab_good, vocab_bad, vocab_good, vocab_bad);
382 }
383
384 static int bisect_next_check(const struct bisect_terms *terms,
385                              const char *current_term)
386 {
387         int missing_good = 1, missing_bad = 1;
388         char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
389         char *good_glob = xstrfmt("%s-*", terms->term_good);
390
391         if (ref_exists(bad_ref))
392                 missing_bad = 0;
393
394         for_each_glob_ref_in(mark_good, good_glob, "refs/bisect/",
395                              (void *) &missing_good);
396
397         free(good_glob);
398         free(bad_ref);
399
400         return decide_next(terms, current_term, missing_good, missing_bad);
401 }
402
403 static int get_terms(struct bisect_terms *terms)
404 {
405         struct strbuf str = STRBUF_INIT;
406         FILE *fp = NULL;
407         int res = 0;
408
409         fp = fopen(git_path_bisect_terms(), "r");
410         if (!fp) {
411                 res = -1;
412                 goto finish;
413         }
414
415         free_terms(terms);
416         strbuf_getline_lf(&str, fp);
417         terms->term_bad = strbuf_detach(&str, NULL);
418         strbuf_getline_lf(&str, fp);
419         terms->term_good = strbuf_detach(&str, NULL);
420
421 finish:
422         if (fp)
423                 fclose(fp);
424         strbuf_release(&str);
425         return res;
426 }
427
428 static int bisect_terms(struct bisect_terms *terms, const char *option)
429 {
430         if (get_terms(terms))
431                 return error(_("no terms defined"));
432
433         if (option == NULL) {
434                 printf(_("Your current terms are %s for the old state\n"
435                          "and %s for the new state.\n"),
436                        terms->term_good, terms->term_bad);
437                 return 0;
438         }
439         if (one_of(option, "--term-good", "--term-old", NULL))
440                 printf("%s\n", terms->term_good);
441         else if (one_of(option, "--term-bad", "--term-new", NULL))
442                 printf("%s\n", terms->term_bad);
443         else
444                 return error(_("invalid argument %s for 'git bisect terms'.\n"
445                                "Supported options are: "
446                                "--term-good|--term-old and "
447                                "--term-bad|--term-new."), option);
448
449         return 0;
450 }
451
452 static int bisect_append_log_quoted(const char **argv)
453 {
454         int res = 0;
455         FILE *fp = fopen(git_path_bisect_log(), "a");
456         struct strbuf orig_args = STRBUF_INIT;
457
458         if (!fp)
459                 return -1;
460
461         if (fprintf(fp, "git bisect start") < 1) {
462                 res = -1;
463                 goto finish;
464         }
465
466         sq_quote_argv(&orig_args, argv);
467         if (fprintf(fp, "%s\n", orig_args.buf) < 1)
468                 res = -1;
469
470 finish:
471         fclose(fp);
472         strbuf_release(&orig_args);
473         return res;
474 }
475
476 static int add_bisect_ref(const char *refname, const struct object_id *oid,
477                           int flags, void *cb)
478 {
479         struct add_bisect_ref_data *data = cb;
480
481         add_pending_oid(data->revs, refname, oid, data->object_flags);
482
483         return 0;
484 }
485
486 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
487 {
488         int res = 0;
489         struct add_bisect_ref_data cb = { revs };
490         char *good = xstrfmt("%s-*", terms->term_good);
491
492         /*
493          * We cannot use terms->term_bad directly in
494          * for_each_glob_ref_in() and we have to append a '*' to it,
495          * otherwise for_each_glob_ref_in() will append '/' and '*'.
496          */
497         char *bad = xstrfmt("%s*", terms->term_bad);
498
499         /*
500          * It is important to reset the flags used by revision walks
501          * as the previous call to bisect_next_all() in turn
502          * sets up a revision walk.
503          */
504         reset_revision_walk();
505         init_revisions(revs, NULL);
506         setup_revisions(0, NULL, revs, NULL);
507         for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
508         cb.object_flags = UNINTERESTING;
509         for_each_glob_ref_in(add_bisect_ref, good, "refs/bisect/", &cb);
510         if (prepare_revision_walk(revs))
511                 res = error(_("revision walk setup failed\n"));
512
513         free(good);
514         free(bad);
515         return res;
516 }
517
518 static int bisect_skipped_commits(struct bisect_terms *terms)
519 {
520         int res;
521         FILE *fp = NULL;
522         struct rev_info revs;
523         struct commit *commit;
524         struct pretty_print_context pp = {0};
525         struct strbuf commit_name = STRBUF_INIT;
526
527         res = prepare_revs(terms, &revs);
528         if (res)
529                 return res;
530
531         fp = fopen(git_path_bisect_log(), "a");
532         if (!fp)
533                 return error_errno(_("could not open '%s' for appending"),
534                                   git_path_bisect_log());
535
536         if (fprintf(fp, "# only skipped commits left to test\n") < 0)
537                 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
538
539         while ((commit = get_revision(&revs)) != NULL) {
540                 strbuf_reset(&commit_name);
541                 format_commit_message(commit, "%s",
542                                       &commit_name, &pp);
543                 fprintf(fp, "# possible first %s commit: [%s] %s\n",
544                         terms->term_bad, oid_to_hex(&commit->object.oid),
545                         commit_name.buf);
546         }
547
548         /*
549          * Reset the flags used by revision walks in case
550          * there is another revision walk after this one.
551          */
552         reset_revision_walk();
553
554         strbuf_release(&commit_name);
555         fclose(fp);
556         return 0;
557 }
558
559 static int bisect_successful(struct bisect_terms *terms)
560 {
561         struct object_id oid;
562         struct commit *commit;
563         struct pretty_print_context pp = {0};
564         struct strbuf commit_name = STRBUF_INIT;
565         char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
566         int res;
567
568         read_ref(bad_ref, &oid);
569         commit = lookup_commit_reference_by_name(bad_ref);
570         format_commit_message(commit, "%s", &commit_name, &pp);
571
572         res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
573                             terms->term_bad, oid_to_hex(&commit->object.oid),
574                             commit_name.buf);
575
576         strbuf_release(&commit_name);
577         free(bad_ref);
578         return res;
579 }
580
581 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
582 {
583         enum bisect_error res;
584
585         if (bisect_autostart(terms))
586                 return BISECT_FAILED;
587
588         if (bisect_next_check(terms, terms->term_good))
589                 return BISECT_FAILED;
590
591         /* Perform all bisection computation */
592         res = bisect_next_all(the_repository, prefix);
593
594         if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
595                 res = bisect_successful(terms);
596                 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
597         } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
598                 res = bisect_skipped_commits(terms);
599                 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
600         }
601         return res;
602 }
603
604 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
605 {
606         if (bisect_next_check(terms, NULL))
607                 return BISECT_OK;
608
609         return bisect_next(terms, prefix);
610 }
611
612 static int bisect_start(struct bisect_terms *terms, const char **argv, int argc)
613 {
614         int no_checkout = 0;
615         int first_parent_only = 0;
616         int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
617         int flags, pathspec_pos, res = 0;
618         struct string_list revs = STRING_LIST_INIT_DUP;
619         struct string_list states = STRING_LIST_INIT_DUP;
620         struct strbuf start_head = STRBUF_INIT;
621         struct strbuf bisect_names = STRBUF_INIT;
622         struct object_id head_oid;
623         struct object_id oid;
624         const char *head;
625
626         if (is_bare_repository())
627                 no_checkout = 1;
628
629         /*
630          * Check for one bad and then some good revisions
631          */
632         for (i = 0; i < argc; i++) {
633                 if (!strcmp(argv[i], "--")) {
634                         has_double_dash = 1;
635                         break;
636                 }
637         }
638
639         for (i = 0; i < argc; i++) {
640                 const char *arg = argv[i];
641                 if (!strcmp(argv[i], "--")) {
642                         break;
643                 } else if (!strcmp(arg, "--no-checkout")) {
644                         no_checkout = 1;
645                 } else if (!strcmp(arg, "--first-parent")) {
646                         first_parent_only = 1;
647                 } else if (!strcmp(arg, "--term-good") ||
648                          !strcmp(arg, "--term-old")) {
649                         i++;
650                         if (argc <= i)
651                                 return error(_("'' is not a valid term"));
652                         must_write_terms = 1;
653                         free((void *) terms->term_good);
654                         terms->term_good = xstrdup(argv[i]);
655                 } else if (skip_prefix(arg, "--term-good=", &arg) ||
656                            skip_prefix(arg, "--term-old=", &arg)) {
657                         must_write_terms = 1;
658                         free((void *) terms->term_good);
659                         terms->term_good = xstrdup(arg);
660                 } else if (!strcmp(arg, "--term-bad") ||
661                          !strcmp(arg, "--term-new")) {
662                         i++;
663                         if (argc <= i)
664                                 return error(_("'' is not a valid term"));
665                         must_write_terms = 1;
666                         free((void *) terms->term_bad);
667                         terms->term_bad = xstrdup(argv[i]);
668                 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
669                            skip_prefix(arg, "--term-new=", &arg)) {
670                         must_write_terms = 1;
671                         free((void *) terms->term_bad);
672                         terms->term_bad = xstrdup(arg);
673                 } else if (starts_with(arg, "--")) {
674                         return error(_("unrecognized option: '%s'"), arg);
675                 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
676                         string_list_append(&revs, oid_to_hex(&oid));
677                 } else if (has_double_dash) {
678                         die(_("'%s' does not appear to be a valid "
679                               "revision"), arg);
680                 } else {
681                         break;
682                 }
683         }
684         pathspec_pos = i;
685
686         /*
687          * The user ran "git bisect start <sha1> <sha1>", hence did not
688          * explicitly specify the terms, but we are already starting to
689          * set references named with the default terms, and won't be able
690          * to change afterwards.
691          */
692         if (revs.nr)
693                 must_write_terms = 1;
694         for (i = 0; i < revs.nr; i++) {
695                 if (bad_seen) {
696                         string_list_append(&states, terms->term_good);
697                 } else {
698                         bad_seen = 1;
699                         string_list_append(&states, terms->term_bad);
700                 }
701         }
702
703         /*
704          * Verify HEAD
705          */
706         head = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
707         if (!head)
708                 if (get_oid("HEAD", &head_oid))
709                         return error(_("bad HEAD - I need a HEAD"));
710
711         /*
712          * Check if we are bisecting
713          */
714         if (!is_empty_or_missing_file(git_path_bisect_start())) {
715                 /* Reset to the rev from where we started */
716                 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
717                 strbuf_trim(&start_head);
718                 if (!no_checkout) {
719                         struct strvec argv = STRVEC_INIT;
720
721                         strvec_pushl(&argv, "checkout", start_head.buf,
722                                      "--", NULL);
723                         if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
724                                 res = error(_("checking out '%s' failed."
725                                                  " Try 'git bisect start "
726                                                  "<valid-branch>'."),
727                                                start_head.buf);
728                                 goto finish;
729                         }
730                 }
731         } else {
732                 /* Get the rev from where we start. */
733                 if (!get_oid(head, &head_oid) &&
734                     !starts_with(head, "refs/heads/")) {
735                         strbuf_reset(&start_head);
736                         strbuf_addstr(&start_head, oid_to_hex(&head_oid));
737                 } else if (!get_oid(head, &head_oid) &&
738                            skip_prefix(head, "refs/heads/", &head)) {
739                         /*
740                          * This error message should only be triggered by
741                          * cogito usage, and cogito users should understand
742                          * it relates to cg-seek.
743                          */
744                         if (!is_empty_or_missing_file(git_path_head_name()))
745                                 return error(_("won't bisect on cg-seek'ed tree"));
746                         strbuf_addstr(&start_head, head);
747                 } else {
748                         return error(_("bad HEAD - strange symbolic ref"));
749                 }
750         }
751
752         /*
753          * Get rid of any old bisect state.
754          */
755         if (bisect_clean_state())
756                 return -1;
757
758         /*
759          * In case of mistaken revs or checkout error, or signals received,
760          * "bisect_auto_next" below may exit or misbehave.
761          * We have to trap this to be able to clean up using
762          * "bisect_clean_state".
763          */
764
765         /*
766          * Write new start state
767          */
768         write_file(git_path_bisect_start(), "%s\n", start_head.buf);
769
770         if (first_parent_only)
771                 write_file(git_path_bisect_first_parent(), "\n");
772
773         if (no_checkout) {
774                 if (get_oid(start_head.buf, &oid) < 0) {
775                         res = error(_("invalid ref: '%s'"), start_head.buf);
776                         goto finish;
777                 }
778                 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
779                                UPDATE_REFS_MSG_ON_ERR)) {
780                         res = -1;
781                         goto finish;
782                 }
783         }
784
785         if (pathspec_pos < argc - 1)
786                 sq_quote_argv(&bisect_names, argv + pathspec_pos);
787         write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
788
789         for (i = 0; i < states.nr; i++)
790                 if (bisect_write(states.items[i].string,
791                                  revs.items[i].string, terms, 1)) {
792                         res = -1;
793                         goto finish;
794                 }
795
796         if (must_write_terms && write_terms(terms->term_bad,
797                                             terms->term_good)) {
798                 res = -1;
799                 goto finish;
800         }
801
802         res = bisect_append_log_quoted(argv);
803         if (res)
804                 res = -1;
805
806 finish:
807         string_list_clear(&revs, 0);
808         string_list_clear(&states, 0);
809         strbuf_release(&start_head);
810         strbuf_release(&bisect_names);
811         return res;
812 }
813
814 static inline int file_is_not_empty(const char *path)
815 {
816         return !is_empty_or_missing_file(path);
817 }
818
819 static int bisect_autostart(struct bisect_terms *terms)
820 {
821         int res;
822         const char *yesno;
823
824         if (file_is_not_empty(git_path_bisect_start()))
825                 return 0;
826
827         fprintf_ln(stderr, _("You need to start by \"git bisect "
828                           "start\"\n"));
829
830         if (!isatty(STDIN_FILENO))
831                 return -1;
832
833         /*
834          * TRANSLATORS: Make sure to include [Y] and [n] in your
835          * translation. The program will only accept English input
836          * at this point.
837          */
838         yesno = git_prompt(_("Do you want me to do it for you "
839                              "[Y/n]? "), PROMPT_ECHO);
840         res = tolower(*yesno) == 'n' ?
841                 -1 : bisect_start(terms, empty_strvec, 0);
842
843         return res;
844 }
845
846 int cmd_bisect__helper(int argc, const char **argv, const char *prefix)
847 {
848         enum {
849                 NEXT_ALL = 1,
850                 WRITE_TERMS,
851                 BISECT_CLEAN_STATE,
852                 CHECK_EXPECTED_REVS,
853                 BISECT_RESET,
854                 BISECT_WRITE,
855                 CHECK_AND_SET_TERMS,
856                 BISECT_NEXT_CHECK,
857                 BISECT_TERMS,
858                 BISECT_START,
859                 BISECT_AUTOSTART,
860                 BISECT_NEXT,
861                 BISECT_AUTO_NEXT
862         } cmdmode = 0;
863         int res = 0, nolog = 0;
864         struct option options[] = {
865                 OPT_CMDMODE(0, "next-all", &cmdmode,
866                          N_("perform 'git bisect next'"), NEXT_ALL),
867                 OPT_CMDMODE(0, "write-terms", &cmdmode,
868                          N_("write the terms to .git/BISECT_TERMS"), WRITE_TERMS),
869                 OPT_CMDMODE(0, "bisect-clean-state", &cmdmode,
870                          N_("cleanup the bisection state"), BISECT_CLEAN_STATE),
871                 OPT_CMDMODE(0, "check-expected-revs", &cmdmode,
872                          N_("check for expected revs"), CHECK_EXPECTED_REVS),
873                 OPT_CMDMODE(0, "bisect-reset", &cmdmode,
874                          N_("reset the bisection state"), BISECT_RESET),
875                 OPT_CMDMODE(0, "bisect-write", &cmdmode,
876                          N_("write out the bisection state in BISECT_LOG"), BISECT_WRITE),
877                 OPT_CMDMODE(0, "check-and-set-terms", &cmdmode,
878                          N_("check and set terms in a bisection state"), CHECK_AND_SET_TERMS),
879                 OPT_CMDMODE(0, "bisect-next-check", &cmdmode,
880                          N_("check whether bad or good terms exist"), BISECT_NEXT_CHECK),
881                 OPT_CMDMODE(0, "bisect-terms", &cmdmode,
882                          N_("print out the bisect terms"), BISECT_TERMS),
883                 OPT_CMDMODE(0, "bisect-start", &cmdmode,
884                          N_("start the bisect session"), BISECT_START),
885                 OPT_CMDMODE(0, "bisect-next", &cmdmode,
886                          N_("find the next bisection commit"), BISECT_NEXT),
887                 OPT_CMDMODE(0, "bisect-auto-next", &cmdmode,
888                          N_("verify the next bisection state then checkout the next bisection commit"), BISECT_AUTO_NEXT),
889                 OPT_CMDMODE(0, "bisect-autostart", &cmdmode,
890                          N_("start the bisection if it has not yet been started"), BISECT_AUTOSTART),
891                 OPT_BOOL(0, "no-log", &nolog,
892                          N_("no log for BISECT_WRITE")),
893                 OPT_END()
894         };
895         struct bisect_terms terms = { .term_good = NULL, .term_bad = NULL };
896
897         argc = parse_options(argc, argv, prefix, options,
898                              git_bisect_helper_usage,
899                              PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_UNKNOWN);
900
901         if (!cmdmode)
902                 usage_with_options(git_bisect_helper_usage, options);
903
904         switch (cmdmode) {
905         case NEXT_ALL:
906                 res = bisect_next_all(the_repository, prefix);
907                 break;
908         case WRITE_TERMS:
909                 if (argc != 2)
910                         return error(_("--write-terms requires two arguments"));
911                 return write_terms(argv[0], argv[1]);
912         case BISECT_CLEAN_STATE:
913                 if (argc != 0)
914                         return error(_("--bisect-clean-state requires no arguments"));
915                 return bisect_clean_state();
916         case CHECK_EXPECTED_REVS:
917                 check_expected_revs(argv, argc);
918                 return 0;
919         case BISECT_RESET:
920                 if (argc > 1)
921                         return error(_("--bisect-reset requires either no argument or a commit"));
922                 return !!bisect_reset(argc ? argv[0] : NULL);
923         case BISECT_WRITE:
924                 if (argc != 4 && argc != 5)
925                         return error(_("--bisect-write requires either 4 or 5 arguments"));
926                 set_terms(&terms, argv[3], argv[2]);
927                 res = bisect_write(argv[0], argv[1], &terms, nolog);
928                 break;
929         case CHECK_AND_SET_TERMS:
930                 if (argc != 3)
931                         return error(_("--check-and-set-terms requires 3 arguments"));
932                 set_terms(&terms, argv[2], argv[1]);
933                 res = check_and_set_terms(&terms, argv[0]);
934                 break;
935         case BISECT_NEXT_CHECK:
936                 if (argc != 2 && argc != 3)
937                         return error(_("--bisect-next-check requires 2 or 3 arguments"));
938                 set_terms(&terms, argv[1], argv[0]);
939                 res = bisect_next_check(&terms, argc == 3 ? argv[2] : NULL);
940                 break;
941         case BISECT_TERMS:
942                 if (argc > 1)
943                         return error(_("--bisect-terms requires 0 or 1 argument"));
944                 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
945                 break;
946         case BISECT_START:
947                 set_terms(&terms, "bad", "good");
948                 res = bisect_start(&terms, argv, argc);
949                 break;
950         case BISECT_NEXT:
951                 if (argc)
952                         return error(_("--bisect-next requires 0 arguments"));
953                 get_terms(&terms);
954                 res = bisect_next(&terms, prefix);
955                 break;
956         case BISECT_AUTO_NEXT:
957                 if (argc)
958                         return error(_("--bisect-auto-next requires 0 arguments"));
959                 get_terms(&terms);
960                 res = bisect_auto_next(&terms, prefix);
961                 break;
962         case BISECT_AUTOSTART:
963                 if (argc)
964                         return error(_("--bisect-autostart does not accept arguments"));
965                 set_terms(&terms, "bad", "good");
966                 res = bisect_autostart(&terms);
967                 break;
968         default:
969                 BUG("unknown subcommand %d", cmdmode);
970         }
971         free_terms(&terms);
972
973         /*
974          * Handle early success
975          * From check_merge_bases > check_good_are_ancestors_of_bad > bisect_next_all
976          */
977         if ((res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) || (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND))
978                 res = BISECT_OK;
979
980         return -res;
981 }