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