Sync with 2.38.5
[git.git] / builtin / bisect--helper.c
blob6e41cbdb2d3785cadb5ab901586585daee8718e0
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"
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 static GIT_PATH_FUNC(git_path_bisect_run, "BISECT_RUN")
23 static const char * const git_bisect_helper_usage[] = {
24 N_("git bisect--helper --bisect-reset [<commit>]"),
25 "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 "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 "git bisect--helper --bisect-visualize",
34 N_("git bisect--helper --bisect-run <cmd>..."),
35 NULL
38 struct add_bisect_ref_data {
39 struct rev_info *revs;
40 unsigned int object_flags;
43 struct bisect_terms {
44 char *term_good;
45 char *term_bad;
48 static void free_terms(struct bisect_terms *terms)
50 FREE_AND_NULL(terms->term_good);
51 FREE_AND_NULL(terms->term_bad);
54 static void set_terms(struct bisect_terms *terms, const char *bad,
55 const char *good)
57 free((void *)terms->term_good);
58 terms->term_good = xstrdup(good);
59 free((void *)terms->term_bad);
60 terms->term_bad = xstrdup(bad);
63 static const char vocab_bad[] = "bad|new";
64 static const char vocab_good[] = "good|old";
66 static int bisect_autostart(struct bisect_terms *terms);
69 * Check whether the string `term` belongs to the set of strings
70 * included in the variable arguments.
72 LAST_ARG_MUST_BE_NULL
73 static int one_of(const char *term, ...)
75 int res = 0;
76 va_list matches;
77 const char *match;
79 va_start(matches, term);
80 while (!res && (match = va_arg(matches, const char *)))
81 res = !strcmp(term, match);
82 va_end(matches);
84 return res;
88 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
89 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
90 * that indicate special success.
93 static int is_bisect_success(enum bisect_error res)
95 return !res ||
96 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
97 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
100 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
102 FILE *fp = NULL;
103 int res = 0;
105 if (strcmp(mode, "w") && strcmp(mode, "a"))
106 BUG("write-in-file does not support '%s' mode", mode);
107 fp = fopen(path, mode);
108 if (!fp)
109 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
110 res = vfprintf(fp, format, args);
112 if (res < 0) {
113 int saved_errno = errno;
114 fclose(fp);
115 errno = saved_errno;
116 return error_errno(_("could not write to file '%s'"), path);
119 return fclose(fp);
122 __attribute__((format (printf, 2, 3)))
123 static int write_to_file(const char *path, const char *format, ...)
125 int res;
126 va_list args;
128 va_start(args, format);
129 res = write_in_file(path, "w", format, args);
130 va_end(args);
132 return res;
135 __attribute__((format (printf, 2, 3)))
136 static int append_to_file(const char *path, const char *format, ...)
138 int res;
139 va_list args;
141 va_start(args, format);
142 res = write_in_file(path, "a", format, args);
143 va_end(args);
145 return res;
148 static int print_file_to_stdout(const char *path)
150 int fd = open(path, O_RDONLY);
151 int ret = 0;
153 if (fd < 0)
154 return error_errno(_("cannot open file '%s' for reading"), path);
155 if (copy_fd(fd, 1) < 0)
156 ret = error_errno(_("failed to read '%s'"), path);
157 close(fd);
158 return ret;
161 static int check_term_format(const char *term, const char *orig_term)
163 int res;
164 char *new_term = xstrfmt("refs/bisect/%s", term);
166 res = check_refname_format(new_term, 0);
167 free(new_term);
169 if (res)
170 return error(_("'%s' is not a valid term"), term);
172 if (one_of(term, "help", "start", "skip", "next", "reset",
173 "visualize", "view", "replay", "log", "run", "terms", NULL))
174 return error(_("can't use the builtin command '%s' as a term"), term);
177 * In theory, nothing prevents swapping completely good and bad,
178 * but this situation could be confusing and hasn't been tested
179 * enough. Forbid it for now.
182 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
183 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
184 return error(_("can't change the meaning of the term '%s'"), term);
186 return 0;
189 static int write_terms(const char *bad, const char *good)
191 int res;
193 if (!strcmp(bad, good))
194 return error(_("please use two different terms"));
196 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
197 return -1;
199 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
201 return res;
204 static int bisect_reset(const char *commit)
206 struct strbuf branch = STRBUF_INIT;
208 if (!commit) {
209 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
210 printf(_("We are not bisecting.\n"));
211 return 0;
213 strbuf_rtrim(&branch);
214 } else {
215 struct object_id oid;
217 if (get_oid_commit(commit, &oid))
218 return error(_("'%s' is not a valid commit"), commit);
219 strbuf_addstr(&branch, commit);
222 if (!ref_exists("BISECT_HEAD")) {
223 struct child_process cmd = CHILD_PROCESS_INIT;
225 cmd.git_cmd = 1;
226 strvec_pushl(&cmd.args, "checkout", branch.buf, "--", NULL);
227 if (run_command(&cmd)) {
228 error(_("could not check out original"
229 " HEAD '%s'. Try 'git bisect"
230 " reset <commit>'."), branch.buf);
231 strbuf_release(&branch);
232 return -1;
236 strbuf_release(&branch);
237 return bisect_clean_state();
240 static void log_commit(FILE *fp, char *fmt, const char *state,
241 struct commit *commit)
243 struct pretty_print_context pp = {0};
244 struct strbuf commit_msg = STRBUF_INIT;
245 char *label = xstrfmt(fmt, state);
247 format_commit_message(commit, "%s", &commit_msg, &pp);
249 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
250 commit_msg.buf);
252 strbuf_release(&commit_msg);
253 free(label);
256 static int bisect_write(const char *state, const char *rev,
257 const struct bisect_terms *terms, int nolog)
259 struct strbuf tag = STRBUF_INIT;
260 struct object_id oid;
261 struct commit *commit;
262 FILE *fp = NULL;
263 int res = 0;
265 if (!strcmp(state, terms->term_bad)) {
266 strbuf_addf(&tag, "refs/bisect/%s", state);
267 } else if (one_of(state, terms->term_good, "skip", NULL)) {
268 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
269 } else {
270 res = error(_("Bad bisect_write argument: %s"), state);
271 goto finish;
274 if (get_oid(rev, &oid)) {
275 res = error(_("couldn't get the oid of the rev '%s'"), rev);
276 goto finish;
279 if (update_ref(NULL, tag.buf, &oid, NULL, 0,
280 UPDATE_REFS_MSG_ON_ERR)) {
281 res = -1;
282 goto finish;
285 fp = fopen(git_path_bisect_log(), "a");
286 if (!fp) {
287 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
288 goto finish;
291 commit = lookup_commit_reference(the_repository, &oid);
292 log_commit(fp, "%s", state, commit);
294 if (!nolog)
295 fprintf(fp, "git bisect %s %s\n", state, rev);
297 finish:
298 if (fp)
299 fclose(fp);
300 strbuf_release(&tag);
301 return res;
304 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
306 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
308 if (one_of(cmd, "skip", "start", "terms", NULL))
309 return 0;
311 if (has_term_file && strcmp(cmd, terms->term_bad) &&
312 strcmp(cmd, terms->term_good))
313 return error(_("Invalid command: you're currently in a "
314 "%s/%s bisect"), terms->term_bad,
315 terms->term_good);
317 if (!has_term_file) {
318 if (one_of(cmd, "bad", "good", NULL)) {
319 set_terms(terms, "bad", "good");
320 return write_terms(terms->term_bad, terms->term_good);
322 if (one_of(cmd, "new", "old", NULL)) {
323 set_terms(terms, "new", "old");
324 return write_terms(terms->term_bad, terms->term_good);
328 return 0;
331 static int inc_nr(const char *refname UNUSED,
332 const struct object_id *oid UNUSED,
333 int flag UNUSED, void *cb_data)
335 unsigned int *nr = (unsigned int *)cb_data;
336 (*nr)++;
337 return 0;
340 static const char need_bad_and_good_revision_warning[] =
341 N_("You need to give me at least one %s and %s revision.\n"
342 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
344 static const char need_bisect_start_warning[] =
345 N_("You need to start by \"git bisect start\".\n"
346 "You then need to give me at least one %s and %s revision.\n"
347 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
349 static int decide_next(const struct bisect_terms *terms,
350 const char *current_term, int missing_good,
351 int missing_bad)
353 if (!missing_good && !missing_bad)
354 return 0;
355 if (!current_term)
356 return -1;
358 if (missing_good && !missing_bad &&
359 !strcmp(current_term, terms->term_good)) {
360 char *yesno;
362 * have bad (or new) but not good (or old). We could bisect
363 * although this is less optimum.
365 warning(_("bisecting only with a %s commit"), terms->term_bad);
366 if (!isatty(0))
367 return 0;
369 * TRANSLATORS: Make sure to include [Y] and [n] in your
370 * translation. The program will only accept English input
371 * at this point.
373 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
374 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
375 return -1;
376 return 0;
379 if (!is_empty_or_missing_file(git_path_bisect_start()))
380 return error(_(need_bad_and_good_revision_warning),
381 vocab_bad, vocab_good, vocab_bad, vocab_good);
382 else
383 return error(_(need_bisect_start_warning),
384 vocab_good, vocab_bad, vocab_good, vocab_bad);
387 static void bisect_status(struct bisect_state *state,
388 const struct bisect_terms *terms)
390 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
391 char *good_glob = xstrfmt("%s-*", terms->term_good);
393 if (ref_exists(bad_ref))
394 state->nr_bad = 1;
396 for_each_glob_ref_in(inc_nr, good_glob, "refs/bisect/",
397 (void *) &state->nr_good);
399 free(good_glob);
400 free(bad_ref);
403 __attribute__((format (printf, 1, 2)))
404 static void bisect_log_printf(const char *fmt, ...)
406 struct strbuf buf = STRBUF_INIT;
407 va_list ap;
409 va_start(ap, fmt);
410 strbuf_vaddf(&buf, fmt, ap);
411 va_end(ap);
413 printf("%s", buf.buf);
414 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
416 strbuf_release(&buf);
419 static void bisect_print_status(const struct bisect_terms *terms)
421 struct bisect_state state = { 0 };
423 bisect_status(&state, terms);
425 /* If we had both, we'd already be started, and shouldn't get here. */
426 if (state.nr_good && state.nr_bad)
427 return;
429 if (!state.nr_good && !state.nr_bad)
430 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
431 else if (state.nr_good)
432 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
433 "status: waiting for bad commit, %d good commits known\n",
434 state.nr_good), state.nr_good);
435 else
436 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
439 static int bisect_next_check(const struct bisect_terms *terms,
440 const char *current_term)
442 struct bisect_state state = { 0 };
443 bisect_status(&state, terms);
444 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
447 static int get_terms(struct bisect_terms *terms)
449 struct strbuf str = STRBUF_INIT;
450 FILE *fp = NULL;
451 int res = 0;
453 fp = fopen(git_path_bisect_terms(), "r");
454 if (!fp) {
455 res = -1;
456 goto finish;
459 free_terms(terms);
460 strbuf_getline_lf(&str, fp);
461 terms->term_bad = strbuf_detach(&str, NULL);
462 strbuf_getline_lf(&str, fp);
463 terms->term_good = strbuf_detach(&str, NULL);
465 finish:
466 if (fp)
467 fclose(fp);
468 strbuf_release(&str);
469 return res;
472 static int bisect_terms(struct bisect_terms *terms, const char *option)
474 if (get_terms(terms))
475 return error(_("no terms defined"));
477 if (!option) {
478 printf(_("Your current terms are %s for the old state\n"
479 "and %s for the new state.\n"),
480 terms->term_good, terms->term_bad);
481 return 0;
483 if (one_of(option, "--term-good", "--term-old", NULL))
484 printf("%s\n", terms->term_good);
485 else if (one_of(option, "--term-bad", "--term-new", NULL))
486 printf("%s\n", terms->term_bad);
487 else
488 return error(_("invalid argument %s for 'git bisect terms'.\n"
489 "Supported options are: "
490 "--term-good|--term-old and "
491 "--term-bad|--term-new."), option);
493 return 0;
496 static int bisect_append_log_quoted(const char **argv)
498 int res = 0;
499 FILE *fp = fopen(git_path_bisect_log(), "a");
500 struct strbuf orig_args = STRBUF_INIT;
502 if (!fp)
503 return -1;
505 if (fprintf(fp, "git bisect start") < 1) {
506 res = -1;
507 goto finish;
510 sq_quote_argv(&orig_args, argv);
511 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
512 res = -1;
514 finish:
515 fclose(fp);
516 strbuf_release(&orig_args);
517 return res;
520 static int add_bisect_ref(const char *refname, const struct object_id *oid,
521 int flags UNUSED, void *cb)
523 struct add_bisect_ref_data *data = cb;
525 add_pending_oid(data->revs, refname, oid, data->object_flags);
527 return 0;
530 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
532 int res = 0;
533 struct add_bisect_ref_data cb = { revs };
534 char *good = xstrfmt("%s-*", terms->term_good);
537 * We cannot use terms->term_bad directly in
538 * for_each_glob_ref_in() and we have to append a '*' to it,
539 * otherwise for_each_glob_ref_in() will append '/' and '*'.
541 char *bad = xstrfmt("%s*", terms->term_bad);
544 * It is important to reset the flags used by revision walks
545 * as the previous call to bisect_next_all() in turn
546 * sets up a revision walk.
548 reset_revision_walk();
549 init_revisions(revs, NULL);
550 setup_revisions(0, NULL, revs, NULL);
551 for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
552 cb.object_flags = UNINTERESTING;
553 for_each_glob_ref_in(add_bisect_ref, good, "refs/bisect/", &cb);
554 if (prepare_revision_walk(revs))
555 res = error(_("revision walk setup failed\n"));
557 free(good);
558 free(bad);
559 return res;
562 static int bisect_skipped_commits(struct bisect_terms *terms)
564 int res;
565 FILE *fp = NULL;
566 struct rev_info revs;
567 struct commit *commit;
568 struct pretty_print_context pp = {0};
569 struct strbuf commit_name = STRBUF_INIT;
571 res = prepare_revs(terms, &revs);
572 if (res)
573 return res;
575 fp = fopen(git_path_bisect_log(), "a");
576 if (!fp)
577 return error_errno(_("could not open '%s' for appending"),
578 git_path_bisect_log());
580 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
581 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
583 while ((commit = get_revision(&revs)) != NULL) {
584 strbuf_reset(&commit_name);
585 format_commit_message(commit, "%s",
586 &commit_name, &pp);
587 fprintf(fp, "# possible first %s commit: [%s] %s\n",
588 terms->term_bad, oid_to_hex(&commit->object.oid),
589 commit_name.buf);
593 * Reset the flags used by revision walks in case
594 * there is another revision walk after this one.
596 reset_revision_walk();
598 strbuf_release(&commit_name);
599 release_revisions(&revs);
600 fclose(fp);
601 return 0;
604 static int bisect_successful(struct bisect_terms *terms)
606 struct object_id oid;
607 struct commit *commit;
608 struct pretty_print_context pp = {0};
609 struct strbuf commit_name = STRBUF_INIT;
610 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
611 int res;
613 read_ref(bad_ref, &oid);
614 commit = lookup_commit_reference_by_name(bad_ref);
615 format_commit_message(commit, "%s", &commit_name, &pp);
617 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
618 terms->term_bad, oid_to_hex(&commit->object.oid),
619 commit_name.buf);
621 strbuf_release(&commit_name);
622 free(bad_ref);
623 return res;
626 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
628 enum bisect_error res;
630 if (bisect_autostart(terms))
631 return BISECT_FAILED;
633 if (bisect_next_check(terms, terms->term_good))
634 return BISECT_FAILED;
636 /* Perform all bisection computation */
637 res = bisect_next_all(the_repository, prefix);
639 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
640 res = bisect_successful(terms);
641 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
642 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
643 res = bisect_skipped_commits(terms);
644 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
646 return res;
649 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
651 if (bisect_next_check(terms, NULL)) {
652 bisect_print_status(terms);
653 return BISECT_OK;
656 return bisect_next(terms, prefix);
659 static enum bisect_error bisect_start(struct bisect_terms *terms, const char **argv, int argc)
661 int no_checkout = 0;
662 int first_parent_only = 0;
663 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
664 int flags, pathspec_pos;
665 enum bisect_error res = BISECT_OK;
666 struct string_list revs = STRING_LIST_INIT_DUP;
667 struct string_list states = STRING_LIST_INIT_DUP;
668 struct strbuf start_head = STRBUF_INIT;
669 struct strbuf bisect_names = STRBUF_INIT;
670 struct object_id head_oid;
671 struct object_id oid;
672 const char *head;
674 if (is_bare_repository())
675 no_checkout = 1;
678 * Check for one bad and then some good revisions
680 for (i = 0; i < argc; i++) {
681 if (!strcmp(argv[i], "--")) {
682 has_double_dash = 1;
683 break;
687 for (i = 0; i < argc; i++) {
688 const char *arg = argv[i];
689 if (!strcmp(argv[i], "--")) {
690 break;
691 } else if (!strcmp(arg, "--no-checkout")) {
692 no_checkout = 1;
693 } else if (!strcmp(arg, "--first-parent")) {
694 first_parent_only = 1;
695 } else if (!strcmp(arg, "--term-good") ||
696 !strcmp(arg, "--term-old")) {
697 i++;
698 if (argc <= i)
699 return error(_("'' is not a valid term"));
700 must_write_terms = 1;
701 free((void *) terms->term_good);
702 terms->term_good = xstrdup(argv[i]);
703 } else if (skip_prefix(arg, "--term-good=", &arg) ||
704 skip_prefix(arg, "--term-old=", &arg)) {
705 must_write_terms = 1;
706 free((void *) terms->term_good);
707 terms->term_good = xstrdup(arg);
708 } else if (!strcmp(arg, "--term-bad") ||
709 !strcmp(arg, "--term-new")) {
710 i++;
711 if (argc <= i)
712 return error(_("'' is not a valid term"));
713 must_write_terms = 1;
714 free((void *) terms->term_bad);
715 terms->term_bad = xstrdup(argv[i]);
716 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
717 skip_prefix(arg, "--term-new=", &arg)) {
718 must_write_terms = 1;
719 free((void *) terms->term_bad);
720 terms->term_bad = xstrdup(arg);
721 } else if (starts_with(arg, "--")) {
722 return error(_("unrecognized option: '%s'"), arg);
723 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
724 string_list_append(&revs, oid_to_hex(&oid));
725 } else if (has_double_dash) {
726 die(_("'%s' does not appear to be a valid "
727 "revision"), arg);
728 } else {
729 break;
732 pathspec_pos = i;
735 * The user ran "git bisect start <sha1> <sha1>", hence did not
736 * explicitly specify the terms, but we are already starting to
737 * set references named with the default terms, and won't be able
738 * to change afterwards.
740 if (revs.nr)
741 must_write_terms = 1;
742 for (i = 0; i < revs.nr; i++) {
743 if (bad_seen) {
744 string_list_append(&states, terms->term_good);
745 } else {
746 bad_seen = 1;
747 string_list_append(&states, terms->term_bad);
752 * Verify HEAD
754 head = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
755 if (!head)
756 if (get_oid("HEAD", &head_oid))
757 return error(_("bad HEAD - I need a HEAD"));
760 * Check if we are bisecting
762 if (!is_empty_or_missing_file(git_path_bisect_start())) {
763 /* Reset to the rev from where we started */
764 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
765 strbuf_trim(&start_head);
766 if (!no_checkout) {
767 struct child_process cmd = CHILD_PROCESS_INIT;
769 cmd.git_cmd = 1;
770 strvec_pushl(&cmd.args, "checkout", start_head.buf,
771 "--", NULL);
772 if (run_command(&cmd)) {
773 res = error(_("checking out '%s' failed."
774 " Try 'git bisect start "
775 "<valid-branch>'."),
776 start_head.buf);
777 goto finish;
780 } else {
781 /* Get the rev from where we start. */
782 if (!get_oid(head, &head_oid) &&
783 !starts_with(head, "refs/heads/")) {
784 strbuf_reset(&start_head);
785 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
786 } else if (!get_oid(head, &head_oid) &&
787 skip_prefix(head, "refs/heads/", &head)) {
789 * This error message should only be triggered by
790 * cogito usage, and cogito users should understand
791 * it relates to cg-seek.
793 if (!is_empty_or_missing_file(git_path_head_name()))
794 return error(_("won't bisect on cg-seek'ed tree"));
795 strbuf_addstr(&start_head, head);
796 } else {
797 return error(_("bad HEAD - strange symbolic ref"));
802 * Get rid of any old bisect state.
804 if (bisect_clean_state())
805 return BISECT_FAILED;
808 * Write new start state
810 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
812 if (first_parent_only)
813 write_file(git_path_bisect_first_parent(), "\n");
815 if (no_checkout) {
816 if (get_oid(start_head.buf, &oid) < 0) {
817 res = error(_("invalid ref: '%s'"), start_head.buf);
818 goto finish;
820 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
821 UPDATE_REFS_MSG_ON_ERR)) {
822 res = BISECT_FAILED;
823 goto finish;
827 if (pathspec_pos < argc - 1)
828 sq_quote_argv(&bisect_names, argv + pathspec_pos);
829 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
831 for (i = 0; i < states.nr; i++)
832 if (bisect_write(states.items[i].string,
833 revs.items[i].string, terms, 1)) {
834 res = BISECT_FAILED;
835 goto finish;
838 if (must_write_terms && write_terms(terms->term_bad,
839 terms->term_good)) {
840 res = BISECT_FAILED;
841 goto finish;
844 res = bisect_append_log_quoted(argv);
845 if (res)
846 res = BISECT_FAILED;
848 finish:
849 string_list_clear(&revs, 0);
850 string_list_clear(&states, 0);
851 strbuf_release(&start_head);
852 strbuf_release(&bisect_names);
853 if (res)
854 return res;
856 res = bisect_auto_next(terms, NULL);
857 if (!is_bisect_success(res))
858 bisect_clean_state();
859 return res;
862 static inline int file_is_not_empty(const char *path)
864 return !is_empty_or_missing_file(path);
867 static int bisect_autostart(struct bisect_terms *terms)
869 int res;
870 const char *yesno;
872 if (file_is_not_empty(git_path_bisect_start()))
873 return 0;
875 fprintf_ln(stderr, _("You need to start by \"git bisect "
876 "start\"\n"));
878 if (!isatty(STDIN_FILENO))
879 return -1;
882 * TRANSLATORS: Make sure to include [Y] and [n] in your
883 * translation. The program will only accept English input
884 * at this point.
886 yesno = git_prompt(_("Do you want me to do it for you "
887 "[Y/n]? "), PROMPT_ECHO);
888 res = tolower(*yesno) == 'n' ?
889 -1 : bisect_start(terms, empty_strvec, 0);
891 return res;
894 static enum bisect_error bisect_state(struct bisect_terms *terms, const char **argv,
895 int argc)
897 const char *state;
898 int i, verify_expected = 1;
899 struct object_id oid, expected;
900 struct strbuf buf = STRBUF_INIT;
901 struct oid_array revs = OID_ARRAY_INIT;
903 if (!argc)
904 return error(_("Please call `--bisect-state` with at least one argument"));
906 if (bisect_autostart(terms))
907 return BISECT_FAILED;
909 state = argv[0];
910 if (check_and_set_terms(terms, state) ||
911 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
912 return BISECT_FAILED;
914 argv++;
915 argc--;
916 if (argc > 1 && !strcmp(state, terms->term_bad))
917 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
919 if (argc == 0) {
920 const char *head = "BISECT_HEAD";
921 enum get_oid_result res_head = get_oid(head, &oid);
923 if (res_head == MISSING_OBJECT) {
924 head = "HEAD";
925 res_head = get_oid(head, &oid);
928 if (res_head)
929 error(_("Bad rev input: %s"), head);
930 oid_array_append(&revs, &oid);
934 * All input revs must be checked before executing bisect_write()
935 * to discard junk revs.
938 for (; argc; argc--, argv++) {
939 struct commit *commit;
941 if (get_oid(*argv, &oid)){
942 error(_("Bad rev input: %s"), *argv);
943 oid_array_clear(&revs);
944 return BISECT_FAILED;
947 commit = lookup_commit_reference(the_repository, &oid);
948 if (!commit)
949 die(_("Bad rev input (not a commit): %s"), *argv);
951 oid_array_append(&revs, &commit->object.oid);
954 if (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
955 get_oid_hex(buf.buf, &expected) < 0)
956 verify_expected = 0; /* Ignore invalid file contents */
957 strbuf_release(&buf);
959 for (i = 0; i < revs.nr; i++) {
960 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
961 oid_array_clear(&revs);
962 return BISECT_FAILED;
964 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
965 unlink_or_warn(git_path_bisect_ancestors_ok());
966 unlink_or_warn(git_path_bisect_expected_rev());
967 verify_expected = 0;
971 oid_array_clear(&revs);
972 return bisect_auto_next(terms, NULL);
975 static enum bisect_error bisect_log(void)
977 int fd, status;
978 const char* filename = git_path_bisect_log();
980 if (is_empty_or_missing_file(filename))
981 return error(_("We are not bisecting."));
983 fd = open(filename, O_RDONLY);
984 if (fd < 0)
985 return BISECT_FAILED;
987 status = copy_fd(fd, STDOUT_FILENO);
988 close(fd);
989 return status ? BISECT_FAILED : BISECT_OK;
992 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
994 const char *p = line->buf + strspn(line->buf, " \t");
995 char *word_end, *rev;
997 if ((!skip_prefix(p, "git bisect", &p) &&
998 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
999 return 0;
1000 p += strspn(p, " \t");
1002 word_end = (char *)p + strcspn(p, " \t");
1003 rev = word_end + strspn(word_end, " \t");
1004 *word_end = '\0'; /* NUL-terminate the word */
1006 get_terms(terms);
1007 if (check_and_set_terms(terms, p))
1008 return -1;
1010 if (!strcmp(p, "start")) {
1011 struct strvec argv = STRVEC_INIT;
1012 int res;
1013 sq_dequote_to_strvec(rev, &argv);
1014 res = bisect_start(terms, argv.v, argv.nr);
1015 strvec_clear(&argv);
1016 return res;
1019 if (one_of(p, terms->term_good,
1020 terms->term_bad, "skip", NULL))
1021 return bisect_write(p, rev, terms, 0);
1023 if (!strcmp(p, "terms")) {
1024 struct strvec argv = STRVEC_INIT;
1025 int res;
1026 sq_dequote_to_strvec(rev, &argv);
1027 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1028 strvec_clear(&argv);
1029 return res;
1031 error(_("'%s'?? what are you talking about?"), p);
1033 return -1;
1036 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1038 FILE *fp = NULL;
1039 enum bisect_error res = BISECT_OK;
1040 struct strbuf line = STRBUF_INIT;
1042 if (is_empty_or_missing_file(filename))
1043 return error(_("cannot read file '%s' for replaying"), filename);
1045 if (bisect_reset(NULL))
1046 return BISECT_FAILED;
1048 fp = fopen(filename, "r");
1049 if (!fp)
1050 return BISECT_FAILED;
1052 while ((strbuf_getline(&line, fp) != EOF) && !res)
1053 res = process_replay_line(terms, &line);
1055 strbuf_release(&line);
1056 fclose(fp);
1058 if (res)
1059 return BISECT_FAILED;
1061 return bisect_auto_next(terms, NULL);
1064 static enum bisect_error bisect_skip(struct bisect_terms *terms, const char **argv, int argc)
1066 int i;
1067 enum bisect_error res;
1068 struct strvec argv_state = STRVEC_INIT;
1070 strvec_push(&argv_state, "skip");
1072 for (i = 0; i < argc; i++) {
1073 const char *dotdot = strstr(argv[i], "..");
1075 if (dotdot) {
1076 struct rev_info revs;
1077 struct commit *commit;
1079 init_revisions(&revs, NULL);
1080 setup_revisions(2, argv + i - 1, &revs, NULL);
1082 if (prepare_revision_walk(&revs))
1083 die(_("revision walk setup failed\n"));
1084 while ((commit = get_revision(&revs)) != NULL)
1085 strvec_push(&argv_state,
1086 oid_to_hex(&commit->object.oid));
1088 reset_revision_walk();
1089 release_revisions(&revs);
1090 } else {
1091 strvec_push(&argv_state, argv[i]);
1094 res = bisect_state(terms, argv_state.v, argv_state.nr);
1096 strvec_clear(&argv_state);
1097 return res;
1100 static int bisect_visualize(struct bisect_terms *terms, const char **argv, int argc)
1102 struct child_process cmd = CHILD_PROCESS_INIT;
1103 struct strbuf sb = STRBUF_INIT;
1105 if (bisect_next_check(terms, NULL) != 0)
1106 return BISECT_FAILED;
1108 cmd.no_stdin = 1;
1109 if (!argc) {
1110 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1111 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1112 strvec_push(&cmd.args, "gitk");
1113 } else {
1114 strvec_push(&cmd.args, "log");
1115 cmd.git_cmd = 1;
1117 } else {
1118 if (argv[0][0] == '-') {
1119 strvec_push(&cmd.args, "log");
1120 cmd.git_cmd = 1;
1121 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1122 cmd.git_cmd = 1;
1124 strvec_pushv(&cmd.args, argv);
1127 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1129 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1130 sq_dequote_to_strvec(sb.buf, &cmd.args);
1131 strbuf_release(&sb);
1133 return run_command(&cmd);
1136 static int get_first_good(const char *refname UNUSED,
1137 const struct object_id *oid,
1138 int flag UNUSED, void *cb_data)
1140 oidcpy(cb_data, oid);
1141 return 1;
1144 static int do_bisect_run(const char *command)
1146 struct child_process cmd = CHILD_PROCESS_INIT;
1148 printf(_("running %s\n"), command);
1149 cmd.use_shell = 1;
1150 strvec_push(&cmd.args, command);
1151 return run_command(&cmd);
1154 static int verify_good(const struct bisect_terms *terms, const char *command)
1156 int rc;
1157 enum bisect_error res;
1158 struct object_id good_rev;
1159 struct object_id current_rev;
1160 char *good_glob = xstrfmt("%s-*", terms->term_good);
1161 int no_checkout = ref_exists("BISECT_HEAD");
1163 for_each_glob_ref_in(get_first_good, good_glob, "refs/bisect/",
1164 &good_rev);
1165 free(good_glob);
1167 if (read_ref(no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1168 return -1;
1170 res = bisect_checkout(&good_rev, no_checkout);
1171 if (res != BISECT_OK)
1172 return -1;
1174 rc = do_bisect_run(command);
1176 res = bisect_checkout(&current_rev, no_checkout);
1177 if (res != BISECT_OK)
1178 return -1;
1180 return rc;
1183 static int bisect_run(struct bisect_terms *terms, const char **argv, int argc)
1185 int res = BISECT_OK;
1186 struct strbuf command = STRBUF_INIT;
1187 const char *new_state;
1188 int temporary_stdout_fd, saved_stdout;
1189 int is_first_run = 1;
1191 if (bisect_next_check(terms, NULL))
1192 return BISECT_FAILED;
1194 if (argc)
1195 sq_quote_argv(&command, argv);
1196 else {
1197 error(_("bisect run failed: no command provided."));
1198 return BISECT_FAILED;
1201 while (1) {
1202 res = do_bisect_run(command.buf);
1205 * Exit code 126 and 127 can either come from the shell
1206 * if it was unable to execute or even find the script,
1207 * or from the script itself. Check with a known-good
1208 * revision to avoid trashing the bisect run due to a
1209 * missing or non-executable script.
1211 if (is_first_run && (res == 126 || res == 127)) {
1212 int rc = verify_good(terms, command.buf);
1213 is_first_run = 0;
1214 if (rc < 0) {
1215 error(_("unable to verify '%s' on good"
1216 " revision"), command.buf);
1217 res = BISECT_FAILED;
1218 break;
1220 if (rc == res) {
1221 error(_("bogus exit code %d for good revision"),
1222 rc);
1223 res = BISECT_FAILED;
1224 break;
1228 if (res < 0 || 128 <= res) {
1229 error(_("bisect run failed: exit code %d from"
1230 " '%s' is < 0 or >= 128"), res, command.buf);
1231 break;
1234 if (res == 125)
1235 new_state = "skip";
1236 else if (!res)
1237 new_state = terms->term_good;
1238 else
1239 new_state = terms->term_bad;
1241 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1243 if (temporary_stdout_fd < 0) {
1244 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1245 break;
1248 fflush(stdout);
1249 saved_stdout = dup(1);
1250 dup2(temporary_stdout_fd, 1);
1252 res = bisect_state(terms, &new_state, 1);
1254 fflush(stdout);
1255 dup2(saved_stdout, 1);
1256 close(saved_stdout);
1257 close(temporary_stdout_fd);
1259 print_file_to_stdout(git_path_bisect_run());
1261 if (res == BISECT_ONLY_SKIPPED_LEFT)
1262 error(_("bisect run cannot continue any more"));
1263 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1264 printf(_("bisect run success"));
1265 res = BISECT_OK;
1266 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1267 printf(_("bisect found first bad commit"));
1268 res = BISECT_OK;
1269 } else if (res) {
1270 error(_("bisect run failed: 'git bisect--helper --bisect-state"
1271 " %s' exited with error code %d"), new_state, res);
1272 } else {
1273 continue;
1275 break;
1278 strbuf_release(&command);
1279 return res;
1282 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1284 if (argc > 1)
1285 return error(_("--bisect-reset requires either no argument or a commit"));
1286 return bisect_reset(argc ? argv[0] : NULL);
1289 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1291 int res;
1292 struct bisect_terms terms = { 0 };
1294 if (argc > 1)
1295 return error(_("--bisect-terms requires 0 or 1 argument"));
1296 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1297 free_terms(&terms);
1298 return res;
1301 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1303 int res;
1304 struct bisect_terms terms = { 0 };
1306 set_terms(&terms, "bad", "good");
1307 res = bisect_start(&terms, argv, argc);
1308 free_terms(&terms);
1309 return res;
1312 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1314 int res;
1315 struct bisect_terms terms = { 0 };
1317 if (argc)
1318 return error(_("--bisect-next requires 0 arguments"));
1319 get_terms(&terms);
1320 res = bisect_next(&terms, prefix);
1321 free_terms(&terms);
1322 return res;
1325 static int cmd_bisect__state(int argc, const char **argv, const char *prefix UNUSED)
1327 int res;
1328 struct bisect_terms terms = { 0 };
1330 set_terms(&terms, "bad", "good");
1331 get_terms(&terms);
1332 res = bisect_state(&terms, argv, argc);
1333 free_terms(&terms);
1334 return res;
1337 static int cmd_bisect__log(int argc, const char **argv UNUSED, const char *prefix UNUSED)
1339 if (argc)
1340 return error(_("--bisect-log requires 0 arguments"));
1341 return bisect_log();
1344 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1346 int res;
1347 struct bisect_terms terms = { 0 };
1349 if (argc != 1)
1350 return error(_("no logfile given"));
1351 set_terms(&terms, "bad", "good");
1352 res = bisect_replay(&terms, argv[0]);
1353 free_terms(&terms);
1354 return res;
1357 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1359 int res;
1360 struct bisect_terms terms = { 0 };
1362 set_terms(&terms, "bad", "good");
1363 get_terms(&terms);
1364 res = bisect_skip(&terms, argv, argc);
1365 free_terms(&terms);
1366 return res;
1369 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1371 int res;
1372 struct bisect_terms terms = { 0 };
1374 get_terms(&terms);
1375 res = bisect_visualize(&terms, argv, argc);
1376 free_terms(&terms);
1377 return res;
1380 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1382 int res;
1383 struct bisect_terms terms = { 0 };
1385 if (!argc)
1386 return error(_("bisect run failed: no command provided."));
1387 get_terms(&terms);
1388 res = bisect_run(&terms, argv, argc);
1389 free_terms(&terms);
1390 return res;
1393 int cmd_bisect__helper(int argc, const char **argv, const char *prefix)
1395 int res = 0;
1396 parse_opt_subcommand_fn *fn = NULL;
1397 struct option options[] = {
1398 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1399 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1400 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1401 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1402 OPT_SUBCOMMAND("state", &fn, cmd_bisect__state),
1403 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1404 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1405 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1406 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1407 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1408 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1409 OPT_END()
1411 argc = parse_options(argc, argv, prefix, options,
1412 git_bisect_helper_usage, 0);
1414 if (!fn)
1415 usage_with_options(git_bisect_helper_usage, options);
1416 argc--;
1417 argv++;
1419 res = fn(argc, argv, prefix);
1422 * Handle early success
1423 * From check_merge_bases > check_good_are_ancestors_of_bad > bisect_next_all
1425 if ((res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) || (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND))
1426 res = BISECT_OK;
1428 return -res;