diff.h: remove unnecessary include of object.h
[git/debian.git] / builtin / bisect.c
blobe8ee4a4dc8d181a4b30bd30f77ace4b47418c574
1 #include "builtin.h"
2 #include "cache.h"
3 #include "hex.h"
4 #include "parse-options.h"
5 #include "bisect.h"
6 #include "refs.h"
7 #include "dir.h"
8 #include "strvec.h"
9 #include "run-command.h"
10 #include "prompt.h"
11 #include "quote.h"
12 #include "revision.h"
14 static GIT_PATH_FUNC(git_path_bisect_terms, "BISECT_TERMS")
15 static GIT_PATH_FUNC(git_path_bisect_expected_rev, "BISECT_EXPECTED_REV")
16 static GIT_PATH_FUNC(git_path_bisect_ancestors_ok, "BISECT_ANCESTORS_OK")
17 static GIT_PATH_FUNC(git_path_bisect_start, "BISECT_START")
18 static GIT_PATH_FUNC(git_path_bisect_log, "BISECT_LOG")
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 #define BUILTIN_GIT_BISECT_START_USAGE \
24 N_("git bisect start [--term-{new,bad}=<term> --term-{old,good}=<term>]" \
25 " [--no-checkout] [--first-parent] [<bad> [<good>...]] [--]" \
26 " [<pathspec>...]")
27 #define BUILTIN_GIT_BISECT_STATE_USAGE \
28 N_("git bisect (good|bad) [<rev>...]")
29 #define BUILTIN_GIT_BISECT_TERMS_USAGE \
30 "git bisect terms [--term-good | --term-bad]"
31 #define BUILTIN_GIT_BISECT_SKIP_USAGE \
32 N_("git bisect skip [(<rev>|<range>)...]")
33 #define BUILTIN_GIT_BISECT_NEXT_USAGE \
34 "git bisect next"
35 #define BUILTIN_GIT_BISECT_RESET_USAGE \
36 N_("git bisect reset [<commit>]")
37 #define BUILTIN_GIT_BISECT_VISUALIZE_USAGE \
38 "git bisect visualize"
39 #define BUILTIN_GIT_BISECT_REPLAY_USAGE \
40 N_("git bisect replay <logfile>")
41 #define BUILTIN_GIT_BISECT_LOG_USAGE \
42 "git bisect log"
43 #define BUILTIN_GIT_BISECT_RUN_USAGE \
44 N_("git bisect run <cmd>...")
46 static const char * const git_bisect_usage[] = {
47 BUILTIN_GIT_BISECT_START_USAGE,
48 BUILTIN_GIT_BISECT_STATE_USAGE,
49 BUILTIN_GIT_BISECT_TERMS_USAGE,
50 BUILTIN_GIT_BISECT_SKIP_USAGE,
51 BUILTIN_GIT_BISECT_NEXT_USAGE,
52 BUILTIN_GIT_BISECT_RESET_USAGE,
53 BUILTIN_GIT_BISECT_VISUALIZE_USAGE,
54 BUILTIN_GIT_BISECT_REPLAY_USAGE,
55 BUILTIN_GIT_BISECT_LOG_USAGE,
56 BUILTIN_GIT_BISECT_RUN_USAGE,
57 NULL
60 struct add_bisect_ref_data {
61 struct rev_info *revs;
62 unsigned int object_flags;
65 struct bisect_terms {
66 char *term_good;
67 char *term_bad;
70 static void free_terms(struct bisect_terms *terms)
72 FREE_AND_NULL(terms->term_good);
73 FREE_AND_NULL(terms->term_bad);
76 static void set_terms(struct bisect_terms *terms, const char *bad,
77 const char *good)
79 free((void *)terms->term_good);
80 terms->term_good = xstrdup(good);
81 free((void *)terms->term_bad);
82 terms->term_bad = xstrdup(bad);
85 static const char vocab_bad[] = "bad|new";
86 static const char vocab_good[] = "good|old";
88 static int bisect_autostart(struct bisect_terms *terms);
91 * Check whether the string `term` belongs to the set of strings
92 * included in the variable arguments.
94 LAST_ARG_MUST_BE_NULL
95 static int one_of(const char *term, ...)
97 int res = 0;
98 va_list matches;
99 const char *match;
101 va_start(matches, term);
102 while (!res && (match = va_arg(matches, const char *)))
103 res = !strcmp(term, match);
104 va_end(matches);
106 return res;
110 * return code BISECT_INTERNAL_SUCCESS_MERGE_BASE
111 * and BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND are codes
112 * that indicate special success.
115 static int is_bisect_success(enum bisect_error res)
117 return !res ||
118 res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND ||
119 res == BISECT_INTERNAL_SUCCESS_MERGE_BASE;
122 static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
124 FILE *fp = NULL;
125 int res = 0;
127 if (strcmp(mode, "w") && strcmp(mode, "a"))
128 BUG("write-in-file does not support '%s' mode", mode);
129 fp = fopen(path, mode);
130 if (!fp)
131 return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
132 res = vfprintf(fp, format, args);
134 if (res < 0) {
135 int saved_errno = errno;
136 fclose(fp);
137 errno = saved_errno;
138 return error_errno(_("could not write to file '%s'"), path);
141 return fclose(fp);
144 __attribute__((format (printf, 2, 3)))
145 static int write_to_file(const char *path, const char *format, ...)
147 int res;
148 va_list args;
150 va_start(args, format);
151 res = write_in_file(path, "w", format, args);
152 va_end(args);
154 return res;
157 __attribute__((format (printf, 2, 3)))
158 static int append_to_file(const char *path, const char *format, ...)
160 int res;
161 va_list args;
163 va_start(args, format);
164 res = write_in_file(path, "a", format, args);
165 va_end(args);
167 return res;
170 static int print_file_to_stdout(const char *path)
172 int fd = open(path, O_RDONLY);
173 int ret = 0;
175 if (fd < 0)
176 return error_errno(_("cannot open file '%s' for reading"), path);
177 if (copy_fd(fd, 1) < 0)
178 ret = error_errno(_("failed to read '%s'"), path);
179 close(fd);
180 return ret;
183 static int check_term_format(const char *term, const char *orig_term)
185 int res;
186 char *new_term = xstrfmt("refs/bisect/%s", term);
188 res = check_refname_format(new_term, 0);
189 free(new_term);
191 if (res)
192 return error(_("'%s' is not a valid term"), term);
194 if (one_of(term, "help", "start", "skip", "next", "reset",
195 "visualize", "view", "replay", "log", "run", "terms", NULL))
196 return error(_("can't use the builtin command '%s' as a term"), term);
199 * In theory, nothing prevents swapping completely good and bad,
200 * but this situation could be confusing and hasn't been tested
201 * enough. Forbid it for now.
204 if ((strcmp(orig_term, "bad") && one_of(term, "bad", "new", NULL)) ||
205 (strcmp(orig_term, "good") && one_of(term, "good", "old", NULL)))
206 return error(_("can't change the meaning of the term '%s'"), term);
208 return 0;
211 static int write_terms(const char *bad, const char *good)
213 int res;
215 if (!strcmp(bad, good))
216 return error(_("please use two different terms"));
218 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
219 return -1;
221 res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
223 return res;
226 static int bisect_reset(const char *commit)
228 struct strbuf branch = STRBUF_INIT;
230 if (!commit) {
231 if (strbuf_read_file(&branch, git_path_bisect_start(), 0) < 1) {
232 printf(_("We are not bisecting.\n"));
233 return 0;
235 strbuf_rtrim(&branch);
236 } else {
237 struct object_id oid;
239 if (get_oid_commit(commit, &oid))
240 return error(_("'%s' is not a valid commit"), commit);
241 strbuf_addstr(&branch, commit);
244 if (!ref_exists("BISECT_HEAD")) {
245 struct child_process cmd = CHILD_PROCESS_INIT;
247 cmd.git_cmd = 1;
248 strvec_pushl(&cmd.args, "checkout", branch.buf, "--", NULL);
249 if (run_command(&cmd)) {
250 error(_("could not check out original"
251 " HEAD '%s'. Try 'git bisect"
252 " reset <commit>'."), branch.buf);
253 strbuf_release(&branch);
254 return -1;
258 strbuf_release(&branch);
259 return bisect_clean_state();
262 static void log_commit(FILE *fp, char *fmt, const char *state,
263 struct commit *commit)
265 struct pretty_print_context pp = {0};
266 struct strbuf commit_msg = STRBUF_INIT;
267 char *label = xstrfmt(fmt, state);
269 format_commit_message(commit, "%s", &commit_msg, &pp);
271 fprintf(fp, "# %s: [%s] %s\n", label, oid_to_hex(&commit->object.oid),
272 commit_msg.buf);
274 strbuf_release(&commit_msg);
275 free(label);
278 static int bisect_write(const char *state, const char *rev,
279 const struct bisect_terms *terms, int nolog)
281 struct strbuf tag = STRBUF_INIT;
282 struct object_id oid;
283 struct commit *commit;
284 FILE *fp = NULL;
285 int res = 0;
287 if (!strcmp(state, terms->term_bad)) {
288 strbuf_addf(&tag, "refs/bisect/%s", state);
289 } else if (one_of(state, terms->term_good, "skip", NULL)) {
290 strbuf_addf(&tag, "refs/bisect/%s-%s", state, rev);
291 } else {
292 res = error(_("Bad bisect_write argument: %s"), state);
293 goto finish;
296 if (get_oid(rev, &oid)) {
297 res = error(_("couldn't get the oid of the rev '%s'"), rev);
298 goto finish;
301 if (update_ref(NULL, tag.buf, &oid, NULL, 0,
302 UPDATE_REFS_MSG_ON_ERR)) {
303 res = -1;
304 goto finish;
307 fp = fopen(git_path_bisect_log(), "a");
308 if (!fp) {
309 res = error_errno(_("couldn't open the file '%s'"), git_path_bisect_log());
310 goto finish;
313 commit = lookup_commit_reference(the_repository, &oid);
314 log_commit(fp, "%s", state, commit);
316 if (!nolog)
317 fprintf(fp, "git bisect %s %s\n", state, rev);
319 finish:
320 if (fp)
321 fclose(fp);
322 strbuf_release(&tag);
323 return res;
326 static int check_and_set_terms(struct bisect_terms *terms, const char *cmd)
328 int has_term_file = !is_empty_or_missing_file(git_path_bisect_terms());
330 if (one_of(cmd, "skip", "start", "terms", NULL))
331 return 0;
333 if (has_term_file && strcmp(cmd, terms->term_bad) &&
334 strcmp(cmd, terms->term_good))
335 return error(_("Invalid command: you're currently in a "
336 "%s/%s bisect"), terms->term_bad,
337 terms->term_good);
339 if (!has_term_file) {
340 if (one_of(cmd, "bad", "good", NULL)) {
341 set_terms(terms, "bad", "good");
342 return write_terms(terms->term_bad, terms->term_good);
344 if (one_of(cmd, "new", "old", NULL)) {
345 set_terms(terms, "new", "old");
346 return write_terms(terms->term_bad, terms->term_good);
350 return 0;
353 static int inc_nr(const char *refname UNUSED,
354 const struct object_id *oid UNUSED,
355 int flag UNUSED, void *cb_data)
357 unsigned int *nr = (unsigned int *)cb_data;
358 (*nr)++;
359 return 0;
362 static const char need_bad_and_good_revision_warning[] =
363 N_("You need to give me at least one %s and %s revision.\n"
364 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
366 static const char need_bisect_start_warning[] =
367 N_("You need to start by \"git bisect start\".\n"
368 "You then need to give me at least one %s and %s revision.\n"
369 "You can use \"git bisect %s\" and \"git bisect %s\" for that.");
371 static int decide_next(const struct bisect_terms *terms,
372 const char *current_term, int missing_good,
373 int missing_bad)
375 if (!missing_good && !missing_bad)
376 return 0;
377 if (!current_term)
378 return -1;
380 if (missing_good && !missing_bad &&
381 !strcmp(current_term, terms->term_good)) {
382 char *yesno;
384 * have bad (or new) but not good (or old). We could bisect
385 * although this is less optimum.
387 warning(_("bisecting only with a %s commit"), terms->term_bad);
388 if (!isatty(0))
389 return 0;
391 * TRANSLATORS: Make sure to include [Y] and [n] in your
392 * translation. The program will only accept English input
393 * at this point.
395 yesno = git_prompt(_("Are you sure [Y/n]? "), PROMPT_ECHO);
396 if (starts_with(yesno, "N") || starts_with(yesno, "n"))
397 return -1;
398 return 0;
401 if (!is_empty_or_missing_file(git_path_bisect_start()))
402 return error(_(need_bad_and_good_revision_warning),
403 vocab_bad, vocab_good, vocab_bad, vocab_good);
404 else
405 return error(_(need_bisect_start_warning),
406 vocab_good, vocab_bad, vocab_good, vocab_bad);
409 static void bisect_status(struct bisect_state *state,
410 const struct bisect_terms *terms)
412 char *bad_ref = xstrfmt("refs/bisect/%s", terms->term_bad);
413 char *good_glob = xstrfmt("%s-*", terms->term_good);
415 if (ref_exists(bad_ref))
416 state->nr_bad = 1;
418 for_each_glob_ref_in(inc_nr, good_glob, "refs/bisect/",
419 (void *) &state->nr_good);
421 free(good_glob);
422 free(bad_ref);
425 __attribute__((format (printf, 1, 2)))
426 static void bisect_log_printf(const char *fmt, ...)
428 struct strbuf buf = STRBUF_INIT;
429 va_list ap;
431 va_start(ap, fmt);
432 strbuf_vaddf(&buf, fmt, ap);
433 va_end(ap);
435 printf("%s", buf.buf);
436 append_to_file(git_path_bisect_log(), "# %s", buf.buf);
438 strbuf_release(&buf);
441 static void bisect_print_status(const struct bisect_terms *terms)
443 struct bisect_state state = { 0 };
445 bisect_status(&state, terms);
447 /* If we had both, we'd already be started, and shouldn't get here. */
448 if (state.nr_good && state.nr_bad)
449 return;
451 if (!state.nr_good && !state.nr_bad)
452 bisect_log_printf(_("status: waiting for both good and bad commits\n"));
453 else if (state.nr_good)
454 bisect_log_printf(Q_("status: waiting for bad commit, %d good commit known\n",
455 "status: waiting for bad commit, %d good commits known\n",
456 state.nr_good), state.nr_good);
457 else
458 bisect_log_printf(_("status: waiting for good commit(s), bad commit known\n"));
461 static int bisect_next_check(const struct bisect_terms *terms,
462 const char *current_term)
464 struct bisect_state state = { 0 };
465 bisect_status(&state, terms);
466 return decide_next(terms, current_term, !state.nr_good, !state.nr_bad);
469 static int get_terms(struct bisect_terms *terms)
471 struct strbuf str = STRBUF_INIT;
472 FILE *fp = NULL;
473 int res = 0;
475 fp = fopen(git_path_bisect_terms(), "r");
476 if (!fp) {
477 res = -1;
478 goto finish;
481 free_terms(terms);
482 strbuf_getline_lf(&str, fp);
483 terms->term_bad = strbuf_detach(&str, NULL);
484 strbuf_getline_lf(&str, fp);
485 terms->term_good = strbuf_detach(&str, NULL);
487 finish:
488 if (fp)
489 fclose(fp);
490 strbuf_release(&str);
491 return res;
494 static int bisect_terms(struct bisect_terms *terms, const char *option)
496 if (get_terms(terms))
497 return error(_("no terms defined"));
499 if (!option) {
500 printf(_("Your current terms are %s for the old state\n"
501 "and %s for the new state.\n"),
502 terms->term_good, terms->term_bad);
503 return 0;
505 if (one_of(option, "--term-good", "--term-old", NULL))
506 printf("%s\n", terms->term_good);
507 else if (one_of(option, "--term-bad", "--term-new", NULL))
508 printf("%s\n", terms->term_bad);
509 else
510 return error(_("invalid argument %s for 'git bisect terms'.\n"
511 "Supported options are: "
512 "--term-good|--term-old and "
513 "--term-bad|--term-new."), option);
515 return 0;
518 static int bisect_append_log_quoted(const char **argv)
520 int res = 0;
521 FILE *fp = fopen(git_path_bisect_log(), "a");
522 struct strbuf orig_args = STRBUF_INIT;
524 if (!fp)
525 return -1;
527 if (fprintf(fp, "git bisect start") < 1) {
528 res = -1;
529 goto finish;
532 sq_quote_argv(&orig_args, argv);
533 if (fprintf(fp, "%s\n", orig_args.buf) < 1)
534 res = -1;
536 finish:
537 fclose(fp);
538 strbuf_release(&orig_args);
539 return res;
542 static int add_bisect_ref(const char *refname, const struct object_id *oid,
543 int flags UNUSED, void *cb)
545 struct add_bisect_ref_data *data = cb;
547 add_pending_oid(data->revs, refname, oid, data->object_flags);
549 return 0;
552 static int prepare_revs(struct bisect_terms *terms, struct rev_info *revs)
554 int res = 0;
555 struct add_bisect_ref_data cb = { revs };
556 char *good = xstrfmt("%s-*", terms->term_good);
559 * We cannot use terms->term_bad directly in
560 * for_each_glob_ref_in() and we have to append a '*' to it,
561 * otherwise for_each_glob_ref_in() will append '/' and '*'.
563 char *bad = xstrfmt("%s*", terms->term_bad);
566 * It is important to reset the flags used by revision walks
567 * as the previous call to bisect_next_all() in turn
568 * sets up a revision walk.
570 reset_revision_walk();
571 init_revisions(revs, NULL);
572 setup_revisions(0, NULL, revs, NULL);
573 for_each_glob_ref_in(add_bisect_ref, bad, "refs/bisect/", &cb);
574 cb.object_flags = UNINTERESTING;
575 for_each_glob_ref_in(add_bisect_ref, good, "refs/bisect/", &cb);
576 if (prepare_revision_walk(revs))
577 res = error(_("revision walk setup failed\n"));
579 free(good);
580 free(bad);
581 return res;
584 static int bisect_skipped_commits(struct bisect_terms *terms)
586 int res;
587 FILE *fp = NULL;
588 struct rev_info revs;
589 struct commit *commit;
590 struct pretty_print_context pp = {0};
591 struct strbuf commit_name = STRBUF_INIT;
593 res = prepare_revs(terms, &revs);
594 if (res)
595 return res;
597 fp = fopen(git_path_bisect_log(), "a");
598 if (!fp)
599 return error_errno(_("could not open '%s' for appending"),
600 git_path_bisect_log());
602 if (fprintf(fp, "# only skipped commits left to test\n") < 0)
603 return error_errno(_("failed to write to '%s'"), git_path_bisect_log());
605 while ((commit = get_revision(&revs)) != NULL) {
606 strbuf_reset(&commit_name);
607 format_commit_message(commit, "%s",
608 &commit_name, &pp);
609 fprintf(fp, "# possible first %s commit: [%s] %s\n",
610 terms->term_bad, oid_to_hex(&commit->object.oid),
611 commit_name.buf);
615 * Reset the flags used by revision walks in case
616 * there is another revision walk after this one.
618 reset_revision_walk();
620 strbuf_release(&commit_name);
621 release_revisions(&revs);
622 fclose(fp);
623 return 0;
626 static int bisect_successful(struct bisect_terms *terms)
628 struct object_id oid;
629 struct commit *commit;
630 struct pretty_print_context pp = {0};
631 struct strbuf commit_name = STRBUF_INIT;
632 char *bad_ref = xstrfmt("refs/bisect/%s",terms->term_bad);
633 int res;
635 read_ref(bad_ref, &oid);
636 commit = lookup_commit_reference_by_name(bad_ref);
637 format_commit_message(commit, "%s", &commit_name, &pp);
639 res = append_to_file(git_path_bisect_log(), "# first %s commit: [%s] %s\n",
640 terms->term_bad, oid_to_hex(&commit->object.oid),
641 commit_name.buf);
643 strbuf_release(&commit_name);
644 free(bad_ref);
645 return res;
648 static enum bisect_error bisect_next(struct bisect_terms *terms, const char *prefix)
650 enum bisect_error res;
652 if (bisect_autostart(terms))
653 return BISECT_FAILED;
655 if (bisect_next_check(terms, terms->term_good))
656 return BISECT_FAILED;
658 /* Perform all bisection computation */
659 res = bisect_next_all(the_repository, prefix);
661 if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
662 res = bisect_successful(terms);
663 return res ? res : BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND;
664 } else if (res == BISECT_ONLY_SKIPPED_LEFT) {
665 res = bisect_skipped_commits(terms);
666 return res ? res : BISECT_ONLY_SKIPPED_LEFT;
668 return res;
671 static enum bisect_error bisect_auto_next(struct bisect_terms *terms, const char *prefix)
673 if (bisect_next_check(terms, NULL)) {
674 bisect_print_status(terms);
675 return BISECT_OK;
678 return bisect_next(terms, prefix);
681 static enum bisect_error bisect_start(struct bisect_terms *terms, int argc,
682 const char **argv)
684 int no_checkout = 0;
685 int first_parent_only = 0;
686 int i, has_double_dash = 0, must_write_terms = 0, bad_seen = 0;
687 int flags, pathspec_pos;
688 enum bisect_error res = BISECT_OK;
689 struct string_list revs = STRING_LIST_INIT_DUP;
690 struct string_list states = STRING_LIST_INIT_DUP;
691 struct strbuf start_head = STRBUF_INIT;
692 struct strbuf bisect_names = STRBUF_INIT;
693 struct object_id head_oid;
694 struct object_id oid;
695 const char *head;
697 if (is_bare_repository())
698 no_checkout = 1;
701 * Check for one bad and then some good revisions
703 for (i = 0; i < argc; i++) {
704 if (!strcmp(argv[i], "--")) {
705 has_double_dash = 1;
706 break;
710 for (i = 0; i < argc; i++) {
711 const char *arg = argv[i];
712 if (!strcmp(argv[i], "--")) {
713 break;
714 } else if (!strcmp(arg, "--no-checkout")) {
715 no_checkout = 1;
716 } else if (!strcmp(arg, "--first-parent")) {
717 first_parent_only = 1;
718 } else if (!strcmp(arg, "--term-good") ||
719 !strcmp(arg, "--term-old")) {
720 i++;
721 if (argc <= i)
722 return error(_("'' is not a valid term"));
723 must_write_terms = 1;
724 free((void *) terms->term_good);
725 terms->term_good = xstrdup(argv[i]);
726 } else if (skip_prefix(arg, "--term-good=", &arg) ||
727 skip_prefix(arg, "--term-old=", &arg)) {
728 must_write_terms = 1;
729 free((void *) terms->term_good);
730 terms->term_good = xstrdup(arg);
731 } else if (!strcmp(arg, "--term-bad") ||
732 !strcmp(arg, "--term-new")) {
733 i++;
734 if (argc <= i)
735 return error(_("'' is not a valid term"));
736 must_write_terms = 1;
737 free((void *) terms->term_bad);
738 terms->term_bad = xstrdup(argv[i]);
739 } else if (skip_prefix(arg, "--term-bad=", &arg) ||
740 skip_prefix(arg, "--term-new=", &arg)) {
741 must_write_terms = 1;
742 free((void *) terms->term_bad);
743 terms->term_bad = xstrdup(arg);
744 } else if (starts_with(arg, "--")) {
745 return error(_("unrecognized option: '%s'"), arg);
746 } else if (!get_oidf(&oid, "%s^{commit}", arg)) {
747 string_list_append(&revs, oid_to_hex(&oid));
748 } else if (has_double_dash) {
749 die(_("'%s' does not appear to be a valid "
750 "revision"), arg);
751 } else {
752 break;
755 pathspec_pos = i;
758 * The user ran "git bisect start <sha1> <sha1>", hence did not
759 * explicitly specify the terms, but we are already starting to
760 * set references named with the default terms, and won't be able
761 * to change afterwards.
763 if (revs.nr)
764 must_write_terms = 1;
765 for (i = 0; i < revs.nr; i++) {
766 if (bad_seen) {
767 string_list_append(&states, terms->term_good);
768 } else {
769 bad_seen = 1;
770 string_list_append(&states, terms->term_bad);
775 * Verify HEAD
777 head = resolve_ref_unsafe("HEAD", 0, &head_oid, &flags);
778 if (!head)
779 if (get_oid("HEAD", &head_oid))
780 return error(_("bad HEAD - I need a HEAD"));
783 * Check if we are bisecting
785 if (!is_empty_or_missing_file(git_path_bisect_start())) {
786 /* Reset to the rev from where we started */
787 strbuf_read_file(&start_head, git_path_bisect_start(), 0);
788 strbuf_trim(&start_head);
789 if (!no_checkout) {
790 struct child_process cmd = CHILD_PROCESS_INIT;
792 cmd.git_cmd = 1;
793 strvec_pushl(&cmd.args, "checkout", start_head.buf,
794 "--", NULL);
795 if (run_command(&cmd)) {
796 res = error(_("checking out '%s' failed."
797 " Try 'git bisect start "
798 "<valid-branch>'."),
799 start_head.buf);
800 goto finish;
803 } else {
804 /* Get the rev from where we start. */
805 if (!get_oid(head, &head_oid) &&
806 !starts_with(head, "refs/heads/")) {
807 strbuf_reset(&start_head);
808 strbuf_addstr(&start_head, oid_to_hex(&head_oid));
809 } else if (!get_oid(head, &head_oid) &&
810 skip_prefix(head, "refs/heads/", &head)) {
811 strbuf_addstr(&start_head, head);
812 } else {
813 return error(_("bad HEAD - strange symbolic ref"));
818 * Get rid of any old bisect state.
820 if (bisect_clean_state())
821 return BISECT_FAILED;
824 * Write new start state
826 write_file(git_path_bisect_start(), "%s\n", start_head.buf);
828 if (first_parent_only)
829 write_file(git_path_bisect_first_parent(), "\n");
831 if (no_checkout) {
832 if (get_oid(start_head.buf, &oid) < 0) {
833 res = error(_("invalid ref: '%s'"), start_head.buf);
834 goto finish;
836 if (update_ref(NULL, "BISECT_HEAD", &oid, NULL, 0,
837 UPDATE_REFS_MSG_ON_ERR)) {
838 res = BISECT_FAILED;
839 goto finish;
843 if (pathspec_pos < argc - 1)
844 sq_quote_argv(&bisect_names, argv + pathspec_pos);
845 write_file(git_path_bisect_names(), "%s\n", bisect_names.buf);
847 for (i = 0; i < states.nr; i++)
848 if (bisect_write(states.items[i].string,
849 revs.items[i].string, terms, 1)) {
850 res = BISECT_FAILED;
851 goto finish;
854 if (must_write_terms && write_terms(terms->term_bad,
855 terms->term_good)) {
856 res = BISECT_FAILED;
857 goto finish;
860 res = bisect_append_log_quoted(argv);
861 if (res)
862 res = BISECT_FAILED;
864 finish:
865 string_list_clear(&revs, 0);
866 string_list_clear(&states, 0);
867 strbuf_release(&start_head);
868 strbuf_release(&bisect_names);
869 if (res)
870 return res;
872 res = bisect_auto_next(terms, NULL);
873 if (!is_bisect_success(res))
874 bisect_clean_state();
875 return res;
878 static inline int file_is_not_empty(const char *path)
880 return !is_empty_or_missing_file(path);
883 static int bisect_autostart(struct bisect_terms *terms)
885 int res;
886 const char *yesno;
888 if (file_is_not_empty(git_path_bisect_start()))
889 return 0;
891 fprintf_ln(stderr, _("You need to start by \"git bisect "
892 "start\"\n"));
894 if (!isatty(STDIN_FILENO))
895 return -1;
898 * TRANSLATORS: Make sure to include [Y] and [n] in your
899 * translation. The program will only accept English input
900 * at this point.
902 yesno = git_prompt(_("Do you want me to do it for you "
903 "[Y/n]? "), PROMPT_ECHO);
904 res = tolower(*yesno) == 'n' ?
905 -1 : bisect_start(terms, 0, empty_strvec);
907 return res;
910 static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
911 const char **argv)
913 const char *state;
914 int i, verify_expected = 1;
915 struct object_id oid, expected;
916 struct strbuf buf = STRBUF_INIT;
917 struct oid_array revs = OID_ARRAY_INIT;
919 if (!argc)
920 return error(_("Please call `--bisect-state` with at least one argument"));
922 if (bisect_autostart(terms))
923 return BISECT_FAILED;
925 state = argv[0];
926 if (check_and_set_terms(terms, state) ||
927 !one_of(state, terms->term_good, terms->term_bad, "skip", NULL))
928 return BISECT_FAILED;
930 argv++;
931 argc--;
932 if (argc > 1 && !strcmp(state, terms->term_bad))
933 return error(_("'git bisect %s' can take only one argument."), terms->term_bad);
935 if (argc == 0) {
936 const char *head = "BISECT_HEAD";
937 enum get_oid_result res_head = get_oid(head, &oid);
939 if (res_head == MISSING_OBJECT) {
940 head = "HEAD";
941 res_head = get_oid(head, &oid);
944 if (res_head)
945 error(_("Bad rev input: %s"), head);
946 oid_array_append(&revs, &oid);
950 * All input revs must be checked before executing bisect_write()
951 * to discard junk revs.
954 for (; argc; argc--, argv++) {
955 struct commit *commit;
957 if (get_oid(*argv, &oid)){
958 error(_("Bad rev input: %s"), *argv);
959 oid_array_clear(&revs);
960 return BISECT_FAILED;
963 commit = lookup_commit_reference(the_repository, &oid);
964 if (!commit)
965 die(_("Bad rev input (not a commit): %s"), *argv);
967 oid_array_append(&revs, &commit->object.oid);
970 if (strbuf_read_file(&buf, git_path_bisect_expected_rev(), 0) < the_hash_algo->hexsz ||
971 get_oid_hex(buf.buf, &expected) < 0)
972 verify_expected = 0; /* Ignore invalid file contents */
973 strbuf_release(&buf);
975 for (i = 0; i < revs.nr; i++) {
976 if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
977 oid_array_clear(&revs);
978 return BISECT_FAILED;
980 if (verify_expected && !oideq(&revs.oid[i], &expected)) {
981 unlink_or_warn(git_path_bisect_ancestors_ok());
982 unlink_or_warn(git_path_bisect_expected_rev());
983 verify_expected = 0;
987 oid_array_clear(&revs);
988 return bisect_auto_next(terms, NULL);
991 static enum bisect_error bisect_log(void)
993 int fd, status;
994 const char* filename = git_path_bisect_log();
996 if (is_empty_or_missing_file(filename))
997 return error(_("We are not bisecting."));
999 fd = open(filename, O_RDONLY);
1000 if (fd < 0)
1001 return BISECT_FAILED;
1003 status = copy_fd(fd, STDOUT_FILENO);
1004 close(fd);
1005 return status ? BISECT_FAILED : BISECT_OK;
1008 static int process_replay_line(struct bisect_terms *terms, struct strbuf *line)
1010 const char *p = line->buf + strspn(line->buf, " \t");
1011 char *word_end, *rev;
1013 if ((!skip_prefix(p, "git bisect", &p) &&
1014 !skip_prefix(p, "git-bisect", &p)) || !isspace(*p))
1015 return 0;
1016 p += strspn(p, " \t");
1018 word_end = (char *)p + strcspn(p, " \t");
1019 rev = word_end + strspn(word_end, " \t");
1020 *word_end = '\0'; /* NUL-terminate the word */
1022 get_terms(terms);
1023 if (check_and_set_terms(terms, p))
1024 return -1;
1026 if (!strcmp(p, "start")) {
1027 struct strvec argv = STRVEC_INIT;
1028 int res;
1029 sq_dequote_to_strvec(rev, &argv);
1030 res = bisect_start(terms, argv.nr, argv.v);
1031 strvec_clear(&argv);
1032 return res;
1035 if (one_of(p, terms->term_good,
1036 terms->term_bad, "skip", NULL))
1037 return bisect_write(p, rev, terms, 0);
1039 if (!strcmp(p, "terms")) {
1040 struct strvec argv = STRVEC_INIT;
1041 int res;
1042 sq_dequote_to_strvec(rev, &argv);
1043 res = bisect_terms(terms, argv.nr == 1 ? argv.v[0] : NULL);
1044 strvec_clear(&argv);
1045 return res;
1047 error(_("'%s'?? what are you talking about?"), p);
1049 return -1;
1052 static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *filename)
1054 FILE *fp = NULL;
1055 enum bisect_error res = BISECT_OK;
1056 struct strbuf line = STRBUF_INIT;
1058 if (is_empty_or_missing_file(filename))
1059 return error(_("cannot read file '%s' for replaying"), filename);
1061 if (bisect_reset(NULL))
1062 return BISECT_FAILED;
1064 fp = fopen(filename, "r");
1065 if (!fp)
1066 return BISECT_FAILED;
1068 while ((strbuf_getline(&line, fp) != EOF) && !res)
1069 res = process_replay_line(terms, &line);
1071 strbuf_release(&line);
1072 fclose(fp);
1074 if (res)
1075 return BISECT_FAILED;
1077 return bisect_auto_next(terms, NULL);
1080 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
1081 const char **argv)
1083 int i;
1084 enum bisect_error res;
1085 struct strvec argv_state = STRVEC_INIT;
1087 strvec_push(&argv_state, "skip");
1089 for (i = 0; i < argc; i++) {
1090 const char *dotdot = strstr(argv[i], "..");
1092 if (dotdot) {
1093 struct rev_info revs;
1094 struct commit *commit;
1096 init_revisions(&revs, NULL);
1097 setup_revisions(2, argv + i - 1, &revs, NULL);
1099 if (prepare_revision_walk(&revs))
1100 die(_("revision walk setup failed\n"));
1101 while ((commit = get_revision(&revs)) != NULL)
1102 strvec_push(&argv_state,
1103 oid_to_hex(&commit->object.oid));
1105 reset_revision_walk();
1106 release_revisions(&revs);
1107 } else {
1108 strvec_push(&argv_state, argv[i]);
1111 res = bisect_state(terms, argv_state.nr, argv_state.v);
1113 strvec_clear(&argv_state);
1114 return res;
1117 static int bisect_visualize(struct bisect_terms *terms, int argc,
1118 const char **argv)
1120 struct child_process cmd = CHILD_PROCESS_INIT;
1121 struct strbuf sb = STRBUF_INIT;
1123 if (bisect_next_check(terms, NULL) != 0)
1124 return BISECT_FAILED;
1126 cmd.no_stdin = 1;
1127 if (!argc) {
1128 if ((getenv("DISPLAY") || getenv("SESSIONNAME") || getenv("MSYSTEM") ||
1129 getenv("SECURITYSESSIONID")) && exists_in_PATH("gitk")) {
1130 strvec_push(&cmd.args, "gitk");
1131 } else {
1132 strvec_push(&cmd.args, "log");
1133 cmd.git_cmd = 1;
1135 } else {
1136 if (argv[0][0] == '-') {
1137 strvec_push(&cmd.args, "log");
1138 cmd.git_cmd = 1;
1139 } else if (strcmp(argv[0], "tig") && !starts_with(argv[0], "git"))
1140 cmd.git_cmd = 1;
1142 strvec_pushv(&cmd.args, argv);
1145 strvec_pushl(&cmd.args, "--bisect", "--", NULL);
1147 strbuf_read_file(&sb, git_path_bisect_names(), 0);
1148 sq_dequote_to_strvec(sb.buf, &cmd.args);
1149 strbuf_release(&sb);
1151 return run_command(&cmd);
1154 static int get_first_good(const char *refname UNUSED,
1155 const struct object_id *oid,
1156 int flag UNUSED, void *cb_data)
1158 oidcpy(cb_data, oid);
1159 return 1;
1162 static int do_bisect_run(const char *command)
1164 struct child_process cmd = CHILD_PROCESS_INIT;
1166 printf(_("running %s\n"), command);
1167 cmd.use_shell = 1;
1168 strvec_push(&cmd.args, command);
1169 return run_command(&cmd);
1172 static int verify_good(const struct bisect_terms *terms, const char *command)
1174 int rc;
1175 enum bisect_error res;
1176 struct object_id good_rev;
1177 struct object_id current_rev;
1178 char *good_glob = xstrfmt("%s-*", terms->term_good);
1179 int no_checkout = ref_exists("BISECT_HEAD");
1181 for_each_glob_ref_in(get_first_good, good_glob, "refs/bisect/",
1182 &good_rev);
1183 free(good_glob);
1185 if (read_ref(no_checkout ? "BISECT_HEAD" : "HEAD", &current_rev))
1186 return -1;
1188 res = bisect_checkout(&good_rev, no_checkout);
1189 if (res != BISECT_OK)
1190 return -1;
1192 rc = do_bisect_run(command);
1194 res = bisect_checkout(&current_rev, no_checkout);
1195 if (res != BISECT_OK)
1196 return -1;
1198 return rc;
1201 static int bisect_run(struct bisect_terms *terms, int argc, const char **argv)
1203 int res = BISECT_OK;
1204 struct strbuf command = STRBUF_INIT;
1205 const char *new_state;
1206 int temporary_stdout_fd, saved_stdout;
1207 int is_first_run = 1;
1209 if (bisect_next_check(terms, NULL))
1210 return BISECT_FAILED;
1212 if (!argc) {
1213 error(_("bisect run failed: no command provided."));
1214 return BISECT_FAILED;
1217 sq_quote_argv(&command, argv);
1218 strbuf_ltrim(&command);
1219 while (1) {
1220 res = do_bisect_run(command.buf);
1223 * Exit code 126 and 127 can either come from the shell
1224 * if it was unable to execute or even find the script,
1225 * or from the script itself. Check with a known-good
1226 * revision to avoid trashing the bisect run due to a
1227 * missing or non-executable script.
1229 if (is_first_run && (res == 126 || res == 127)) {
1230 int rc = verify_good(terms, command.buf);
1231 is_first_run = 0;
1232 if (rc < 0 || 128 <= rc) {
1233 error(_("unable to verify %s on good"
1234 " revision"), command.buf);
1235 res = BISECT_FAILED;
1236 break;
1238 if (rc == res) {
1239 error(_("bogus exit code %d for good revision"),
1240 rc);
1241 res = BISECT_FAILED;
1242 break;
1246 if (res < 0 || 128 <= res) {
1247 error(_("bisect run failed: exit code %d from"
1248 " %s is < 0 or >= 128"), res, command.buf);
1249 break;
1252 if (res == 125)
1253 new_state = "skip";
1254 else if (!res)
1255 new_state = terms->term_good;
1256 else
1257 new_state = terms->term_bad;
1259 temporary_stdout_fd = open(git_path_bisect_run(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
1261 if (temporary_stdout_fd < 0) {
1262 res = error_errno(_("cannot open file '%s' for writing"), git_path_bisect_run());
1263 break;
1266 fflush(stdout);
1267 saved_stdout = dup(1);
1268 dup2(temporary_stdout_fd, 1);
1270 res = bisect_state(terms, 1, &new_state);
1272 fflush(stdout);
1273 dup2(saved_stdout, 1);
1274 close(saved_stdout);
1275 close(temporary_stdout_fd);
1277 print_file_to_stdout(git_path_bisect_run());
1279 if (res == BISECT_ONLY_SKIPPED_LEFT)
1280 error(_("bisect run cannot continue any more"));
1281 else if (res == BISECT_INTERNAL_SUCCESS_MERGE_BASE) {
1282 puts(_("bisect run success"));
1283 res = BISECT_OK;
1284 } else if (res == BISECT_INTERNAL_SUCCESS_1ST_BAD_FOUND) {
1285 puts(_("bisect found first bad commit"));
1286 res = BISECT_OK;
1287 } else if (res) {
1288 error(_("bisect run failed: 'git bisect %s'"
1289 " exited with error code %d"), new_state, res);
1290 } else {
1291 continue;
1293 break;
1296 strbuf_release(&command);
1297 return res;
1300 static int cmd_bisect__reset(int argc, const char **argv, const char *prefix UNUSED)
1302 if (argc > 1)
1303 return error(_("'%s' requires either no argument or a commit"),
1304 "git bisect reset");
1305 return bisect_reset(argc ? argv[0] : NULL);
1308 static int cmd_bisect__terms(int argc, const char **argv, const char *prefix UNUSED)
1310 int res;
1311 struct bisect_terms terms = { 0 };
1313 if (argc > 1)
1314 return error(_("'%s' requires 0 or 1 argument"),
1315 "git bisect terms");
1316 res = bisect_terms(&terms, argc == 1 ? argv[0] : NULL);
1317 free_terms(&terms);
1318 return res;
1321 static int cmd_bisect__start(int argc, const char **argv, const char *prefix UNUSED)
1323 int res;
1324 struct bisect_terms terms = { 0 };
1326 set_terms(&terms, "bad", "good");
1327 res = bisect_start(&terms, argc, argv);
1328 free_terms(&terms);
1329 return res;
1332 static int cmd_bisect__next(int argc, const char **argv UNUSED, const char *prefix)
1334 int res;
1335 struct bisect_terms terms = { 0 };
1337 if (argc)
1338 return error(_("'%s' requires 0 arguments"),
1339 "git bisect next");
1340 get_terms(&terms);
1341 res = bisect_next(&terms, prefix);
1342 free_terms(&terms);
1343 return res;
1346 static int cmd_bisect__log(int argc UNUSED, const char **argv UNUSED, const char *prefix UNUSED)
1348 return bisect_log();
1351 static int cmd_bisect__replay(int argc, const char **argv, const char *prefix UNUSED)
1353 int res;
1354 struct bisect_terms terms = { 0 };
1356 if (argc != 1)
1357 return error(_("no logfile given"));
1358 set_terms(&terms, "bad", "good");
1359 res = bisect_replay(&terms, argv[0]);
1360 free_terms(&terms);
1361 return res;
1364 static int cmd_bisect__skip(int argc, const char **argv, const char *prefix UNUSED)
1366 int res;
1367 struct bisect_terms terms = { 0 };
1369 set_terms(&terms, "bad", "good");
1370 get_terms(&terms);
1371 res = bisect_skip(&terms, argc, argv);
1372 free_terms(&terms);
1373 return res;
1376 static int cmd_bisect__visualize(int argc, const char **argv, const char *prefix UNUSED)
1378 int res;
1379 struct bisect_terms terms = { 0 };
1381 get_terms(&terms);
1382 res = bisect_visualize(&terms, argc, argv);
1383 free_terms(&terms);
1384 return res;
1387 static int cmd_bisect__run(int argc, const char **argv, const char *prefix UNUSED)
1389 int res;
1390 struct bisect_terms terms = { 0 };
1392 if (!argc)
1393 return error(_("'%s' failed: no command provided."), "git bisect run");
1394 get_terms(&terms);
1395 res = bisect_run(&terms, argc, argv);
1396 free_terms(&terms);
1397 return res;
1400 int cmd_bisect(int argc, const char **argv, const char *prefix)
1402 int res = 0;
1403 parse_opt_subcommand_fn *fn = NULL;
1404 struct option options[] = {
1405 OPT_SUBCOMMAND("reset", &fn, cmd_bisect__reset),
1406 OPT_SUBCOMMAND("terms", &fn, cmd_bisect__terms),
1407 OPT_SUBCOMMAND("start", &fn, cmd_bisect__start),
1408 OPT_SUBCOMMAND("next", &fn, cmd_bisect__next),
1409 OPT_SUBCOMMAND("log", &fn, cmd_bisect__log),
1410 OPT_SUBCOMMAND("replay", &fn, cmd_bisect__replay),
1411 OPT_SUBCOMMAND("skip", &fn, cmd_bisect__skip),
1412 OPT_SUBCOMMAND("visualize", &fn, cmd_bisect__visualize),
1413 OPT_SUBCOMMAND("view", &fn, cmd_bisect__visualize),
1414 OPT_SUBCOMMAND("run", &fn, cmd_bisect__run),
1415 OPT_END()
1417 argc = parse_options(argc, argv, prefix, options, git_bisect_usage,
1418 PARSE_OPT_SUBCOMMAND_OPTIONAL);
1420 if (!fn) {
1421 struct bisect_terms terms = { 0 };
1423 if (!argc)
1424 usage_msg_opt(_("need a command"), git_bisect_usage, options);
1426 set_terms(&terms, "bad", "good");
1427 get_terms(&terms);
1428 if (check_and_set_terms(&terms, argv[0]))
1429 usage_msg_optf(_("unknown command: '%s'"), git_bisect_usage,
1430 options, argv[0]);
1431 res = bisect_state(&terms, argc, argv);
1432 free_terms(&terms);
1433 } else {
1434 argc--;
1435 argv++;
1436 res = fn(argc, argv, prefix);
1439 return is_bisect_success(res) ? 0 : -res;