Merge branch 'jn/mergetool-hideresolved-is-optional'
[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                 if (get_oid(*argv, &oid)){
878                         error(_("Bad rev input: %s"), *argv);
879                         oid_array_clear(&revs);
880                         return BISECT_FAILED;
881                 }
882                 oid_array_append(&revs, &oid);
883         }
884
885         if (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
886             get_oid_hex(buf.buf, &expected) < 0)
887                 verify_expected = 0; /* Ignore invalid file contents */
888         strbuf_release(&buf);
889
890         for (i = 0; i < revs.nr; i++) {
891                 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
892                         oid_array_clear(&revs);
893                         return BISECT_FAILED;
894                 }
895                 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
896                         unlink_or_warn(git_path_bisect_ancestors_ok());
897                         unlink_or_warn(git_path_bisect_expected_rev());
898                         verify_expected = 0;
899                 }
900         }
901
902         oid_array_clear(&revs);
903         return bisect_auto_next(terms, NULL);
904 }
905
906 static enum bisect_error bisect_log(void)
907 {
908         int fd, status;
909         const char* filename = git_path_bisect_log();
910
911         if (is_empty_or_missing_file(filename))
912                 return error(_("We are not bisecting."));
913
914         fd = open(filename, O_RDONLY);
915         if (fd < 0)
916                 return BISECT_FAILED;
917
918         status = copy_fd(fd, STDOUT_FILENO);
919         close(fd);
920         return status ? BISECT_FAILED : BISECT_OK;
921 }
922
923 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
924 {
925         const char *p = line->buf + strspn(line->buf, " \t");
926         char *word_end, *rev;
927
928         if ((!skip_prefix(p, "git bisect", &p) &&
929         !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
930                 return 0;
931         p += strspn(p, " \t");
932
933         word_end = (char *)p + strcspn(p, " \t");
934         rev = word_end + strspn(word_end, " \t");
935         *word_end = '\0'; /* NUL-terminate the word */
936
937         get_terms(terms);
938         if (check_and_set_terms(terms, p))
939                 return -1;
940
941         if (!strcmp(p, "start")) {
942                 struct strvec argv = STRVEC_INIT;
943                 int res;
944                 sq_dequote_to_strvec(rev, &argv);
945                 res = bisect_start(terms, argv.v, argv.nr);
946                 strvec_clear(&argv);
947                 return res;
948         }
949
950         if (one_of(p, terms->term_good,
951            terms->term_bad, "skip", NULL))
952                 return bisect_write(p, rev, terms, 0);
953
954         if (!strcmp(p, "terms")) {
955                 struct strvec argv = STRVEC_INIT;
956                 int res;
957                 sq_dequote_to_strvec(rev, &argv);
958                 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
959                 strvec_clear(&argv);
960                 return res;
961         }
962         error(_("'%s'?? what are you talking about?"), p);
963
964         return -1;
965 }
966
967 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
968 {
969         FILE *fp = NULL;
970         enum bisect_error res = BISECT_OK;
971         struct strbuf line = STRBUF_INIT;
972
973         if (is_empty_or_missing_file(filename))
974                 return error(_("cannot read file '%s' for replaying"), filename);
975
976         if (bisect_reset(NULL))
977                 return BISECT_FAILED;
978
979         fp = fopen(filename, "r");
980         if (!fp)
981                 return BISECT_FAILED;
982
983         while ((strbuf_getline(&line, fp) != EOF) && !res)
984                 res = process_replay_line(terms, &line);
985
986         strbuf_release(&line);
987         fclose(fp);
988
989         if (res)
990                 return BISECT_FAILED;
991
992         return bisect_auto_next(terms, NULL);
993 }
994
995 static enum bisect_error bisect_skip(struct bisect_terms *terms, const char **argv, int argc)
996 {
997         int i;
998         enum bisect_error res;
999         struct strvec argv_state = STRVEC_INIT;
1000
1001         strvec_push(&argv_state, "skip");
1002
1003         for (i = 0; i < argc; i++) {
1004                 const char *dotdot = strstr(argv[i], "..");
1005
1006                 if (dotdot) {
1007                         struct rev_info revs;
1008                         struct commit *commit;
1009
1010                         init_revisions(&revs, NULL);
1011                         setup_revisions(2, argv + i - 1, &revs, NULL);
1012
1013                         if (prepare_revision_walk(&revs))
1014                                 die(_("revision walk setup failed\n"));
1015                         while ((commit = get_revision(&revs)) != NULL)
1016                                 strvec_push(&argv_state,
1017                                                 oid_to_hex(&commit->object.oid));
1018
1019                         reset_revision_walk();
1020                 } else {
1021                         strvec_push(&argv_state, argv[i]);
1022                 }
1023         }
1024         res = bisect_state(terms, argv_state.v, argv_state.nr);
1025
1026         strvec_clear(&argv_state);
1027         return res;
1028 }
1029
1030 int cmd_bisect__helper(int argc, const char **argv, const char *prefix)
1031 {
1032         enum {
1033                 BISECT_RESET = 1,
1034                 BISECT_NEXT_CHECK,
1035                 BISECT_TERMS,
1036                 BISECT_START,
1037                 BISECT_AUTOSTART,
1038                 BISECT_NEXT,
1039                 BISECT_STATE,
1040                 BISECT_LOG,
1041                 BISECT_REPLAY,
1042                 BISECT_SKIP
1043         } cmdmode = 0;
1044         int res = 0, nolog = 0;
1045         struct option options[] = {
1046                 OPT_CMDMODE(0, "bisect-reset", &cmdmode,
1047                          N_("reset the bisection state"), BISECT_RESET),
1048                 OPT_CMDMODE(0, "bisect-next-check", &cmdmode,
1049                          N_("check whether bad or good terms exist"), BISECT_NEXT_CHECK),
1050                 OPT_CMDMODE(0, "bisect-terms", &cmdmode,
1051                          N_("print out the bisect terms"), BISECT_TERMS),
1052                 OPT_CMDMODE(0, "bisect-start", &cmdmode,
1053                          N_("start the bisect session"), BISECT_START),
1054                 OPT_CMDMODE(0, "bisect-next", &cmdmode,
1055                          N_("find the next bisection commit"), BISECT_NEXT),
1056                 OPT_CMDMODE(0, "bisect-state", &cmdmode,
1057                          N_("mark the state of ref (or refs)"), BISECT_STATE),
1058                 OPT_CMDMODE(0, "bisect-log", &cmdmode,
1059                          N_("list the bisection steps so far"), BISECT_LOG),
1060                 OPT_CMDMODE(0, "bisect-replay", &cmdmode,
1061                          N_("replay the bisection process from the given file"), BISECT_REPLAY),
1062                 OPT_CMDMODE(0, "bisect-skip", &cmdmode,
1063                          N_("skip some commits for checkout"), BISECT_SKIP),
1064                 OPT_BOOL(0, "no-log", &nolog,
1065                          N_("no log for BISECT_WRITE")),
1066                 OPT_END()
1067         };
1068         struct bisect_terms terms = { .term_good = NULL, .term_bad = NULL };
1069
1070         argc = parse_options(argc, argv, prefix, options,
1071                              git_bisect_helper_usage,
1072                              PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_UNKNOWN);
1073
1074         if (!cmdmode)
1075                 usage_with_options(git_bisect_helper_usage, options);
1076
1077         switch (cmdmode) {
1078         case BISECT_RESET:
1079                 if (argc > 1)
1080                         return error(_("--bisect-reset requires either no argument or a commit"));
1081                 res = bisect_reset(argc ? argv[0] : NULL);
1082                 break;
1083         case BISECT_NEXT_CHECK:
1084                 if (argc != 2 && argc != 3)
1085                         return error(_("--bisect-next-check requires 2 or 3 arguments"));
1086                 set_terms(&terms, argv[1], argv[0]);
1087                 res = bisect_next_check(&terms, argc == 3 ? argv[2] : NULL);
1088                 break;
1089         case BISECT_TERMS:
1090                 if (argc > 1)
1091                         return error(_("--bisect-terms requires 0 or 1 argument"));
1092                 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1093                 break;
1094         case BISECT_START:
1095                 set_terms(&terms, "bad", "good");
1096                 res = bisect_start(&terms, argv, argc);
1097                 break;
1098         case BISECT_NEXT:
1099                 if (argc)
1100                         return error(_("--bisect-next requires 0 arguments"));
1101                 get_terms(&terms);
1102                 res = bisect_next(&terms, prefix);
1103                 break;
1104         case BISECT_STATE:
1105                 set_terms(&terms, "bad", "good");
1106                 get_terms(&terms);
1107                 res = bisect_state(&terms, argv, argc);
1108                 break;
1109         case BISECT_LOG:
1110                 if (argc)
1111                         return error(_("--bisect-log requires 0 arguments"));
1112                 res = bisect_log();
1113                 break;
1114         case BISECT_REPLAY:
1115                 if (argc != 1)
1116                         return error(_("no logfile given"));
1117                 set_terms(&terms, "bad", "good");
1118                 res = bisect_replay(&terms, argv[0]);
1119                 break;
1120         case BISECT_SKIP:
1121                 set_terms(&terms, "bad", "good");
1122                 res = bisect_skip(&terms, argv, argc);
1123                 break;
1124         default:
1125                 BUG("unknown subcommand %d", cmdmode);
1126         }
1127         free_terms(&terms);
1128
1129         /*
1130          * Handle early success
1131          * From check_merge_bases > check_good_are_ancestors_of_bad > bisect_next_all
1132          */
1133         if ((res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) || (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND))
1134                 res = BISECT_OK;
1135
1136         return -res;
1137 }